diff --git a/src/intTest/java/com/box/sdk/BoxRetentionPolicyAssignmentIT.java b/src/intTest/java/com/box/sdk/BoxRetentionPolicyAssignmentIT.java index afb11fb35..5c56b40e3 100644 --- a/src/intTest/java/com/box/sdk/BoxRetentionPolicyAssignmentIT.java +++ b/src/intTest/java/com/box/sdk/BoxRetentionPolicyAssignmentIT.java @@ -11,12 +11,10 @@ import static com.box.sdk.UniqueTestFolder.uploadTwoFileVersionsToSpecifiedFolder; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; -import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import java.util.List; -import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import org.junit.AfterClass; @@ -30,7 +28,7 @@ public class BoxRetentionPolicyAssignmentIT { private static BoxRetentionPolicy policy; @BeforeClass - public static void beforeClass() throws Exception { + public static void beforeClass() { BoxAPIConnection api = jwtApiForServiceAccount(); policy = RetentionPolicyUtils.getOneDayRetentionPolicy(api); setupUniqeFolder(); @@ -42,82 +40,93 @@ public static void tearDown() { } @Test - public void attachPolicyToFileAndGetFilesUnderRetentionAndDeleteAttachment() { + public void attachPolicyToFileAndGetFilesUnderRetentionAndDeleteAttachment() throws InterruptedException { //given BoxAPIConnection api = jwtApiForServiceAccount(); BoxFolder.Info folder = getUniqueFolder(api) .createFolder(randomizeName("attachPolicyToFileAndGetFilesUnderRetention")); - BoxRetentionPolicyAssignment.Info assignmentInfo = createAssignmentToFolder( + try { + BoxRetentionPolicyAssignment.Info assignmentInfo = createAssignmentToFolder( api, policy.getID(), folder.getID() - ); - BoxFile boxFile = uploadFileWithSomeContent("file_with_retention.txt", folder.getResource()); + ); + BoxFile boxFile = uploadFileWithSomeContent("file_with_retention.txt", folder.getResource()); - //when - BoxRetentionPolicyAssignment assignment = new BoxRetentionPolicyAssignment(api, assignmentInfo.getID()); - Iterable filesUnderRetention = - new BoxRetentionPolicyAssignment(api, assignmentInfo.getID()).getFilesUnderRetention(5); + //when + BoxRetentionPolicyAssignment assignment = new BoxRetentionPolicyAssignment(api, assignmentInfo.getID()); + Iterable filesUnderRetention = + new BoxRetentionPolicyAssignment(api, assignmentInfo.getID()).getFilesUnderRetention(5); - //then - Optional matchingFileWithRetention1 = - StreamSupport.stream(filesUnderRetention.spliterator(), false) - .filter(f -> f.getID().equals(boxFile.getID())) - .findFirst(); - assertTrue(matchingFileWithRetention1.isPresent()); - - //when - assignment.delete(); - - //then - Optional matchingFileWithRetention2 = + //then + List matchingFileWithRetention1 = StreamSupport.stream(filesUnderRetention.spliterator(), false) + .filter(f -> f.getID().equals(boxFile.getID())) + .collect(Collectors.toList()); + assertThat(matchingFileWithRetention1, hasSize(1)); + + //when + assignment.delete(); + Retry.retry(() -> { + Iterable filesUnderRetention2 = + new BoxRetentionPolicyAssignment(api, assignmentInfo.getID()).getFilesUnderRetention(5); + + //then + List matchingFileWithRetention2 = + StreamSupport.stream(filesUnderRetention2.spliterator(), false) .filter(f -> f.getID().equals(boxFile.getID())) - .findFirst(); - assertFalse(matchingFileWithRetention2.isPresent()); - - //cleanup - deleteFolder(folder.getResource()); + .collect(Collectors.toList()); + assertTrue(matchingFileWithRetention2.isEmpty()); + }, 3, 1000); + } finally { + //cleanup + deleteFolder(folder.getResource()); + } } @Test - public void attachPolicyToFileAndGetFileVersionsUnderRetentionAndDeleteAttachment() { + public void attachPolicyToFileAndGetFileVersionsUnderRetentionAndDeleteAttachment() throws InterruptedException { //given BoxAPIConnection api = jwtApiForServiceAccount(); BoxFolder folder = getUniqueFolder(api) .createFolder(randomizeName("attachPolicyToFileAndGetFileVersionsUnderRetention")) .getResource(); - BoxRetentionPolicyAssignment.Info assignmentInfo = createAssignmentToFolder( + try { + BoxRetentionPolicyAssignment.Info assignmentInfo = createAssignmentToFolder( api, policy.getID(), folder.getID() - ); - BoxFile boxFile = uploadTwoFileVersionsToSpecifiedFolder( - "file_with_retention.txt", - "v1", - "v2", - folder, - mock(ProgressListener.class) - ); - - //when - BoxRetentionPolicyAssignment assignment = new BoxRetentionPolicyAssignment(api, assignmentInfo.getID()); - Iterable filesVersionsUnderRetention = assignment.getFileVersionsUnderRetention(5); - - //then - List matchingFileWithRetention1 = - StreamSupport.stream(filesVersionsUnderRetention.spliterator(), false) - .filter(f -> f.getID().equals(boxFile.getID())) - .collect(Collectors.toList()); - assertThat(matchingFileWithRetention1, hasSize(1)); - - //when - assignment.delete(); - - //then - List matchingFileWithRetention2 = - StreamSupport.stream(filesVersionsUnderRetention.spliterator(), false) + ); + BoxFile boxFile = uploadTwoFileVersionsToSpecifiedFolder( + "file_with_retention.txt", + "v1", + "v2", + folder, + mock(ProgressListener.class) + ); + + //when + BoxRetentionPolicyAssignment assignment = new BoxRetentionPolicyAssignment(api, assignmentInfo.getID()); + Iterable filesVersionsUnderRetention1 = assignment.getFileVersionsUnderRetention(5); + + //then + List matchingFileWithRetention1 = + StreamSupport.stream(filesVersionsUnderRetention1.spliterator(), false) + .filter(f -> f.getID().equals(boxFile.getID())) + .collect(Collectors.toList()); + assertThat(matchingFileWithRetention1, hasSize(1)); + + //when + assignment.delete(); + Retry.retry(() -> { + Iterable filesVersionsUnderRetention2 = assignment.getFileVersionsUnderRetention(5); + + //then + List matchingFileWithRetention2 = + StreamSupport.stream(filesVersionsUnderRetention2.spliterator(), false) .filter(f -> f.getID().equals(boxFile.getID())) .collect(Collectors.toList()); - assertTrue(matchingFileWithRetention2.isEmpty()); - - //cleanup - deleteFolder(folder); + assertTrue(matchingFileWithRetention2.isEmpty()); + }, 3, 1000); + } finally { + //cleanup + deleteFolder(folder); + } } } diff --git a/src/intTest/java/com/box/sdk/MetadataIT.java b/src/intTest/java/com/box/sdk/MetadataIT.java index 01d8d6e42..5cf55fc70 100644 --- a/src/intTest/java/com/box/sdk/MetadataIT.java +++ b/src/intTest/java/com/box/sdk/MetadataIT.java @@ -22,12 +22,12 @@ public class MetadataIT { @BeforeClass - public static void beforeClass() throws Exception { + public static void beforeClass() { setupUniqeFolder(); } @AfterClass - public static void afterClass() throws Exception { + public static void afterClass() { removeUniqueFolder(); } @@ -37,6 +37,7 @@ public void testMetadataPrecisionFloat() { BoxAPIConnection api = jwtApiForServiceAccount(); long timestamp = Calendar.getInstance().getTimeInMillis(); + String scope = "enterprise"; String templateKey = "precision" + timestamp; String fieldKey = "testPrecision"; @@ -47,28 +48,33 @@ public void testMetadataPrecisionFloat() { valueField.setDisplayName("Value Field"); fields.add(valueField); - MetadataTemplate template = MetadataTemplate.createMetadataTemplate(api, "enterprise", - templateKey, "Precision " + timestamp, false, fields); - assertEquals("float", template.getFields().get(0).getType()); + MetadataTemplate template = MetadataTemplate.createMetadataTemplate( + api, scope, templateKey, "Precision " + timestamp, false, fields + ); + try { + assertEquals("float", template.getFields().get(0).getType()); - // Add template to item - Metadata mdValues = new Metadata(); - mdValues.add("/" + fieldKey, expectedValueFloat); - BoxFolder rootFolder = getUniqueFolder(api); - BoxFolder.Info folder = rootFolder.createFolder("Metadata Precision Test " + timestamp); - Metadata actualMD = folder.getResource().createMetadata(templateKey, mdValues); + // Add template to item + Metadata mdValues = new Metadata(); + mdValues.add("/" + fieldKey, expectedValueFloat); + BoxFolder rootFolder = getUniqueFolder(api); + BoxFolder.Info folder = rootFolder.createFolder("Metadata Precision Test " + timestamp); + Metadata actualMD = folder.getResource().createMetadata(templateKey, mdValues); - assertEquals(templateKey, actualMD.getTemplateName()); + assertEquals(templateKey, actualMD.getTemplateName()); - final double actualValueDouble = actualMD.getDouble("/" + fieldKey); + final double actualValueDouble = actualMD.getDouble("/" + fieldKey); - // Instead of "hard-coding" the delta to 4.0, let's calculate it and then validate it - final double delta = actualValueDouble - (double) expectedValueFloat; - assertEquals(4.0, delta, 0); + // Instead of "hard-coding" the delta to 4.0, let's calculate it and then validate it + final double delta = actualValueDouble - (double) expectedValueFloat; + assertEquals(4.0, delta, 0); - // Now that we know delta is 4.0, when can use it for this validation - assertEquals(expectedValueFloat, actualValueDouble, delta); + // Now that we know delta is 4.0, when can use it for this validation + assertEquals(expectedValueFloat, actualValueDouble, delta); + } finally { + this.deleteMetadata(api, template); + } } @Test @@ -89,18 +95,21 @@ public void testMetadataPrecisionDouble() { MetadataTemplate template = MetadataTemplate.createMetadataTemplate(api, "enterprise", templateKey, "Precision " + timestamp, false, fields); + try { + assertEquals("float", template.getFields().get(0).getType()); - assertEquals("float", template.getFields().get(0).getType()); - - // Add template to item - Metadata mdValues = new Metadata(); - mdValues.add("/" + fieldKey, valueDouble); - BoxFolder rootFolder = getUniqueFolder(api); - BoxFolder.Info folder = rootFolder.createFolder("Metadata Precision Test " + timestamp); - Metadata actualMD = folder.getResource().createMetadata(templateKey, mdValues); + // Add template to item + Metadata mdValues = new Metadata(); + mdValues.add("/" + fieldKey, valueDouble); + BoxFolder rootFolder = getUniqueFolder(api); + BoxFolder.Info folder = rootFolder.createFolder("Metadata Precision Test " + timestamp); + Metadata actualMD = folder.getResource().createMetadata(templateKey, mdValues); - assertEquals(templateKey, actualMD.getTemplateName()); - assertEquals(valueDouble, actualMD.getDouble("/" + fieldKey), 0); + assertEquals(templateKey, actualMD.getTemplateName()); + assertEquals(valueDouble, actualMD.getDouble("/" + fieldKey), 0); + } finally { + this.deleteMetadata(api, template); + } } @Test @@ -255,7 +264,7 @@ public void testMultiSelectMetadataCRUD() { private void deleteMetadata(BoxAPIConnection api, MetadataTemplate template) { if (template != null) { - MetadataTemplate.deleteMetadataTemplate(api, "enterprise", template.getTemplateKey()); + MetadataTemplate.deleteMetadataTemplate(api, template.getScope(), template.getTemplateKey()); } } diff --git a/src/intTest/java/com/box/sdk/MetadataTemplateIT.java b/src/intTest/java/com/box/sdk/MetadataTemplateIT.java index d9e72b940..e7a2c4f3d 100644 --- a/src/intTest/java/com/box/sdk/MetadataTemplateIT.java +++ b/src/intTest/java/com/box/sdk/MetadataTemplateIT.java @@ -38,31 +38,7 @@ public static void tearDown() { } @Test - public void testDeleteMetadataTemplateSucceeds() { - String scope = "enterprise"; - String template = "testtemplate"; - String displayName = "Test Template"; - int errorResponseStatusCode = 404; - - BoxAPIConnection api = jwtApiForServiceAccount(); - - try { - MetadataTemplate.createMetadataTemplate(api, scope, template, displayName, false, null); - } catch (BoxAPIException e) { - System.out.print("Error while making callout to createMetdataTemplate(): " + e); - } - - MetadataTemplate.deleteMetadataTemplate(api, scope, template); - - try { - MetadataTemplate.getMetadataTemplate(api, template); - } catch (BoxAPIException e) { - assertEquals(errorResponseStatusCode, e.getResponseCode()); - } - } - - @Test - public void createMetadataTemplateSucceeds() { + public void createAndDeleteMetadataTemplateSucceeds() { BoxAPIConnection api = jwtApiForServiceAccount(); MetadataTemplate.Field ctField = new MetadataTemplate.Field(); @@ -84,58 +60,37 @@ public void createMetadataTemplateSucceeds() { fields.add(ctField); fields.add(fyField); - try { - MetadataTemplate.createMetadataTemplate(api, "enterprise", - "documentFlow03", "Document Flow 03", false, fields); - } catch (BoxAPIException apiEx) { - //Delete MetadataTemplate is yet to be supported. Due to that template might be existing already. - //This expects the conflict error. To check the MetadataTemplate creation, please replace the id. - assertEquals(409, apiEx.getResponseCode()); - } + String scope = "enterprise"; + String templateKey = "documentFlow03"; + MetadataTemplate.createMetadataTemplate( + api, scope, templateKey, "Document Flow 03", false, fields + ); - MetadataTemplate storedTemplate = MetadataTemplate.getMetadataTemplate(api, "documentFlow03"); + MetadataTemplate storedTemplate = MetadataTemplate.getMetadataTemplate(api, templateKey, scope); Assert.assertNotNull(storedTemplate); - } - - private List addFieldsHelper() { - List fieldOperations = new ArrayList<>(); - MetadataTemplate.FieldOperation customerFieldOp = new MetadataTemplate.FieldOperation(); - customerFieldOp.setOp(MetadataTemplate.Operation.addField); - - MetadataTemplate.Field customerTeam = new MetadataTemplate.Field(); - customerTeam.setType("string"); - customerTeam.setKey("customerTeam"); - customerTeam.setDisplayName("Customer Team"); - customerFieldOp.setData(customerTeam); - fieldOperations.add(customerFieldOp); - - MetadataTemplate.FieldOperation departmentFieldOp = new MetadataTemplate.FieldOperation(); - departmentFieldOp.setOp(MetadataTemplate.Operation.addField); - - MetadataTemplate.Field deptField = new MetadataTemplate.Field(); - deptField.setType("enum"); - deptField.setKey("department"); - deptField.setDisplayName("Department"); - - List options = new ArrayList<>(); - options.add("Beauty"); - options.add("Shoes"); - deptField.setOptions(options); - departmentFieldOp.setData(deptField); - fieldOperations.add(departmentFieldOp); - return fieldOperations; + MetadataTemplate.deleteMetadataTemplate(api, scope, templateKey); + try { + MetadataTemplate.getMetadataTemplate(api, templateKey, scope); + } catch (BoxAPIException e) { + assertEquals(e.getResponseCode(), e.getResponseCode()); + } } @Test public void updateMetadataTemplateFieldsSucceeds() { BoxAPIConnection api = jwtApiForServiceAccount(); + String scope = "enterprise"; + String templateKey = "documentFlow03"; + MetadataTemplate template = MetadataTemplate.createMetadataTemplate( + api, scope, templateKey, templateKey, false, new ArrayList<>() + ); try { //Test adding fields List fieldOperations = this.addFieldsHelper(); - MetadataTemplate template = MetadataTemplate.updateMetadataTemplate(api, - "enterprise", "documentFlow03", fieldOperations); + template = MetadataTemplate.updateMetadataTemplate(api, + scope, templateKey, fieldOperations); Assert.assertNotNull(template); boolean foundDeptField = false; @@ -179,7 +134,7 @@ public void updateMetadataTemplateFieldsSucceeds() { fieldOperations.add(editEnumOption); template = MetadataTemplate.updateMetadataTemplate(api, - "enterprise", "documentFlow03", fieldOperations); + scope, templateKey, fieldOperations); boolean foundBabyEnumOption = false; for (MetadataTemplate.Field field : template.getFields()) { if ("customerTeam".equals(field.getKey())) { @@ -213,7 +168,7 @@ public void updateMetadataTemplateFieldsSucceeds() { fieldOperations.add(deleteEnumOption); - template = MetadataTemplate.updateMetadataTemplate(api, "enterprise", "documentFlow03", fieldOperations); + template = MetadataTemplate.updateMetadataTemplate(api, scope, templateKey, fieldOperations); for (MetadataTemplate.Field field : template.getFields()) { if ("newCustomerTeamKey".equals(field.getKey())) { @@ -227,7 +182,7 @@ public void updateMetadataTemplateFieldsSucceeds() { } } } finally { - this.tearDownFields(api); + deleteMetadataTemplate(api, template); } } @@ -235,6 +190,10 @@ public void updateMetadataTemplateFieldsSucceeds() { public void getAllMetadataSucceeds() { BoxFile uploadedFile = null; BoxAPIConnection api = jwtApiForServiceAccount(); + String scope = "enterprise"; + String templateKey = "documentFlow03"; + MetadataTemplate template = null; + try { BoxFolder rootFolder = BoxFolder.getRootFolder(api); String fileName = "[getAllMetadataSucceeds] Test File.txt"; @@ -250,16 +209,19 @@ public void getAllMetadataSucceeds() { assertEquals("Smith", check1.getString("/lastName")); //Create fields before test + MetadataTemplate.createMetadataTemplate(api, scope, templateKey, templateKey, false, new ArrayList<>()); List fieldOperations = this.addFieldsHelper(); - MetadataTemplate template = MetadataTemplate.updateMetadataTemplate(api, - "enterprise", "documentFlow03", fieldOperations); + + template = MetadataTemplate.updateMetadataTemplate( + api, scope, templateKey, fieldOperations + ); Assert.assertNotNull(template); Metadata customerMetaData = new Metadata(); customerMetaData.add("/customerTeam", "MyTeam"); customerMetaData.add("/department", "Beauty"); - uploadedFile.createMetadata("documentFlow03", "enterprise", customerMetaData); + uploadedFile.createMetadata(templateKey, scope, customerMetaData); Iterable allMetadata = uploadedFile.getAllMetadata("/firstName", "/lastName"); Assert.assertNotNull(allMetadata); @@ -272,7 +234,7 @@ public void getAllMetadataSucceeds() { assertEquals("John", metadata.getString("/firstName")); assertEquals("Smith", metadata.getString("/lastName")); } - if (metadata.getTemplateName().equals("documentFlow03")) { + if (metadata.getTemplateName().equals(templateKey)) { assertEquals("MyTeam", metadata.getString("/customerTeam")); assertEquals("Beauty", metadata.getString("/department")); } @@ -280,7 +242,7 @@ public void getAllMetadataSucceeds() { Assert.assertTrue("Should have at least 2 templates", numTemplates >= 2); } finally { deleteFile(uploadedFile); - this.tearDownFields(api); + deleteMetadataTemplate(api, template); } } @@ -291,14 +253,16 @@ public void executeMetadataTemplateQuery() { BoxFolder one = null; BoxFolder two = null; + MetadataTemplate.Field metadataField = new MetadataTemplate.Field(); + metadataField.setType("float"); + metadataField.setKey("myField"); + metadataField.setDisplayName("Value"); + List fields = new ArrayList<>(); + fields.add(metadataField); + MetadataTemplate template = MetadataTemplate.createMetadataTemplate( + api, "enterprise", templateKey, "My Template", false, fields + ); try { - MetadataTemplate.Field metadataField = new MetadataTemplate.Field(); - metadataField.setType("float"); - metadataField.setKey("myField"); - metadataField.setDisplayName("Value"); - List fields = new ArrayList<>(); - fields.add(metadataField); - MetadataTemplate.createMetadataTemplate(api, "enterprise", templateKey, "My Template", false, fields); BoxFolder rootFolder = getUniqueFolder(api); one = rootFolder.createFolder("one").getResource(); @@ -317,22 +281,45 @@ public void executeMetadataTemplateQuery() { assertThat(foundFolder.getName(), is("one")); assertThat(iterator.hasNext(), is(false)); } finally { - MetadataTemplate.deleteMetadataTemplate(api, "enterprise", templateKey); + deleteMetadataTemplate(api, template); deleteFolder(one); deleteFolder(two); } } - private void tearDownFields(BoxAPIConnection api) { + private List addFieldsHelper() { List fieldOperations = new ArrayList<>(); - MetadataTemplate template = MetadataTemplate.getMetadataTemplate(api, "documentFlow03", "enterprise"); - for (MetadataTemplate.Field field : template.getFields()) { - MetadataTemplate.FieldOperation deleteField = new MetadataTemplate.FieldOperation(); - deleteField.setOp(MetadataTemplate.Operation.removeField); - deleteField.setFieldKey(field.getKey()); - fieldOperations.add(deleteField); - } - MetadataTemplate.updateMetadataTemplate(api, "enterprise", "documentFlow03", fieldOperations); + MetadataTemplate.FieldOperation customerFieldOp = new MetadataTemplate.FieldOperation(); + customerFieldOp.setOp(MetadataTemplate.Operation.addField); + + MetadataTemplate.Field customerTeam = new MetadataTemplate.Field(); + customerTeam.setType("string"); + customerTeam.setKey("customerTeam"); + customerTeam.setDisplayName("Customer Team"); + customerFieldOp.setData(customerTeam); + fieldOperations.add(customerFieldOp); + + MetadataTemplate.FieldOperation departmentFieldOp = new MetadataTemplate.FieldOperation(); + departmentFieldOp.setOp(MetadataTemplate.Operation.addField); + + MetadataTemplate.Field deptField = new MetadataTemplate.Field(); + deptField.setType("enum"); + deptField.setKey("department"); + deptField.setDisplayName("Department"); + + List options = new ArrayList<>(); + options.add("Beauty"); + options.add("Shoes"); + deptField.setOptions(options); + departmentFieldOp.setData(deptField); + + fieldOperations.add(departmentFieldOp); + return fieldOperations; } + private static void deleteMetadataTemplate(BoxAPIConnection api, MetadataTemplate template) { + if (template != null) { + MetadataTemplate.deleteMetadataTemplate(api, template.getScope(), template.getTemplateKey()); + } + } } diff --git a/src/main/java/com/box/sdk/BoxUser.java b/src/main/java/com/box/sdk/BoxUser.java index 7351b4d57..9a8ab515e 100644 --- a/src/main/java/com/box/sdk/BoxUser.java +++ b/src/main/java/com/box/sdk/BoxUser.java @@ -1,6 +1,7 @@ package com.box.sdk; import static com.box.sdk.http.HttpMethod.DELETE; +import static com.box.sdk.internal.utils.JsonUtils.addIfNotNull; import com.eclipsesource.json.Json; import com.eclipsesource.json.JsonArray; @@ -142,22 +143,23 @@ public static BoxUser.Info createEnterpriseUser(BoxAPIConnection api, String log requestJSON.add("status", params.getStatus().toJSONValue()); } - requestJSON.add("language", params.getLanguage()); - requestJSON.add("is_sync_enabled", params.getIsSyncEnabled()); - requestJSON.add("job_title", params.getJobTitle()); - requestJSON.add("phone", params.getPhone()); - requestJSON.add("address", params.getAddress()); - requestJSON.add("space_amount", params.getSpaceAmount()); - requestJSON.add("can_see_managed_users", params.getCanSeeManagedUsers()); - requestJSON.add("timezone", params.getTimezone()); - requestJSON.add("is_exempt_from_device_limits", params.getIsExemptFromDeviceLimits()); - requestJSON.add("is_exempt_from_login_verification", params.getIsExemptFromLoginVerification()); - requestJSON.add("is_platform_access_only", params.getIsPlatformAccessOnly()); - requestJSON.add("external_app_user_id", params.getExternalAppUserId()); - requestJSON.add("is_external_collab_restricted", params.getIsExternalCollabRestricted()); if (params.getTrackingCodes() != null) { requestJSON.add("tracking_codes", toTrackingCodesJson(params.getTrackingCodes())); } + + addIfNotNull(requestJSON, "language", params.getLanguage()); + addIfNotNull(requestJSON, "is_sync_enabled", params.getIsSyncEnabled()); + addIfNotNull(requestJSON, "job_title", params.getJobTitle()); + addIfNotNull(requestJSON, "phone", params.getPhone()); + addIfNotNull(requestJSON, "address", params.getAddress()); + addIfNotNull(requestJSON, "space_amount", params.getSpaceAmount()); + addIfNotNull(requestJSON, "can_see_managed_users", params.getCanSeeManagedUsers()); + addIfNotNull(requestJSON, "timezone", params.getTimezone()); + addIfNotNull(requestJSON, "is_exempt_from_device_limits", params.getIsExemptFromDeviceLimits()); + addIfNotNull(requestJSON, "is_exempt_from_login_verification", params.getIsExemptFromLoginVerification()); + addIfNotNull(requestJSON, "is_platform_access_only", params.getIsPlatformAccessOnly()); + addIfNotNull(requestJSON, "external_app_user_id", params.getExternalAppUserId()); + addIfNotNull(requestJSON, "is_external_collab_restricted", params.getIsExternalCollabRestricted()); } URL url = USERS_URL_TEMPLATE.build(api.getBaseURL()); diff --git a/src/main/java/com/box/sdk/CreateUserParams.java b/src/main/java/com/box/sdk/CreateUserParams.java index 9634df42e..a2f75f3d8 100644 --- a/src/main/java/com/box/sdk/CreateUserParams.java +++ b/src/main/java/com/box/sdk/CreateUserParams.java @@ -1,20 +1,21 @@ package com.box.sdk; +import java.util.HashMap; import java.util.Map; /** * Contains optional parameters for creating a new enterprise user on Box. */ public class CreateUserParams { - private boolean canSeeManagedUsers; - private boolean isExemptFromDeviceLimits; - private boolean isExemptFromLoginVerification; - private boolean isPlatformAccessOnly; - private boolean isSyncEnabled; - private boolean isExternalCollabRestricted; + private Boolean canSeeManagedUsers; + private Boolean isExemptFromDeviceLimits; + private Boolean isExemptFromLoginVerification; + private Boolean isPlatformAccessOnly; + private Boolean isSyncEnabled; + private Boolean isExternalCollabRestricted; private BoxUser.Role role; private BoxUser.Status status; - private long spaceAmount; + private Long spaceAmount; private String address; private String jobTitle; private String language; @@ -28,7 +29,7 @@ public class CreateUserParams { * * @return true if the new user will be able to see other enterprise users in their contact list; otherwise false. */ - public boolean getCanSeeManagedUsers() { + public Boolean getCanSeeManagedUsers() { return this.canSeeManagedUsers; } @@ -49,7 +50,7 @@ public CreateUserParams setCanSeeManagedUsers(boolean canSeeManagedUsers) { * * @return true if the new user will be exempt from Enterprise device limits; otherwise false. */ - public boolean getIsExemptFromDeviceLimits() { + public Boolean getIsExemptFromDeviceLimits() { return this.isExemptFromDeviceLimits; } @@ -69,7 +70,7 @@ public CreateUserParams setIsExemptFromDeviceLimits(boolean isExemptFromDeviceLi * * @return true if the new user will be required to use two-factor authentication; otherwise false. */ - public boolean getIsExemptFromLoginVerification() { + public Boolean getIsExemptFromLoginVerification() { return this.isExemptFromLoginVerification; } @@ -90,7 +91,7 @@ public CreateUserParams setIsExemptFromLoginVerification(boolean isExemptFromLog * * @return true if the new user is an app user for Box Developer Addition; otherwise false. */ - public boolean getIsPlatformAccessOnly() { + public Boolean getIsPlatformAccessOnly() { return this.isPlatformAccessOnly; } @@ -111,7 +112,7 @@ public CreateUserParams setIsPlatformAccessOnly(boolean isPlatformAccessOnly) { * * @return true if the new user will be able to use Box Sync; otherwise false. */ - public boolean getIsSyncEnabled() { + public Boolean getIsSyncEnabled() { return this.isSyncEnabled; } @@ -171,7 +172,7 @@ public CreateUserParams setStatus(BoxUser.Status status) { * * @return what the new user's total available space will be in bytes. */ - public long getSpaceAmount() { + public Long getSpaceAmount() { return this.spaceAmount; } @@ -311,7 +312,7 @@ public CreateUserParams setExternalAppUserId(String externalAppUserId) { * * @return true if the user is not able to collaborate with users outside their enterpise; otherwise false. */ - public boolean getIsExternalCollabRestricted() { + public Boolean getIsExternalCollabRestricted() { return this.isExternalCollabRestricted; } @@ -349,4 +350,20 @@ public CreateUserParams setTrackingCodes(Map trackingCodes) { this.trackingCodes = trackingCodes; return this; } + + /** + * Add an element the map of tracking codes. Tracking codes allow an admin to generate reports from the admin + * console and assign an attribute to a specific group of users. This setting must be enabled for an + * enterprise before it can be used. + * @param key of a tracking code + * @param value of a tracking code + * @return this CreateUserParams object for chaining. + */ + public CreateUserParams addTrackingCode(String key, String value) { + if (this.trackingCodes == null) { + this.trackingCodes = new HashMap<>(); + } + this.trackingCodes.put(key, value); + return this; + } } diff --git a/src/main/java/com/box/sdk/internal/utils/JsonUtils.java b/src/main/java/com/box/sdk/internal/utils/JsonUtils.java index ab8ddf96d..d7ef65970 100644 --- a/src/main/java/com/box/sdk/internal/utils/JsonUtils.java +++ b/src/main/java/com/box/sdk/internal/utils/JsonUtils.java @@ -54,6 +54,19 @@ public static void addIfNotNull(JsonObject jsonObject, String propertyName, Inte } } + /** + * Adds Long property to the json object if it's not null. + * + * @param jsonObject json object that the key/value will be added to. + * @param propertyName name of the property in json (key). + * @param propertyValue value of the property. + */ + public static void addIfNotNull(JsonObject jsonObject, String propertyName, Long propertyValue) { + if (propertyValue != null) { + jsonObject.add(propertyName, propertyValue); + } + } + /** * Adds Enum property to the json object if it's not null. * diff --git a/src/test/java/com/box/sdk/BoxUserTest.java b/src/test/java/com/box/sdk/BoxUserTest.java index 682fde14a..4b4c1c737 100644 --- a/src/test/java/com/box/sdk/BoxUserTest.java +++ b/src/test/java/com/box/sdk/BoxUserTest.java @@ -58,6 +58,7 @@ public void testGetAvatar() throws IOException { wireMockRule.stubFor(WireMock.get(WireMock.urlPathEqualTo(expectedURL)) .willReturn(WireMock.aResponse() + .withStatus(200) .withHeader("Content-Type", "image/png") .withBody(fileByteArray))); @@ -90,14 +91,10 @@ public void testGetCurrentUserInfoSucceeds() throws IOException { String result = TestUtils.getFixture("BoxUser/GetCurrentUserInfo200"); wireMockRule.stubFor(WireMock.get(WireMock.urlPathEqualTo(userURL)) - .willReturn(WireMock.aResponse() - .withHeader("Content-Type", "application/json") - .withBody(result))); + .willReturn(WireMock.okForContentType("application/json", result))); wireMockRule.stubFor(WireMock.get(WireMock.urlPathEqualTo(userInfoURL)) - .willReturn(WireMock.aResponse() - .withHeader("Content-Type", "application/json") - .withBody(result))); + .willReturn(WireMock.okForContentType("application/json", result))); BoxUser user = BoxUser.getCurrentUser(this.api); BoxUser.Info info = user.getInfo(); @@ -119,9 +116,7 @@ public void testGetUserInfoByIDSucceeds() throws IOException { String result = TestUtils.getFixture("BoxUser/GetCurrentUserInfo200"); wireMockRule.stubFor(WireMock.get(WireMock.urlPathEqualTo(userURL)) - .willReturn(WireMock.aResponse() - .withHeader("Content-Type", "application/json") - .withBody(result))); + .willReturn(WireMock.okForContentType("application/json", result))); BoxUser user = new BoxUser(this.api, userID); BoxUser.Info userInfo = user.getInfo(); @@ -145,9 +140,7 @@ public void testGetUserInfoWithNoNotificationEmailByIDSucceeds() throws IOExcept String result = TestUtils.getFixture("BoxUser/GetCurrentUserInfoWithNoNotifcationEmail200"); wireMockRule.stubFor(WireMock.get(WireMock.urlPathEqualTo(userURL)) - .willReturn(WireMock.aResponse() - .withHeader("Content-Type", "application/json") - .withBody(result))); + .willReturn(WireMock.okForContentType("application/json", result))); BoxUser user = new BoxUser(this.api, userID); BoxUser.Info userInfo = user.getInfo(); @@ -169,9 +162,7 @@ public void testCreateAppUserSucceeds() throws IOException { String result = TestUtils.getFixture("BoxUser/CreateAppUser201"); wireMockRule.stubFor(WireMock.post(WireMock.urlPathEqualTo(userURL)) - .willReturn(WireMock.aResponse() - .withHeader("Content-Type", "application/json") - .withBody(result))); + .willReturn(WireMock.okForContentType("application/json", result))); BoxUser.Info createdUserInfo = BoxUser.createAppUser(this.api, userName); @@ -191,9 +182,7 @@ public void testCreateManagedUserSucceeds() throws IOException { String result = TestUtils.getFixture("BoxUser/CreateManagedUser201"); wireMockRule.stubFor(WireMock.post(WireMock.urlPathEqualTo(userURL)) - .willReturn(WireMock.aResponse() - .withHeader("Content-Type", "application/json") - .withBody(result))); + .willReturn(WireMock.okForContentType("application/json", result))); BoxUser.Info createdUserInfo = BoxUser.createEnterpriseUser(this.api, userLogin, userName); @@ -203,6 +192,29 @@ public void testCreateManagedUserSucceeds() throws IOException { assertEquals(userTimeZone, createdUserInfo.getTimezone()); } + @Test + public void testCreateManagedUserDoesNotIncludeNotdefinedOptionalFields() throws IOException { + final String userURL = "/2.0/users"; + final String userName = "Test Managed User"; + final String userLogin = "test@user.com"; + final boolean isSyncEnabled = false; + + String result = TestUtils.getFixture("BoxUser/CreateManagedUser201"); + + JsonObject createBody = new JsonObject() + .add("name", userName) + .add("login", userLogin) + .add("is_sync_enabled", isSyncEnabled); + + wireMockRule.stubFor(WireMock.post(WireMock.urlPathEqualTo(userURL)) + .withRequestBody(WireMock.equalToJson(createBody.toString())) + .willReturn(WireMock.okForContentType("application/json", result))); + + CreateUserParams optionalParams = new CreateUserParams(); + optionalParams.setIsSyncEnabled(isSyncEnabled); + BoxUser.createEnterpriseUser(this.api, userLogin, userName, optionalParams); + } + @Test public void testUpdateUserInfoSucceedsAndSendsCorrectJson() throws IOException { final String userID = "12345"; @@ -222,9 +234,7 @@ public void testUpdateUserInfoSucceedsAndSendsCorrectJson() throws IOException { wireMockRule.stubFor(WireMock.put(WireMock.urlPathEqualTo(userURL)) .withRequestBody(WireMock.equalToJson(userObject.toString())) - .willReturn(WireMock.aResponse() - .withHeader("Content-Type", "application/json") - .withBody(result))); + .willReturn(WireMock.okForContentType("application/json", result))); BoxUser user = new BoxUser(this.api, userID); BoxUser.Info info = user.new Info(); @@ -247,9 +257,7 @@ public void testDeleteUserSucceeds() { final String userURL = "/2.0/users/" + userID; wireMockRule.stubFor(WireMock.delete(WireMock.urlPathEqualTo(userURL)) - .willReturn(WireMock.aResponse() - .withHeader("Content-Type", "application/json") - .withStatus(204))); + .willReturn(WireMock.noContent())); BoxUser user = new BoxUser(this.api, userID); user.delete(false, false); @@ -267,9 +275,7 @@ public void testCreateEmailAliasSucceeds() throws IOException { wireMockRule.stubFor(WireMock.post(WireMock.urlPathEqualTo(emailAliasURL)) .withRequestBody(WireMock.equalToJson(emailAliasObject.toString())) - .willReturn(WireMock.aResponse() - .withHeader("Content-Type", "application/json") - .withBody(result))); + .willReturn(WireMock.okForContentType("application/json", result))); BoxUser user = new BoxUser(this.api, userID); EmailAlias alias = user.addEmailAlias(emailAlias); @@ -288,9 +294,7 @@ public void testGetEmailAliasSucceeds() throws IOException { String result = TestUtils.getFixture("BoxUser/GetUserEmailAlias200"); wireMockRule.stubFor(WireMock.get(WireMock.urlPathEqualTo(emailAliasURL)) - .willReturn(WireMock.aResponse() - .withHeader("Content-Type", "application/json") - .withBody(result))); + .willReturn(WireMock.okForContentType("application/json", result))); BoxUser user = new BoxUser(this.api, userID); Collection emailAliases = user.getEmailAliases(); @@ -306,9 +310,7 @@ public void testDeleteEmailAliasSucceeds() { final String deleteAliasURL = "/2.0/users/" + userID + "/email_aliases/" + aliasID; wireMockRule.stubFor(WireMock.delete(WireMock.urlPathEqualTo(deleteAliasURL)) - .willReturn(WireMock.aResponse() - .withHeader("Content-Type", "application/json") - .withStatus(204))); + .willReturn(WireMock.noContent())); BoxUser user = new BoxUser(this.api, userID); user.deleteEmailAlias(aliasID); @@ -327,9 +329,7 @@ public void testGetAllEnterpriseUsersSucceeds() throws IOException { String result = TestUtils.getFixture("BoxUser/GetAllEnterpriseUsers200"); wireMockRule.stubFor(WireMock.get(WireMock.urlPathEqualTo(getAllUsersURL)) - .willReturn(WireMock.aResponse() - .withHeader("Content-Type", "application/json") - .withBody(result))); + .willReturn(WireMock.okForContentType("application/json", result))); Iterator users = BoxUser.getAllEnterpriseUsers(this.api).iterator(); BoxUser.Info firstUser = users.next(); @@ -360,9 +360,7 @@ public void testGetAllEnterpriseUsersMarkerPaginationSucceeds() throws IOExcepti wireMockRule.stubFor(WireMock.get(WireMock.urlPathEqualTo(getAllUsersURL)) .withQueryParam("usemarker", WireMock.equalTo("true")) .withQueryParam("limit", WireMock.equalTo("100")) - .willReturn(WireMock.aResponse() - .withHeader("Content-Type", "application/json") - .withBody(result))); + .willReturn(WireMock.okForContentType("application/json", result))); Iterator users = BoxUser.getAllEnterpriseUsers(this.api, true, null).iterator(); BoxUser.Info firstUser = users.next(); @@ -395,9 +393,7 @@ public void testTransferContent() throws IOException { wireMockRule.stubFor(WireMock.put(WireMock.urlPathEqualTo(transferContentURL)) .withRequestBody(WireMock.equalToJson(ownedBy.toString())) - .willReturn(WireMock.aResponse() - .withHeader("Content-Type", "application/json") - .withBody(result))); + .willReturn(WireMock.okForContentType("application/json", result))); BoxUser sourceUser = new BoxUser(this.api, sourceUserID); BoxFolder.Info movedFolder = sourceUser.transferContent(destinationUserID); @@ -414,9 +410,7 @@ public void testDeserializationException() throws IOException { String result = TestUtils.getFixture("BoxUser/GetUserInfoCausesDeserializationException"); wireMockRule.stubFor(WireMock.get(WireMock.urlPathEqualTo(usersURL)) - .willReturn(WireMock.aResponse() - .withHeader("Content-Type", "application/json") - .withBody(result))); + .willReturn(WireMock.okForContentType("application/json", result))); BoxUser.Info userInfo = new BoxUser(this.api, userID).getInfo(); assertEquals("12345", userInfo.getID()); @@ -437,9 +431,7 @@ public void testCreateReadAddTrackingCodesSucceeds() throws IOException { String createResponse = TestUtils.getFixture("BoxUser/CreateTrackingCodes200"); wireMockRule.stubFor(WireMock.put(WireMock.urlPathEqualTo(usersURL)) .withRequestBody(WireMock.equalToJson(createBody)) - .willReturn(WireMock.aResponse() - .withHeader("Content-Type", "application/json") - .withBody(createResponse))); + .willReturn(WireMock.okForContentType("application/json", createResponse))); // Mock: Verify change String twoTrackingCodesResponse = TestUtils.getFixture("BoxUser/GetUserTwoTrackingCodes200"); @@ -461,9 +453,7 @@ public void testCreateReadAddTrackingCodesSucceeds() throws IOException { String updateResponse = TestUtils.getFixture("BoxUser/UpdateTrackingCodes200"); wireMockRule.stubFor(WireMock.put(WireMock.urlPathEqualTo(usersURL)) .withRequestBody(WireMock.equalToJson(updateBody)) - .willReturn(WireMock.aResponse() - .withHeader("Content-Type", "application/json") - .withBody(updateResponse))); + .willReturn(WireMock.okForContentType("application/json", updateResponse))); // Mock: Verify change String threeTrackingCodesResponse = TestUtils.getFixture("BoxUser/GetUserThreeTrackingCodes200"); @@ -471,9 +461,7 @@ public void testCreateReadAddTrackingCodesSucceeds() throws IOException { .withQueryParam("fields", WireMock.equalTo("tracking_codes")) .inScenario("Get Tracking Code Scenario") .whenScenarioStateIs("1st Request") - .willReturn(WireMock.aResponse() - .withHeader("Content-Type", "application/json") - .withBody(threeTrackingCodesResponse)) + .willReturn(WireMock.okForContentType("application/json", threeTrackingCodesResponse)) .willSetStateTo("2nd Request")); // Create two tracking codes @@ -507,6 +495,7 @@ public void uploadAvatarAsFile() { String filePath = getSampleFilePath(fileName); File file = new File(filePath); + String responseBody = "{\"pic_urls\": {\"small\": \"url1\",\"large\": \"url2\",\"preview\": \"url3\"}}"; wireMockRule.stubFor(WireMock.post(WireMock.urlPathEqualTo("/2.0/users/12345/avatar")) .withHeader("Content-Type", new ContainsPattern("multipart/form-data")) .withMultipartRequestBody( @@ -514,9 +503,7 @@ public void uploadAvatarAsFile() { .withName("pic") .withHeader("Content-Type", new EqualToPattern("image/png")) ) - .willReturn(WireMock.aResponse() - .withHeader("Content-Type", "application/json") - .withBody("{\"pic_urls\": {\"small\": \"url1\",\"large\": \"url2\",\"preview\": \"url3\"}}"))); + .willReturn(WireMock.okForContentType("application/json", responseBody))); AvatarUploadResponse response = user.uploadAvatar(file); @@ -532,6 +519,7 @@ public void uploadAvatarAsStream() throws IOException { String fileName = "red_100x100.png"; String filePath = getSampleFilePath(fileName); + String responseBody = "{\"pic_urls\": {\"small\": \"url1\",\"large\": \"url2\",\"preview\": \"url3\"}}"; wireMockRule.stubFor(WireMock.post(WireMock.urlPathEqualTo("/2.0/users/12345/avatar")) .withHeader("Content-Type", new ContainsPattern("multipart/form-data")) .withMultipartRequestBody( @@ -539,9 +527,7 @@ public void uploadAvatarAsStream() throws IOException { .withName("pic") .withHeader("Content-Type", new EqualToPattern("image/png")) ) - .willReturn(WireMock.aResponse() - .withHeader("Content-Type", "application/json") - .withBody("{\"pic_urls\": {\"small\": \"url1\",\"large\": \"url2\",\"preview\": \"url3\"}}"))); + .willReturn(WireMock.okForContentType("application/json", responseBody))); AvatarUploadResponse response = user.uploadAvatar(Files.newInputStream(Paths.get(filePath)), fileName); @@ -556,7 +542,7 @@ public void deleteAvatar() { BoxUser user = new BoxUser(api, userID); wireMockRule.stubFor(WireMock.delete(WireMock.urlPathEqualTo("/2.0/users/12345/avatar")) - .willReturn(WireMock.aResponse().withStatus(204))); + .willReturn(WireMock.noContent())); user.deleteAvatar(); }