From e037c46d6e16dcdf824797be1d40efacafa435aa Mon Sep 17 00:00:00 2001 From: lsocha Date: Tue, 23 Sep 2025 12:56:51 +0200 Subject: [PATCH 1/7] docs: Move docs to new directory --- doc/{ => sdk}/ai.md | 0 doc/{ => sdk}/android.md | 0 doc/{ => sdk}/authentication.md | 0 doc/{ => sdk}/classifications.md | 0 doc/{ => sdk}/collaboration_allowlists.md | 0 doc/{ => sdk}/collaborations.md | 0 doc/{ => sdk}/collections.md | 0 doc/{ => sdk}/comments.md | 0 doc/{ => sdk}/configuration.md | 0 doc/{ => sdk}/css/javadoc.css | 0 doc/{ => sdk}/devices.md | 0 doc/{ => sdk}/events.md | 0 doc/{ => sdk}/file_requests.md | 0 doc/{ => sdk}/files.md | 0 doc/{ => sdk}/folders.md | 0 doc/{ => sdk}/groups.md | 0 doc/{ => sdk}/legal_holds.md | 0 doc/{ => sdk}/logging.md | 0 doc/{ => sdk}/metadata_template.md | 0 doc/{ => sdk}/overview.md | 0 doc/{ => sdk}/recent_items.md | 0 doc/{ => sdk}/retention_policies.md | 0 doc/{ => sdk}/search.md | 0 doc/{ => sdk}/shared-items.md | 0 doc/{ => sdk}/sign_requests.md | 0 doc/{ => sdk}/sign_templates.md | 0 doc/{ => sdk}/storage_policy.md | 0 doc/{ => sdk}/tasks.md | 0 doc/{ => sdk}/terms_of_service.md | 0 doc/{ => sdk}/trash.md | 0 doc/{ => sdk}/upgrading.md | 0 doc/{ => sdk}/users.md | 0 doc/{ => sdk}/watermarking.md | 0 doc/{ => sdk}/webhooks.md | 0 doc/{ => sdk}/weblinks.md | 0 doc/{ => sdk}/zip_download.md | 0 {doc/upgrades => migration-guides}/3.x.x to 4.x.x.md | 0 37 files changed, 0 insertions(+), 0 deletions(-) rename doc/{ => sdk}/ai.md (100%) rename doc/{ => sdk}/android.md (100%) rename doc/{ => sdk}/authentication.md (100%) rename doc/{ => sdk}/classifications.md (100%) rename doc/{ => sdk}/collaboration_allowlists.md (100%) rename doc/{ => sdk}/collaborations.md (100%) rename doc/{ => sdk}/collections.md (100%) rename doc/{ => sdk}/comments.md (100%) rename doc/{ => sdk}/configuration.md (100%) rename doc/{ => sdk}/css/javadoc.css (100%) rename doc/{ => sdk}/devices.md (100%) rename doc/{ => sdk}/events.md (100%) rename doc/{ => sdk}/file_requests.md (100%) rename doc/{ => sdk}/files.md (100%) rename doc/{ => sdk}/folders.md (100%) rename doc/{ => sdk}/groups.md (100%) rename doc/{ => sdk}/legal_holds.md (100%) rename doc/{ => sdk}/logging.md (100%) rename doc/{ => sdk}/metadata_template.md (100%) rename doc/{ => sdk}/overview.md (100%) rename doc/{ => sdk}/recent_items.md (100%) rename doc/{ => sdk}/retention_policies.md (100%) rename doc/{ => sdk}/search.md (100%) rename doc/{ => sdk}/shared-items.md (100%) rename doc/{ => sdk}/sign_requests.md (100%) rename doc/{ => sdk}/sign_templates.md (100%) rename doc/{ => sdk}/storage_policy.md (100%) rename doc/{ => sdk}/tasks.md (100%) rename doc/{ => sdk}/terms_of_service.md (100%) rename doc/{ => sdk}/trash.md (100%) rename doc/{ => sdk}/upgrading.md (100%) rename doc/{ => sdk}/users.md (100%) rename doc/{ => sdk}/watermarking.md (100%) rename doc/{ => sdk}/webhooks.md (100%) rename doc/{ => sdk}/weblinks.md (100%) rename doc/{ => sdk}/zip_download.md (100%) rename {doc/upgrades => migration-guides}/3.x.x to 4.x.x.md (100%) diff --git a/doc/ai.md b/doc/sdk/ai.md similarity index 100% rename from doc/ai.md rename to doc/sdk/ai.md diff --git a/doc/android.md b/doc/sdk/android.md similarity index 100% rename from doc/android.md rename to doc/sdk/android.md diff --git a/doc/authentication.md b/doc/sdk/authentication.md similarity index 100% rename from doc/authentication.md rename to doc/sdk/authentication.md diff --git a/doc/classifications.md b/doc/sdk/classifications.md similarity index 100% rename from doc/classifications.md rename to doc/sdk/classifications.md diff --git a/doc/collaboration_allowlists.md b/doc/sdk/collaboration_allowlists.md similarity index 100% rename from doc/collaboration_allowlists.md rename to doc/sdk/collaboration_allowlists.md diff --git a/doc/collaborations.md b/doc/sdk/collaborations.md similarity index 100% rename from doc/collaborations.md rename to doc/sdk/collaborations.md diff --git a/doc/collections.md b/doc/sdk/collections.md similarity index 100% rename from doc/collections.md rename to doc/sdk/collections.md diff --git a/doc/comments.md b/doc/sdk/comments.md similarity index 100% rename from doc/comments.md rename to doc/sdk/comments.md diff --git a/doc/configuration.md b/doc/sdk/configuration.md similarity index 100% rename from doc/configuration.md rename to doc/sdk/configuration.md diff --git a/doc/css/javadoc.css b/doc/sdk/css/javadoc.css similarity index 100% rename from doc/css/javadoc.css rename to doc/sdk/css/javadoc.css diff --git a/doc/devices.md b/doc/sdk/devices.md similarity index 100% rename from doc/devices.md rename to doc/sdk/devices.md diff --git a/doc/events.md b/doc/sdk/events.md similarity index 100% rename from doc/events.md rename to doc/sdk/events.md diff --git a/doc/file_requests.md b/doc/sdk/file_requests.md similarity index 100% rename from doc/file_requests.md rename to doc/sdk/file_requests.md diff --git a/doc/files.md b/doc/sdk/files.md similarity index 100% rename from doc/files.md rename to doc/sdk/files.md diff --git a/doc/folders.md b/doc/sdk/folders.md similarity index 100% rename from doc/folders.md rename to doc/sdk/folders.md diff --git a/doc/groups.md b/doc/sdk/groups.md similarity index 100% rename from doc/groups.md rename to doc/sdk/groups.md diff --git a/doc/legal_holds.md b/doc/sdk/legal_holds.md similarity index 100% rename from doc/legal_holds.md rename to doc/sdk/legal_holds.md diff --git a/doc/logging.md b/doc/sdk/logging.md similarity index 100% rename from doc/logging.md rename to doc/sdk/logging.md diff --git a/doc/metadata_template.md b/doc/sdk/metadata_template.md similarity index 100% rename from doc/metadata_template.md rename to doc/sdk/metadata_template.md diff --git a/doc/overview.md b/doc/sdk/overview.md similarity index 100% rename from doc/overview.md rename to doc/sdk/overview.md diff --git a/doc/recent_items.md b/doc/sdk/recent_items.md similarity index 100% rename from doc/recent_items.md rename to doc/sdk/recent_items.md diff --git a/doc/retention_policies.md b/doc/sdk/retention_policies.md similarity index 100% rename from doc/retention_policies.md rename to doc/sdk/retention_policies.md diff --git a/doc/search.md b/doc/sdk/search.md similarity index 100% rename from doc/search.md rename to doc/sdk/search.md diff --git a/doc/shared-items.md b/doc/sdk/shared-items.md similarity index 100% rename from doc/shared-items.md rename to doc/sdk/shared-items.md diff --git a/doc/sign_requests.md b/doc/sdk/sign_requests.md similarity index 100% rename from doc/sign_requests.md rename to doc/sdk/sign_requests.md diff --git a/doc/sign_templates.md b/doc/sdk/sign_templates.md similarity index 100% rename from doc/sign_templates.md rename to doc/sdk/sign_templates.md diff --git a/doc/storage_policy.md b/doc/sdk/storage_policy.md similarity index 100% rename from doc/storage_policy.md rename to doc/sdk/storage_policy.md diff --git a/doc/tasks.md b/doc/sdk/tasks.md similarity index 100% rename from doc/tasks.md rename to doc/sdk/tasks.md diff --git a/doc/terms_of_service.md b/doc/sdk/terms_of_service.md similarity index 100% rename from doc/terms_of_service.md rename to doc/sdk/terms_of_service.md diff --git a/doc/trash.md b/doc/sdk/trash.md similarity index 100% rename from doc/trash.md rename to doc/sdk/trash.md diff --git a/doc/upgrading.md b/doc/sdk/upgrading.md similarity index 100% rename from doc/upgrading.md rename to doc/sdk/upgrading.md diff --git a/doc/users.md b/doc/sdk/users.md similarity index 100% rename from doc/users.md rename to doc/sdk/users.md diff --git a/doc/watermarking.md b/doc/sdk/watermarking.md similarity index 100% rename from doc/watermarking.md rename to doc/sdk/watermarking.md diff --git a/doc/webhooks.md b/doc/sdk/webhooks.md similarity index 100% rename from doc/webhooks.md rename to doc/sdk/webhooks.md diff --git a/doc/weblinks.md b/doc/sdk/weblinks.md similarity index 100% rename from doc/weblinks.md rename to doc/sdk/weblinks.md diff --git a/doc/zip_download.md b/doc/sdk/zip_download.md similarity index 100% rename from doc/zip_download.md rename to doc/sdk/zip_download.md diff --git a/doc/upgrades/3.x.x to 4.x.x.md b/migration-guides/3.x.x to 4.x.x.md similarity index 100% rename from doc/upgrades/3.x.x to 4.x.x.md rename to migration-guides/3.x.x to 4.x.x.md From 2551e5a79e8d5c2d803b63b20f1201b25a8c5c91 Mon Sep 17 00:00:00 2001 From: lsocha Date: Tue, 23 Sep 2025 13:49:19 +0200 Subject: [PATCH 2/7] chore: Add code formatter --- build.gradle | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/build.gradle b/build.gradle index dfb0b8ba2..9bf31e02d 100644 --- a/build.gradle +++ b/build.gradle @@ -1,5 +1,6 @@ plugins { id "com.github.nbaztec.coveralls-jacoco" version "1.2.14" + id "com.diffplug.spotless" version "6.2.0" id "checkstyle" id "jacoco" id "java" @@ -151,6 +152,13 @@ artifacts { archives sourcesJar, javadocJar } +spotless { + java { + googleJavaFormat "1.7" + target "src/**/*.java" + } +} + test { useJUnit { excludeCategories "com.box.sdk.IntegrationTestJWT" From c7d50d580eed1040cd34100655264ec175b5b0e3 Mon Sep 17 00:00:00 2001 From: box-sdk-build <94016436+box-sdk-build@users.noreply.github.com> Date: Wed, 24 Sep 2025 10:22:21 +0200 Subject: [PATCH 3/7] feat: Add generated SDK (box/box-codegen#838) (#1438) --- .codegen.json | 1 + docs/sdkgen/Authentication.md | 365 ++ docs/sdkgen/Client.md | 194 + docs/sdkgen/Configuration.md | 51 + docs/sdkgen/EventStream.md | 29 + docs/sdkgen/README.md | 87 + docs/sdkgen/ai.md | 166 + docs/sdkgen/aistudio.md | 158 + docs/sdkgen/appitemassociations.md | 80 + docs/sdkgen/archives.md | 100 + docs/sdkgen/authorization.md | 134 + docs/sdkgen/avatars.md | 101 + docs/sdkgen/chunkeduploads.md | 450 ++ docs/sdkgen/classifications.md | 148 + docs/sdkgen/collaborationallowlistentries.md | 129 + .../collaborationallowlistexempttargets.md | 129 + docs/sdkgen/collections.md | 91 + docs/sdkgen/comments.md | 171 + docs/sdkgen/devicepinners.md | 99 + docs/sdkgen/docgen.md | 126 + docs/sdkgen/docgentemplate.md | 188 + docs/sdkgen/downloads.md | 120 + docs/sdkgen/emailaliases.md | 99 + docs/sdkgen/events.md | 137 + docs/sdkgen/externalusers.md | 35 + docs/sdkgen/fileclassifications.md | 151 + docs/sdkgen/filemetadata.md | 194 + docs/sdkgen/filerequests.md | 131 + docs/sdkgen/files.md | 245 ++ docs/sdkgen/fileversionlegalholds.md | 85 + docs/sdkgen/fileversionretentions.md | 74 + docs/sdkgen/fileversions.md | 200 + docs/sdkgen/filewatermarks.md | 99 + docs/sdkgen/folderclassifications.md | 151 + docs/sdkgen/folderlocks.md | 106 + docs/sdkgen/foldermetadata.md | 199 + docs/sdkgen/folders.md | 245 ++ docs/sdkgen/folderwatermarks.md | 100 + docs/sdkgen/groups.md | 171 + docs/sdkgen/hubcollaborations.md | 160 + docs/sdkgen/hubitems.md | 66 + docs/sdkgen/hubs.md | 224 + docs/sdkgen/integrationmappings.md | 273 ++ docs/sdkgen/invites.md | 76 + docs/sdkgen/legalholdpolicies.md | 161 + docs/sdkgen/legalholdpolicyassignments.md | 179 + docs/sdkgen/listcollaborations.md | 152 + docs/sdkgen/memberships.md | 210 + docs/sdkgen/metadatacascadepolicies.md | 172 + docs/sdkgen/metadatatemplates.md | 272 ++ docs/sdkgen/recentitems.md | 36 + docs/sdkgen/retentionpolicies.md | 158 + docs/sdkgen/retentionpolicyassignments.md | 165 + docs/sdkgen/search.md | 71 + docs/sdkgen/sessiontermination.md | 70 + docs/sdkgen/sharedlinksappitems.md | 35 + docs/sdkgen/sharedlinksfiles.md | 181 + docs/sdkgen/sharedlinksfolders.md | 178 + docs/sdkgen/sharedlinksweblinks.md | 179 + .../sdkgen/shieldinformationbarrierreports.md | 94 + docs/sdkgen/shieldinformationbarriers.md | 129 + .../shieldinformationbarriersegmentmembers.md | 129 + ...ldinformationbarriersegmentrestrictions.md | 131 + .../shieldinformationbarriersegments.md | 158 + docs/sdkgen/shieldlists.md | 154 + docs/sdkgen/signrequests.md | 154 + docs/sdkgen/signtemplates.md | 64 + docs/sdkgen/skills.md | 164 + docs/sdkgen/storagepolicies.md | 64 + docs/sdkgen/storagepolicyassignments.md | 165 + docs/sdkgen/taskassignments.md | 163 + docs/sdkgen/tasks.md | 162 + docs/sdkgen/termsofservices.md | 126 + docs/sdkgen/termsofserviceuserstatuses.md | 98 + docs/sdkgen/transfer.md | 72 + docs/sdkgen/trashedfiles.md | 117 + docs/sdkgen/trashedfolders.md | 124 + docs/sdkgen/trasheditems.md | 42 + docs/sdkgen/trashedweblinks.md | 107 + docs/sdkgen/uploads.md | 144 + docs/sdkgen/usercollaborations.md | 148 + docs/sdkgen/users.md | 230 + docs/sdkgen/webhooks.md | 196 + docs/sdkgen/weblinks.md | 127 + docs/sdkgen/workflows.md | 73 + docs/sdkgen/zipdownloads.md | 163 + .../com/box/sdk/example/AccessAsAppUser.java | 73 +- ...rEditionAPIConnectionAsEnterpriseUser.java | 43 +- .../com/box/sdk/example/CreateAppUser.java | 52 +- .../java/com/box/sdk/example/Main.java | 53 +- .../sdk/example/SearchExamplesAsAppUser.java | 479 +- src/intTest/java/com/box/sdk/BoxAIIT.java | 609 +-- .../java/com/box/sdk/BoxAPIConnectionIT.java | 469 +- .../java/com/box/sdk/BoxAPIRequestIT.java | 28 +- .../java/com/box/sdk/BoxApiProvider.java | 47 +- .../box/sdk/BoxClassificationTemplateIT.java | 178 +- .../box/sdk/BoxCollaborationAllowlistIT.java | 98 +- .../java/com/box/sdk/BoxCollaborationIT.java | 332 +- .../java/com/box/sdk/BoxCollectionIT.java | 23 +- .../java/com/box/sdk/BoxCommentIT.java | 185 +- src/intTest/java/com/box/sdk/BoxFileIT.java | 2319 +++++----- src/intTest/java/com/box/sdk/BoxFolderIT.java | 1730 ++++---- src/intTest/java/com/box/sdk/BoxGroupIT.java | 272 +- .../com/box/sdk/BoxGroupMembershipIT.java | 191 +- .../java/com/box/sdk/BoxRecentsIT.java | 122 +- .../sdk/BoxRetentionPolicyAssignmentIT.java | 187 +- .../java/com/box/sdk/BoxSignRequestIT.java | 433 +- src/intTest/java/com/box/sdk/BoxTaskIT.java | 80 +- .../java/com/box/sdk/BoxTermsOfServiceIT.java | 47 +- .../sdk/BoxTransactionalAPIConnectionIT.java | 185 +- src/intTest/java/com/box/sdk/BoxTrashIT.java | 388 +- src/intTest/java/com/box/sdk/BoxUserIT.java | 271 +- .../java/com/box/sdk/BoxWebHookIT.java | 373 +- .../java/com/box/sdk/BoxWebLinkIT.java | 347 +- src/intTest/java/com/box/sdk/BoxZipIT.java | 98 +- .../java/com/box/sdk/CleanupTools.java | 64 +- src/intTest/java/com/box/sdk/EventLogIT.java | 207 +- .../java/com/box/sdk/EventStreamIT.java | 124 +- src/intTest/java/com/box/sdk/FileUtils.java | 65 +- src/intTest/java/com/box/sdk/MetadataIT.java | 389 +- .../java/com/box/sdk/MetadataTemplateIT.java | 558 ++- .../com/box/sdk/RetentionPolicyUtils.java | 56 +- src/intTest/java/com/box/sdk/Retry.java | 60 +- src/intTest/java/com/box/sdk/TestConfig.java | 254 +- .../java/com/box/sdk/UniqueTestFolder.java | 251 +- .../java/com/box/sdkgen/ai/AiITest.java | 436 ++ .../box/sdkgen/aistudio/AiStudioITest.java | 98 + .../AppItemAssociationsITest.java | 66 + .../box/sdkgen/archives/ArchivesITest.java | 39 + .../java/com/box/sdkgen/auth/AuthITest.java | 386 ++ .../com/box/sdkgen/avatars/AvatarsITest.java | 43 + .../chunkeduploads/ChunkedUploadsITest.java | 239 + .../chunkeduploads/TestPartAccumulator.java | 100 + .../classifications/ClassificationsITest.java | 68 + .../com/box/sdkgen/client/ClientITest.java | 224 + .../client/InterceptorAddingRoleToFields.java | 32 + .../client/InterceptorChangingResponse.java | 24 + .../client/InterceptorThrowingError.java | 22 + .../CollaborationAllowlistEntriesITest.java | 49 + ...laborationAllowlistExemptTargetsITest.java | 61 + .../box/sdkgen/comments/CommentsITest.java | 81 + .../box/sdkgen/commons/CommonsManager.java | 187 + .../devicepinners/DevicePinnersITest.java | 40 + .../com/box/sdkgen/docgen/DocgenITest.java | 106 + .../docgentemplate/DocgenTemplateITest.java | 50 + .../box/sdkgen/downloads/DownloadsITest.java | 77 + .../emailaliases/EmailAliasesITest.java | 42 + .../com/box/sdkgen/events/EventsITest.java | 119 + .../externalusers/ExternalUsersITest.java | 53 + .../FileClassificationsITest.java | 98 + .../filemetadata/FileMetadataITest.java | 266 ++ .../filerequests/FileRequestsITest.java | 55 + .../java/com/box/sdkgen/files/FilesITest.java | 183 + .../FileVersionLegalHoldsITest.java | 34 + .../FileVersionRetentionsITest.java | 111 + .../fileversions/FileVersionsITest.java | 146 + .../filewatermarks/FileWatermarksITest.java | 51 + .../FolderClassificationsITest.java | 98 + .../sdkgen/folderlocks/FolderLocksITest.java | 48 + .../foldermetadata/FolderMetadataITest.java | 275 ++ .../com/box/sdkgen/folders/FoldersITest.java | 128 + .../FolderWatermarksITest.java | 46 + .../com/box/sdkgen/groups/GroupsITest.java | 59 + .../HubCollaborationsITest.java | 94 + .../box/sdkgen/hubitems/HubItemsITest.java | 92 + .../java/com/box/sdkgen/hubs/HubsITest.java | 105 + .../IntegrationMappingsITest.java | 151 + .../com/box/sdkgen/invites/InvitesITest.java | 42 + .../LegalHoldPoliciesITest.java | 77 + .../LegalHoldPolicyAssignmentsITest.java | 86 + .../ListCollaborationsITest.java | 86 + .../sdkgen/memberships/MembershipsITest.java | 70 + .../MetadataCascadePoliciesITest.java | 106 + .../MetadataTemplatesITest.java | 185 + .../sdkgen/recentitems/RecentItemsITest.java | 18 + .../RetentionPoliciesITest.java | 57 + .../RetentionPolicyAssignmentsITest.java | 115 + .../com/box/sdkgen/search/SearchITest.java | 284 ++ .../SessionTerminationITest.java | 51 + .../SharedLinksAppItemsITest.java | 28 + .../SharedLinksFilesITest.java | 119 + .../SharedLinksFoldersITest.java | 115 + .../SharedLinksWebLinksITest.java | 122 + .../ShieldInformationBarrierReportsITest.java | 66 + .../ShieldInformationBarriersITest.java | 44 + ...InformationBarrierSegmentMembersITest.java | 83 + ...mationBarrierSegmentRestrictionsITest.java | 115 + ...ShieldInformationBarrierSegmentsITest.java | 80 + .../sdkgen/shieldlists/ShieldListsITest.java | 107 + .../signrequests/SignRequestsITest.java | 162 + .../signtemplates/SignTemplatesITest.java | 41 + .../com/box/sdkgen/skills/SkillsITest.java | 103 + .../StoragePolicicyAssignmentsITest.java | 90 + .../storagepolicies/StoragePoliciesITest.java | 26 + .../taskassignments/TaskAssignmentsITest.java | 90 + .../java/com/box/sdkgen/tasks/TasksITest.java | 73 + .../termsofservices/TermsOfServicesITest.java | 42 + .../TermsOfServiceUserStatusesITest.java | 68 + .../box/sdkgen/transfer/TransferITest.java | 52 + .../trashedfiles/TrashedFilesITest.java | 54 + .../trashedfolders/TrashedFoldersITest.java | 43 + .../trasheditems/TrashedItemsITest.java | 22 + .../trashedweblinks/TrashedWebLinksITest.java | 53 + .../com/box/sdkgen/uploads/UploadsITest.java | 119 + .../UserCollaborationsITest.java | 167 + .../java/com/box/sdkgen/users/UsersITest.java | 55 + .../box/sdkgen/webhooks/WebhooksITest.java | 273 ++ .../box/sdkgen/weblinks/WeblinksITest.java | 64 + .../box/sdkgen/workflows/WorkflowsITest.java | 84 + .../zipdownloads/ZipDownloadsITest.java | 89 + .../box/sdk/AbstractBoxMultipartRequest.java | 290 +- .../com/box/sdk/AvatarUploadResponse.java | 68 +- .../com/box/sdk/BCPrivateKeyDecryptor.java | 89 +- src/main/java/com/box/sdk/BackoffCounter.java | 117 +- src/main/java/com/box/sdk/Base64.java | 171 +- .../java/com/box/sdk/BinaryBodyUtils.java | 323 +- src/main/java/com/box/sdk/BoxAI.java | 752 ++-- src/main/java/com/box/sdk/BoxAIAgent.java | 226 +- src/main/java/com/box/sdk/BoxAIAgentAsk.java | 308 +- .../com/box/sdk/BoxAIAgentAskBasicText.java | 366 +- .../com/box/sdk/BoxAIAgentAskLongText.java | 429 +- .../com/box/sdk/BoxAIAgentEmbeddings.java | 154 +- .../box/sdk/BoxAIAgentEmbeddingsStrategy.java | 142 +- .../java/com/box/sdk/BoxAIAgentExtract.java | 180 +- .../box/sdk/BoxAIAgentExtractStructured.java | 181 +- .../box/sdk/BoxAIAgentLLMEndpointParams.java | 125 +- .../BoxAIAgentLLMEndpointParamsGoogle.java | 242 +- .../BoxAIAgentLLMEndpointParamsOpenAI.java | 380 +- .../java/com/box/sdk/BoxAIAgentTextGen.java | 106 +- .../box/sdk/BoxAIAgentTextGenBasicGen.java | 445 +- .../java/com/box/sdk/BoxAIDialogueEntry.java | 173 +- .../java/com/box/sdk/BoxAIExtractField.java | 130 +- .../com/box/sdk/BoxAIExtractFieldOption.java | 33 +- .../box/sdk/BoxAIExtractMetadataTemplate.java | 81 +- .../sdk/BoxAIExtractStructuredResponse.java | 141 +- src/main/java/com/box/sdk/BoxAIItem.java | 211 +- src/main/java/com/box/sdk/BoxAIResponse.java | 142 +- .../java/com/box/sdk/BoxAPIConnection.java | 2497 +++++------ .../com/box/sdk/BoxAPIConnectionListener.java | 42 +- .../java/com/box/sdk/BoxAPIException.java | 329 +- src/main/java/com/box/sdk/BoxAPIRequest.java | 1323 +++--- src/main/java/com/box/sdk/BoxAPIResponse.java | 618 +-- .../com/box/sdk/BoxAPIResponseException.java | 125 +- .../java/com/box/sdk/BoxCCGAPIConnection.java | 244 +- .../java/com/box/sdk/BoxClassification.java | 106 +- .../java/com/box/sdk/BoxCollaboration.java | 1186 ++--- .../box/sdk/BoxCollaborationAllowlist.java | 483 +-- ...BoxCollaborationAllowlistExemptTarget.java | 392 +- .../com/box/sdk/BoxCollaborationIterator.java | 52 +- .../java/com/box/sdk/BoxCollaborator.java | 340 +- src/main/java/com/box/sdk/BoxCollection.java | 297 +- .../com/box/sdk/BoxCollectionIterator.java | 52 +- src/main/java/com/box/sdk/BoxComment.java | 546 ++- src/main/java/com/box/sdk/BoxConfig.java | 354 +- src/main/java/com/box/sdk/BoxDateFormat.java | 143 +- .../box/sdk/BoxDeserializationException.java | 93 +- .../sdk/BoxDeveloperEditionAPIConnection.java | 946 ++-- src/main/java/com/box/sdk/BoxDevicePin.java | 462 +- src/main/java/com/box/sdk/BoxEnterprise.java | 99 +- src/main/java/com/box/sdk/BoxEvent.java | 1578 +++---- src/main/java/com/box/sdk/BoxFile.java | 3848 +++++++++-------- src/main/java/com/box/sdk/BoxFileRequest.java | 833 ++-- .../com/box/sdk/BoxFileUploadSession.java | 797 ++-- .../com/box/sdk/BoxFileUploadSessionPart.java | 192 +- .../box/sdk/BoxFileUploadSessionPartList.java | 144 +- src/main/java/com/box/sdk/BoxFileVersion.java | 578 ++- .../com/box/sdk/BoxFileVersionLegalHold.java | 283 +- .../com/box/sdk/BoxFileVersionRetention.java | 554 ++- src/main/java/com/box/sdk/BoxFolder.java | 3238 +++++++------- src/main/java/com/box/sdk/BoxFolderLock.java | 268 +- .../java/com/box/sdk/BoxGlobalSettings.java | 144 +- src/main/java/com/box/sdk/BoxGroup.java | 913 ++-- .../java/com/box/sdk/BoxGroupIterator.java | 38 +- .../java/com/box/sdk/BoxGroupMembership.java | 673 ++- .../box/sdk/BoxGroupMembershipIterator.java | 93 +- .../com/box/sdk/BoxImageMultipartRequest.java | 69 +- src/main/java/com/box/sdk/BoxInvite.java | 414 +- src/main/java/com/box/sdk/BoxItem.java | 1147 ++--- .../java/com/box/sdk/BoxItemIterator.java | 97 +- src/main/java/com/box/sdk/BoxJSONObject.java | 440 +- src/main/java/com/box/sdk/BoxJSONRequest.java | 203 +- .../java/com/box/sdk/BoxJSONResponse.java | 181 +- .../com/box/sdk/BoxLegalHoldAssignment.java | 412 +- .../java/com/box/sdk/BoxLegalHoldPolicy.java | 1036 +++-- src/main/java/com/box/sdk/BoxLock.java | 228 +- src/main/java/com/box/sdk/BoxLogger.java | 304 +- .../com/box/sdk/BoxMetadataCascadePolicy.java | 421 +- .../java/com/box/sdk/BoxMetadataFilter.java | 207 +- .../com/box/sdk/BoxMetadataQueryItem.java | 144 +- .../java/com/box/sdk/BoxMultipartRequest.java | 43 +- .../com/box/sdk/BoxNotificationEmail.java | 120 +- src/main/java/com/box/sdk/BoxRecentItem.java | 166 +- src/main/java/com/box/sdk/BoxRecents.java | 58 +- src/main/java/com/box/sdk/BoxResource.java | 338 +- .../java/com/box/sdk/BoxResourceIterable.java | 414 +- .../java/com/box/sdk/BoxResourceType.java | 15 +- .../java/com/box/sdk/BoxRetentionPolicy.java | 1635 ++++--- .../box/sdk/BoxRetentionPolicyAssignment.java | 850 ++-- src/main/java/com/box/sdk/BoxSearch.java | 164 +- .../java/com/box/sdk/BoxSearchParameters.java | 968 ++--- .../java/com/box/sdk/BoxSearchSharedLink.java | 145 +- .../box/sdk/BoxSensitiveDataSanitizer.java | 110 +- src/main/java/com/box/sdk/BoxSharedLink.java | 757 ++-- src/main/java/com/box/sdk/BoxSignRequest.java | 1311 +++--- .../box/sdk/BoxSignRequestCreateParams.java | 673 +-- .../java/com/box/sdk/BoxSignRequestFile.java | 161 +- .../com/box/sdk/BoxSignRequestPrefillTag.java | 240 +- .../box/sdk/BoxSignRequestSignatureColor.java | 50 +- .../com/box/sdk/BoxSignRequestSigner.java | 1475 +++---- .../com/box/sdk/BoxSignRequestSignerRole.java | 49 +- .../java/com/box/sdk/BoxSignTemplate.java | 681 ++- .../sdk/BoxSignTemplateAdditionalInfo.java | 51 +- ...BoxSignTemplateAdditionalInfoRequired.java | 35 +- .../sdk/BoxSignTemplateCustomBranding.java | 106 +- .../box/sdk/BoxSignTemplateReadySignLink.java | 160 +- .../com/box/sdk/BoxSignTemplateSigner.java | 1121 +++-- .../java/com/box/sdk/BoxStoragePolicy.java | 268 +- .../box/sdk/BoxStoragePolicyAssignment.java | 453 +- src/main/java/com/box/sdk/BoxTask.java | 778 ++-- .../java/com/box/sdk/BoxTaskAssignment.java | 556 ++- .../box/sdk/BoxTaskAssignmentIterator.java | 99 +- .../java/com/box/sdk/BoxTermsOfService.java | 624 ++- .../box/sdk/BoxTermsOfServiceUserStatus.java | 484 +-- .../sdk/BoxTransactionalAPIConnection.java | 235 +- src/main/java/com/box/sdk/BoxTrash.java | 530 ++- src/main/java/com/box/sdk/BoxUploadEmail.java | 151 +- src/main/java/com/box/sdk/BoxUser.java | 2462 +++++------ .../java/com/box/sdk/BoxUserIterator.java | 38 +- src/main/java/com/box/sdk/BoxWatermark.java | 193 +- src/main/java/com/box/sdk/BoxWebHook.java | 1381 +++--- .../box/sdk/BoxWebHookSignatureVerifier.java | 366 +- src/main/java/com/box/sdk/BoxWebLink.java | 479 +- src/main/java/com/box/sdk/BoxZip.java | 151 +- src/main/java/com/box/sdk/BoxZipConflict.java | 67 +- .../java/com/box/sdk/BoxZipConflictItem.java | 131 +- .../com/box/sdk/BoxZipDownloadStatus.java | 211 +- src/main/java/com/box/sdk/BoxZipInfo.java | 175 +- src/main/java/com/box/sdk/BoxZipItem.java | 83 +- .../java/com/box/sdk/CreateUserParams.java | 730 ++-- src/main/java/com/box/sdk/DateRange.java | 119 +- .../box/sdk/DeveloperEditionEntityType.java | 46 +- src/main/java/com/box/sdk/EmailAlias.java | 117 +- .../java/com/box/sdk/EncryptionAlgorithm.java | 22 +- .../com/box/sdk/EnterpriseEventsRequest.java | 198 +- .../sdk/EnterpriseEventsStreamRequest.java | 121 +- src/main/java/com/box/sdk/EventListener.java | 48 +- src/main/java/com/box/sdk/EventLog.java | 510 ++- src/main/java/com/box/sdk/EventStream.java | 400 +- .../java/com/box/sdk/FileUploadParams.java | 393 +- src/main/java/com/box/sdk/Filter.java | 2 +- .../java/com/box/sdk/IAccessTokenCache.java | 36 +- .../com/box/sdk/IPrivateKeyDecryptor.java | 22 +- .../box/sdk/InMemoryLRUAccessTokenCache.java | 73 +- .../com/box/sdk/JWTEncryptionPreferences.java | 175 +- src/main/java/com/box/sdk/JsonIterator.java | 172 +- src/main/java/com/box/sdk/LRUCache.java | 30 +- .../java/com/box/sdk/LargeFileUpload.java | 546 +-- .../java/com/box/sdk/LargeFileUploadTask.java | 97 +- src/main/java/com/box/sdk/Metadata.java | 964 ++--- .../java/com/box/sdk/MetadataFieldFilter.java | 82 +- src/main/java/com/box/sdk/MetadataQuery.java | 505 ++- .../java/com/box/sdk/MetadataTemplate.java | 2375 +++++----- .../java/com/box/sdk/PagingParameters.java | 138 +- .../java/com/box/sdk/PartialCollection.java | 251 +- .../java/com/box/sdk/ProgressInputStream.java | 102 +- .../java/com/box/sdk/ProgressListener.java | 22 +- .../com/box/sdk/ProgressOutputStream.java | 98 +- .../java/com/box/sdk/QueryStringBuilder.java | 124 +- .../com/box/sdk/RealtimeServerConnection.java | 94 +- src/main/java/com/box/sdk/Representation.java | 318 +- .../com/box/sdk/RequestBodyFromCallback.java | 32 +- .../com/box/sdk/RequestBodyFromStream.java | 125 +- .../java/com/box/sdk/RequestInterceptor.java | 33 +- .../com/box/sdk/RetentionPolicyParams.java | 318 +- src/main/java/com/box/sdk/ScopedToken.java | 180 +- .../com/box/sdk/SharedLinkAPIConnection.java | 324 +- src/main/java/com/box/sdk/SizeRange.java | 126 +- src/main/java/com/box/sdk/SortParameters.java | 95 +- .../java/com/box/sdk/StandardCharsets.java | 16 +- src/main/java/com/box/sdk/Time.java | 19 +- src/main/java/com/box/sdk/URLTemplate.java | 197 +- .../java/com/box/sdk/UploadFileCallback.java | 18 +- .../java/com/box/sdk/ZstdInterceptor.java | 121 +- .../java/com/box/sdk/http/ContentType.java | 33 +- .../java/com/box/sdk/http/HttpHeaders.java | 81 +- .../java/com/box/sdk/http/HttpMethod.java | 66 +- .../com/box/sdk/internal/package-info.java | 6 +- .../com/box/sdk/internal/pool/MacPool.java | 116 +- .../sdk/internal/utils/CollectionUtils.java | 107 +- .../com/box/sdk/internal/utils/JsonUtils.java | 182 +- .../com/box/sdk/internal/utils/Parsers.java | 97 +- src/main/java/com/box/sdk/package-info.java | 4 +- .../sharedlink/AbstractSharedLinkRequest.java | 114 +- .../sdk/sharedlink/BoxSharedLinkRequest.java | 58 +- ...oxSharedLinkWithoutPermissionsRequest.java | 8 +- .../java/com/box/sdkgen/box/BoxConstants.java | 12 + .../box/sdkgen/box/ccgauth/BoxCCGAuth.java | 169 + .../com/box/sdkgen/box/ccgauth/CCGConfig.java | 89 + .../BoxDeveloperTokenAuth.java | 147 + .../DeveloperTokenConfig.java | 44 + .../box/sdkgen/box/errors/BoxAPIError.java | 114 + .../box/sdkgen/box/errors/BoxSDKError.java | 84 + .../box/sdkgen/box/errors/RequestInfo.java | 135 + .../box/sdkgen/box/errors/ResponseInfo.java | 174 + .../sdkgen/box/eventstream/EventStream.java | 47 + .../box/eventstream/EventStreamIterator.java | 345 ++ .../box/sdkgen/box/jwtauth/BoxJWTAuth.java | 207 + .../com/box/sdkgen/box/jwtauth/JWTConfig.java | 232 + .../box/jwtauth/JwtConfigAppSettings.java | 75 + .../jwtauth/JwtConfigAppSettingsAppAuth.java | 75 + .../box/sdkgen/box/jwtauth/JwtConfigFile.java | 108 + .../com/box/sdkgen/box/oauth/BoxOAuth.java | 177 + .../box/oauth/GetAuthorizeUrlOptions.java | 86 + .../com/box/sdkgen/box/oauth/OAuthConfig.java | 61 + .../tokenstorage/InMemoryTokenStorage.java | 48 + .../sdkgen/box/tokenstorage/TokenStorage.java | 11 + .../java/com/box/sdkgen/client/BoxClient.java | 1346 ++++++ .../com/box/sdkgen/internal/Nullable.java | 10 + .../sdkgen/internal/NullableFieldTracker.java | 26 + .../internal/NullablePropertyFilter.java | 38 + .../com/box/sdkgen/internal/OneOfFive.java | 53 + .../com/box/sdkgen/internal/OneOfFour.java | 48 + .../com/box/sdkgen/internal/OneOfOne.java | 33 + .../com/box/sdkgen/internal/OneOfSix.java | 58 + .../com/box/sdkgen/internal/OneOfThree.java | 43 + .../com/box/sdkgen/internal/OneOfTwo.java | 38 + .../sdkgen/internal/SerializableObject.java | 18 + .../internal/logging/DataSanitizer.java | 39 + .../sdkgen/internal/utils/DateTimeUtils.java | 37 + .../box/sdkgen/internal/utils/DateUtils.java | 36 + .../utils/DefaultPrivateKeyDecryptor.java | 61 + .../com/box/sdkgen/internal/utils/Entry.java | 23 + .../com/box/sdkgen/internal/utils/Hash.java | 34 + .../box/sdkgen/internal/utils/HashName.java | 17 + .../sdkgen/internal/utils/JwtAlgorithm.java | 29 + .../com/box/sdkgen/internal/utils/JwtKey.java | 19 + .../sdkgen/internal/utils/JwtSignOptions.java | 95 + .../internal/utils/PrivateKeyDecryptor.java | 9 + .../sdkgen/internal/utils/UtilsManager.java | 512 +++ .../com/box/sdkgen/managers/ai/AiManager.java | 206 + .../managers/ai/CreateAiAskHeaders.java | 40 + .../managers/ai/CreateAiExtractHeaders.java | 40 + .../ai/CreateAiExtractStructuredHeaders.java | 40 + .../managers/ai/CreateAiTextGenHeaders.java | 40 + .../ai/GetAiAgentDefaultConfigHeaders.java | 40 + .../GetAiAgentDefaultConfigQueryParams.java | 70 + ...gentDefaultConfigQueryParamsModeField.java | 65 + .../managers/aistudio/AiStudioManager.java | 223 + .../aistudio/CreateAiAgentHeaders.java | 40 + .../aistudio/DeleteAiAgentByIdHeaders.java | 40 + .../aistudio/GetAiAgentByIdHeaders.java | 40 + .../aistudio/GetAiAgentByIdQueryParams.java | 32 + .../managers/aistudio/GetAiAgentsHeaders.java | 40 + .../aistudio/GetAiAgentsQueryParams.java | 102 + .../aistudio/UpdateAiAgentByIdHeaders.java | 40 + .../AppItemAssociationsManager.java | 165 + .../GetFileAppItemAssociationsHeaders.java | 40 + ...GetFileAppItemAssociationsQueryParams.java | 58 + .../GetFolderAppItemAssociationsHeaders.java | 40 + ...tFolderAppItemAssociationsQueryParams.java | 58 + .../managers/archives/ArchivesManager.java | 164 + .../archives/CreateArchiveV2025R0Headers.java | 63 + .../CreateArchiveV2025R0RequestBody.java | 43 + .../DeleteArchiveByIdV2025R0Headers.java | 63 + .../archives/GetArchivesV2025R0Headers.java | 63 + .../GetArchivesV2025R0QueryParams.java | 44 + .../authorization/AuthorizationManager.java | 173 + .../authorization/AuthorizeUserHeaders.java | 40 + .../AuthorizeUserQueryParams.java | 99 + ...orizeUserQueryParamsResponseTypeField.java | 62 + .../RefreshAccessTokenHeaders.java | 40 + .../RequestAccessTokenHeaders.java | 40 + .../RevokeAccessTokenHeaders.java | 40 + .../managers/avatars/AvatarsManager.java | 153 + .../avatars/CreateUserAvatarHeaders.java | 40 + .../avatars/CreateUserAvatarRequestBody.java | 61 + .../avatars/DeleteUserAvatarHeaders.java | 40 + .../avatars/GetUserAvatarHeaders.java | 40 + .../chunkeduploads/ChunkedUploadsManager.java | 520 +++ ...teFileUploadSessionCommitByUrlHeaders.java | 79 + ...leUploadSessionCommitByUrlRequestBody.java | 47 + .../CreateFileUploadSessionCommitHeaders.java | 79 + ...ateFileUploadSessionCommitRequestBody.java | 45 + ...leUploadSessionForExistingFileHeaders.java | 40 + ...loadSessionForExistingFileRequestBody.java | 90 + .../CreateFileUploadSessionHeaders.java | 40 + .../CreateFileUploadSessionRequestBody.java | 77 + .../DeleteFileUploadSessionByIdHeaders.java | 40 + .../DeleteFileUploadSessionByUrlHeaders.java | 40 + .../GetFileUploadSessionByIdHeaders.java | 40 + .../GetFileUploadSessionByUrlHeaders.java | 40 + ...GetFileUploadSessionPartsByUrlHeaders.java | 40 + ...ileUploadSessionPartsByUrlQueryParams.java | 44 + .../GetFileUploadSessionPartsHeaders.java | 40 + .../GetFileUploadSessionPartsQueryParams.java | 44 + .../chunkeduploads/PartAccumulator.java | 47 + .../UploadFilePartByUrlHeaders.java | 62 + .../chunkeduploads/UploadFilePartHeaders.java | 62 + .../AddClassificationHeaders.java | 40 + .../AddClassificationRequestBody.java | 146 + ...AddClassificationRequestBodyDataField.java | 86 + ...dyDataStaticConfigClassificationField.java | 89 + ...ationRequestBodyDataStaticConfigField.java | 68 + ...lassificationRequestBodyFieldKeyField.java | 62 + .../AddClassificationRequestBodyOpField.java | 62 + .../ClassificationsManager.java | 173 + .../CreateClassificationTemplateHeaders.java | 40 + ...eateClassificationTemplateRequestBody.java | 233 + ...onTemplateRequestBodyDisplayNameField.java | 63 + ...lateRequestBodyFieldsDisplayNameField.java | 66 + ...icationTemplateRequestBodyFieldsField.java | 216 + ...tionTemplateRequestBodyFieldsKeyField.java | 62 + ...TemplateRequestBodyFieldsOptionsField.java | 89 + ...ptionsStaticConfigClassificationField.java | 92 + ...estBodyFieldsOptionsStaticConfigField.java | 73 + ...ionTemplateRequestBodyFieldsTypeField.java | 63 + ...ficationTemplateRequestBodyScopeField.java | 62 + ...onTemplateRequestBodyTemplateKeyField.java | 63 + .../GetClassificationTemplateHeaders.java | 40 + .../UpdateClassificationHeaders.java | 40 + .../UpdateClassificationRequestBody.java | 165 + ...ateClassificationRequestBodyDataField.java | 86 + ...dyDataStaticConfigClassificationField.java | 89 + ...ationRequestBodyDataStaticConfigField.java | 68 + ...lassificationRequestBodyFieldKeyField.java | 62 + ...pdateClassificationRequestBodyOpField.java | 62 + .../CollaborationAllowlistEntriesManager.java | 196 + ...ateCollaborationWhitelistEntryHeaders.java | 40 + ...ollaborationWhitelistEntryRequestBody.java | 81 + ...itelistEntryRequestBodyDirectionField.java | 67 + ...ollaborationWhitelistEntryByIdHeaders.java | 40 + ...tCollaborationWhitelistEntriesHeaders.java | 40 + ...laborationWhitelistEntriesQueryParams.java | 44 + ...ollaborationWhitelistEntryByIdHeaders.java | 40 + ...borationAllowlistExemptTargetsManager.java | 201 + ...aborationWhitelistExemptTargetHeaders.java | 40 + ...ationWhitelistExemptTargetRequestBody.java | 45 + ...elistExemptTargetRequestBodyUserField.java | 50 + ...ationWhitelistExemptTargetByIdHeaders.java | 40 + ...ationWhitelistExemptTargetByIdHeaders.java | 40 + ...borationWhitelistExemptTargetsHeaders.java | 40 + ...tionWhitelistExemptTargetsQueryParams.java | 44 + .../collections/CollectionsManager.java | 177 + .../collections/GetCollectionByIdHeaders.java | 40 + .../GetCollectionItemsHeaders.java | 40 + .../GetCollectionItemsQueryParams.java | 60 + .../collections/GetCollectionsHeaders.java | 40 + .../GetCollectionsQueryParams.java | 60 + .../managers/comments/CommentsManager.java | 283 ++ .../comments/CreateCommentHeaders.java | 40 + .../comments/CreateCommentQueryParams.java | 32 + .../comments/CreateCommentRequestBody.java | 106 + .../CreateCommentRequestBodyItemField.java | 77 + ...CreateCommentRequestBodyItemTypeField.java | 63 + .../comments/DeleteCommentByIdHeaders.java | 40 + .../comments/GetCommentByIdHeaders.java | 40 + .../comments/GetCommentByIdQueryParams.java | 32 + .../comments/GetFileCommentsHeaders.java | 40 + .../comments/GetFileCommentsQueryParams.java | 60 + .../comments/UpdateCommentByIdHeaders.java | 40 + .../UpdateCommentByIdQueryParams.java | 32 + .../UpdateCommentByIdRequestBody.java | 62 + .../DeleteDevicePinnerByIdHeaders.java | 40 + .../devicepinners/DevicePinnersManager.java | 167 + .../GetDevicePinnerByIdHeaders.java | 40 + .../GetEnterpriseDevicePinnersHeaders.java | 40 + ...GetEnterpriseDevicePinnersQueryParams.java | 67 + ...evicePinnersQueryParamsDirectionField.java | 63 + .../CreateDocgenBatchV2025R0Headers.java | 63 + .../sdkgen/managers/docgen/DocgenManager.java | 226 + .../GetDocgenBatchJobByIdV2025R0Headers.java | 63 + ...tDocgenBatchJobByIdV2025R0QueryParams.java | 44 + .../GetDocgenJobByIdV2025R0Headers.java | 63 + .../docgen/GetDocgenJobsV2025R0Headers.java | 63 + .../GetDocgenJobsV2025R0QueryParams.java | 44 + .../CreateDocgenTemplateV2025R0Headers.java | 63 + ...eleteDocgenTemplateByIdV2025R0Headers.java | 63 + .../docgentemplate/DocgenTemplateManager.java | 315 ++ .../GetDocgenTemplateByIdV2025R0Headers.java | 63 + ...etDocgenTemplateJobByIdV2025R0Headers.java | 63 + ...cgenTemplateJobByIdV2025R0QueryParams.java | 44 + .../GetDocgenTemplateTagsV2025R0Headers.java | 63 + ...tDocgenTemplateTagsV2025R0QueryParams.java | 58 + .../GetDocgenTemplatesV2025R0Headers.java | 63 + .../GetDocgenTemplatesV2025R0QueryParams.java | 44 + .../downloads/DownloadFileHeaders.java | 68 + .../downloads/DownloadFileQueryParams.java | 44 + .../DownloadFileToOutputStreamHeaders.java | 68 + ...DownloadFileToOutputStreamQueryParams.java | 44 + .../managers/downloads/DownloadsManager.java | 212 + .../downloads/GetDownloadFileUrlHeaders.java | 68 + .../GetDownloadFileUrlQueryParams.java | 44 + .../CreateUserEmailAliasHeaders.java | 40 + .../CreateUserEmailAliasRequestBody.java | 43 + .../DeleteUserEmailAliasByIdHeaders.java | 40 + .../emailaliases/EmailAliasesManager.java | 150 + .../GetUserEmailAliasesHeaders.java | 40 + .../sdkgen/managers/events/EventsManager.java | 146 + .../events/GetEventStreamHeaders.java | 40 + .../events/GetEventStreamQueryParams.java | 175 + ...tEventStreamQueryParamsEventTypeField.java | 176 + ...EventStreamQueryParamsStreamTypeField.java | 66 + .../managers/events/GetEventsHeaders.java | 40 + .../managers/events/GetEventsQueryParams.java | 171 + .../GetEventsQueryParamsEventTypeField.java | 176 + .../GetEventsQueryParamsStreamTypeField.java | 66 + .../GetEventsWithLongPollingHeaders.java | 40 + .../externalusers/ExternalUsersManager.java | 101 + ...obToDeleteExternalUsersV2025R0Headers.java | 63 + .../AddClassificationToFileHeaders.java | 40 + .../AddClassificationToFileRequestBody.java | 68 + .../DeleteClassificationFromFileHeaders.java | 40 + .../FileClassificationsManager.java | 192 + .../GetClassificationOnFileHeaders.java | 40 + .../UpdateClassificationOnFileHeaders.java | 40 + ...UpdateClassificationOnFileRequestBody.java | 147 + ...lassificationOnFileRequestBodyOpField.java | 62 + ...ssificationOnFileRequestBodyPathField.java | 62 + .../CreateFileMetadataByIdHeaders.java | 40 + .../CreateFileMetadataByIdScope.java | 63 + .../DeleteFileMetadataByIdHeaders.java | 40 + .../DeleteFileMetadataByIdScope.java | 63 + .../filemetadata/FileMetadataManager.java | 241 ++ .../GetFileMetadataByIdHeaders.java | 40 + .../GetFileMetadataByIdScope.java | 63 + .../filemetadata/GetFileMetadataHeaders.java | 40 + .../UpdateFileMetadataByIdHeaders.java | 40 + .../UpdateFileMetadataByIdRequestBody.java | 161 + ...ateFileMetadataByIdRequestBodyOpField.java | 67 + .../UpdateFileMetadataByIdScope.java | 63 + .../CreateFileRequestCopyHeaders.java | 40 + .../DeleteFileRequestByIdHeaders.java | 40 + .../filerequests/FileRequestsManager.java | 183 + .../GetFileRequestByIdHeaders.java | 40 + .../UpdateFileRequestByIdHeaders.java | 54 + .../managers/files/CopyFileHeaders.java | 40 + .../managers/files/CopyFileQueryParams.java | 32 + .../managers/files/CopyFileRequestBody.java | 106 + .../files/CopyFileRequestBodyParentField.java | 43 + .../managers/files/DeleteFileByIdHeaders.java | 54 + .../sdkgen/managers/files/FilesManager.java | 373 ++ .../managers/files/GetFileByIdHeaders.java | 82 + .../files/GetFileByIdQueryParams.java | 32 + .../files/GetFileThumbnailByIdExtension.java | 63 + .../files/GetFileThumbnailByIdHeaders.java | 40 + .../GetFileThumbnailByIdQueryParams.java | 72 + .../files/GetFileThumbnailUrlExtension.java | 63 + .../files/GetFileThumbnailUrlHeaders.java | 40 + .../files/GetFileThumbnailUrlQueryParams.java | 72 + .../managers/files/UpdateFileByIdHeaders.java | 54 + .../files/UpdateFileByIdQueryParams.java | 32 + .../files/UpdateFileByIdRequestBody.java | 234 + ...teFileByIdRequestBodyCollectionsField.java | 85 + ...ateFileByIdRequestBodyLockAccessField.java | 62 + .../UpdateFileByIdRequestBodyLockField.java | 127 + .../UpdateFileByIdRequestBodyParentField.java | 86 + ...equestBodyPermissionsCanDownloadField.java | 63 + ...teFileByIdRequestBodyPermissionsField.java | 87 + ...eByIdRequestBodySharedLinkAccessField.java | 64 + ...ateFileByIdRequestBodySharedLinkField.java | 167 + ...RequestBodySharedLinkPermissionsField.java | 69 + .../FileVersionLegalHoldsManager.java | 126 + .../GetFileVersionLegalHoldByIdHeaders.java | 40 + .../GetFileVersionLegalHoldsHeaders.java | 40 + .../GetFileVersionLegalHoldsQueryParams.java | 59 + .../FileVersionRetentionsManager.java | 140 + .../GetFileVersionRetentionByIdHeaders.java | 40 + .../GetFileVersionRetentionsHeaders.java | 40 + .../GetFileVersionRetentionsQueryParams.java | 141 + ...ionsQueryParamsDispositionActionField.java | 66 + .../DeleteFileVersionByIdHeaders.java | 54 + .../fileversions/FileVersionsManager.java | 309 ++ .../GetFileVersionByIdHeaders.java | 40 + .../GetFileVersionByIdQueryParams.java | 32 + .../fileversions/GetFileVersionsHeaders.java | 40 + .../GetFileVersionsQueryParams.java | 60 + .../PromoteFileVersionHeaders.java | 40 + .../PromoteFileVersionQueryParams.java | 32 + .../PromoteFileVersionRequestBody.java | 100 + ...romoteFileVersionRequestBodyTypeField.java | 62 + .../UpdateFileVersionByIdHeaders.java | 40 + .../UpdateFileVersionByIdRequestBody.java | 67 + .../DeleteFileWatermarkHeaders.java | 40 + .../filewatermarks/FileWatermarksManager.java | 146 + .../GetFileWatermarkHeaders.java | 40 + .../UpdateFileWatermarkHeaders.java | 40 + .../UpdateFileWatermarkRequestBody.java | 44 + ...ileWatermarkRequestBodyWatermarkField.java | 90 + ...rmarkRequestBodyWatermarkImprintField.java | 62 + .../AddClassificationToFolderHeaders.java | 40 + .../AddClassificationToFolderRequestBody.java | 68 + ...DeleteClassificationFromFolderHeaders.java | 40 + .../FolderClassificationsManager.java | 195 + .../GetClassificationOnFolderHeaders.java | 40 + .../UpdateClassificationOnFolderHeaders.java | 40 + ...dateClassificationOnFolderRequestBody.java | 147 + ...ssificationOnFolderRequestBodyOpField.java | 62 + ...ificationOnFolderRequestBodyPathField.java | 62 + .../folderlocks/CreateFolderLockHeaders.java | 40 + .../CreateFolderLockRequestBody.java | 90 + ...reateFolderLockRequestBodyFolderField.java | 59 + ...rLockRequestBodyLockedOperationsField.java | 60 + .../DeleteFolderLockByIdHeaders.java | 40 + .../folderlocks/FolderLocksManager.java | 145 + .../folderlocks/GetFolderLocksHeaders.java | 40 + .../GetFolderLocksQueryParams.java | 14 + .../CreateFolderMetadataByIdHeaders.java | 40 + .../CreateFolderMetadataByIdScope.java | 63 + .../DeleteFolderMetadataByIdHeaders.java | 40 + .../DeleteFolderMetadataByIdScope.java | 63 + .../foldermetadata/FolderMetadataManager.java | 241 ++ .../GetFolderMetadataByIdHeaders.java | 40 + .../GetFolderMetadataByIdScope.java | 63 + .../GetFolderMetadataHeaders.java | 40 + .../UpdateFolderMetadataByIdHeaders.java | 40 + .../UpdateFolderMetadataByIdRequestBody.java | 161 + ...eFolderMetadataByIdRequestBodyOpField.java | 67 + .../UpdateFolderMetadataByIdScope.java | 63 + .../managers/folders/CopyFolderHeaders.java | 40 + .../folders/CopyFolderQueryParams.java | 32 + .../folders/CopyFolderRequestBody.java | 86 + .../CopyFolderRequestBodyParentField.java | 43 + .../managers/folders/CreateFolderHeaders.java | 40 + .../folders/CreateFolderQueryParams.java | 32 + .../folders/CreateFolderRequestBody.java | 143 + ...questBodyFolderUploadEmailAccessField.java | 63 + ...lderRequestBodyFolderUploadEmailField.java | 79 + .../CreateFolderRequestBodyParentField.java | 43 + ...CreateFolderRequestBodySyncStateField.java | 64 + .../folders/DeleteFolderByIdHeaders.java | 54 + .../folders/DeleteFolderByIdQueryParams.java | 30 + .../managers/folders/FoldersManager.java | 363 ++ .../folders/GetFolderByIdHeaders.java | 68 + .../folders/GetFolderByIdQueryParams.java | 99 + ...etFolderByIdQueryParamsDirectionField.java | 63 + .../GetFolderByIdQueryParamsSortField.java | 65 + .../folders/GetFolderItemsHeaders.java | 54 + .../folders/GetFolderItemsQueryParams.java | 127 + ...tFolderItemsQueryParamsDirectionField.java | 63 + .../GetFolderItemsQueryParamsSortField.java | 65 + .../folders/UpdateFolderByIdHeaders.java | 54 + .../folders/UpdateFolderByIdQueryParams.java | 32 + .../folders/UpdateFolderByIdRequestBody.java | 298 ++ ...FolderByIdRequestBodyCollectionsField.java | 85 + ...questBodyFolderUploadEmailAccessField.java | 64 + ...ByIdRequestBodyFolderUploadEmailField.java | 81 + ...pdateFolderByIdRequestBodyParentField.java | 86 + ...rByIdRequestBodySharedLinkAccessField.java | 64 + ...eFolderByIdRequestBodySharedLinkField.java | 168 + ...RequestBodySharedLinkPermissionsField.java | 69 + ...teFolderByIdRequestBodySyncStateField.java | 64 + .../DeleteFolderWatermarkHeaders.java | 40 + .../FolderWatermarksManager.java | 147 + .../GetFolderWatermarkHeaders.java | 40 + .../UpdateFolderWatermarkHeaders.java | 40 + .../UpdateFolderWatermarkRequestBody.java | 44 + ...derWatermarkRequestBodyWatermarkField.java | 91 + ...rmarkRequestBodyWatermarkImprintField.java | 62 + .../managers/groups/CreateGroupHeaders.java | 40 + .../groups/CreateGroupQueryParams.java | 32 + .../groups/CreateGroupRequestBody.java | 209 + ...roupRequestBodyInvitabilityLevelField.java | 64 + ...equestBodyMemberViewabilityLevelField.java | 64 + .../groups/DeleteGroupByIdHeaders.java | 40 + .../managers/groups/GetGroupByIdHeaders.java | 40 + .../groups/GetGroupByIdQueryParams.java | 32 + .../managers/groups/GetGroupsHeaders.java | 40 + .../managers/groups/GetGroupsQueryParams.java | 74 + .../sdkgen/managers/groups/GroupsManager.java | 274 ++ .../groups/UpdateGroupByIdHeaders.java | 40 + .../groups/UpdateGroupByIdQueryParams.java | 32 + .../groups/UpdateGroupByIdRequestBody.java | 210 + ...ByIdRequestBodyInvitabilityLevelField.java | 64 + ...equestBodyMemberViewabilityLevelField.java | 64 + .../CreateHubCollaborationV2025R0Headers.java | 63 + ...eteHubCollaborationByIdV2025R0Headers.java | 63 + ...GetHubCollaborationByIdV2025R0Headers.java | 63 + .../GetHubCollaborationsV2025R0Headers.java | 63 + ...etHubCollaborationsV2025R0QueryParams.java | 59 + .../HubCollaborationsManager.java | 236 + ...ateHubCollaborationByIdV2025R0Headers.java | 63 + .../hubitems/GetHubItemsV2025R0Headers.java | 63 + .../GetHubItemsV2025R0QueryParams.java | 59 + .../managers/hubitems/HubItemsManager.java | 137 + .../ManageHubItemsV2025R0Headers.java | 63 + .../managers/hubs/CopyHubV2025R0Headers.java | 63 + .../hubs/CreateHubV2025R0Headers.java | 63 + .../hubs/DeleteHubByIdV2025R0Headers.java | 63 + .../hubs/GetEnterpriseHubsV2025R0Headers.java | 63 + .../GetEnterpriseHubsV2025R0QueryParams.java | 95 + ...eHubsV2025R0QueryParamsDirectionField.java | 63 + .../hubs/GetHubByIdV2025R0Headers.java | 63 + .../managers/hubs/GetHubsV2025R0Headers.java | 63 + .../hubs/GetHubsV2025R0QueryParams.java | 107 + ...tHubsV2025R0QueryParamsDirectionField.java | 63 + .../box/sdkgen/managers/hubs/HubsManager.java | 312 ++ .../hubs/UpdateHubByIdV2025R0Headers.java | 63 + .../CreateSlackIntegrationMappingHeaders.java | 40 + .../CreateTeamsIntegrationMappingHeaders.java | 40 + ...eteSlackIntegrationMappingByIdHeaders.java | 40 + ...eteTeamsIntegrationMappingByIdHeaders.java | 40 + .../GetSlackIntegrationMappingHeaders.java | 40 + ...GetSlackIntegrationMappingQueryParams.java | 134 + ...ionMappingQueryParamsBoxItemTypeField.java | 62 + ...appingQueryParamsPartnerItemTypeField.java | 65 + .../GetTeamsIntegrationMappingHeaders.java | 40 + ...GetTeamsIntegrationMappingQueryParams.java | 92 + ...ionMappingQueryParamsBoxItemTypeField.java | 62 + ...appingQueryParamsPartnerItemTypeField.java | 66 + .../IntegrationMappingsManager.java | 363 ++ ...ateSlackIntegrationMappingByIdHeaders.java | 40 + ...lackIntegrationMappingByIdRequestBody.java | 89 + ...ateTeamsIntegrationMappingByIdHeaders.java | 40 + ...eamsIntegrationMappingByIdRequestBody.java | 66 + .../managers/invites/CreateInviteHeaders.java | 40 + .../invites/CreateInviteQueryParams.java | 32 + .../invites/CreateInviteRequestBody.java | 62 + ...ateInviteRequestBodyActionableByField.java | 62 + ...reateInviteRequestBodyEnterpriseField.java | 43 + .../invites/GetInviteByIdHeaders.java | 40 + .../invites/GetInviteByIdQueryParams.java | 32 + .../managers/invites/InvitesManager.java | 141 + .../CreateLegalHoldPolicyHeaders.java | 40 + .../CreateLegalHoldPolicyRequestBody.java | 156 + .../DeleteLegalHoldPolicyByIdHeaders.java | 40 + .../GetLegalHoldPoliciesHeaders.java | 40 + .../GetLegalHoldPoliciesQueryParams.java | 74 + .../GetLegalHoldPolicyByIdHeaders.java | 40 + .../LegalHoldPoliciesManager.java | 231 + .../UpdateLegalHoldPolicyByIdHeaders.java | 40 + .../UpdateLegalHoldPolicyByIdRequestBody.java | 107 + ...reateLegalHoldPolicyAssignmentHeaders.java | 40 + ...eLegalHoldPolicyAssignmentRequestBody.java | 63 + ...icyAssignmentRequestBodyAssignToField.java | 80 + ...ssignmentRequestBodyAssignToTypeField.java | 70 + ...eLegalHoldPolicyAssignmentByIdHeaders.java | 40 + ...tLegalHoldPolicyAssignmentByIdHeaders.java | 40 + ...HoldPolicyAssignmentFileOnHoldHeaders.java | 40 + ...PolicyAssignmentFileOnHoldQueryParams.java | 60 + .../GetLegalHoldPolicyAssignmentsHeaders.java | 40 + ...LegalHoldPolicyAssignmentsQueryParams.java | 112 + ...signmentsQueryParamsAssignToTypeField.java | 70 + .../LegalHoldPolicyAssignmentsManager.java | 244 ++ .../GetCollaborationsHeaders.java | 40 + .../GetCollaborationsQueryParams.java | 84 + ...tCollaborationsQueryParamsStatusField.java | 62 + .../GetFileCollaborationsHeaders.java | 40 + .../GetFileCollaborationsQueryParams.java | 60 + .../GetFolderCollaborationsHeaders.java | 40 + .../GetFolderCollaborationsQueryParams.java | 60 + .../GetGroupCollaborationsHeaders.java | 40 + .../GetGroupCollaborationsQueryParams.java | 44 + .../ListCollaborationsManager.java | 238 + .../CreateGroupMembershipHeaders.java | 40 + .../CreateGroupMembershipQueryParams.java | 32 + .../CreateGroupMembershipRequestBody.java | 147 + ...eGroupMembershipRequestBodyGroupField.java | 44 + ...teGroupMembershipRequestBodyRoleField.java | 63 + ...teGroupMembershipRequestBodyUserField.java | 44 + .../DeleteGroupMembershipByIdHeaders.java | 40 + .../GetGroupMembershipByIdHeaders.java | 40 + .../GetGroupMembershipByIdQueryParams.java | 32 + .../GetGroupMembershipsHeaders.java | 40 + .../GetGroupMembershipsQueryParams.java | 44 + .../GetUserMembershipsHeaders.java | 40 + .../GetUserMembershipsQueryParams.java | 44 + .../memberships/MembershipsManager.java | 357 ++ .../UpdateGroupMembershipByIdHeaders.java | 40 + .../UpdateGroupMembershipByIdQueryParams.java | 32 + .../UpdateGroupMembershipByIdRequestBody.java | 107 + ...oupMembershipByIdRequestBodyRoleField.java | 63 + .../ApplyMetadataCascadePolicyHeaders.java | 40 + ...ApplyMetadataCascadePolicyRequestBody.java | 72 + ...icyRequestBodyConflictResolutionField.java | 66 + .../CreateMetadataCascadePolicyHeaders.java | 40 + ...reateMetadataCascadePolicyRequestBody.java | 94 + ...ataCascadePolicyRequestBodyScopeField.java | 63 + ...eleteMetadataCascadePolicyByIdHeaders.java | 40 + .../GetMetadataCascadePoliciesHeaders.java | 40 + ...GetMetadataCascadePoliciesQueryParams.java | 73 + .../GetMetadataCascadePolicyByIdHeaders.java | 40 + .../MetadataCascadePoliciesManager.java | 215 + .../CreateMetadataTemplateHeaders.java | 40 + .../CreateMetadataTemplateRequestBody.java | 162 + ...etadataTemplateRequestBodyFieldsField.java | 192 + ...TemplateRequestBodyFieldsOptionsField.java | 44 + ...ataTemplateRequestBodyFieldsTypeField.java | 66 + .../DeleteMetadataTemplateHeaders.java | 40 + .../DeleteMetadataTemplateScope.java | 63 + ...GetEnterpriseMetadataTemplatesHeaders.java | 40 + ...nterpriseMetadataTemplatesQueryParams.java | 44 + .../GetGlobalMetadataTemplatesHeaders.java | 40 + ...GetGlobalMetadataTemplatesQueryParams.java | 44 + .../GetMetadataTemplateByIdHeaders.java | 40 + .../GetMetadataTemplateHeaders.java | 40 + .../GetMetadataTemplateScope.java | 63 + ...tMetadataTemplatesByInstanceIdHeaders.java | 40 + ...adataTemplatesByInstanceIdQueryParams.java | 59 + .../MetadataTemplatesManager.java | 339 ++ .../UpdateMetadataTemplateHeaders.java | 40 + .../UpdateMetadataTemplateRequestBody.java | 233 + ...ateMetadataTemplateRequestBodyOpField.java | 74 + .../UpdateMetadataTemplateScope.java | 63 + .../recentitems/GetRecentItemsHeaders.java | 40 + .../GetRecentItemsQueryParams.java | 60 + .../recentitems/RecentItemsManager.java | 105 + .../CreateRetentionPolicyHeaders.java | 40 + .../CreateRetentionPolicyRequestBody.java | 346 ++ ...licyRequestBodyDispositionActionField.java | 64 + ...ntionPolicyRequestBodyPolicyTypeField.java | 63 + ...onPolicyRequestBodyRetentionTypeField.java | 63 + .../DeleteRetentionPolicyByIdHeaders.java | 40 + .../GetRetentionPoliciesHeaders.java | 40 + .../GetRetentionPoliciesQueryParams.java | 109 + ...ionPoliciesQueryParamsPolicyTypeField.java | 63 + .../GetRetentionPolicyByIdHeaders.java | 40 + .../GetRetentionPolicyByIdQueryParams.java | 32 + .../RetentionPoliciesManager.java | 253 ++ .../UpdateRetentionPolicyByIdHeaders.java | 40 + .../UpdateRetentionPolicyByIdRequestBody.java | 250 ++ ...reateRetentionPolicyAssignmentHeaders.java | 40 + ...eRetentionPolicyAssignmentRequestBody.java | 132 + ...icyAssignmentRequestBodyAssignToField.java | 114 + ...ssignmentRequestBodyAssignToTypeField.java | 67 + ...ssignmentRequestBodyFilterFieldsField.java | 86 + ...eRetentionPolicyAssignmentByIdHeaders.java | 40 + ...UnderRetentionPolicyAssignmentHeaders.java | 40 + ...rRetentionPolicyAssignmentQueryParams.java | 44 + ...tRetentionPolicyAssignmentByIdHeaders.java | 40 + ...entionPolicyAssignmentByIdQueryParams.java | 32 + .../GetRetentionPolicyAssignmentsHeaders.java | 40 + ...RetentionPolicyAssignmentsQueryParams.java | 80 + ...PolicyAssignmentsQueryParamsTypeField.java | 64 + .../RetentionPolicyAssignmentsManager.java | 278 ++ .../search/SearchByMetadataQueryHeaders.java | 40 + .../search/SearchForContentHeaders.java | 40 + .../search/SearchForContentQueryParams.java | 407 ++ ...orContentQueryParamsContentTypesField.java | 66 + ...chForContentQueryParamsDirectionField.java | 63 + ...SearchForContentQueryParamsScopeField.java | 63 + .../SearchForContentQueryParamsSortField.java | 63 + ...orContentQueryParamsTrashContentField.java | 64 + .../SearchForContentQueryParamsTypeField.java | 64 + .../sdkgen/managers/search/SearchManager.java | 154 + .../SessionTerminationManager.java | 119 + .../TerminateGroupsSessionsHeaders.java | 40 + .../TerminateGroupsSessionsRequestBody.java | 45 + .../TerminateUsersSessionsHeaders.java | 40 + .../TerminateUsersSessionsRequestBody.java | 63 + .../FindAppItemForSharedLinkHeaders.java | 51 + .../SharedLinksAppItemsManager.java | 89 + .../AddShareLinkToFileHeaders.java | 40 + .../AddShareLinkToFileQueryParams.java | 14 + .../AddShareLinkToFileRequestBody.java | 64 + ...oFileRequestBodySharedLinkAccessField.java | 64 + ...eLinkToFileRequestBodySharedLinkField.java | 169 + ...RequestBodySharedLinkPermissionsField.java | 109 + .../FindFileForSharedLinkHeaders.java | 65 + .../FindFileForSharedLinkQueryParams.java | 32 + .../GetSharedLinkForFileHeaders.java | 40 + .../GetSharedLinkForFileQueryParams.java | 14 + .../RemoveSharedLinkFromFileHeaders.java | 40 + .../RemoveSharedLinkFromFileQueryParams.java | 14 + .../RemoveSharedLinkFromFileRequestBody.java | 67 + ...inkFromFileRequestBodySharedLinkField.java | 17 + .../SharedLinksFilesManager.java | 291 ++ .../UpdateSharedLinkOnFileHeaders.java | 40 + .../UpdateSharedLinkOnFileQueryParams.java | 14 + .../UpdateSharedLinkOnFileRequestBody.java | 64 + ...nFileRequestBodySharedLinkAccessField.java | 65 + ...dLinkOnFileRequestBodySharedLinkField.java | 170 + ...RequestBodySharedLinkPermissionsField.java | 110 + .../AddShareLinkToFolderHeaders.java | 40 + .../AddShareLinkToFolderQueryParams.java | 14 + .../AddShareLinkToFolderRequestBody.java | 64 + ...olderRequestBodySharedLinkAccessField.java | 64 + ...inkToFolderRequestBodySharedLinkField.java | 170 + ...RequestBodySharedLinkPermissionsField.java | 109 + .../FindFolderForSharedLinkHeaders.java | 65 + .../FindFolderForSharedLinkQueryParams.java | 32 + .../GetSharedLinkForFolderHeaders.java | 40 + .../GetSharedLinkForFolderQueryParams.java | 14 + .../RemoveSharedLinkFromFolderHeaders.java | 40 + ...RemoveSharedLinkFromFolderQueryParams.java | 14 + ...RemoveSharedLinkFromFolderRequestBody.java | 67 + ...kFromFolderRequestBodySharedLinkField.java | 17 + .../SharedLinksFoldersManager.java | 300 ++ .../UpdateSharedLinkOnFolderHeaders.java | 40 + .../UpdateSharedLinkOnFolderQueryParams.java | 14 + .../UpdateSharedLinkOnFolderRequestBody.java | 64 + ...olderRequestBodySharedLinkAccessField.java | 66 + ...inkOnFolderRequestBodySharedLinkField.java | 169 + ...RequestBodySharedLinkPermissionsField.java | 110 + .../AddShareLinkToWebLinkHeaders.java | 40 + .../AddShareLinkToWebLinkQueryParams.java | 14 + .../AddShareLinkToWebLinkRequestBody.java | 64 + ...bLinkRequestBodySharedLinkAccessField.java | 64 + ...nkToWebLinkRequestBodySharedLinkField.java | 170 + ...RequestBodySharedLinkPermissionsField.java | 109 + .../FindWebLinkForSharedLinkHeaders.java | 65 + .../FindWebLinkForSharedLinkQueryParams.java | 32 + .../GetSharedLinkForWebLinkHeaders.java | 40 + .../GetSharedLinkForWebLinkQueryParams.java | 14 + .../RemoveSharedLinkFromWebLinkHeaders.java | 40 + ...emoveSharedLinkFromWebLinkQueryParams.java | 14 + ...emoveSharedLinkFromWebLinkRequestBody.java | 67 + ...FromWebLinkRequestBodySharedLinkField.java | 17 + .../SharedLinksWebLinksManager.java | 300 ++ .../UpdateSharedLinkOnWebLinkHeaders.java | 40 + .../UpdateSharedLinkOnWebLinkQueryParams.java | 14 + .../UpdateSharedLinkOnWebLinkRequestBody.java | 64 + ...bLinkRequestBodySharedLinkAccessField.java | 67 + ...nkOnWebLinkRequestBodySharedLinkField.java | 171 + ...RequestBodySharedLinkPermissionsField.java | 110 + ...ShieldInformationBarrierReportHeaders.java | 40 + ...ldInformationBarrierReportByIdHeaders.java | 40 + ...hieldInformationBarrierReportsHeaders.java | 40 + ...dInformationBarrierReportsQueryParams.java | 59 + ...hieldInformationBarrierReportsManager.java | 163 + ...CreateShieldInformationBarrierHeaders.java | 40 + ...teShieldInformationBarrierRequestBody.java | 46 + ...etShieldInformationBarrierByIdHeaders.java | 40 + .../GetShieldInformationBarriersHeaders.java | 40 + ...tShieldInformationBarriersQueryParams.java | 44 + .../ShieldInformationBarriersManager.java | 196 + ...ShieldInformationBarrierStatusHeaders.java | 40 + ...ldInformationBarrierStatusRequestBody.java | 81 + ...onBarrierStatusRequestBodyStatusField.java | 66 + ...nformationBarrierSegmentMemberHeaders.java | 40 + ...mationBarrierSegmentMemberRequestBody.java | 157 + ...yShieldInformationBarrierSegmentField.java | 127 + ...eldInformationBarrierSegmentTypeField.java | 81 + ...rierSegmentMemberRequestBodyTypeField.java | 66 + ...mationBarrierSegmentMemberByIdHeaders.java | 40 + ...mationBarrierSegmentMemberByIdHeaders.java | 40 + ...formationBarrierSegmentMembersHeaders.java | 40 + ...ationBarrierSegmentMembersQueryParams.java | 60 + ...formationBarrierSegmentMembersManager.java | 193 + ...ationBarrierSegmentRestrictionHeaders.java | 40 + ...nBarrierSegmentRestrictionRequestBody.java | 179 + ...tionRequestBodyRestrictedSegmentField.java | 121 + ...RequestBodyRestrictedSegmentTypeField.java | 80 + ...yShieldInformationBarrierSegmentField.java | 127 + ...eldInformationBarrierSegmentTypeField.java | 81 + ...egmentRestrictionRequestBodyTypeField.java | 69 + ...nBarrierSegmentRestrictionByIdHeaders.java | 40 + ...nBarrierSegmentRestrictionByIdHeaders.java | 40 + ...tionBarrierSegmentRestrictionsHeaders.java | 40 + ...BarrierSegmentRestrictionsQueryParams.java | 60 + ...tionBarrierSegmentRestrictionsManager.java | 199 + ...hieldInformationBarrierSegmentHeaders.java | 40 + ...dInformationBarrierSegmentRequestBody.java | 109 + ...dInformationBarrierSegmentByIdHeaders.java | 40 + ...dInformationBarrierSegmentByIdHeaders.java | 40 + ...ieldInformationBarrierSegmentsHeaders.java | 40 + ...InformationBarrierSegmentsQueryParams.java | 59 + ...ieldInformationBarrierSegmentsManager.java | 241 ++ ...dInformationBarrierSegmentByIdHeaders.java | 40 + ...ormationBarrierSegmentByIdRequestBody.java | 87 + .../CreateShieldListV2025R0Headers.java | 63 + .../DeleteShieldListByIdV2025R0Headers.java | 63 + .../GetShieldListByIdV2025R0Headers.java | 63 + .../GetShieldListsV2025R0Headers.java | 63 + .../shieldlists/ShieldListsManager.java | 222 + .../UpdateShieldListByIdV2025R0Headers.java | 63 + .../CancelSignRequestHeaders.java | 40 + .../CreateSignRequestHeaders.java | 40 + .../GetSignRequestByIdHeaders.java | 40 + .../signrequests/GetSignRequestsHeaders.java | 40 + .../GetSignRequestsQueryParams.java | 74 + .../ResendSignRequestHeaders.java | 40 + .../signrequests/SignRequestsManager.java | 211 + .../GetSignTemplateByIdHeaders.java | 40 + .../GetSignTemplatesHeaders.java | 40 + .../GetSignTemplatesQueryParams.java | 44 + .../signtemplates/SignTemplatesManager.java | 130 + .../CreateBoxSkillCardsOnFileHeaders.java | 40 + .../CreateBoxSkillCardsOnFileRequestBody.java | 45 + .../DeleteBoxSkillCardsFromFileHeaders.java | 40 + .../skills/GetBoxSkillCardsOnFileHeaders.java | 40 + .../sdkgen/managers/skills/SkillsManager.java | 212 + .../UpdateAllSkillCardsOnFileHeaders.java | 40 + .../UpdateAllSkillCardsOnFileRequestBody.java | 176 + ...lSkillCardsOnFileRequestBodyFileField.java | 101 + ...llCardsOnFileRequestBodyFileTypeField.java | 62 + ...ardsOnFileRequestBodyFileVersionField.java | 102 + ...OnFileRequestBodyFileVersionTypeField.java | 64 + ...llCardsOnFileRequestBodyMetadataField.java | 65 + ...killCardsOnFileRequestBodyStatusField.java | 66 + ...SkillCardsOnFileRequestBodyUsageField.java | 85 + .../UpdateBoxSkillCardsOnFileHeaders.java | 40 + .../UpdateBoxSkillCardsOnFileRequestBody.java | 145 + ...BoxSkillCardsOnFileRequestBodyOpField.java | 62 + .../GetStoragePoliciesHeaders.java | 40 + .../GetStoragePoliciesQueryParams.java | 60 + .../GetStoragePolicyByIdHeaders.java | 40 + .../StoragePoliciesManager.java | 132 + .../CreateStoragePolicyAssignmentHeaders.java | 40 + ...ateStoragePolicyAssignmentRequestBody.java | 65 + ...yAssignmentRequestBodyAssignedToField.java | 80 + ...ignmentRequestBodyAssignedToTypeField.java | 66 + ...signmentRequestBodyStoragePolicyField.java | 111 + ...mentRequestBodyStoragePolicyTypeField.java | 66 + ...eteStoragePolicyAssignmentByIdHeaders.java | 40 + ...GetStoragePolicyAssignmentByIdHeaders.java | 40 + .../GetStoragePolicyAssignmentsHeaders.java | 40 + ...etStoragePolicyAssignmentsQueryParams.java | 83 + ...nmentsQueryParamsResolvedForTypeField.java | 66 + .../StoragePolicyAssignmentsManager.java | 214 + ...ateStoragePolicyAssignmentByIdHeaders.java | 40 + ...toragePolicyAssignmentByIdRequestBody.java | 51 + ...mentByIdRequestBodyStoragePolicyField.java | 113 + ...ByIdRequestBodyStoragePolicyTypeField.java | 67 + .../CreateTaskAssignmentHeaders.java | 40 + .../CreateTaskAssignmentRequestBody.java | 61 + ...askAssignmentRequestBodyAssignToField.java | 85 + ...ateTaskAssignmentRequestBodyTaskField.java | 108 + ...askAssignmentRequestBodyTaskTypeField.java | 62 + .../DeleteTaskAssignmentByIdHeaders.java | 40 + .../GetTaskAssignmentByIdHeaders.java | 40 + .../GetTaskAssignmentsHeaders.java | 40 + .../TaskAssignmentsManager.java | 214 + .../UpdateTaskAssignmentByIdHeaders.java | 40 + .../UpdateTaskAssignmentByIdRequestBody.java | 106 + ...ntByIdRequestBodyResolutionStateField.java | 66 + .../managers/tasks/CreateTaskHeaders.java | 40 + .../managers/tasks/CreateTaskRequestBody.java | 177 + .../CreateTaskRequestBodyActionField.java | 63 + ...ateTaskRequestBodyCompletionRuleField.java | 63 + .../tasks/CreateTaskRequestBodyItemField.java | 97 + .../CreateTaskRequestBodyItemTypeField.java | 62 + .../managers/tasks/DeleteTaskByIdHeaders.java | 40 + .../managers/tasks/GetFileTasksHeaders.java | 40 + .../managers/tasks/GetTaskByIdHeaders.java | 40 + .../sdkgen/managers/tasks/TasksManager.java | 200 + .../managers/tasks/UpdateTaskByIdHeaders.java | 40 + .../tasks/UpdateTaskByIdRequestBody.java | 160 + .../UpdateTaskByIdRequestBodyActionField.java | 63 + ...askByIdRequestBodyCompletionRuleField.java | 63 + .../CreateTermsOfServiceHeaders.java | 40 + .../CreateTermsOfServiceRequestBody.java | 143 + ...eTermsOfServiceRequestBodyStatusField.java | 63 + ...TermsOfServiceRequestBodyTosTypeField.java | 63 + .../GetTermsOfServiceByIdHeaders.java | 40 + .../GetTermsOfServiceHeaders.java | 40 + .../GetTermsOfServiceQueryParams.java | 37 + ...TermsOfServiceQueryParamsTosTypeField.java | 63 + .../TermsOfServicesManager.java | 187 + .../UpdateTermsOfServiceByIdHeaders.java | 40 + .../UpdateTermsOfServiceByIdRequestBody.java | 78 + ...msOfServiceByIdRequestBodyStatusField.java | 63 + ...ateTermsOfServiceStatusForUserHeaders.java | 40 + ...ermsOfServiceStatusForUserRequestBody.java | 76 + ...rviceStatusForUserRequestBodyTosField.java | 110 + ...eStatusForUserRequestBodyTosTypeField.java | 64 + ...viceStatusForUserRequestBodyUserField.java | 110 + ...StatusForUserRequestBodyUserTypeField.java | 65 + .../GetTermsOfServiceUserStatusesHeaders.java | 40 + ...TermsOfServiceUserStatusesQueryParams.java | 45 + .../TermsOfServiceUserStatusesManager.java | 164 + ...ermsOfServiceStatusForUserByIdHeaders.java | 40 + ...OfServiceStatusForUserByIdRequestBody.java | 50 + .../managers/transfer/TransferManager.java | 121 + .../transfer/TransferOwnedFolderHeaders.java | 40 + .../TransferOwnedFolderQueryParams.java | 46 + .../TransferOwnedFolderRequestBody.java | 45 + ...ferOwnedFolderRequestBodyOwnedByField.java | 44 + .../DeleteTrashedFileByIdHeaders.java | 40 + .../GetTrashedFileByIdHeaders.java | 40 + .../GetTrashedFileByIdQueryParams.java | 32 + .../RestoreFileFromTrashHeaders.java | 40 + .../RestoreFileFromTrashQueryParams.java | 32 + .../RestoreFileFromTrashRequestBody.java | 84 + ...reFileFromTrashRequestBodyParentField.java | 63 + .../trashedfiles/TrashedFilesManager.java | 219 + .../DeleteTrashedFolderByIdHeaders.java | 40 + .../GetTrashedFolderByIdHeaders.java | 40 + .../GetTrashedFolderByIdQueryParams.java | 32 + .../RestoreFolderFromTrashHeaders.java | 40 + .../RestoreFolderFromTrashQueryParams.java | 32 + .../RestoreFolderFromTrashRequestBody.java | 84 + ...FolderFromTrashRequestBodyParentField.java | 63 + .../trashedfolders/TrashedFoldersManager.java | 222 + .../trasheditems/GetTrashedItemsHeaders.java | 40 + .../GetTrashedItemsQueryParams.java | 127 + ...TrashedItemsQueryParamsDirectionField.java | 63 + .../GetTrashedItemsQueryParamsSortField.java | 64 + .../trasheditems/TrashedItemsManager.java | 109 + .../DeleteTrashedWebLinkByIdHeaders.java | 40 + .../GetTrashedWebLinkByIdHeaders.java | 40 + .../GetTrashedWebLinkByIdQueryParams.java | 32 + .../RestoreWeblinkFromTrashHeaders.java | 40 + .../RestoreWeblinkFromTrashQueryParams.java | 32 + .../RestoreWeblinkFromTrashRequestBody.java | 84 + ...eblinkFromTrashRequestBodyParentField.java | 63 + .../TrashedWebLinksManager.java | 223 + .../PreflightFileUploadCheckHeaders.java | 40 + .../PreflightFileUploadCheckRequestBody.java | 104 + ...FileUploadCheckRequestBodyParentField.java | 63 + .../managers/uploads/UploadFileHeaders.java | 54 + .../uploads/UploadFileQueryParams.java | 32 + .../uploads/UploadFileRequestBody.java | 72 + .../UploadFileRequestBodyAttributesField.java | 134 + ...dFileRequestBodyAttributesParentField.java | 44 + .../uploads/UploadFileVersionHeaders.java | 68 + .../uploads/UploadFileVersionQueryParams.java | 32 + .../uploads/UploadFileVersionRequestBody.java | 73 + ...FileVersionRequestBodyAttributesField.java | 95 + .../UploadWithPreflightCheckHeaders.java | 54 + .../UploadWithPreflightCheckQueryParams.java | 32 + .../UploadWithPreflightCheckRequestBody.java | 74 + ...flightCheckRequestBodyAttributesField.java | 153 + ...CheckRequestBodyAttributesParentField.java | 44 + .../managers/uploads/UploadsManager.java | 294 ++ .../CreateCollaborationHeaders.java | 40 + .../CreateCollaborationQueryParams.java | 46 + .../CreateCollaborationRequestBody.java | 202 + ...aborationRequestBodyAccessibleByField.java | 130 + ...ationRequestBodyAccessibleByTypeField.java | 63 + ...eateCollaborationRequestBodyItemField.java | 100 + ...CollaborationRequestBodyItemTypeField.java | 63 + ...eateCollaborationRequestBodyRoleField.java | 68 + .../DeleteCollaborationByIdHeaders.java | 40 + .../GetCollaborationByIdHeaders.java | 40 + .../GetCollaborationByIdQueryParams.java | 32 + .../UpdateCollaborationByIdHeaders.java | 40 + .../UpdateCollaborationByIdRequestBody.java | 166 + ...CollaborationByIdRequestBodyRoleField.java | 69 + ...llaborationByIdRequestBodyStatusField.java | 64 + .../UserCollaborationsManager.java | 213 + .../managers/users/CreateUserHeaders.java | 40 + .../managers/users/CreateUserQueryParams.java | 32 + .../managers/users/CreateUserRequestBody.java | 442 ++ .../users/CreateUserRequestBodyRoleField.java | 63 + .../CreateUserRequestBodyStatusField.java | 65 + .../managers/users/DeleteUserByIdHeaders.java | 40 + .../users/DeleteUserByIdQueryParams.java | 44 + .../managers/users/GetUserByIdHeaders.java | 40 + .../users/GetUserByIdQueryParams.java | 32 + .../managers/users/GetUserMeHeaders.java | 40 + .../managers/users/GetUserMeQueryParams.java | 32 + .../managers/users/GetUsersHeaders.java | 40 + .../managers/users/GetUsersQueryParams.java | 136 + .../GetUsersQueryParamsUserTypeField.java | 64 + .../managers/users/UpdateUserByIdHeaders.java | 40 + .../users/UpdateUserByIdQueryParams.java | 32 + .../users/UpdateUserByIdRequestBody.java | 511 +++ ...ByIdRequestBodyNotificationEmailField.java | 63 + .../UpdateUserByIdRequestBodyRoleField.java | 63 + .../UpdateUserByIdRequestBodyStatusField.java | 65 + .../sdkgen/managers/users/UsersManager.java | 324 ++ .../webhooks/CreateWebhookHeaders.java | 40 + .../webhooks/CreateWebhookRequestBody.java | 145 + .../CreateWebhookRequestBodyTargetField.java | 100 + ...eateWebhookRequestBodyTargetTypeField.java | 63 + ...CreateWebhookRequestBodyTriggersField.java | 104 + .../webhooks/DeleteWebhookByIdHeaders.java | 40 + .../webhooks/GetWebhookByIdHeaders.java | 40 + .../managers/webhooks/GetWebhooksHeaders.java | 40 + .../webhooks/GetWebhooksQueryParams.java | 44 + .../webhooks/UpdateWebhookByIdHeaders.java | 40 + .../UpdateWebhookByIdRequestBody.java | 176 + ...dateWebhookByIdRequestBodyTargetField.java | 100 + ...WebhookByIdRequestBodyTargetTypeField.java | 63 + ...teWebhookByIdRequestBodyTriggersField.java | 104 + .../managers/webhooks/WebhooksManager.java | 278 ++ .../weblinks/CreateWebLinkHeaders.java | 40 + .../weblinks/CreateWebLinkRequestBody.java | 124 + .../CreateWebLinkRequestBodyParentField.java | 43 + .../weblinks/DeleteWebLinkByIdHeaders.java | 40 + .../weblinks/GetWebLinkByIdHeaders.java | 54 + .../weblinks/UpdateWebLinkByIdHeaders.java | 40 + .../UpdateWebLinkByIdRequestBody.java | 144 + ...dateWebLinkByIdRequestBodyParentField.java | 86 + ...kByIdRequestBodySharedLinkAccessField.java | 64 + ...WebLinkByIdRequestBodySharedLinkField.java | 149 + .../managers/weblinks/WebLinksManager.java | 181 + .../workflows/GetWorkflowsHeaders.java | 40 + .../workflows/GetWorkflowsQueryParams.java | 73 + .../workflows/StartWorkflowHeaders.java | 40 + .../workflows/StartWorkflowRequestBody.java | 158 + .../StartWorkflowRequestBodyFilesField.java | 100 + ...tartWorkflowRequestBodyFilesTypeField.java | 62 + .../StartWorkflowRequestBodyFlowField.java | 84 + .../StartWorkflowRequestBodyFolderField.java | 100 + ...artWorkflowRequestBodyFolderTypeField.java | 62 + .../StartWorkflowRequestBodyTypeField.java | 62 + .../managers/workflows/WorkflowsManager.java | 123 + .../CreateZipDownloadHeaders.java | 40 + .../zipdownloads/DownloadZipHeaders.java | 40 + .../GetZipDownloadContentHeaders.java | 40 + .../GetZipDownloadStatusHeaders.java | 40 + .../zipdownloads/ZipDownloadsManager.java | 149 + .../networking/auth/Authentication.java | 27 + .../sdkgen/networking/baseurls/BaseUrls.java | 99 + .../boxnetworkclient/BoxNetworkClient.java | 393 ++ .../DefaultNetworkClient.java | 293 ++ .../networking/fetchoptions/FetchOptions.java | 201 + .../fetchoptions/MultipartItem.java | 90 + .../fetchoptions/ResponseFormat.java | 61 + .../fetchresponse/FetchResponse.java | 88 + .../networking/interceptors/Interceptor.java | 11 + .../networking/network/NetworkSession.java | 240 + .../networkclient/NetworkClient.java | 9 + .../networking/proxyconfig/ProxyConfig.java | 59 + .../networking/retries/BoxRetryStrategy.java | 134 + .../networking/retries/RetryStrategy.java | 11 + .../sdkgen/networking/version/Version.java | 8 + .../BoxVersionHeaderV2025R0.java | 62 + .../schemas/accesstoken/AccessToken.java | 190 + .../AccessTokenIssuedTokenTypeField.java | 62 + .../AccessTokenTokenTypeField.java | 62 + .../box/sdkgen/schemas/aiagent/AiAgent.java | 107 + .../AiAgentAllowedEntity.java | 83 + .../sdkgen/schemas/aiagentask/AiAgentAsk.java | 233 + .../aiagentask/AiAgentAskTypeField.java | 60 + .../AiAgentBasicGenTool.java | 170 + .../AiAgentBasicTextTool.java | 150 + .../AiAgentBasicTextToolBase.java | 132 + .../AiAgentBasicTextToolTextGen.java | 150 + .../aiagentextract/AiAgentExtract.java | 146 + .../AiAgentExtractTypeField.java | 62 + .../AiAgentExtractStructured.java | 151 + .../AiAgentExtractStructuredTypeField.java | 62 + .../schemas/aiagentinfo/AiAgentInfo.java | 85 + .../aiagentinfo/AiAgentInfoModelsField.java | 106 + .../AiAgentLongTextTool.java | 155 + .../AiAgentLongTextToolEmbeddingsField.java | 84 + ...ntLongTextToolEmbeddingsStrategyField.java | 88 + .../AiAgentLongTextToolTextGen.java | 155 + ...entLongTextToolTextGenEmbeddingsField.java | 85 + ...extToolTextGenEmbeddingsStrategyField.java | 88 + .../aiagentreference/AiAgentReference.java | 92 + .../AiAgentReferenceTypeField.java | 62 + .../AiAgentSpreadsheetTool.java | 132 + .../aiagenttextgen/AiAgentTextGen.java | 96 + .../AiAgentTextGenTypeField.java | 62 + .../com/box/sdkgen/schemas/aiask/AiAsk.java | 198 + .../sdkgen/schemas/aiask/AiAskModeField.java | 60 + .../sdkgen/schemas/aiaskagent/AiAskAgent.java | 74 + .../sdkgen/schemas/aicitation/AiCitation.java | 133 + .../aicitation/AiCitationTypeField.java | 60 + .../aidialoguehistory/AiDialogueHistory.java | 112 + .../sdkgen/schemas/aiextract/AiExtract.java | 120 + .../aiextractagent/AiExtractAgent.java | 75 + .../aiextractresponse/AiExtractResponse.java | 17 + .../AiExtractStructured.java | 142 + .../AiExtractStructuredFieldsField.java | 164 + ...AiExtractStructuredFieldsOptionsField.java | 43 + ...xtractStructuredMetadataTemplateField.java | 122 + ...ctStructuredMetadataTemplateTypeField.java | 62 + .../AiExtractStructuredAgent.java | 78 + .../AiExtractStructuredResponse.java | 135 + .../sdkgen/schemas/aiitemask/AiItemAsk.java | 121 + .../schemas/aiitemask/AiItemAskTypeField.java | 61 + .../sdkgen/schemas/aiitembase/AiItemBase.java | 118 + .../aiitembase/AiItemBaseTypeField.java | 60 + .../AiLlmEndpointParams.java | 136 + .../AiLlmEndpointParamsAws.java | 132 + .../AiLlmEndpointParamsAwsTypeField.java | 62 + .../AiLlmEndpointParamsGoogle.java | 155 + .../AiLlmEndpointParamsGoogleTypeField.java | 62 + .../AiLlmEndpointParamsIbm.java | 154 + .../AiLlmEndpointParamsIbmTypeField.java | 62 + .../AiLlmEndpointParamsOpenAi.java | 197 + .../AiLlmEndpointParamsOpenAiTypeField.java | 62 + .../AiMultipleAgentResponse.java | 134 + .../sdkgen/schemas/airesponse/AiResponse.java | 133 + .../airesponsefull/AiResponseFull.java | 107 + .../AiSingleAgentResponse.java | 292 ++ .../AiSingleAgentResponseTypeField.java | 62 + .../AiSingleAgentResponseFull.java | 239 + .../aistudioagentask/AiStudioAgentAsk.java | 317 ++ .../AiStudioAgentAskTypeField.java | 62 + .../AiStudioAgentAskResponse.java | 322 ++ .../AiStudioAgentAskResponseTypeField.java | 62 + .../AiStudioAgentBasicGenTool.java | 182 + .../AiStudioAgentBasicGenToolResponse.java | 193 + .../AiStudioAgentBasicTextTool.java | 157 + .../AiStudioAgentBasicTextToolResponse.java | 168 + .../AiStudioAgentExtract.java | 210 + .../AiStudioAgentExtractTypeField.java | 62 + .../AiStudioAgentExtractResponse.java | 214 + ...AiStudioAgentExtractResponseTypeField.java | 62 + .../AiStudioAgentLongTextTool.java | 170 + .../AiStudioAgentLongTextToolResponse.java | 181 + .../AiStudioAgentSpreadsheetTool.java | 108 + .../AiStudioAgentSpreadsheetToolResponse.java | 128 + .../AiStudioAgentTextGen.java | 190 + .../AiStudioAgentTextGenTypeField.java | 62 + .../AiStudioAgentTextGenResponse.java | 194 + ...AiStudioAgentTextGenResponseTypeField.java | 62 + .../sdkgen/schemas/aitextgen/AiTextGen.java | 141 + .../aitextgen/AiTextGenItemsField.java | 118 + .../aitextgen/AiTextGenItemsTypeField.java | 62 + .../aitextgenagent/AiTextGenAgent.java | 75 + .../box/sdkgen/schemas/appitem/AppItem.java | 117 + .../schemas/appitem/AppItemTypeField.java | 60 + .../AppItemAssociatedItem.java | 109 + .../AppItemAssociation.java | 205 + .../AppItemAssociationTypeField.java | 62 + .../AppItemAssociations.java | 133 + .../AppItemEventSource.java | 159 + .../AppItemEventSourceTypeField.java | 62 + .../classification/Classification.java | 220 + .../ClassificationTemplateField.java | 62 + .../ClassificationTemplate.java | 256 ++ ...lassificationTemplateDisplayNameField.java | 62 + ...icationTemplateFieldsDisplayNameField.java | 62 + .../ClassificationTemplateFieldsField.java | 223 + .../ClassificationTemplateFieldsKeyField.java | 62 + ...ssificationTemplateFieldsOptionsField.java | 104 + ...ptionsStaticConfigClassificationField.java | 89 + ...emplateFieldsOptionsStaticConfigField.java | 68 + ...ClassificationTemplateFieldsTypeField.java | 62 + ...lassificationTemplateTemplateKeyField.java | 62 + .../ClassificationTemplateTypeField.java | 62 + .../schemas/clienterror/ClientError.java | 205 + .../clienterror/ClientErrorCodeField.java | 76 + .../clienterror/ClientErrorTypeField.java | 60 + .../schemas/collaboration/Collaboration.java | 440 ++ ...tionAcceptanceRequirementsStatusField.java | 126 + ...sStatusStrongPasswordRequirementField.java | 99 + ...sStatusTermsOfServiceRequirementField.java | 95 + ...oFactorAuthenticationRequirementField.java | 99 + .../collaboration/CollaborationRoleField.java | 69 + .../CollaborationStatusField.java | 64 + .../collaboration/CollaborationTypeField.java | 62 + .../CollaborationAccessGrantee.java | 93 + .../CollaborationAllowlistEntries.java | 133 + .../CollaborationAllowlistEntry.java | 195 + ...aborationAllowlistEntryDirectionField.java | 64 + ...borationAllowlistEntryEnterpriseField.java | 121 + ...tionAllowlistEntryEnterpriseTypeField.java | 62 + .../CollaborationAllowlistEntryTypeField.java | 62 + .../CollaborationAllowlistExemptTarget.java | 187 + ...nAllowlistExemptTargetEnterpriseField.java | 121 + ...owlistExemptTargetEnterpriseTypeField.java | 62 + ...orationAllowlistExemptTargetTypeField.java | 62 + .../CollaborationAllowlistExemptTargets.java | 133 + .../collaborationitem/CollaborationItem.java | 220 + .../collaborations/Collaborations.java | 133 + .../CollaborationsOffsetPaginated.java | 127 + .../CollaboratorVariable.java | 145 + .../CollaboratorVariableTypeField.java | 62 + ...CollaboratorVariableVariableTypeField.java | 62 + ...ollaboratorVariableVariableValueField.java | 108 + ...boratorVariableVariableValueTypeField.java | 62 + .../sdkgen/schemas/collection/Collection.java | 151 + .../CollectionCollectionTypeField.java | 62 + .../collection/CollectionNameField.java | 60 + .../collection/CollectionTypeField.java | 60 + .../schemas/collections/Collections.java | 146 + .../CollectionsOrderDirectionField.java | 63 + .../collections/CollectionsOrderField.java | 96 + .../box/sdkgen/schemas/comment/Comment.java | 204 + .../schemas/comment/CommentItemField.java | 76 + .../schemas/commentbase/CommentBase.java | 86 + .../commentbase/CommentBaseTypeField.java | 60 + .../schemas/commentfull/CommentFull.java | 167 + .../box/sdkgen/schemas/comments/Comments.java | 146 + .../comments/CommentsOrderDirectionField.java | 63 + .../schemas/comments/CommentsOrderField.java | 95 + .../CompletionRuleVariable.java | 175 + .../CompletionRuleVariableTypeField.java | 62 + ...mpletionRuleVariableVariableTypeField.java | 62 + ...pletionRuleVariableVariableValueField.java | 63 + .../schemas/conflicterror/ConflictError.java | 140 + .../ConflictErrorContextInfoField.java | 64 + .../schemas/createaiagent/CreateAiAgent.java | 221 + .../createaiagent/CreateAiAgentTypeField.java | 62 + .../schemas/devicepinner/DevicePinner.java | 137 + .../devicepinner/DevicePinnerTypeField.java | 60 + .../schemas/devicepinners/DevicePinners.java | 127 + .../DevicePinnersOrderByField.java | 62 + .../DevicePinnersOrderDirectionField.java | 63 + .../DevicePinnersOrderField.java | 103 + .../sdkgen/schemas/emailalias/EmailAlias.java | 135 + .../emailalias/EmailAliasTypeField.java | 60 + .../schemas/emailaliases/EmailAliases.java | 88 + .../enterprisebase/EnterpriseBase.java | 86 + .../EnterpriseBaseTypeField.java | 62 + .../com/box/sdkgen/schemas/event/Event.java | 289 ++ .../event/EventAdditionalDetailsField.java | 17 + .../schemas/event/EventEventTypeField.java | 203 + .../com/box/sdkgen/schemas/events/Events.java | 119 + .../events/EventsNextStreamPositionField.java | 67 + .../schemas/eventsource/EventSource.java | 187 + .../EventSourceClassificationField.java | 62 + .../eventsource/EventSourceItemTypeField.java | 63 + .../EventSourceResource.java | 136 + .../com/box/sdkgen/schemas/file/File.java | 486 +++ .../schemas/file/FileItemStatusField.java | 62 + .../schemas/file/FilePathCollectionField.java | 63 + .../file/FileSharedLinkAccessField.java | 64 + .../FileSharedLinkEffectiveAccessField.java | 64 + ...ileSharedLinkEffectivePermissionField.java | 65 + .../schemas/file/FileSharedLinkField.java | 433 ++ .../file/FileSharedLinkPermissionsField.java | 77 + .../box/sdkgen/schemas/filebase/FileBase.java | 120 + .../schemas/filebase/FileBaseTypeField.java | 60 + .../schemas/fileconflict/FileConflict.java | 132 + .../box/sdkgen/schemas/filefull/FileFull.java | 912 ++++ .../FileFullAllowedInviteeRolesField.java | 68 + .../filefull/FileFullClassificationField.java | 104 + .../FileFullExpiringEmbedLinkField.java | 165 + ...leFullExpiringEmbedLinkTokenTypeField.java | 62 + .../filefull/FileFullLockAppTypeField.java | 65 + .../schemas/filefull/FileFullLockField.java | 214 + .../filefull/FileFullLockTypeField.java | 60 + .../filefull/FileFullMetadataField.java | 66 + .../filefull/FileFullPermissionsField.java | 215 + ...ullRepresentationsEntriesContentField.java | 69 + .../FileFullRepresentationsEntriesField.java | 142 + ...leFullRepresentationsEntriesInfoField.java | 62 + ...RepresentationsEntriesPropertiesField.java | 105 + ...FullRepresentationsEntriesStatusField.java | 79 + ...epresentationsEntriesStatusStateField.java | 65 + .../FileFullRepresentationsField.java | 63 + ...eFullSharedLinkPermissionOptionsField.java | 64 + .../filefull/FileFullWatermarkInfoField.java | 64 + .../box/sdkgen/schemas/filemini/FileMini.java | 166 + .../schemas/filerequest/FileRequest.java | 384 ++ .../filerequest/FileRequestStatusField.java | 63 + .../filerequest/FileRequestTypeField.java | 60 + .../FileRequestCopyRequest.java | 143 + .../FileRequestCopyRequestFolderField.java | 102 + ...FileRequestCopyRequestFolderTypeField.java | 62 + .../FileRequestUpdateRequest.java | 184 + .../FileRequestUpdateRequestStatusField.java | 63 + .../com/box/sdkgen/schemas/files/Files.java | 88 + .../schemas/filesonhold/FilesOnHold.java | 133 + .../FilesUnderRetention.java | 133 + .../schemas/fileversion/FileVersion.java | 340 ++ .../fileversionbase/FileVersionBase.java | 90 + .../FileVersionBaseTypeField.java | 62 + .../fileversionfull/FileVersionFull.java | 247 ++ .../FileVersionLegalHold.java | 186 + .../FileVersionLegalHoldTypeField.java | 62 + .../FileVersionLegalHolds.java | 133 + .../fileversionmini/FileVersionMini.java | 94 + .../FileVersionRetention.java | 207 + .../FileVersionRetentionTypeField.java | 62 + .../FileVersionRetentions.java | 133 + .../schemas/fileversions/FileVersions.java | 146 + .../FileVersionsOrderDirectionField.java | 63 + .../fileversions/FileVersionsOrderField.java | 96 + .../com/box/sdkgen/schemas/folder/Folder.java | 511 +++ .../FolderFolderUploadEmailAccessField.java | 63 + .../folder/FolderFolderUploadEmailField.java | 97 + .../schemas/folder/FolderItemStatusField.java | 62 + .../folder/FolderPathCollectionField.java | 63 + .../folder/FolderSharedLinkAccessField.java | 64 + .../FolderSharedLinkEffectiveAccessField.java | 64 + ...derSharedLinkEffectivePermissionField.java | 65 + .../schemas/folder/FolderSharedLinkField.java | 436 ++ .../FolderSharedLinkPermissionsField.java | 77 + .../sdkgen/schemas/folderbase/FolderBase.java | 120 + .../folderbase/FolderBaseTypeField.java | 60 + .../sdkgen/schemas/folderfull/FolderFull.java | 791 ++++ .../FolderFullAllowedInviteeRolesField.java | 68 + ...ullAllowedSharedLinkAccessLevelsField.java | 64 + .../FolderFullClassificationField.java | 104 + .../folderfull/FolderFullMetadataField.java | 66 + .../FolderFullPermissionsField.java | 140 + .../folderfull/FolderFullSyncStateField.java | 64 + .../FolderFullWatermarkInfoField.java | 64 + .../sdkgen/schemas/folderlock/FolderLock.java | 193 + .../FolderLockLockedOperationsField.java | 59 + .../schemas/folderlocks/FolderLocks.java | 111 + .../sdkgen/schemas/foldermini/FolderMini.java | 126 + .../folderreference/FolderReference.java | 90 + .../FolderReferenceTypeField.java | 62 + .../com/box/sdkgen/schemas/group/Group.java | 152 + .../sdkgen/schemas/groupbase/GroupBase.java | 90 + .../schemas/groupbase/GroupBaseTypeField.java | 60 + .../sdkgen/schemas/groupfull/GroupFull.java | 283 ++ .../GroupFullInvitabilityLevelField.java | 64 + .../GroupFullMemberViewabilityLevelField.java | 64 + .../groupfull/GroupFullPermissionsField.java | 68 + .../groupmembership/GroupMembership.java | 208 + .../GroupMembershipRoleField.java | 63 + .../GroupMembershipTypeField.java | 62 + .../groupmemberships/GroupMemberships.java | 146 + .../GroupMembershipsOrderDirectionField.java | 63 + .../GroupMembershipsOrderField.java | 98 + .../sdkgen/schemas/groupmini/GroupMini.java | 123 + .../groupmini/GroupMiniGroupTypeField.java | 63 + .../com/box/sdkgen/schemas/groups/Groups.java | 146 + .../groups/GroupsOrderDirectionField.java | 63 + .../schemas/groups/GroupsOrderField.java | 86 + .../IntegrationMapping.java | 289 ++ ...ntegrationMappingIntegrationTypeField.java | 62 + .../IntegrationMappingBase.java | 96 + .../IntegrationMappingBaseTypeField.java | 62 + .../IntegrationMappingBoxItemSlack.java | 108 + ...tegrationMappingBoxItemSlackTypeField.java | 62 + .../IntegrationMappingPartnerItemSlack.java | 154 + ...ationMappingPartnerItemSlackTypeField.java | 62 + .../IntegrationMappingPartnerItemTeams.java | 94 + ...ationMappingPartnerItemTeamsTypeField.java | 63 + ...nMappingPartnerItemTeamsCreateRequest.java | 114 + ...artnerItemTeamsCreateRequestTypeField.java | 65 + .../IntegrationMappings.java | 111 + .../IntegrationMappingSlackCreateRequest.java | 111 + .../IntegrationMappingSlackOptions.java | 68 + .../IntegrationMappingsTeams.java | 64 + .../IntegrationMappingTeams.java | 226 + ...ationMappingTeamsIntegrationTypeField.java | 62 + .../IntegrationMappingTeamsCreateRequest.java | 65 + .../com/box/sdkgen/schemas/invite/Invite.java | 226 + .../schemas/invite/InviteInvitedToField.java | 114 + .../invite/InviteInvitedToTypeField.java | 62 + .../schemas/invite/InviteTypeField.java | 60 + .../com/box/sdkgen/schemas/item/Item.java | 126 + .../com/box/sdkgen/schemas/items/Items.java | 191 + .../items/ItemsOrderDirectionField.java | 63 + .../sdkgen/schemas/items/ItemsOrderField.java | 86 + .../ItemsOffsetPaginated.java | 146 + ...emsOffsetPaginatedOrderDirectionField.java | 63 + .../ItemsOffsetPaginatedOrderField.java | 100 + .../keywordskillcard/KeywordSkillCard.java | 218 + .../KeywordSkillCardEntriesField.java | 62 + .../KeywordSkillCardInvocationField.java | 106 + .../KeywordSkillCardInvocationTypeField.java | 62 + .../KeywordSkillCardSkillCardTitleField.java | 86 + .../KeywordSkillCardSkillCardTypeField.java | 62 + .../KeywordSkillCardSkillField.java | 94 + .../KeywordSkillCardSkillTypeField.java | 62 + .../KeywordSkillCardTypeField.java | 62 + .../legalholdpolicies/LegalHoldPolicies.java | 133 + .../legalholdpolicy/LegalHoldPolicy.java | 328 ++ .../LegalHoldPolicyAssignmentCountsField.java | 125 + .../LegalHoldPolicyStatusField.java | 65 + .../LegalHoldPolicyAssignedItem.java | 221 + .../LegalHoldPolicyAssignment.java | 206 + .../LegalHoldPolicyAssignmentBase.java | 100 + ...egalHoldPolicyAssignmentBaseTypeField.java | 62 + .../LegalHoldPolicyAssignments.java | 133 + .../LegalHoldPolicyMini.java | 95 + .../LegalHoldPolicyMiniTypeField.java | 62 + .../box/sdkgen/schemas/metadata/Metadata.java | 90 + .../schemas/metadatabase/MetadataBase.java | 128 + .../MetadataCascadePolicies.java | 133 + .../MetadataCascadePolicy.java | 182 + ...dataCascadePolicyOwnerEnterpriseField.java | 101 + ...CascadePolicyOwnerEnterpriseTypeField.java | 62 + .../MetadataCascadePolicyParentField.java | 99 + .../MetadataCascadePolicyParentTypeField.java | 62 + .../MetadataCascadePolicyTypeField.java | 62 + .../schemas/metadataerror/MetadataError.java | 106 + .../MetadataFieldFilterDateRange.java | 84 + .../MetadataFieldFilterFloatRange.java | 76 + .../metadatafilter/MetadataFilter.java | 116 + .../MetadataFilterScopeField.java | 64 + .../MetadataFilterValue.java | 118 + .../schemas/metadatafull/MetadataFull.java | 194 + .../MetadataInstanceValue.java | 96 + .../schemas/metadataquery/MetadataQuery.java | 205 + .../MetadataQueryOrderByDirectionField.java | 63 + .../MetadataQueryOrderByField.java | 99 + .../MetadataQueryResultItem.java | 264 ++ .../MetadataQueryResults.java | 108 + .../sdkgen/schemas/metadatas/Metadatas.java | 78 + .../metadatatemplate/MetadataTemplate.java | 217 + .../MetadataTemplateFieldsField.java | 203 + .../MetadataTemplateFieldsOptionsField.java | 86 + .../MetadataTemplateFieldsTypeField.java | 67 + .../MetadataTemplateTypeField.java | 62 + .../metadatatemplates/MetadataTemplates.java | 133 + .../schemas/oauth2error/OAuth2Error.java | 87 + .../box/sdkgen/schemas/outcome/Outcome.java | 170 + .../postoauth2revoke/PostOAuth2Revoke.java | 107 + .../postoauth2token/PostOAuth2Token.java | 412 ++ .../PostOAuth2TokenActorTokenTypeField.java | 62 + .../PostOAuth2TokenBoxSubjectTypeField.java | 63 + .../PostOAuth2TokenGrantTypeField.java | 67 + .../PostOAuth2TokenSubjectTokenTypeField.java | 62 + .../PostOAuth2TokenRefreshAccessToken.java | 149 + ...TokenRefreshAccessTokenGrantTypeField.java | 62 + .../realtimeserver/RealtimeServer.java | 145 + .../realtimeservers/RealtimeServers.java | 88 + .../sdkgen/schemas/recentitem/RecentItem.java | 181 + .../RecentItemInteractionTypeField.java | 66 + .../RecentItemResource.java | 220 + .../schemas/recentitems/RecentItems.java | 133 + .../box/sdkgen/schemas/resource/Resource.java | 106 + .../schemas/resourcescope/ResourceScope.java | 99 + .../ResourceScopeScopeField.java | 75 + .../retentionpolicies/RetentionPolicies.java | 111 + .../retentionpolicy/RetentionPolicy.java | 386 ++ .../RetentionPolicyAssignmentCountsField.java | 106 + .../RetentionPolicyPolicyTypeField.java | 63 + .../RetentionPolicyRetentionTypeField.java | 63 + .../RetentionPolicyStatusField.java | 63 + .../RetentionPolicyAssignment.java | 244 ++ ...entionPolicyAssignmentAssignedToField.java | 102 + ...onPolicyAssignmentAssignedToTypeField.java | 64 + ...tionPolicyAssignmentFilterFieldsField.java | 88 + .../RetentionPolicyAssignmentTypeField.java | 62 + .../RetentionPolicyAssignments.java | 111 + .../RetentionPolicyBase.java | 95 + .../RetentionPolicyBaseTypeField.java | 62 + .../RetentionPolicyMini.java | 152 + ...ntionPolicyMiniDispositionActionField.java | 63 + .../schemas/rolevariable/RoleVariable.java | 158 + .../rolevariable/RoleVariableTypeField.java | 60 + .../RoleVariableVariableTypeField.java | 62 + .../RoleVariableVariableValueField.java | 68 + .../searchresultitem/SearchResultItem.java | 220 + .../schemas/searchresults/SearchResults.java | 164 + .../searchresults/SearchResultsTypeField.java | 62 + .../SearchResultsResponse.java | 100 + .../SearchResultsWithSharedLinks.java | 172 + ...SearchResultsWithSharedLinksTypeField.java | 62 + .../SearchResultWithSharedLink.java | 125 + .../SearchResultWithSharedLinkItem.java | 224 + .../SessionTerminationMessage.java | 62 + .../ShieldInformationBarrier.java | 287 ++ .../ShieldInformationBarrierStatusField.java | 66 + .../ShieldInformationBarrierTypeField.java | 62 + .../ShieldInformationBarrierBase.java | 100 + ...ShieldInformationBarrierBaseTypeField.java | 62 + .../ShieldInformationBarrierReference.java | 69 + .../ShieldInformationBarrierReport.java | 221 + ...ldInformationBarrierReportStatusField.java | 65 + .../ShieldInformationBarrierReportBase.java | 100 + ...InformationBarrierReportBaseTypeField.java | 62 + ...ShieldInformationBarrierReportDetails.java | 62 + ...ationBarrierReportDetailsDetailsField.java | 69 + .../ShieldInformationBarrierReports.java | 111 + .../ShieldInformationBarriers.java | 111 + .../ShieldInformationBarrierSegment.java | 257 ++ ...eldInformationBarrierSegmentTypeField.java | 62 + ...ShieldInformationBarrierSegmentMember.java | 233 + ...rShieldInformationBarrierSegmentField.java | 115 + ...eldInformationBarrierSegmentTypeField.java | 78 + ...ldInformationBarrierSegmentMemberBase.java | 101 + ...tionBarrierSegmentMemberBaseTypeField.java | 62 + ...ldInformationBarrierSegmentMemberMini.java | 98 + ...hieldInformationBarrierSegmentMembers.java | 111 + ...dInformationBarrierSegmentRestriction.java | 222 + ...ormationBarrierSegmentRestrictionBase.java | 101 + ...arrierSegmentRestrictionBaseTypeField.java | 63 + ...ormationBarrierSegmentRestrictionMini.java | 132 + ...RestrictionMiniRestrictedSegmentField.java | 112 + ...rictionMiniRestrictedSegmentTypeField.java | 70 + ...iShieldInformationBarrierSegmentField.java | 121 + ...eldInformationBarrierSegmentTypeField.java | 80 + ...InformationBarrierSegmentRestrictions.java | 112 + .../ShieldInformationBarrierSegments.java | 111 + .../schemas/signrequest/SignRequest.java | 541 +++ .../SignRequestSignFilesField.java | 89 + .../signrequest/SignRequestStatusField.java | 73 + .../signrequest/SignRequestTypeField.java | 60 + .../signrequestbase/SignRequestBase.java | 339 ++ .../SignRequestCreateRequest.java | 324 ++ ...questCreateRequestSignatureColorField.java | 64 + .../SignRequestCreateSigner.java | 325 ++ .../SignRequestCreateSignerRoleField.java | 64 + .../SignRequestPrefillTag.java | 143 + .../schemas/signrequests/SignRequests.java | 111 + .../signrequestsigner/SignRequestSigner.java | 321 ++ .../SignRequestSignerSignerDecisionField.java | 130 + ...nRequestSignerSignerDecisionTypeField.java | 63 + .../SignRequestSignerInput.java | 202 + ...ignRequestSignerInputContentTypeField.java | 76 + .../SignRequestSignerInputTypeField.java | 67 + .../schemas/signtemplate/SignTemplate.java | 427 ++ .../SignTemplateAdditionalInfoField.java | 159 + ...emplateAdditionalInfoNonEditableField.java | 67 + ...gnTemplateAdditionalInfoRequiredField.java | 146 + ...ateAdditionalInfoRequiredSignersField.java | 62 + .../SignTemplateCustomBrandingField.java | 137 + .../SignTemplateReadySignLinkField.java | 170 + .../signtemplate/SignTemplateTypeField.java | 60 + .../schemas/signtemplates/SignTemplates.java | 133 + .../sdkgen/schemas/skillcard/SkillCard.java | 128 + .../SkillCardsMetadata.java | 229 + .../statusskillcard/StatusSkillCard.java | 216 + .../StatusSkillCardInvocationField.java | 105 + .../StatusSkillCardInvocationTypeField.java | 62 + .../StatusSkillCardSkillCardTitleField.java | 86 + .../StatusSkillCardSkillCardTypeField.java | 62 + .../StatusSkillCardSkillField.java | 94 + .../StatusSkillCardSkillTypeField.java | 62 + .../StatusSkillCardStatusCodeField.java | 66 + .../StatusSkillCardStatusField.java | 104 + .../StatusSkillCardTypeField.java | 62 + .../storagepolicies/StoragePolicies.java | 133 + .../schemas/storagepolicy/StoragePolicy.java | 94 + .../StoragePolicyAssignment.java | 146 + ...toragePolicyAssignmentAssignedToField.java | 84 + .../StoragePolicyAssignmentTypeField.java | 62 + .../StoragePolicyAssignments.java | 133 + .../storagepolicymini/StoragePolicyMini.java | 92 + .../StoragePolicyMiniTypeField.java | 62 + .../com/box/sdkgen/schemas/task/Task.java | 307 ++ .../sdkgen/schemas/task/TaskActionField.java | 61 + .../schemas/task/TaskCompletionRuleField.java | 63 + .../sdkgen/schemas/task/TaskTypeField.java | 59 + .../taskassignment/TaskAssignment.java | 285 ++ .../TaskAssignmentResolutionStateField.java | 65 + .../TaskAssignmentTypeField.java | 62 + .../taskassignments/TaskAssignments.java | 88 + .../com/box/sdkgen/schemas/tasks/Tasks.java | 88 + .../templatesigner/TemplateSigner.java | 297 ++ .../TemplateSignerRoleField.java | 64 + .../TemplateSignerInput.java | 359 ++ .../TemplateSignerInputContentTypeField.java | 76 + .../TemplateSignerInputCoordinatesField.java | 84 + .../TemplateSignerInputDimensionsField.java | 84 + .../TemplateSignerInputTypeField.java | 68 + .../termsofservice/TermsOfService.java | 214 + .../TermsOfServiceEnterpriseField.java | 116 + .../TermsOfServiceEnterpriseTypeField.java | 62 + .../TermsOfServiceStatusField.java | 63 + .../TermsOfServiceTosTypeField.java | 63 + .../TermsOfServiceBase.java | 94 + .../TermsOfServiceBaseTypeField.java | 62 + .../termsofservices/TermsOfServices.java | 88 + .../TermsOfServiceUserStatus.java | 211 + .../TermsOfServiceUserStatusTypeField.java | 62 + .../TermsOfServiceUserStatuses.java | 88 + .../timelineskillcard/TimelineSkillCard.java | 240 + .../TimelineSkillCardEntriesAppearsField.java | 84 + .../TimelineSkillCardEntriesField.java | 107 + .../TimelineSkillCardInvocationField.java | 107 + .../TimelineSkillCardInvocationTypeField.java | 62 + .../TimelineSkillCardSkillCardTitleField.java | 86 + .../TimelineSkillCardSkillCardTypeField.java | 62 + .../TimelineSkillCardSkillField.java | 102 + .../TimelineSkillCardSkillTypeField.java | 62 + .../TimelineSkillCardTypeField.java | 62 + .../schemas/trackingcode/TrackingCode.java | 114 + .../trackingcode/TrackingCodeTypeField.java | 60 + .../TranscriptSkillCard.java | 244 ++ ...ranscriptSkillCardEntriesAppearsField.java | 62 + .../TranscriptSkillCardEntriesField.java | 85 + .../TranscriptSkillCardInvocationField.java | 108 + ...ranscriptSkillCardInvocationTypeField.java | 62 + ...ranscriptSkillCardSkillCardTitleField.java | 86 + ...TranscriptSkillCardSkillCardTypeField.java | 62 + .../TranscriptSkillCardSkillField.java | 104 + .../TranscriptSkillCardSkillTypeField.java | 62 + .../TranscriptSkillCardTypeField.java | 62 + .../sdkgen/schemas/trashfile/TrashFile.java | 592 +++ .../trashfile/TrashFileItemStatusField.java | 64 + .../TrashFilePathCollectionEntriesField.java | 164 + ...ashFilePathCollectionEntriesTypeField.java | 62 + .../TrashFilePathCollectionField.java | 62 + .../schemas/trashfile/TrashFileTypeField.java | 60 + .../trashfilerestored/TrashFileRestored.java | 590 +++ .../TrashFileRestoredItemStatusField.java | 64 + .../TrashFileRestoredPathCollectionField.java | 63 + .../TrashFileRestoredTypeField.java | 62 + .../schemas/trashfolder/TrashFolder.java | 571 +++ .../TrashFolderItemStatusField.java | 64 + ...TrashFolderPathCollectionEntriesField.java | 164 + ...hFolderPathCollectionEntriesTypeField.java | 62 + .../TrashFolderPathCollectionField.java | 62 + .../trashfolder/TrashFolderTypeField.java | 60 + .../TrashFolderRestored.java | 533 +++ .../TrashFolderRestoredItemStatusField.java | 64 + ...rashFolderRestoredPathCollectionField.java | 63 + .../TrashFolderRestoredTypeField.java | 62 + .../schemas/trashweblink/TrashWebLink.java | 456 ++ .../TrashWebLinkItemStatusField.java | 64 + ...rashWebLinkPathCollectionEntriesField.java | 164 + ...WebLinkPathCollectionEntriesTypeField.java | 62 + .../TrashWebLinkPathCollectionField.java | 62 + .../trashweblink/TrashWebLinkTypeField.java | 60 + .../TrashWebLinkRestored.java | 457 ++ .../TrashWebLinkRestoredItemStatusField.java | 64 + ...ashWebLinkRestoredPathCollectionField.java | 63 + .../TrashWebLinkRestoredTypeField.java | 62 + .../schemas/uploadedpart/UploadedPart.java | 63 + .../sdkgen/schemas/uploadpart/UploadPart.java | 98 + .../uploadpartmini/UploadPartMini.java | 106 + .../schemas/uploadparts/UploadParts.java | 146 + .../UploadPartsOrderDirectionField.java | 63 + .../uploadparts/UploadPartsOrderField.java | 96 + .../schemas/uploadsession/UploadSession.java | 201 + .../UploadSessionSessionEndpointsField.java | 165 + .../uploadsession/UploadSessionTypeField.java | 62 + .../sdkgen/schemas/uploadurl/UploadUrl.java | 88 + .../com/box/sdkgen/schemas/user/User.java | 387 ++ .../user/UserNotificationEmailField.java | 86 + .../sdkgen/schemas/user/UserStatusField.java | 63 + .../sdkgen/schemas/useravatar/UserAvatar.java | 64 + .../useravatar/UserAvatarPicUrlsField.java | 104 + .../box/sdkgen/schemas/userbase/UserBase.java | 90 + .../schemas/userbase/UserBaseTypeField.java | 60 + .../UserCollaborations.java | 133 + .../box/sdkgen/schemas/userfull/UserFull.java | 527 +++ .../userfull/UserFullEnterpriseField.java | 115 + .../userfull/UserFullEnterpriseTypeField.java | 62 + .../schemas/userfull/UserFullRoleField.java | 62 + .../UserIntegrationMappings.java | 113 + .../box/sdkgen/schemas/usermini/UserMini.java | 113 + .../com/box/sdkgen/schemas/users/Users.java | 191 + .../users/UsersOrderDirectionField.java | 63 + .../sdkgen/schemas/users/UsersOrderField.java | 86 + .../archivesv2025r0/ArchivesV2025R0.java | 111 + .../archivev2025r0/ArchiveV2025R0.java | 134 + .../ArchiveV2025R0TypeField.java | 62 + .../ClientErrorV2025R0.java | 207 + .../ClientErrorV2025R0CodeField.java | 78 + .../ClientErrorV2025R0TypeField.java | 62 + .../DocGenBatchBaseV2025R0.java | 96 + .../DocGenBatchBaseV2025R0TypeField.java | 62 + .../DocGenBatchCreateRequestV2025R0.java | 173 + ...eRequestV2025R0DestinationFolderField.java | 110 + ...uestV2025R0DestinationFolderTypeField.java | 65 + .../DocGenDocumentGenerationDataV2025R0.java | 64 + .../DocGenJobBaseV2025R0.java | 94 + .../DocGenJobBaseV2025R0TypeField.java | 62 + .../DocGenJobFullV2025R0.java | 260 ++ .../DocGenJobsFullV2025R0.java | 133 + .../docgenjobsv2025r0/DocGenJobsV2025R0.java | 133 + .../docgenjobv2025r0/DocGenJobV2025R0.java | 257 ++ .../DocGenJobV2025R0StatusField.java | 66 + .../DocGenTagsProcessingMessageV2025R0.java | 43 + .../docgentagsv2025r0/DocGenTagsV2025R0.java | 133 + .../docgentagv2025r0/DocGenTagV2025R0.java | 92 + .../DocGenTagV2025R0TagTypeField.java | 67 + .../DocGenTemplateBaseV2025R0.java | 63 + .../DocGenTemplateCreateRequestV2025R0.java | 44 + .../DocGenTemplatesV2025R0.java | 133 + .../DocGenTemplateV2025R0.java | 81 + .../EnterpriseReferenceV2025R0.java | 90 + .../EnterpriseReferenceV2025R0TypeField.java | 62 + .../ExternalUserDeletionResultV2025R0.java | 105 + ...nalUsersSubmitDeleteJobRequestV2025R0.java | 52 + ...alUsersSubmitDeleteJobResponseV2025R0.java | 47 + .../FileReferenceV2025R0.java | 93 + .../FileReferenceV2025R0TypeField.java | 62 + .../FileVersionBaseV2025R0.java | 96 + .../FileVersionBaseV2025R0TypeField.java | 62 + .../FolderReferenceV2025R0.java | 94 + .../FolderReferenceV2025R0TypeField.java | 62 + .../groupbasev2025r0/GroupBaseV2025R0.java | 90 + .../GroupBaseV2025R0TypeField.java | 62 + .../groupminiv2025r0/GroupMiniV2025R0.java | 125 + .../GroupMiniV2025R0GroupTypeField.java | 63 + .../HubAccessGranteeV2025R0.java | 95 + .../hubbasev2025r0/HubBaseV2025R0.java | 90 + .../HubBaseV2025R0TypeField.java | 62 + .../HubCollaborationCreateRequestV2025R0.java | 76 + ...CreateRequestV2025R0AccessibleByField.java | 107 + ...aborationCreateRequestV2025R0HubField.java | 109 + ...ationCreateRequestV2025R0HubTypeField.java | 62 + .../HubCollaborationsV2025R0.java | 111 + .../HubCollaborationUpdateRequestV2025R0.java | 62 + .../HubCollaborationUserV2025R0.java | 113 + .../HubCollaborationV2025R0.java | 228 + ...25R0AcceptanceRequirementsStatusField.java | 128 + ...sStatusStrongPasswordRequirementField.java | 101 + ...sStatusTermsOfServiceRequirementField.java | 97 + ...oFactorAuthenticationRequirementField.java | 105 + .../HubCollaborationV2025R0StatusField.java | 64 + .../HubCollaborationV2025R0TypeField.java | 62 + .../HubCopyRequestV2025R0.java | 84 + .../HubCreateRequestV2025R0.java | 86 + .../HubItemOperationResultV2025R0.java | 142 + .../HubItemOperationV2025R0.java | 121 + .../HubItemOperationV2025R0ActionField.java | 63 + .../HubItemReferenceV2025R0.java | 105 + .../HubItemsManageRequestV2025R0.java | 64 + .../HubItemsManageResponseV2025R0.java | 46 + .../hubitemsv2025r0/HubItemsV2025R0.java | 111 + .../hubitemv2025r0/HubItemV2025R0.java | 86 + .../HubItemV2025R0TypeField.java | 64 + .../v2025r0/hubsv2025r0/HubsV2025R0.java | 111 + .../HubUpdateRequestV2025R0.java | 174 + .../v2025r0/hubv2025r0/HubV2025R0.java | 317 ++ .../ShieldListContentCountryV2025R0.java | 110 + ...eldListContentCountryV2025R0TypeField.java | 62 + .../ShieldListContentDomainV2025R0.java | 109 + ...ieldListContentDomainV2025R0TypeField.java | 62 + .../ShieldListContentEmailV2025R0.java | 112 + ...hieldListContentEmailV2025R0TypeField.java | 62 + .../ShieldListContentIntegrationV2025R0.java | 111 + ...ntIntegrationV2025R0IntegrationsField.java | 63 + ...istContentIntegrationV2025R0TypeField.java | 62 + .../ShieldListContentIpV2025R0.java | 108 + .../ShieldListContentIpV2025R0TypeField.java | 62 + .../ShieldListContentRequestV2025R0.java | 121 + .../ShieldListContentV2025R0.java | 136 + .../ShieldListMiniV2025R0.java | 139 + .../ShieldListMiniV2025R0ContentField.java | 62 + .../ShieldListMiniV2025R0TypeField.java | 62 + .../ShieldListsCreateV2025R0.java | 158 + .../ShieldListsUpdateV2025R0.java | 158 + .../ShieldListsV2025R0.java | 64 + .../shieldlistv2025r0/ShieldListV2025R0.java | 394 ++ .../TermsOfServiceBaseV2025R0.java | 97 + .../TermsOfServiceBaseV2025R0TypeField.java | 62 + .../userbasev2025r0/UserBaseV2025R0.java | 90 + .../UserBaseV2025R0TypeField.java | 62 + .../userminiv2025r0/UserMiniV2025R0.java | 113 + .../UserReferenceV2025R0.java | 93 + .../UserReferenceV2025R0TypeField.java | 62 + .../WeblinkReferenceV2025R0.java | 95 + .../WeblinkReferenceV2025R0TypeField.java | 62 + .../sdkgen/schemas/watermark/Watermark.java | 62 + .../watermark/WatermarkWatermarkField.java | 96 + .../box/sdkgen/schemas/webhook/Webhook.java | 235 + .../schemas/webhook/WebhookTriggersField.java | 102 + .../schemas/webhookmini/WebhookMini.java | 114 + .../webhookmini/WebhookMiniTargetField.java | 86 + .../WebhookMiniTargetTypeField.java | 63 + .../webhookmini/WebhookMiniTypeField.java | 60 + .../box/sdkgen/schemas/webhooks/Webhooks.java | 133 + .../box/sdkgen/schemas/weblink/WebLink.java | 401 ++ .../weblink/WebLinkItemStatusField.java | 64 + .../weblink/WebLinkPathCollectionField.java | 63 + .../weblink/WebLinkSharedLinkAccessField.java | 64 + ...WebLinkSharedLinkEffectiveAccessField.java | 64 + ...inkSharedLinkEffectivePermissionField.java | 65 + .../weblink/WebLinkSharedLinkField.java | 439 ++ .../WebLinkSharedLinkPermissionsField.java | 77 + .../schemas/weblinkbase/WebLinkBase.java | 118 + .../weblinkbase/WebLinkBaseTypeField.java | 60 + .../schemas/weblinkmini/WebLinkMini.java | 144 + .../box/sdkgen/schemas/workflow/Workflow.java | 129 + .../schemas/workflow/WorkflowFlowsField.java | 180 + .../WorkflowFlowsOutcomesActionTypeField.java | 84 + .../workflow/WorkflowFlowsOutcomesField.java | 170 + ...lowsOutcomesIfRejectedActionTypeField.java | 84 + .../WorkflowFlowsOutcomesIfRejectedField.java | 155 + ...kflowFlowsOutcomesIfRejectedTypeField.java | 62 + .../WorkflowFlowsOutcomesTypeField.java | 62 + .../workflow/WorkflowFlowsTriggerField.java | 131 + .../WorkflowFlowsTriggerScopeField.java | 117 + .../WorkflowFlowsTriggerScopeObjectField.java | 100 + ...kflowFlowsTriggerScopeObjectTypeField.java | 62 + .../WorkflowFlowsTriggerScopeTypeField.java | 62 + .../WorkflowFlowsTriggerTriggerTypeField.java | 62 + .../WorkflowFlowsTriggerTypeField.java | 62 + .../workflow/WorkflowFlowsTypeField.java | 62 + .../schemas/workflowmini/WorkflowMini.java | 154 + .../workflowmini/WorkflowMiniTypeField.java | 60 + .../sdkgen/schemas/workflows/Workflows.java | 133 + .../schemas/zipdownload/ZipDownload.java | 135 + .../ZipDownloadNameConflictsField.java | 138 + .../ZipDownloadNameConflictsTypeField.java | 63 + .../ZipDownloadRequest.java | 89 + .../ZipDownloadRequestItemsField.java | 73 + .../ZipDownloadRequestItemsTypeField.java | 63 + .../zipdownloadstatus/ZipDownloadStatus.java | 159 + .../ZipDownloadStatusStateField.java | 64 + .../serialization/json/EnumWrapper.java | 109 + .../serialization/json/JsonManager.java | 116 + .../sdkgen/serialization/json/Valuable.java | 5 + .../com/box/sdk/AcceptAllHostsVerifier.java | 8 +- src/test/java/com/box/sdk/BoxAITest.java | 803 ++-- .../com/box/sdk/BoxAPIConnectionForTests.java | 59 +- .../com/box/sdk/BoxAPIConnectionTest.java | 1744 ++++---- .../java/com/box/sdk/BoxAPIRequestTest.java | 620 +-- .../box/sdk/BoxAPIResponseExceptionTest.java | 485 ++- .../java/com/box/sdk/BoxAPIResponseTest.java | 288 +- .../com/box/sdk/BoxCCGAPIConnectionTest.java | 591 +-- ...ollaborationAllowlistExemptTargetTest.java | 212 +- .../sdk/BoxCollaborationAllowlistTest.java | 246 +- .../com/box/sdk/BoxCollaborationTest.java | 571 +-- .../java/com/box/sdk/BoxCollectionTest.java | 228 +- src/test/java/com/box/sdk/BoxCommentTest.java | 242 +- .../java/com/box/sdk/BoxDateFormatTest.java | 127 +- .../BoxDeveloperEditionAPIConnectionTest.java | 537 +-- .../java/com/box/sdk/BoxDevicePinTest.java | 195 +- src/test/java/com/box/sdk/BoxEventTest.java | 267 +- .../java/com/box/sdk/BoxFileRequestTest.java | 223 +- src/test/java/com/box/sdk/BoxFileTest.java | 2398 +++++----- .../box/sdk/BoxFileVersionLegalHoldTest.java | 141 +- .../box/sdk/BoxFileVersionRetentionTest.java | 315 +- .../java/com/box/sdk/BoxFileVersionTest.java | 183 +- src/test/java/com/box/sdk/BoxFolderTest.java | 2951 +++++++------ .../com/box/sdk/BoxGroupMembershipTest.java | 149 +- src/test/java/com/box/sdk/BoxGroupTest.java | 694 +-- src/test/java/com/box/sdk/BoxInviteTest.java | 216 +- src/test/java/com/box/sdk/BoxItemTest.java | 180 +- .../java/com/box/sdk/BoxJSONRequestTest.java | 39 +- .../sdk/BoxLegalHoldPolicyAssignmentTest.java | 303 +- .../com/box/sdk/BoxLegalHoldPolicyTest.java | 491 ++- src/test/java/com/box/sdk/BoxLoggerTest.java | 60 +- .../box/sdk/BoxMetadataCascadePolicyTest.java | 242 +- .../com/box/sdk/BoxResourceIterableTest.java | 309 +- .../java/com/box/sdk/BoxResourceTest.java | 118 +- .../sdk/BoxRetentionPolicyAssignmentTest.java | 732 ++-- .../com/box/sdk/BoxRetentionPolicyTest.java | 284 +- .../com/box/sdk/BoxSearchParametersTest.java | 478 +- src/test/java/com/box/sdk/BoxSearchTest.java | 164 +- .../sdk/BoxSensitiveDataSanitizerTest.java | 172 +- .../java/com/box/sdk/BoxSharedLinkTest.java | 91 +- .../java/com/box/sdk/BoxSignRequestTest.java | 455 +- .../java/com/box/sdk/BoxSignTemplateTest.java | 235 +- .../sdk/BoxStoragePolicyAssignmentTest.java | 363 +- .../com/box/sdk/BoxStoragePolicyTest.java | 88 +- .../com/box/sdk/BoxTaskAssignmentTest.java | 396 +- src/test/java/com/box/sdk/BoxTaskTest.java | 373 +- .../com/box/sdk/BoxTermsOfServiceTest.java | 201 +- .../sdk/BoxTermsOfServiceUserStatusTest.java | 70 +- .../BoxTransactionalAPIConnectionTest.java | 33 +- src/test/java/com/box/sdk/BoxTrashTest.java | 496 +-- .../java/com/box/sdk/BoxURLTemplateTest.java | 94 +- src/test/java/com/box/sdk/BoxUserTest.java | 1049 ++--- .../java/com/box/sdk/BoxWatermarkTest.java | 260 +- .../sdk/BoxWebHookSignatureVerifierTest.java | 202 +- src/test/java/com/box/sdk/BoxWebHookTest.java | 281 +- src/test/java/com/box/sdk/BoxWebLinkTest.java | 247 +- src/test/java/com/box/sdk/BoxZipTest.java | 99 +- src/test/java/com/box/sdk/EventLogTest.java | 341 +- .../java/com/box/sdk/EventStreamTest.java | 370 +- .../java/com/box/sdk/IntegrationTestJWT.java | 7 +- .../com/box/sdk/JSONRequestInterceptor.java | 52 +- src/test/java/com/box/sdk/LRUCacheTest.java | 82 +- .../java/com/box/sdk/MetadataQueryTest.java | 119 +- .../com/box/sdk/MetadataTemplateTest.java | 555 +-- src/test/java/com/box/sdk/MetadataTest.java | 344 +- .../com/box/sdk/PagingParametersTest.java | 100 +- .../com/box/sdk/QueryStringBuilderTest.java | 97 +- .../box/sdk/RequestBodyFromStreamTest.java | 146 +- .../java/com/box/sdk/SortParametersTest.java | 37 +- src/test/java/com/box/sdk/TestUtils.java | 74 +- .../com/box/sdk/TrustAllTrustManager.java | 18 +- .../internal/utils/CollectionUtilsTest.java | 48 +- 2127 files changed, 236053 insertions(+), 53512 deletions(-) create mode 100644 .codegen.json create mode 100644 docs/sdkgen/Authentication.md create mode 100644 docs/sdkgen/Client.md create mode 100644 docs/sdkgen/Configuration.md create mode 100644 docs/sdkgen/EventStream.md create mode 100644 docs/sdkgen/README.md create mode 100644 docs/sdkgen/ai.md create mode 100644 docs/sdkgen/aistudio.md create mode 100644 docs/sdkgen/appitemassociations.md create mode 100644 docs/sdkgen/archives.md create mode 100644 docs/sdkgen/authorization.md create mode 100644 docs/sdkgen/avatars.md create mode 100644 docs/sdkgen/chunkeduploads.md create mode 100644 docs/sdkgen/classifications.md create mode 100644 docs/sdkgen/collaborationallowlistentries.md create mode 100644 docs/sdkgen/collaborationallowlistexempttargets.md create mode 100644 docs/sdkgen/collections.md create mode 100644 docs/sdkgen/comments.md create mode 100644 docs/sdkgen/devicepinners.md create mode 100644 docs/sdkgen/docgen.md create mode 100644 docs/sdkgen/docgentemplate.md create mode 100644 docs/sdkgen/downloads.md create mode 100644 docs/sdkgen/emailaliases.md create mode 100644 docs/sdkgen/events.md create mode 100644 docs/sdkgen/externalusers.md create mode 100644 docs/sdkgen/fileclassifications.md create mode 100644 docs/sdkgen/filemetadata.md create mode 100644 docs/sdkgen/filerequests.md create mode 100644 docs/sdkgen/files.md create mode 100644 docs/sdkgen/fileversionlegalholds.md create mode 100644 docs/sdkgen/fileversionretentions.md create mode 100644 docs/sdkgen/fileversions.md create mode 100644 docs/sdkgen/filewatermarks.md create mode 100644 docs/sdkgen/folderclassifications.md create mode 100644 docs/sdkgen/folderlocks.md create mode 100644 docs/sdkgen/foldermetadata.md create mode 100644 docs/sdkgen/folders.md create mode 100644 docs/sdkgen/folderwatermarks.md create mode 100644 docs/sdkgen/groups.md create mode 100644 docs/sdkgen/hubcollaborations.md create mode 100644 docs/sdkgen/hubitems.md create mode 100644 docs/sdkgen/hubs.md create mode 100644 docs/sdkgen/integrationmappings.md create mode 100644 docs/sdkgen/invites.md create mode 100644 docs/sdkgen/legalholdpolicies.md create mode 100644 docs/sdkgen/legalholdpolicyassignments.md create mode 100644 docs/sdkgen/listcollaborations.md create mode 100644 docs/sdkgen/memberships.md create mode 100644 docs/sdkgen/metadatacascadepolicies.md create mode 100644 docs/sdkgen/metadatatemplates.md create mode 100644 docs/sdkgen/recentitems.md create mode 100644 docs/sdkgen/retentionpolicies.md create mode 100644 docs/sdkgen/retentionpolicyassignments.md create mode 100644 docs/sdkgen/search.md create mode 100644 docs/sdkgen/sessiontermination.md create mode 100644 docs/sdkgen/sharedlinksappitems.md create mode 100644 docs/sdkgen/sharedlinksfiles.md create mode 100644 docs/sdkgen/sharedlinksfolders.md create mode 100644 docs/sdkgen/sharedlinksweblinks.md create mode 100644 docs/sdkgen/shieldinformationbarrierreports.md create mode 100644 docs/sdkgen/shieldinformationbarriers.md create mode 100644 docs/sdkgen/shieldinformationbarriersegmentmembers.md create mode 100644 docs/sdkgen/shieldinformationbarriersegmentrestrictions.md create mode 100644 docs/sdkgen/shieldinformationbarriersegments.md create mode 100644 docs/sdkgen/shieldlists.md create mode 100644 docs/sdkgen/signrequests.md create mode 100644 docs/sdkgen/signtemplates.md create mode 100644 docs/sdkgen/skills.md create mode 100644 docs/sdkgen/storagepolicies.md create mode 100644 docs/sdkgen/storagepolicyassignments.md create mode 100644 docs/sdkgen/taskassignments.md create mode 100644 docs/sdkgen/tasks.md create mode 100644 docs/sdkgen/termsofservices.md create mode 100644 docs/sdkgen/termsofserviceuserstatuses.md create mode 100644 docs/sdkgen/transfer.md create mode 100644 docs/sdkgen/trashedfiles.md create mode 100644 docs/sdkgen/trashedfolders.md create mode 100644 docs/sdkgen/trasheditems.md create mode 100644 docs/sdkgen/trashedweblinks.md create mode 100644 docs/sdkgen/uploads.md create mode 100644 docs/sdkgen/usercollaborations.md create mode 100644 docs/sdkgen/users.md create mode 100644 docs/sdkgen/webhooks.md create mode 100644 docs/sdkgen/weblinks.md create mode 100644 docs/sdkgen/workflows.md create mode 100644 docs/sdkgen/zipdownloads.md create mode 100644 src/intTest/java/com/box/sdkgen/ai/AiITest.java create mode 100644 src/intTest/java/com/box/sdkgen/aistudio/AiStudioITest.java create mode 100644 src/intTest/java/com/box/sdkgen/appitemassociations/AppItemAssociationsITest.java create mode 100644 src/intTest/java/com/box/sdkgen/archives/ArchivesITest.java create mode 100644 src/intTest/java/com/box/sdkgen/auth/AuthITest.java create mode 100644 src/intTest/java/com/box/sdkgen/avatars/AvatarsITest.java create mode 100644 src/intTest/java/com/box/sdkgen/chunkeduploads/ChunkedUploadsITest.java create mode 100644 src/intTest/java/com/box/sdkgen/chunkeduploads/TestPartAccumulator.java create mode 100644 src/intTest/java/com/box/sdkgen/classifications/ClassificationsITest.java create mode 100644 src/intTest/java/com/box/sdkgen/client/ClientITest.java create mode 100644 src/intTest/java/com/box/sdkgen/client/InterceptorAddingRoleToFields.java create mode 100644 src/intTest/java/com/box/sdkgen/client/InterceptorChangingResponse.java create mode 100644 src/intTest/java/com/box/sdkgen/client/InterceptorThrowingError.java create mode 100644 src/intTest/java/com/box/sdkgen/collaborationallowlistentries/CollaborationAllowlistEntriesITest.java create mode 100644 src/intTest/java/com/box/sdkgen/collaborationallowlistexempttargets/CollaborationAllowlistExemptTargetsITest.java create mode 100644 src/intTest/java/com/box/sdkgen/comments/CommentsITest.java create mode 100644 src/intTest/java/com/box/sdkgen/commons/CommonsManager.java create mode 100644 src/intTest/java/com/box/sdkgen/devicepinners/DevicePinnersITest.java create mode 100644 src/intTest/java/com/box/sdkgen/docgen/DocgenITest.java create mode 100644 src/intTest/java/com/box/sdkgen/docgentemplate/DocgenTemplateITest.java create mode 100644 src/intTest/java/com/box/sdkgen/downloads/DownloadsITest.java create mode 100644 src/intTest/java/com/box/sdkgen/emailaliases/EmailAliasesITest.java create mode 100644 src/intTest/java/com/box/sdkgen/events/EventsITest.java create mode 100644 src/intTest/java/com/box/sdkgen/externalusers/ExternalUsersITest.java create mode 100644 src/intTest/java/com/box/sdkgen/fileclassifications/FileClassificationsITest.java create mode 100644 src/intTest/java/com/box/sdkgen/filemetadata/FileMetadataITest.java create mode 100644 src/intTest/java/com/box/sdkgen/filerequests/FileRequestsITest.java create mode 100644 src/intTest/java/com/box/sdkgen/files/FilesITest.java create mode 100644 src/intTest/java/com/box/sdkgen/fileversionlegalholds/FileVersionLegalHoldsITest.java create mode 100644 src/intTest/java/com/box/sdkgen/fileversionretentions/FileVersionRetentionsITest.java create mode 100644 src/intTest/java/com/box/sdkgen/fileversions/FileVersionsITest.java create mode 100644 src/intTest/java/com/box/sdkgen/filewatermarks/FileWatermarksITest.java create mode 100644 src/intTest/java/com/box/sdkgen/folderclassifications/FolderClassificationsITest.java create mode 100644 src/intTest/java/com/box/sdkgen/folderlocks/FolderLocksITest.java create mode 100644 src/intTest/java/com/box/sdkgen/foldermetadata/FolderMetadataITest.java create mode 100644 src/intTest/java/com/box/sdkgen/folders/FoldersITest.java create mode 100644 src/intTest/java/com/box/sdkgen/folderwatermarks/FolderWatermarksITest.java create mode 100644 src/intTest/java/com/box/sdkgen/groups/GroupsITest.java create mode 100644 src/intTest/java/com/box/sdkgen/hubcollaborations/HubCollaborationsITest.java create mode 100644 src/intTest/java/com/box/sdkgen/hubitems/HubItemsITest.java create mode 100644 src/intTest/java/com/box/sdkgen/hubs/HubsITest.java create mode 100644 src/intTest/java/com/box/sdkgen/integrationmappings/IntegrationMappingsITest.java create mode 100644 src/intTest/java/com/box/sdkgen/invites/InvitesITest.java create mode 100644 src/intTest/java/com/box/sdkgen/legalholdpolicies/LegalHoldPoliciesITest.java create mode 100644 src/intTest/java/com/box/sdkgen/legalholdpolicyassignments/LegalHoldPolicyAssignmentsITest.java create mode 100644 src/intTest/java/com/box/sdkgen/listcollaborations/ListCollaborationsITest.java create mode 100644 src/intTest/java/com/box/sdkgen/memberships/MembershipsITest.java create mode 100644 src/intTest/java/com/box/sdkgen/metadatacascadepolicies/MetadataCascadePoliciesITest.java create mode 100644 src/intTest/java/com/box/sdkgen/metadatatemplates/MetadataTemplatesITest.java create mode 100644 src/intTest/java/com/box/sdkgen/recentitems/RecentItemsITest.java create mode 100644 src/intTest/java/com/box/sdkgen/retentionpolicies/RetentionPoliciesITest.java create mode 100644 src/intTest/java/com/box/sdkgen/retentionpolicyassignments/RetentionPolicyAssignmentsITest.java create mode 100644 src/intTest/java/com/box/sdkgen/search/SearchITest.java create mode 100644 src/intTest/java/com/box/sdkgen/sessiontermination/SessionTerminationITest.java create mode 100644 src/intTest/java/com/box/sdkgen/sharedlinksappitems/SharedLinksAppItemsITest.java create mode 100644 src/intTest/java/com/box/sdkgen/sharedlinksfiles/SharedLinksFilesITest.java create mode 100644 src/intTest/java/com/box/sdkgen/sharedlinksfolders/SharedLinksFoldersITest.java create mode 100644 src/intTest/java/com/box/sdkgen/sharedlinksweblinks/SharedLinksWebLinksITest.java create mode 100644 src/intTest/java/com/box/sdkgen/shieldinformationbarrierreports/ShieldInformationBarrierReportsITest.java create mode 100644 src/intTest/java/com/box/sdkgen/shieldinformationbarriers/ShieldInformationBarriersITest.java create mode 100644 src/intTest/java/com/box/sdkgen/shieldinformationbarriersegmentmembers/ShieldInformationBarrierSegmentMembersITest.java create mode 100644 src/intTest/java/com/box/sdkgen/shieldinformationbarriersegmentrestrictions/ShieldInformationBarrierSegmentRestrictionsITest.java create mode 100644 src/intTest/java/com/box/sdkgen/shieldinformationbarriersegments/ShieldInformationBarrierSegmentsITest.java create mode 100644 src/intTest/java/com/box/sdkgen/shieldlists/ShieldListsITest.java create mode 100644 src/intTest/java/com/box/sdkgen/signrequests/SignRequestsITest.java create mode 100644 src/intTest/java/com/box/sdkgen/signtemplates/SignTemplatesITest.java create mode 100644 src/intTest/java/com/box/sdkgen/skills/SkillsITest.java create mode 100644 src/intTest/java/com/box/sdkgen/storagepolicicyassignments/StoragePolicicyAssignmentsITest.java create mode 100644 src/intTest/java/com/box/sdkgen/storagepolicies/StoragePoliciesITest.java create mode 100644 src/intTest/java/com/box/sdkgen/taskassignments/TaskAssignmentsITest.java create mode 100644 src/intTest/java/com/box/sdkgen/tasks/TasksITest.java create mode 100644 src/intTest/java/com/box/sdkgen/termsofservices/TermsOfServicesITest.java create mode 100644 src/intTest/java/com/box/sdkgen/termsofserviceuserstatuses/TermsOfServiceUserStatusesITest.java create mode 100644 src/intTest/java/com/box/sdkgen/transfer/TransferITest.java create mode 100644 src/intTest/java/com/box/sdkgen/trashedfiles/TrashedFilesITest.java create mode 100644 src/intTest/java/com/box/sdkgen/trashedfolders/TrashedFoldersITest.java create mode 100644 src/intTest/java/com/box/sdkgen/trasheditems/TrashedItemsITest.java create mode 100644 src/intTest/java/com/box/sdkgen/trashedweblinks/TrashedWebLinksITest.java create mode 100644 src/intTest/java/com/box/sdkgen/uploads/UploadsITest.java create mode 100644 src/intTest/java/com/box/sdkgen/usercollaborations/UserCollaborationsITest.java create mode 100644 src/intTest/java/com/box/sdkgen/users/UsersITest.java create mode 100644 src/intTest/java/com/box/sdkgen/webhooks/WebhooksITest.java create mode 100644 src/intTest/java/com/box/sdkgen/weblinks/WeblinksITest.java create mode 100644 src/intTest/java/com/box/sdkgen/workflows/WorkflowsITest.java create mode 100644 src/intTest/java/com/box/sdkgen/zipdownloads/ZipDownloadsITest.java create mode 100644 src/main/java/com/box/sdkgen/box/BoxConstants.java create mode 100644 src/main/java/com/box/sdkgen/box/ccgauth/BoxCCGAuth.java create mode 100644 src/main/java/com/box/sdkgen/box/ccgauth/CCGConfig.java create mode 100644 src/main/java/com/box/sdkgen/box/developertokenauth/BoxDeveloperTokenAuth.java create mode 100644 src/main/java/com/box/sdkgen/box/developertokenauth/DeveloperTokenConfig.java create mode 100644 src/main/java/com/box/sdkgen/box/errors/BoxAPIError.java create mode 100644 src/main/java/com/box/sdkgen/box/errors/BoxSDKError.java create mode 100644 src/main/java/com/box/sdkgen/box/errors/RequestInfo.java create mode 100644 src/main/java/com/box/sdkgen/box/errors/ResponseInfo.java create mode 100644 src/main/java/com/box/sdkgen/box/eventstream/EventStream.java create mode 100644 src/main/java/com/box/sdkgen/box/eventstream/EventStreamIterator.java create mode 100644 src/main/java/com/box/sdkgen/box/jwtauth/BoxJWTAuth.java create mode 100644 src/main/java/com/box/sdkgen/box/jwtauth/JWTConfig.java create mode 100644 src/main/java/com/box/sdkgen/box/jwtauth/JwtConfigAppSettings.java create mode 100644 src/main/java/com/box/sdkgen/box/jwtauth/JwtConfigAppSettingsAppAuth.java create mode 100644 src/main/java/com/box/sdkgen/box/jwtauth/JwtConfigFile.java create mode 100644 src/main/java/com/box/sdkgen/box/oauth/BoxOAuth.java create mode 100644 src/main/java/com/box/sdkgen/box/oauth/GetAuthorizeUrlOptions.java create mode 100644 src/main/java/com/box/sdkgen/box/oauth/OAuthConfig.java create mode 100644 src/main/java/com/box/sdkgen/box/tokenstorage/InMemoryTokenStorage.java create mode 100644 src/main/java/com/box/sdkgen/box/tokenstorage/TokenStorage.java create mode 100644 src/main/java/com/box/sdkgen/client/BoxClient.java create mode 100644 src/main/java/com/box/sdkgen/internal/Nullable.java create mode 100644 src/main/java/com/box/sdkgen/internal/NullableFieldTracker.java create mode 100644 src/main/java/com/box/sdkgen/internal/NullablePropertyFilter.java create mode 100644 src/main/java/com/box/sdkgen/internal/OneOfFive.java create mode 100644 src/main/java/com/box/sdkgen/internal/OneOfFour.java create mode 100644 src/main/java/com/box/sdkgen/internal/OneOfOne.java create mode 100644 src/main/java/com/box/sdkgen/internal/OneOfSix.java create mode 100644 src/main/java/com/box/sdkgen/internal/OneOfThree.java create mode 100644 src/main/java/com/box/sdkgen/internal/OneOfTwo.java create mode 100644 src/main/java/com/box/sdkgen/internal/SerializableObject.java create mode 100644 src/main/java/com/box/sdkgen/internal/logging/DataSanitizer.java create mode 100644 src/main/java/com/box/sdkgen/internal/utils/DateTimeUtils.java create mode 100644 src/main/java/com/box/sdkgen/internal/utils/DateUtils.java create mode 100644 src/main/java/com/box/sdkgen/internal/utils/DefaultPrivateKeyDecryptor.java create mode 100644 src/main/java/com/box/sdkgen/internal/utils/Entry.java create mode 100644 src/main/java/com/box/sdkgen/internal/utils/Hash.java create mode 100644 src/main/java/com/box/sdkgen/internal/utils/HashName.java create mode 100644 src/main/java/com/box/sdkgen/internal/utils/JwtAlgorithm.java create mode 100644 src/main/java/com/box/sdkgen/internal/utils/JwtKey.java create mode 100644 src/main/java/com/box/sdkgen/internal/utils/JwtSignOptions.java create mode 100644 src/main/java/com/box/sdkgen/internal/utils/PrivateKeyDecryptor.java create mode 100644 src/main/java/com/box/sdkgen/internal/utils/UtilsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/ai/AiManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/ai/CreateAiAskHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/ai/CreateAiExtractHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/ai/CreateAiExtractStructuredHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/ai/CreateAiTextGenHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/ai/GetAiAgentDefaultConfigHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/ai/GetAiAgentDefaultConfigQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/ai/GetAiAgentDefaultConfigQueryParamsModeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/aistudio/AiStudioManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/aistudio/CreateAiAgentHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/aistudio/DeleteAiAgentByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/aistudio/GetAiAgentByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/aistudio/GetAiAgentByIdQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/aistudio/GetAiAgentsHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/aistudio/GetAiAgentsQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/aistudio/UpdateAiAgentByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/appitemassociations/AppItemAssociationsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/appitemassociations/GetFileAppItemAssociationsHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/appitemassociations/GetFileAppItemAssociationsQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/appitemassociations/GetFolderAppItemAssociationsHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/appitemassociations/GetFolderAppItemAssociationsQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/archives/ArchivesManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/archives/CreateArchiveV2025R0Headers.java create mode 100644 src/main/java/com/box/sdkgen/managers/archives/CreateArchiveV2025R0RequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/archives/DeleteArchiveByIdV2025R0Headers.java create mode 100644 src/main/java/com/box/sdkgen/managers/archives/GetArchivesV2025R0Headers.java create mode 100644 src/main/java/com/box/sdkgen/managers/archives/GetArchivesV2025R0QueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/authorization/AuthorizationManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/authorization/AuthorizeUserHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/authorization/AuthorizeUserQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/authorization/AuthorizeUserQueryParamsResponseTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/authorization/RefreshAccessTokenHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/authorization/RequestAccessTokenHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/authorization/RevokeAccessTokenHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/avatars/AvatarsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/avatars/CreateUserAvatarHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/avatars/CreateUserAvatarRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/avatars/DeleteUserAvatarHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/avatars/GetUserAvatarHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/chunkeduploads/ChunkedUploadsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/chunkeduploads/CreateFileUploadSessionCommitByUrlHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/chunkeduploads/CreateFileUploadSessionCommitByUrlRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/chunkeduploads/CreateFileUploadSessionCommitHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/chunkeduploads/CreateFileUploadSessionCommitRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/chunkeduploads/CreateFileUploadSessionForExistingFileHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/chunkeduploads/CreateFileUploadSessionForExistingFileRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/chunkeduploads/CreateFileUploadSessionHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/chunkeduploads/CreateFileUploadSessionRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/chunkeduploads/DeleteFileUploadSessionByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/chunkeduploads/DeleteFileUploadSessionByUrlHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/chunkeduploads/GetFileUploadSessionByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/chunkeduploads/GetFileUploadSessionByUrlHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/chunkeduploads/GetFileUploadSessionPartsByUrlHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/chunkeduploads/GetFileUploadSessionPartsByUrlQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/chunkeduploads/GetFileUploadSessionPartsHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/chunkeduploads/GetFileUploadSessionPartsQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/chunkeduploads/PartAccumulator.java create mode 100644 src/main/java/com/box/sdkgen/managers/chunkeduploads/UploadFilePartByUrlHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/chunkeduploads/UploadFilePartHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/classifications/AddClassificationHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/classifications/AddClassificationRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/classifications/AddClassificationRequestBodyDataField.java create mode 100644 src/main/java/com/box/sdkgen/managers/classifications/AddClassificationRequestBodyDataStaticConfigClassificationField.java create mode 100644 src/main/java/com/box/sdkgen/managers/classifications/AddClassificationRequestBodyDataStaticConfigField.java create mode 100644 src/main/java/com/box/sdkgen/managers/classifications/AddClassificationRequestBodyFieldKeyField.java create mode 100644 src/main/java/com/box/sdkgen/managers/classifications/AddClassificationRequestBodyOpField.java create mode 100644 src/main/java/com/box/sdkgen/managers/classifications/ClassificationsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/classifications/CreateClassificationTemplateHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/classifications/CreateClassificationTemplateRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/classifications/CreateClassificationTemplateRequestBodyDisplayNameField.java create mode 100644 src/main/java/com/box/sdkgen/managers/classifications/CreateClassificationTemplateRequestBodyFieldsDisplayNameField.java create mode 100644 src/main/java/com/box/sdkgen/managers/classifications/CreateClassificationTemplateRequestBodyFieldsField.java create mode 100644 src/main/java/com/box/sdkgen/managers/classifications/CreateClassificationTemplateRequestBodyFieldsKeyField.java create mode 100644 src/main/java/com/box/sdkgen/managers/classifications/CreateClassificationTemplateRequestBodyFieldsOptionsField.java create mode 100644 src/main/java/com/box/sdkgen/managers/classifications/CreateClassificationTemplateRequestBodyFieldsOptionsStaticConfigClassificationField.java create mode 100644 src/main/java/com/box/sdkgen/managers/classifications/CreateClassificationTemplateRequestBodyFieldsOptionsStaticConfigField.java create mode 100644 src/main/java/com/box/sdkgen/managers/classifications/CreateClassificationTemplateRequestBodyFieldsTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/classifications/CreateClassificationTemplateRequestBodyScopeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/classifications/CreateClassificationTemplateRequestBodyTemplateKeyField.java create mode 100644 src/main/java/com/box/sdkgen/managers/classifications/GetClassificationTemplateHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/classifications/UpdateClassificationHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/classifications/UpdateClassificationRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/classifications/UpdateClassificationRequestBodyDataField.java create mode 100644 src/main/java/com/box/sdkgen/managers/classifications/UpdateClassificationRequestBodyDataStaticConfigClassificationField.java create mode 100644 src/main/java/com/box/sdkgen/managers/classifications/UpdateClassificationRequestBodyDataStaticConfigField.java create mode 100644 src/main/java/com/box/sdkgen/managers/classifications/UpdateClassificationRequestBodyFieldKeyField.java create mode 100644 src/main/java/com/box/sdkgen/managers/classifications/UpdateClassificationRequestBodyOpField.java create mode 100644 src/main/java/com/box/sdkgen/managers/collaborationallowlistentries/CollaborationAllowlistEntriesManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/collaborationallowlistentries/CreateCollaborationWhitelistEntryHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/collaborationallowlistentries/CreateCollaborationWhitelistEntryRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/collaborationallowlistentries/CreateCollaborationWhitelistEntryRequestBodyDirectionField.java create mode 100644 src/main/java/com/box/sdkgen/managers/collaborationallowlistentries/DeleteCollaborationWhitelistEntryByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/collaborationallowlistentries/GetCollaborationWhitelistEntriesHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/collaborationallowlistentries/GetCollaborationWhitelistEntriesQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/collaborationallowlistentries/GetCollaborationWhitelistEntryByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/collaborationallowlistexempttargets/CollaborationAllowlistExemptTargetsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/collaborationallowlistexempttargets/CreateCollaborationWhitelistExemptTargetHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/collaborationallowlistexempttargets/CreateCollaborationWhitelistExemptTargetRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/collaborationallowlistexempttargets/CreateCollaborationWhitelistExemptTargetRequestBodyUserField.java create mode 100644 src/main/java/com/box/sdkgen/managers/collaborationallowlistexempttargets/DeleteCollaborationWhitelistExemptTargetByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/collaborationallowlistexempttargets/GetCollaborationWhitelistExemptTargetByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/collaborationallowlistexempttargets/GetCollaborationWhitelistExemptTargetsHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/collaborationallowlistexempttargets/GetCollaborationWhitelistExemptTargetsQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/collections/CollectionsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/collections/GetCollectionByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/collections/GetCollectionItemsHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/collections/GetCollectionItemsQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/collections/GetCollectionsHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/collections/GetCollectionsQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/comments/CommentsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/comments/CreateCommentHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/comments/CreateCommentQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/comments/CreateCommentRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/comments/CreateCommentRequestBodyItemField.java create mode 100644 src/main/java/com/box/sdkgen/managers/comments/CreateCommentRequestBodyItemTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/comments/DeleteCommentByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/comments/GetCommentByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/comments/GetCommentByIdQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/comments/GetFileCommentsHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/comments/GetFileCommentsQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/comments/UpdateCommentByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/comments/UpdateCommentByIdQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/comments/UpdateCommentByIdRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/devicepinners/DeleteDevicePinnerByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/devicepinners/DevicePinnersManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/devicepinners/GetDevicePinnerByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/devicepinners/GetEnterpriseDevicePinnersHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/devicepinners/GetEnterpriseDevicePinnersQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/devicepinners/GetEnterpriseDevicePinnersQueryParamsDirectionField.java create mode 100644 src/main/java/com/box/sdkgen/managers/docgen/CreateDocgenBatchV2025R0Headers.java create mode 100644 src/main/java/com/box/sdkgen/managers/docgen/DocgenManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/docgen/GetDocgenBatchJobByIdV2025R0Headers.java create mode 100644 src/main/java/com/box/sdkgen/managers/docgen/GetDocgenBatchJobByIdV2025R0QueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/docgen/GetDocgenJobByIdV2025R0Headers.java create mode 100644 src/main/java/com/box/sdkgen/managers/docgen/GetDocgenJobsV2025R0Headers.java create mode 100644 src/main/java/com/box/sdkgen/managers/docgen/GetDocgenJobsV2025R0QueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/docgentemplate/CreateDocgenTemplateV2025R0Headers.java create mode 100644 src/main/java/com/box/sdkgen/managers/docgentemplate/DeleteDocgenTemplateByIdV2025R0Headers.java create mode 100644 src/main/java/com/box/sdkgen/managers/docgentemplate/DocgenTemplateManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/docgentemplate/GetDocgenTemplateByIdV2025R0Headers.java create mode 100644 src/main/java/com/box/sdkgen/managers/docgentemplate/GetDocgenTemplateJobByIdV2025R0Headers.java create mode 100644 src/main/java/com/box/sdkgen/managers/docgentemplate/GetDocgenTemplateJobByIdV2025R0QueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/docgentemplate/GetDocgenTemplateTagsV2025R0Headers.java create mode 100644 src/main/java/com/box/sdkgen/managers/docgentemplate/GetDocgenTemplateTagsV2025R0QueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/docgentemplate/GetDocgenTemplatesV2025R0Headers.java create mode 100644 src/main/java/com/box/sdkgen/managers/docgentemplate/GetDocgenTemplatesV2025R0QueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/downloads/DownloadFileHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/downloads/DownloadFileQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/downloads/DownloadFileToOutputStreamHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/downloads/DownloadFileToOutputStreamQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/downloads/DownloadsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/downloads/GetDownloadFileUrlHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/downloads/GetDownloadFileUrlQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/emailaliases/CreateUserEmailAliasHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/emailaliases/CreateUserEmailAliasRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/emailaliases/DeleteUserEmailAliasByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/emailaliases/EmailAliasesManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/emailaliases/GetUserEmailAliasesHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/events/EventsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/events/GetEventStreamHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/events/GetEventStreamQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/events/GetEventStreamQueryParamsEventTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/events/GetEventStreamQueryParamsStreamTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/events/GetEventsHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/events/GetEventsQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/events/GetEventsQueryParamsEventTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/events/GetEventsQueryParamsStreamTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/events/GetEventsWithLongPollingHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/externalusers/ExternalUsersManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/externalusers/SubmitJobToDeleteExternalUsersV2025R0Headers.java create mode 100644 src/main/java/com/box/sdkgen/managers/fileclassifications/AddClassificationToFileHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/fileclassifications/AddClassificationToFileRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/fileclassifications/DeleteClassificationFromFileHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/fileclassifications/FileClassificationsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/fileclassifications/GetClassificationOnFileHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/fileclassifications/UpdateClassificationOnFileHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/fileclassifications/UpdateClassificationOnFileRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/fileclassifications/UpdateClassificationOnFileRequestBodyOpField.java create mode 100644 src/main/java/com/box/sdkgen/managers/fileclassifications/UpdateClassificationOnFileRequestBodyPathField.java create mode 100644 src/main/java/com/box/sdkgen/managers/filemetadata/CreateFileMetadataByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/filemetadata/CreateFileMetadataByIdScope.java create mode 100644 src/main/java/com/box/sdkgen/managers/filemetadata/DeleteFileMetadataByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/filemetadata/DeleteFileMetadataByIdScope.java create mode 100644 src/main/java/com/box/sdkgen/managers/filemetadata/FileMetadataManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/filemetadata/GetFileMetadataByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/filemetadata/GetFileMetadataByIdScope.java create mode 100644 src/main/java/com/box/sdkgen/managers/filemetadata/GetFileMetadataHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/filemetadata/UpdateFileMetadataByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/filemetadata/UpdateFileMetadataByIdRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/filemetadata/UpdateFileMetadataByIdRequestBodyOpField.java create mode 100644 src/main/java/com/box/sdkgen/managers/filemetadata/UpdateFileMetadataByIdScope.java create mode 100644 src/main/java/com/box/sdkgen/managers/filerequests/CreateFileRequestCopyHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/filerequests/DeleteFileRequestByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/filerequests/FileRequestsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/filerequests/GetFileRequestByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/filerequests/UpdateFileRequestByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/files/CopyFileHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/files/CopyFileQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/files/CopyFileRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/files/CopyFileRequestBodyParentField.java create mode 100644 src/main/java/com/box/sdkgen/managers/files/DeleteFileByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/files/FilesManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/files/GetFileByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/files/GetFileByIdQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/files/GetFileThumbnailByIdExtension.java create mode 100644 src/main/java/com/box/sdkgen/managers/files/GetFileThumbnailByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/files/GetFileThumbnailByIdQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/files/GetFileThumbnailUrlExtension.java create mode 100644 src/main/java/com/box/sdkgen/managers/files/GetFileThumbnailUrlHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/files/GetFileThumbnailUrlQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/files/UpdateFileByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/files/UpdateFileByIdQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/files/UpdateFileByIdRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/files/UpdateFileByIdRequestBodyCollectionsField.java create mode 100644 src/main/java/com/box/sdkgen/managers/files/UpdateFileByIdRequestBodyLockAccessField.java create mode 100644 src/main/java/com/box/sdkgen/managers/files/UpdateFileByIdRequestBodyLockField.java create mode 100644 src/main/java/com/box/sdkgen/managers/files/UpdateFileByIdRequestBodyParentField.java create mode 100644 src/main/java/com/box/sdkgen/managers/files/UpdateFileByIdRequestBodyPermissionsCanDownloadField.java create mode 100644 src/main/java/com/box/sdkgen/managers/files/UpdateFileByIdRequestBodyPermissionsField.java create mode 100644 src/main/java/com/box/sdkgen/managers/files/UpdateFileByIdRequestBodySharedLinkAccessField.java create mode 100644 src/main/java/com/box/sdkgen/managers/files/UpdateFileByIdRequestBodySharedLinkField.java create mode 100644 src/main/java/com/box/sdkgen/managers/files/UpdateFileByIdRequestBodySharedLinkPermissionsField.java create mode 100644 src/main/java/com/box/sdkgen/managers/fileversionlegalholds/FileVersionLegalHoldsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/fileversionlegalholds/GetFileVersionLegalHoldByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/fileversionlegalholds/GetFileVersionLegalHoldsHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/fileversionlegalholds/GetFileVersionLegalHoldsQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/fileversionretentions/FileVersionRetentionsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/fileversionretentions/GetFileVersionRetentionByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/fileversionretentions/GetFileVersionRetentionsHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/fileversionretentions/GetFileVersionRetentionsQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/fileversionretentions/GetFileVersionRetentionsQueryParamsDispositionActionField.java create mode 100644 src/main/java/com/box/sdkgen/managers/fileversions/DeleteFileVersionByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/fileversions/FileVersionsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/fileversions/GetFileVersionByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/fileversions/GetFileVersionByIdQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/fileversions/GetFileVersionsHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/fileversions/GetFileVersionsQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/fileversions/PromoteFileVersionHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/fileversions/PromoteFileVersionQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/fileversions/PromoteFileVersionRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/fileversions/PromoteFileVersionRequestBodyTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/fileversions/UpdateFileVersionByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/fileversions/UpdateFileVersionByIdRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/filewatermarks/DeleteFileWatermarkHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/filewatermarks/FileWatermarksManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/filewatermarks/GetFileWatermarkHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/filewatermarks/UpdateFileWatermarkHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/filewatermarks/UpdateFileWatermarkRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/filewatermarks/UpdateFileWatermarkRequestBodyWatermarkField.java create mode 100644 src/main/java/com/box/sdkgen/managers/filewatermarks/UpdateFileWatermarkRequestBodyWatermarkImprintField.java create mode 100644 src/main/java/com/box/sdkgen/managers/folderclassifications/AddClassificationToFolderHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/folderclassifications/AddClassificationToFolderRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/folderclassifications/DeleteClassificationFromFolderHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/folderclassifications/FolderClassificationsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/folderclassifications/GetClassificationOnFolderHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/folderclassifications/UpdateClassificationOnFolderHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/folderclassifications/UpdateClassificationOnFolderRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/folderclassifications/UpdateClassificationOnFolderRequestBodyOpField.java create mode 100644 src/main/java/com/box/sdkgen/managers/folderclassifications/UpdateClassificationOnFolderRequestBodyPathField.java create mode 100644 src/main/java/com/box/sdkgen/managers/folderlocks/CreateFolderLockHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/folderlocks/CreateFolderLockRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/folderlocks/CreateFolderLockRequestBodyFolderField.java create mode 100644 src/main/java/com/box/sdkgen/managers/folderlocks/CreateFolderLockRequestBodyLockedOperationsField.java create mode 100644 src/main/java/com/box/sdkgen/managers/folderlocks/DeleteFolderLockByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/folderlocks/FolderLocksManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/folderlocks/GetFolderLocksHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/folderlocks/GetFolderLocksQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/foldermetadata/CreateFolderMetadataByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/foldermetadata/CreateFolderMetadataByIdScope.java create mode 100644 src/main/java/com/box/sdkgen/managers/foldermetadata/DeleteFolderMetadataByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/foldermetadata/DeleteFolderMetadataByIdScope.java create mode 100644 src/main/java/com/box/sdkgen/managers/foldermetadata/FolderMetadataManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/foldermetadata/GetFolderMetadataByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/foldermetadata/GetFolderMetadataByIdScope.java create mode 100644 src/main/java/com/box/sdkgen/managers/foldermetadata/GetFolderMetadataHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/foldermetadata/UpdateFolderMetadataByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/foldermetadata/UpdateFolderMetadataByIdRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/foldermetadata/UpdateFolderMetadataByIdRequestBodyOpField.java create mode 100644 src/main/java/com/box/sdkgen/managers/foldermetadata/UpdateFolderMetadataByIdScope.java create mode 100644 src/main/java/com/box/sdkgen/managers/folders/CopyFolderHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/folders/CopyFolderQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/folders/CopyFolderRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/folders/CopyFolderRequestBodyParentField.java create mode 100644 src/main/java/com/box/sdkgen/managers/folders/CreateFolderHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/folders/CreateFolderQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/folders/CreateFolderRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/folders/CreateFolderRequestBodyFolderUploadEmailAccessField.java create mode 100644 src/main/java/com/box/sdkgen/managers/folders/CreateFolderRequestBodyFolderUploadEmailField.java create mode 100644 src/main/java/com/box/sdkgen/managers/folders/CreateFolderRequestBodyParentField.java create mode 100644 src/main/java/com/box/sdkgen/managers/folders/CreateFolderRequestBodySyncStateField.java create mode 100644 src/main/java/com/box/sdkgen/managers/folders/DeleteFolderByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/folders/DeleteFolderByIdQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/folders/FoldersManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/folders/GetFolderByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/folders/GetFolderByIdQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/folders/GetFolderByIdQueryParamsDirectionField.java create mode 100644 src/main/java/com/box/sdkgen/managers/folders/GetFolderByIdQueryParamsSortField.java create mode 100644 src/main/java/com/box/sdkgen/managers/folders/GetFolderItemsHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/folders/GetFolderItemsQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/folders/GetFolderItemsQueryParamsDirectionField.java create mode 100644 src/main/java/com/box/sdkgen/managers/folders/GetFolderItemsQueryParamsSortField.java create mode 100644 src/main/java/com/box/sdkgen/managers/folders/UpdateFolderByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/folders/UpdateFolderByIdQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/folders/UpdateFolderByIdRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/folders/UpdateFolderByIdRequestBodyCollectionsField.java create mode 100644 src/main/java/com/box/sdkgen/managers/folders/UpdateFolderByIdRequestBodyFolderUploadEmailAccessField.java create mode 100644 src/main/java/com/box/sdkgen/managers/folders/UpdateFolderByIdRequestBodyFolderUploadEmailField.java create mode 100644 src/main/java/com/box/sdkgen/managers/folders/UpdateFolderByIdRequestBodyParentField.java create mode 100644 src/main/java/com/box/sdkgen/managers/folders/UpdateFolderByIdRequestBodySharedLinkAccessField.java create mode 100644 src/main/java/com/box/sdkgen/managers/folders/UpdateFolderByIdRequestBodySharedLinkField.java create mode 100644 src/main/java/com/box/sdkgen/managers/folders/UpdateFolderByIdRequestBodySharedLinkPermissionsField.java create mode 100644 src/main/java/com/box/sdkgen/managers/folders/UpdateFolderByIdRequestBodySyncStateField.java create mode 100644 src/main/java/com/box/sdkgen/managers/folderwatermarks/DeleteFolderWatermarkHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/folderwatermarks/FolderWatermarksManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/folderwatermarks/GetFolderWatermarkHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/folderwatermarks/UpdateFolderWatermarkHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/folderwatermarks/UpdateFolderWatermarkRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/folderwatermarks/UpdateFolderWatermarkRequestBodyWatermarkField.java create mode 100644 src/main/java/com/box/sdkgen/managers/folderwatermarks/UpdateFolderWatermarkRequestBodyWatermarkImprintField.java create mode 100644 src/main/java/com/box/sdkgen/managers/groups/CreateGroupHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/groups/CreateGroupQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/groups/CreateGroupRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/groups/CreateGroupRequestBodyInvitabilityLevelField.java create mode 100644 src/main/java/com/box/sdkgen/managers/groups/CreateGroupRequestBodyMemberViewabilityLevelField.java create mode 100644 src/main/java/com/box/sdkgen/managers/groups/DeleteGroupByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/groups/GetGroupByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/groups/GetGroupByIdQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/groups/GetGroupsHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/groups/GetGroupsQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/groups/GroupsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/groups/UpdateGroupByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/groups/UpdateGroupByIdQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/groups/UpdateGroupByIdRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/groups/UpdateGroupByIdRequestBodyInvitabilityLevelField.java create mode 100644 src/main/java/com/box/sdkgen/managers/groups/UpdateGroupByIdRequestBodyMemberViewabilityLevelField.java create mode 100644 src/main/java/com/box/sdkgen/managers/hubcollaborations/CreateHubCollaborationV2025R0Headers.java create mode 100644 src/main/java/com/box/sdkgen/managers/hubcollaborations/DeleteHubCollaborationByIdV2025R0Headers.java create mode 100644 src/main/java/com/box/sdkgen/managers/hubcollaborations/GetHubCollaborationByIdV2025R0Headers.java create mode 100644 src/main/java/com/box/sdkgen/managers/hubcollaborations/GetHubCollaborationsV2025R0Headers.java create mode 100644 src/main/java/com/box/sdkgen/managers/hubcollaborations/GetHubCollaborationsV2025R0QueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/hubcollaborations/HubCollaborationsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/hubcollaborations/UpdateHubCollaborationByIdV2025R0Headers.java create mode 100644 src/main/java/com/box/sdkgen/managers/hubitems/GetHubItemsV2025R0Headers.java create mode 100644 src/main/java/com/box/sdkgen/managers/hubitems/GetHubItemsV2025R0QueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/hubitems/HubItemsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/hubitems/ManageHubItemsV2025R0Headers.java create mode 100644 src/main/java/com/box/sdkgen/managers/hubs/CopyHubV2025R0Headers.java create mode 100644 src/main/java/com/box/sdkgen/managers/hubs/CreateHubV2025R0Headers.java create mode 100644 src/main/java/com/box/sdkgen/managers/hubs/DeleteHubByIdV2025R0Headers.java create mode 100644 src/main/java/com/box/sdkgen/managers/hubs/GetEnterpriseHubsV2025R0Headers.java create mode 100644 src/main/java/com/box/sdkgen/managers/hubs/GetEnterpriseHubsV2025R0QueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/hubs/GetEnterpriseHubsV2025R0QueryParamsDirectionField.java create mode 100644 src/main/java/com/box/sdkgen/managers/hubs/GetHubByIdV2025R0Headers.java create mode 100644 src/main/java/com/box/sdkgen/managers/hubs/GetHubsV2025R0Headers.java create mode 100644 src/main/java/com/box/sdkgen/managers/hubs/GetHubsV2025R0QueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/hubs/GetHubsV2025R0QueryParamsDirectionField.java create mode 100644 src/main/java/com/box/sdkgen/managers/hubs/HubsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/hubs/UpdateHubByIdV2025R0Headers.java create mode 100644 src/main/java/com/box/sdkgen/managers/integrationmappings/CreateSlackIntegrationMappingHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/integrationmappings/CreateTeamsIntegrationMappingHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/integrationmappings/DeleteSlackIntegrationMappingByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/integrationmappings/DeleteTeamsIntegrationMappingByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/integrationmappings/GetSlackIntegrationMappingHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/integrationmappings/GetSlackIntegrationMappingQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/integrationmappings/GetSlackIntegrationMappingQueryParamsBoxItemTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/integrationmappings/GetSlackIntegrationMappingQueryParamsPartnerItemTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/integrationmappings/GetTeamsIntegrationMappingHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/integrationmappings/GetTeamsIntegrationMappingQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/integrationmappings/GetTeamsIntegrationMappingQueryParamsBoxItemTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/integrationmappings/GetTeamsIntegrationMappingQueryParamsPartnerItemTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/integrationmappings/IntegrationMappingsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/integrationmappings/UpdateSlackIntegrationMappingByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/integrationmappings/UpdateSlackIntegrationMappingByIdRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/integrationmappings/UpdateTeamsIntegrationMappingByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/integrationmappings/UpdateTeamsIntegrationMappingByIdRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/invites/CreateInviteHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/invites/CreateInviteQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/invites/CreateInviteRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/invites/CreateInviteRequestBodyActionableByField.java create mode 100644 src/main/java/com/box/sdkgen/managers/invites/CreateInviteRequestBodyEnterpriseField.java create mode 100644 src/main/java/com/box/sdkgen/managers/invites/GetInviteByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/invites/GetInviteByIdQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/invites/InvitesManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/legalholdpolicies/CreateLegalHoldPolicyHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/legalholdpolicies/CreateLegalHoldPolicyRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/legalholdpolicies/DeleteLegalHoldPolicyByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/legalholdpolicies/GetLegalHoldPoliciesHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/legalholdpolicies/GetLegalHoldPoliciesQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/legalholdpolicies/GetLegalHoldPolicyByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/legalholdpolicies/LegalHoldPoliciesManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/legalholdpolicies/UpdateLegalHoldPolicyByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/legalholdpolicies/UpdateLegalHoldPolicyByIdRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/legalholdpolicyassignments/CreateLegalHoldPolicyAssignmentHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/legalholdpolicyassignments/CreateLegalHoldPolicyAssignmentRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/legalholdpolicyassignments/CreateLegalHoldPolicyAssignmentRequestBodyAssignToField.java create mode 100644 src/main/java/com/box/sdkgen/managers/legalholdpolicyassignments/CreateLegalHoldPolicyAssignmentRequestBodyAssignToTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/legalholdpolicyassignments/DeleteLegalHoldPolicyAssignmentByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/legalholdpolicyassignments/GetLegalHoldPolicyAssignmentByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/legalholdpolicyassignments/GetLegalHoldPolicyAssignmentFileOnHoldHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/legalholdpolicyassignments/GetLegalHoldPolicyAssignmentFileOnHoldQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/legalholdpolicyassignments/GetLegalHoldPolicyAssignmentsHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/legalholdpolicyassignments/GetLegalHoldPolicyAssignmentsQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/legalholdpolicyassignments/GetLegalHoldPolicyAssignmentsQueryParamsAssignToTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/legalholdpolicyassignments/LegalHoldPolicyAssignmentsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/listcollaborations/GetCollaborationsHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/listcollaborations/GetCollaborationsQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/listcollaborations/GetCollaborationsQueryParamsStatusField.java create mode 100644 src/main/java/com/box/sdkgen/managers/listcollaborations/GetFileCollaborationsHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/listcollaborations/GetFileCollaborationsQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/listcollaborations/GetFolderCollaborationsHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/listcollaborations/GetFolderCollaborationsQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/listcollaborations/GetGroupCollaborationsHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/listcollaborations/GetGroupCollaborationsQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/listcollaborations/ListCollaborationsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/memberships/CreateGroupMembershipHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/memberships/CreateGroupMembershipQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/memberships/CreateGroupMembershipRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/memberships/CreateGroupMembershipRequestBodyGroupField.java create mode 100644 src/main/java/com/box/sdkgen/managers/memberships/CreateGroupMembershipRequestBodyRoleField.java create mode 100644 src/main/java/com/box/sdkgen/managers/memberships/CreateGroupMembershipRequestBodyUserField.java create mode 100644 src/main/java/com/box/sdkgen/managers/memberships/DeleteGroupMembershipByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/memberships/GetGroupMembershipByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/memberships/GetGroupMembershipByIdQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/memberships/GetGroupMembershipsHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/memberships/GetGroupMembershipsQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/memberships/GetUserMembershipsHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/memberships/GetUserMembershipsQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/memberships/MembershipsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/memberships/UpdateGroupMembershipByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/memberships/UpdateGroupMembershipByIdQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/memberships/UpdateGroupMembershipByIdRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/memberships/UpdateGroupMembershipByIdRequestBodyRoleField.java create mode 100644 src/main/java/com/box/sdkgen/managers/metadatacascadepolicies/ApplyMetadataCascadePolicyHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/metadatacascadepolicies/ApplyMetadataCascadePolicyRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/metadatacascadepolicies/ApplyMetadataCascadePolicyRequestBodyConflictResolutionField.java create mode 100644 src/main/java/com/box/sdkgen/managers/metadatacascadepolicies/CreateMetadataCascadePolicyHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/metadatacascadepolicies/CreateMetadataCascadePolicyRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/metadatacascadepolicies/CreateMetadataCascadePolicyRequestBodyScopeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/metadatacascadepolicies/DeleteMetadataCascadePolicyByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/metadatacascadepolicies/GetMetadataCascadePoliciesHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/metadatacascadepolicies/GetMetadataCascadePoliciesQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/metadatacascadepolicies/GetMetadataCascadePolicyByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/metadatacascadepolicies/MetadataCascadePoliciesManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/metadatatemplates/CreateMetadataTemplateHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/metadatatemplates/CreateMetadataTemplateRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/metadatatemplates/CreateMetadataTemplateRequestBodyFieldsField.java create mode 100644 src/main/java/com/box/sdkgen/managers/metadatatemplates/CreateMetadataTemplateRequestBodyFieldsOptionsField.java create mode 100644 src/main/java/com/box/sdkgen/managers/metadatatemplates/CreateMetadataTemplateRequestBodyFieldsTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/metadatatemplates/DeleteMetadataTemplateHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/metadatatemplates/DeleteMetadataTemplateScope.java create mode 100644 src/main/java/com/box/sdkgen/managers/metadatatemplates/GetEnterpriseMetadataTemplatesHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/metadatatemplates/GetEnterpriseMetadataTemplatesQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/metadatatemplates/GetGlobalMetadataTemplatesHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/metadatatemplates/GetGlobalMetadataTemplatesQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/metadatatemplates/GetMetadataTemplateByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/metadatatemplates/GetMetadataTemplateHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/metadatatemplates/GetMetadataTemplateScope.java create mode 100644 src/main/java/com/box/sdkgen/managers/metadatatemplates/GetMetadataTemplatesByInstanceIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/metadatatemplates/GetMetadataTemplatesByInstanceIdQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/metadatatemplates/MetadataTemplatesManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/metadatatemplates/UpdateMetadataTemplateHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/metadatatemplates/UpdateMetadataTemplateRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/metadatatemplates/UpdateMetadataTemplateRequestBodyOpField.java create mode 100644 src/main/java/com/box/sdkgen/managers/metadatatemplates/UpdateMetadataTemplateScope.java create mode 100644 src/main/java/com/box/sdkgen/managers/recentitems/GetRecentItemsHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/recentitems/GetRecentItemsQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/recentitems/RecentItemsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/retentionpolicies/CreateRetentionPolicyHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/retentionpolicies/CreateRetentionPolicyRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/retentionpolicies/CreateRetentionPolicyRequestBodyDispositionActionField.java create mode 100644 src/main/java/com/box/sdkgen/managers/retentionpolicies/CreateRetentionPolicyRequestBodyPolicyTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/retentionpolicies/CreateRetentionPolicyRequestBodyRetentionTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/retentionpolicies/DeleteRetentionPolicyByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/retentionpolicies/GetRetentionPoliciesHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/retentionpolicies/GetRetentionPoliciesQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/retentionpolicies/GetRetentionPoliciesQueryParamsPolicyTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/retentionpolicies/GetRetentionPolicyByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/retentionpolicies/GetRetentionPolicyByIdQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/retentionpolicies/RetentionPoliciesManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/retentionpolicies/UpdateRetentionPolicyByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/retentionpolicies/UpdateRetentionPolicyByIdRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/retentionpolicyassignments/CreateRetentionPolicyAssignmentHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/retentionpolicyassignments/CreateRetentionPolicyAssignmentRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/retentionpolicyassignments/CreateRetentionPolicyAssignmentRequestBodyAssignToField.java create mode 100644 src/main/java/com/box/sdkgen/managers/retentionpolicyassignments/CreateRetentionPolicyAssignmentRequestBodyAssignToTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/retentionpolicyassignments/CreateRetentionPolicyAssignmentRequestBodyFilterFieldsField.java create mode 100644 src/main/java/com/box/sdkgen/managers/retentionpolicyassignments/DeleteRetentionPolicyAssignmentByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/retentionpolicyassignments/GetFilesUnderRetentionPolicyAssignmentHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/retentionpolicyassignments/GetFilesUnderRetentionPolicyAssignmentQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/retentionpolicyassignments/GetRetentionPolicyAssignmentByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/retentionpolicyassignments/GetRetentionPolicyAssignmentByIdQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/retentionpolicyassignments/GetRetentionPolicyAssignmentsHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/retentionpolicyassignments/GetRetentionPolicyAssignmentsQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/retentionpolicyassignments/GetRetentionPolicyAssignmentsQueryParamsTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/retentionpolicyassignments/RetentionPolicyAssignmentsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/search/SearchByMetadataQueryHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/search/SearchForContentHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/search/SearchForContentQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/search/SearchForContentQueryParamsContentTypesField.java create mode 100644 src/main/java/com/box/sdkgen/managers/search/SearchForContentQueryParamsDirectionField.java create mode 100644 src/main/java/com/box/sdkgen/managers/search/SearchForContentQueryParamsScopeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/search/SearchForContentQueryParamsSortField.java create mode 100644 src/main/java/com/box/sdkgen/managers/search/SearchForContentQueryParamsTrashContentField.java create mode 100644 src/main/java/com/box/sdkgen/managers/search/SearchForContentQueryParamsTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/search/SearchManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/sessiontermination/SessionTerminationManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/sessiontermination/TerminateGroupsSessionsHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/sessiontermination/TerminateGroupsSessionsRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/sessiontermination/TerminateUsersSessionsHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/sessiontermination/TerminateUsersSessionsRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksappitems/FindAppItemForSharedLinkHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksappitems/SharedLinksAppItemsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfiles/AddShareLinkToFileHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfiles/AddShareLinkToFileQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfiles/AddShareLinkToFileRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfiles/AddShareLinkToFileRequestBodySharedLinkAccessField.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfiles/AddShareLinkToFileRequestBodySharedLinkField.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfiles/AddShareLinkToFileRequestBodySharedLinkPermissionsField.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfiles/FindFileForSharedLinkHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfiles/FindFileForSharedLinkQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfiles/GetSharedLinkForFileHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfiles/GetSharedLinkForFileQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfiles/RemoveSharedLinkFromFileHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfiles/RemoveSharedLinkFromFileQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfiles/RemoveSharedLinkFromFileRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfiles/RemoveSharedLinkFromFileRequestBodySharedLinkField.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfiles/SharedLinksFilesManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfiles/UpdateSharedLinkOnFileHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfiles/UpdateSharedLinkOnFileQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfiles/UpdateSharedLinkOnFileRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfiles/UpdateSharedLinkOnFileRequestBodySharedLinkAccessField.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfiles/UpdateSharedLinkOnFileRequestBodySharedLinkField.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfiles/UpdateSharedLinkOnFileRequestBodySharedLinkPermissionsField.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfolders/AddShareLinkToFolderHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfolders/AddShareLinkToFolderQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfolders/AddShareLinkToFolderRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfolders/AddShareLinkToFolderRequestBodySharedLinkAccessField.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfolders/AddShareLinkToFolderRequestBodySharedLinkField.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfolders/AddShareLinkToFolderRequestBodySharedLinkPermissionsField.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfolders/FindFolderForSharedLinkHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfolders/FindFolderForSharedLinkQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfolders/GetSharedLinkForFolderHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfolders/GetSharedLinkForFolderQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfolders/RemoveSharedLinkFromFolderHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfolders/RemoveSharedLinkFromFolderQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfolders/RemoveSharedLinkFromFolderRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfolders/RemoveSharedLinkFromFolderRequestBodySharedLinkField.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfolders/SharedLinksFoldersManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfolders/UpdateSharedLinkOnFolderHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfolders/UpdateSharedLinkOnFolderQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfolders/UpdateSharedLinkOnFolderRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfolders/UpdateSharedLinkOnFolderRequestBodySharedLinkAccessField.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfolders/UpdateSharedLinkOnFolderRequestBodySharedLinkField.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksfolders/UpdateSharedLinkOnFolderRequestBodySharedLinkPermissionsField.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksweblinks/AddShareLinkToWebLinkHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksweblinks/AddShareLinkToWebLinkQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksweblinks/AddShareLinkToWebLinkRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksweblinks/AddShareLinkToWebLinkRequestBodySharedLinkAccessField.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksweblinks/AddShareLinkToWebLinkRequestBodySharedLinkField.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksweblinks/AddShareLinkToWebLinkRequestBodySharedLinkPermissionsField.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksweblinks/FindWebLinkForSharedLinkHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksweblinks/FindWebLinkForSharedLinkQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksweblinks/GetSharedLinkForWebLinkHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksweblinks/GetSharedLinkForWebLinkQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksweblinks/RemoveSharedLinkFromWebLinkHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksweblinks/RemoveSharedLinkFromWebLinkQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksweblinks/RemoveSharedLinkFromWebLinkRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksweblinks/RemoveSharedLinkFromWebLinkRequestBodySharedLinkField.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksweblinks/SharedLinksWebLinksManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksweblinks/UpdateSharedLinkOnWebLinkHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksweblinks/UpdateSharedLinkOnWebLinkQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksweblinks/UpdateSharedLinkOnWebLinkRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksweblinks/UpdateSharedLinkOnWebLinkRequestBodySharedLinkAccessField.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksweblinks/UpdateSharedLinkOnWebLinkRequestBodySharedLinkField.java create mode 100644 src/main/java/com/box/sdkgen/managers/sharedlinksweblinks/UpdateSharedLinkOnWebLinkRequestBodySharedLinkPermissionsField.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarrierreports/CreateShieldInformationBarrierReportHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarrierreports/GetShieldInformationBarrierReportByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarrierreports/GetShieldInformationBarrierReportsHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarrierreports/GetShieldInformationBarrierReportsQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarrierreports/ShieldInformationBarrierReportsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriers/CreateShieldInformationBarrierHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriers/CreateShieldInformationBarrierRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriers/GetShieldInformationBarrierByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriers/GetShieldInformationBarriersHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriers/GetShieldInformationBarriersQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriers/ShieldInformationBarriersManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriers/UpdateShieldInformationBarrierStatusHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriers/UpdateShieldInformationBarrierStatusRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriers/UpdateShieldInformationBarrierStatusRequestBodyStatusField.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriersegmentmembers/CreateShieldInformationBarrierSegmentMemberHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriersegmentmembers/CreateShieldInformationBarrierSegmentMemberRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriersegmentmembers/CreateShieldInformationBarrierSegmentMemberRequestBodyShieldInformationBarrierSegmentField.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriersegmentmembers/CreateShieldInformationBarrierSegmentMemberRequestBodyShieldInformationBarrierSegmentTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriersegmentmembers/CreateShieldInformationBarrierSegmentMemberRequestBodyTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriersegmentmembers/DeleteShieldInformationBarrierSegmentMemberByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriersegmentmembers/GetShieldInformationBarrierSegmentMemberByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriersegmentmembers/GetShieldInformationBarrierSegmentMembersHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriersegmentmembers/GetShieldInformationBarrierSegmentMembersQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriersegmentmembers/ShieldInformationBarrierSegmentMembersManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriersegmentrestrictions/CreateShieldInformationBarrierSegmentRestrictionHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriersegmentrestrictions/CreateShieldInformationBarrierSegmentRestrictionRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriersegmentrestrictions/CreateShieldInformationBarrierSegmentRestrictionRequestBodyRestrictedSegmentField.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriersegmentrestrictions/CreateShieldInformationBarrierSegmentRestrictionRequestBodyRestrictedSegmentTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriersegmentrestrictions/CreateShieldInformationBarrierSegmentRestrictionRequestBodyShieldInformationBarrierSegmentField.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriersegmentrestrictions/CreateShieldInformationBarrierSegmentRestrictionRequestBodyShieldInformationBarrierSegmentTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriersegmentrestrictions/CreateShieldInformationBarrierSegmentRestrictionRequestBodyTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriersegmentrestrictions/DeleteShieldInformationBarrierSegmentRestrictionByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriersegmentrestrictions/GetShieldInformationBarrierSegmentRestrictionByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriersegmentrestrictions/GetShieldInformationBarrierSegmentRestrictionsHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriersegmentrestrictions/GetShieldInformationBarrierSegmentRestrictionsQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriersegmentrestrictions/ShieldInformationBarrierSegmentRestrictionsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriersegments/CreateShieldInformationBarrierSegmentHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriersegments/CreateShieldInformationBarrierSegmentRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriersegments/DeleteShieldInformationBarrierSegmentByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriersegments/GetShieldInformationBarrierSegmentByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriersegments/GetShieldInformationBarrierSegmentsHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriersegments/GetShieldInformationBarrierSegmentsQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriersegments/ShieldInformationBarrierSegmentsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriersegments/UpdateShieldInformationBarrierSegmentByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldinformationbarriersegments/UpdateShieldInformationBarrierSegmentByIdRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldlists/CreateShieldListV2025R0Headers.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldlists/DeleteShieldListByIdV2025R0Headers.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldlists/GetShieldListByIdV2025R0Headers.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldlists/GetShieldListsV2025R0Headers.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldlists/ShieldListsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/shieldlists/UpdateShieldListByIdV2025R0Headers.java create mode 100644 src/main/java/com/box/sdkgen/managers/signrequests/CancelSignRequestHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/signrequests/CreateSignRequestHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/signrequests/GetSignRequestByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/signrequests/GetSignRequestsHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/signrequests/GetSignRequestsQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/signrequests/ResendSignRequestHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/signrequests/SignRequestsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/signtemplates/GetSignTemplateByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/signtemplates/GetSignTemplatesHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/signtemplates/GetSignTemplatesQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/signtemplates/SignTemplatesManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/skills/CreateBoxSkillCardsOnFileHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/skills/CreateBoxSkillCardsOnFileRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/skills/DeleteBoxSkillCardsFromFileHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/skills/GetBoxSkillCardsOnFileHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/skills/SkillsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/skills/UpdateAllSkillCardsOnFileHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/skills/UpdateAllSkillCardsOnFileRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/skills/UpdateAllSkillCardsOnFileRequestBodyFileField.java create mode 100644 src/main/java/com/box/sdkgen/managers/skills/UpdateAllSkillCardsOnFileRequestBodyFileTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/skills/UpdateAllSkillCardsOnFileRequestBodyFileVersionField.java create mode 100644 src/main/java/com/box/sdkgen/managers/skills/UpdateAllSkillCardsOnFileRequestBodyFileVersionTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/skills/UpdateAllSkillCardsOnFileRequestBodyMetadataField.java create mode 100644 src/main/java/com/box/sdkgen/managers/skills/UpdateAllSkillCardsOnFileRequestBodyStatusField.java create mode 100644 src/main/java/com/box/sdkgen/managers/skills/UpdateAllSkillCardsOnFileRequestBodyUsageField.java create mode 100644 src/main/java/com/box/sdkgen/managers/skills/UpdateBoxSkillCardsOnFileHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/skills/UpdateBoxSkillCardsOnFileRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/skills/UpdateBoxSkillCardsOnFileRequestBodyOpField.java create mode 100644 src/main/java/com/box/sdkgen/managers/storagepolicies/GetStoragePoliciesHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/storagepolicies/GetStoragePoliciesQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/storagepolicies/GetStoragePolicyByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/storagepolicies/StoragePoliciesManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/storagepolicyassignments/CreateStoragePolicyAssignmentHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/storagepolicyassignments/CreateStoragePolicyAssignmentRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/storagepolicyassignments/CreateStoragePolicyAssignmentRequestBodyAssignedToField.java create mode 100644 src/main/java/com/box/sdkgen/managers/storagepolicyassignments/CreateStoragePolicyAssignmentRequestBodyAssignedToTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/storagepolicyassignments/CreateStoragePolicyAssignmentRequestBodyStoragePolicyField.java create mode 100644 src/main/java/com/box/sdkgen/managers/storagepolicyassignments/CreateStoragePolicyAssignmentRequestBodyStoragePolicyTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/storagepolicyassignments/DeleteStoragePolicyAssignmentByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/storagepolicyassignments/GetStoragePolicyAssignmentByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/storagepolicyassignments/GetStoragePolicyAssignmentsHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/storagepolicyassignments/GetStoragePolicyAssignmentsQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/storagepolicyassignments/GetStoragePolicyAssignmentsQueryParamsResolvedForTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/storagepolicyassignments/StoragePolicyAssignmentsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/storagepolicyassignments/UpdateStoragePolicyAssignmentByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/storagepolicyassignments/UpdateStoragePolicyAssignmentByIdRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/storagepolicyassignments/UpdateStoragePolicyAssignmentByIdRequestBodyStoragePolicyField.java create mode 100644 src/main/java/com/box/sdkgen/managers/storagepolicyassignments/UpdateStoragePolicyAssignmentByIdRequestBodyStoragePolicyTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/taskassignments/CreateTaskAssignmentHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/taskassignments/CreateTaskAssignmentRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/taskassignments/CreateTaskAssignmentRequestBodyAssignToField.java create mode 100644 src/main/java/com/box/sdkgen/managers/taskassignments/CreateTaskAssignmentRequestBodyTaskField.java create mode 100644 src/main/java/com/box/sdkgen/managers/taskassignments/CreateTaskAssignmentRequestBodyTaskTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/taskassignments/DeleteTaskAssignmentByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/taskassignments/GetTaskAssignmentByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/taskassignments/GetTaskAssignmentsHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/taskassignments/TaskAssignmentsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/taskassignments/UpdateTaskAssignmentByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/taskassignments/UpdateTaskAssignmentByIdRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/taskassignments/UpdateTaskAssignmentByIdRequestBodyResolutionStateField.java create mode 100644 src/main/java/com/box/sdkgen/managers/tasks/CreateTaskHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/tasks/CreateTaskRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/tasks/CreateTaskRequestBodyActionField.java create mode 100644 src/main/java/com/box/sdkgen/managers/tasks/CreateTaskRequestBodyCompletionRuleField.java create mode 100644 src/main/java/com/box/sdkgen/managers/tasks/CreateTaskRequestBodyItemField.java create mode 100644 src/main/java/com/box/sdkgen/managers/tasks/CreateTaskRequestBodyItemTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/tasks/DeleteTaskByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/tasks/GetFileTasksHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/tasks/GetTaskByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/tasks/TasksManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/tasks/UpdateTaskByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/tasks/UpdateTaskByIdRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/tasks/UpdateTaskByIdRequestBodyActionField.java create mode 100644 src/main/java/com/box/sdkgen/managers/tasks/UpdateTaskByIdRequestBodyCompletionRuleField.java create mode 100644 src/main/java/com/box/sdkgen/managers/termsofservices/CreateTermsOfServiceHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/termsofservices/CreateTermsOfServiceRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/termsofservices/CreateTermsOfServiceRequestBodyStatusField.java create mode 100644 src/main/java/com/box/sdkgen/managers/termsofservices/CreateTermsOfServiceRequestBodyTosTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/termsofservices/GetTermsOfServiceByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/termsofservices/GetTermsOfServiceHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/termsofservices/GetTermsOfServiceQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/termsofservices/GetTermsOfServiceQueryParamsTosTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/termsofservices/TermsOfServicesManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/termsofservices/UpdateTermsOfServiceByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/termsofservices/UpdateTermsOfServiceByIdRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/termsofservices/UpdateTermsOfServiceByIdRequestBodyStatusField.java create mode 100644 src/main/java/com/box/sdkgen/managers/termsofserviceuserstatuses/CreateTermsOfServiceStatusForUserHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/termsofserviceuserstatuses/CreateTermsOfServiceStatusForUserRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/termsofserviceuserstatuses/CreateTermsOfServiceStatusForUserRequestBodyTosField.java create mode 100644 src/main/java/com/box/sdkgen/managers/termsofserviceuserstatuses/CreateTermsOfServiceStatusForUserRequestBodyTosTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/termsofserviceuserstatuses/CreateTermsOfServiceStatusForUserRequestBodyUserField.java create mode 100644 src/main/java/com/box/sdkgen/managers/termsofserviceuserstatuses/CreateTermsOfServiceStatusForUserRequestBodyUserTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/termsofserviceuserstatuses/GetTermsOfServiceUserStatusesHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/termsofserviceuserstatuses/GetTermsOfServiceUserStatusesQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/termsofserviceuserstatuses/TermsOfServiceUserStatusesManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/termsofserviceuserstatuses/UpdateTermsOfServiceStatusForUserByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/termsofserviceuserstatuses/UpdateTermsOfServiceStatusForUserByIdRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/transfer/TransferManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/transfer/TransferOwnedFolderHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/transfer/TransferOwnedFolderQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/transfer/TransferOwnedFolderRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/transfer/TransferOwnedFolderRequestBodyOwnedByField.java create mode 100644 src/main/java/com/box/sdkgen/managers/trashedfiles/DeleteTrashedFileByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/trashedfiles/GetTrashedFileByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/trashedfiles/GetTrashedFileByIdQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/trashedfiles/RestoreFileFromTrashHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/trashedfiles/RestoreFileFromTrashQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/trashedfiles/RestoreFileFromTrashRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/trashedfiles/RestoreFileFromTrashRequestBodyParentField.java create mode 100644 src/main/java/com/box/sdkgen/managers/trashedfiles/TrashedFilesManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/trashedfolders/DeleteTrashedFolderByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/trashedfolders/GetTrashedFolderByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/trashedfolders/GetTrashedFolderByIdQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/trashedfolders/RestoreFolderFromTrashHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/trashedfolders/RestoreFolderFromTrashQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/trashedfolders/RestoreFolderFromTrashRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/trashedfolders/RestoreFolderFromTrashRequestBodyParentField.java create mode 100644 src/main/java/com/box/sdkgen/managers/trashedfolders/TrashedFoldersManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/trasheditems/GetTrashedItemsHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/trasheditems/GetTrashedItemsQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/trasheditems/GetTrashedItemsQueryParamsDirectionField.java create mode 100644 src/main/java/com/box/sdkgen/managers/trasheditems/GetTrashedItemsQueryParamsSortField.java create mode 100644 src/main/java/com/box/sdkgen/managers/trasheditems/TrashedItemsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/trashedweblinks/DeleteTrashedWebLinkByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/trashedweblinks/GetTrashedWebLinkByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/trashedweblinks/GetTrashedWebLinkByIdQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/trashedweblinks/RestoreWeblinkFromTrashHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/trashedweblinks/RestoreWeblinkFromTrashQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/trashedweblinks/RestoreWeblinkFromTrashRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/trashedweblinks/RestoreWeblinkFromTrashRequestBodyParentField.java create mode 100644 src/main/java/com/box/sdkgen/managers/trashedweblinks/TrashedWebLinksManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/uploads/PreflightFileUploadCheckHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/uploads/PreflightFileUploadCheckRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/uploads/PreflightFileUploadCheckRequestBodyParentField.java create mode 100644 src/main/java/com/box/sdkgen/managers/uploads/UploadFileHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/uploads/UploadFileQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/uploads/UploadFileRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/uploads/UploadFileRequestBodyAttributesField.java create mode 100644 src/main/java/com/box/sdkgen/managers/uploads/UploadFileRequestBodyAttributesParentField.java create mode 100644 src/main/java/com/box/sdkgen/managers/uploads/UploadFileVersionHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/uploads/UploadFileVersionQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/uploads/UploadFileVersionRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/uploads/UploadFileVersionRequestBodyAttributesField.java create mode 100644 src/main/java/com/box/sdkgen/managers/uploads/UploadWithPreflightCheckHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/uploads/UploadWithPreflightCheckQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/uploads/UploadWithPreflightCheckRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/uploads/UploadWithPreflightCheckRequestBodyAttributesField.java create mode 100644 src/main/java/com/box/sdkgen/managers/uploads/UploadWithPreflightCheckRequestBodyAttributesParentField.java create mode 100644 src/main/java/com/box/sdkgen/managers/uploads/UploadsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/usercollaborations/CreateCollaborationHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/usercollaborations/CreateCollaborationQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/usercollaborations/CreateCollaborationRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/usercollaborations/CreateCollaborationRequestBodyAccessibleByField.java create mode 100644 src/main/java/com/box/sdkgen/managers/usercollaborations/CreateCollaborationRequestBodyAccessibleByTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/usercollaborations/CreateCollaborationRequestBodyItemField.java create mode 100644 src/main/java/com/box/sdkgen/managers/usercollaborations/CreateCollaborationRequestBodyItemTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/usercollaborations/CreateCollaborationRequestBodyRoleField.java create mode 100644 src/main/java/com/box/sdkgen/managers/usercollaborations/DeleteCollaborationByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/usercollaborations/GetCollaborationByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/usercollaborations/GetCollaborationByIdQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/usercollaborations/UpdateCollaborationByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/usercollaborations/UpdateCollaborationByIdRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/usercollaborations/UpdateCollaborationByIdRequestBodyRoleField.java create mode 100644 src/main/java/com/box/sdkgen/managers/usercollaborations/UpdateCollaborationByIdRequestBodyStatusField.java create mode 100644 src/main/java/com/box/sdkgen/managers/usercollaborations/UserCollaborationsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/users/CreateUserHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/users/CreateUserQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/users/CreateUserRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/users/CreateUserRequestBodyRoleField.java create mode 100644 src/main/java/com/box/sdkgen/managers/users/CreateUserRequestBodyStatusField.java create mode 100644 src/main/java/com/box/sdkgen/managers/users/DeleteUserByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/users/DeleteUserByIdQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/users/GetUserByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/users/GetUserByIdQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/users/GetUserMeHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/users/GetUserMeQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/users/GetUsersHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/users/GetUsersQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/users/GetUsersQueryParamsUserTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/users/UpdateUserByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/users/UpdateUserByIdQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/users/UpdateUserByIdRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/users/UpdateUserByIdRequestBodyNotificationEmailField.java create mode 100644 src/main/java/com/box/sdkgen/managers/users/UpdateUserByIdRequestBodyRoleField.java create mode 100644 src/main/java/com/box/sdkgen/managers/users/UpdateUserByIdRequestBodyStatusField.java create mode 100644 src/main/java/com/box/sdkgen/managers/users/UsersManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/webhooks/CreateWebhookHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/webhooks/CreateWebhookRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/webhooks/CreateWebhookRequestBodyTargetField.java create mode 100644 src/main/java/com/box/sdkgen/managers/webhooks/CreateWebhookRequestBodyTargetTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/webhooks/CreateWebhookRequestBodyTriggersField.java create mode 100644 src/main/java/com/box/sdkgen/managers/webhooks/DeleteWebhookByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/webhooks/GetWebhookByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/webhooks/GetWebhooksHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/webhooks/GetWebhooksQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/webhooks/UpdateWebhookByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/webhooks/UpdateWebhookByIdRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/webhooks/UpdateWebhookByIdRequestBodyTargetField.java create mode 100644 src/main/java/com/box/sdkgen/managers/webhooks/UpdateWebhookByIdRequestBodyTargetTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/webhooks/UpdateWebhookByIdRequestBodyTriggersField.java create mode 100644 src/main/java/com/box/sdkgen/managers/webhooks/WebhooksManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/weblinks/CreateWebLinkHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/weblinks/CreateWebLinkRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/weblinks/CreateWebLinkRequestBodyParentField.java create mode 100644 src/main/java/com/box/sdkgen/managers/weblinks/DeleteWebLinkByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/weblinks/GetWebLinkByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/weblinks/UpdateWebLinkByIdHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/weblinks/UpdateWebLinkByIdRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/weblinks/UpdateWebLinkByIdRequestBodyParentField.java create mode 100644 src/main/java/com/box/sdkgen/managers/weblinks/UpdateWebLinkByIdRequestBodySharedLinkAccessField.java create mode 100644 src/main/java/com/box/sdkgen/managers/weblinks/UpdateWebLinkByIdRequestBodySharedLinkField.java create mode 100644 src/main/java/com/box/sdkgen/managers/weblinks/WebLinksManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/workflows/GetWorkflowsHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/workflows/GetWorkflowsQueryParams.java create mode 100644 src/main/java/com/box/sdkgen/managers/workflows/StartWorkflowHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/workflows/StartWorkflowRequestBody.java create mode 100644 src/main/java/com/box/sdkgen/managers/workflows/StartWorkflowRequestBodyFilesField.java create mode 100644 src/main/java/com/box/sdkgen/managers/workflows/StartWorkflowRequestBodyFilesTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/workflows/StartWorkflowRequestBodyFlowField.java create mode 100644 src/main/java/com/box/sdkgen/managers/workflows/StartWorkflowRequestBodyFolderField.java create mode 100644 src/main/java/com/box/sdkgen/managers/workflows/StartWorkflowRequestBodyFolderTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/workflows/StartWorkflowRequestBodyTypeField.java create mode 100644 src/main/java/com/box/sdkgen/managers/workflows/WorkflowsManager.java create mode 100644 src/main/java/com/box/sdkgen/managers/zipdownloads/CreateZipDownloadHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/zipdownloads/DownloadZipHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/zipdownloads/GetZipDownloadContentHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/zipdownloads/GetZipDownloadStatusHeaders.java create mode 100644 src/main/java/com/box/sdkgen/managers/zipdownloads/ZipDownloadsManager.java create mode 100644 src/main/java/com/box/sdkgen/networking/auth/Authentication.java create mode 100644 src/main/java/com/box/sdkgen/networking/baseurls/BaseUrls.java create mode 100644 src/main/java/com/box/sdkgen/networking/boxnetworkclient/BoxNetworkClient.java create mode 100644 src/main/java/com/box/sdkgen/networking/defaultnetworkclient/DefaultNetworkClient.java create mode 100644 src/main/java/com/box/sdkgen/networking/fetchoptions/FetchOptions.java create mode 100644 src/main/java/com/box/sdkgen/networking/fetchoptions/MultipartItem.java create mode 100644 src/main/java/com/box/sdkgen/networking/fetchoptions/ResponseFormat.java create mode 100644 src/main/java/com/box/sdkgen/networking/fetchresponse/FetchResponse.java create mode 100644 src/main/java/com/box/sdkgen/networking/interceptors/Interceptor.java create mode 100644 src/main/java/com/box/sdkgen/networking/network/NetworkSession.java create mode 100644 src/main/java/com/box/sdkgen/networking/networkclient/NetworkClient.java create mode 100644 src/main/java/com/box/sdkgen/networking/proxyconfig/ProxyConfig.java create mode 100644 src/main/java/com/box/sdkgen/networking/retries/BoxRetryStrategy.java create mode 100644 src/main/java/com/box/sdkgen/networking/retries/RetryStrategy.java create mode 100644 src/main/java/com/box/sdkgen/networking/version/Version.java create mode 100644 src/main/java/com/box/sdkgen/parameters/v2025r0/boxversionheaderv2025r0/BoxVersionHeaderV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/accesstoken/AccessToken.java create mode 100644 src/main/java/com/box/sdkgen/schemas/accesstoken/AccessTokenIssuedTokenTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/accesstoken/AccessTokenTokenTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiagent/AiAgent.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiagentallowedentity/AiAgentAllowedEntity.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiagentask/AiAgentAsk.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiagentask/AiAgentAskTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiagentbasicgentool/AiAgentBasicGenTool.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiagentbasictexttool/AiAgentBasicTextTool.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiagentbasictexttoolbase/AiAgentBasicTextToolBase.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiagentbasictexttooltextgen/AiAgentBasicTextToolTextGen.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiagentextract/AiAgentExtract.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiagentextract/AiAgentExtractTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiagentextractstructured/AiAgentExtractStructured.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiagentextractstructured/AiAgentExtractStructuredTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiagentinfo/AiAgentInfo.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiagentinfo/AiAgentInfoModelsField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiagentlongtexttool/AiAgentLongTextTool.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiagentlongtexttool/AiAgentLongTextToolEmbeddingsField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiagentlongtexttool/AiAgentLongTextToolEmbeddingsStrategyField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiagentlongtexttooltextgen/AiAgentLongTextToolTextGen.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiagentlongtexttooltextgen/AiAgentLongTextToolTextGenEmbeddingsField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiagentlongtexttooltextgen/AiAgentLongTextToolTextGenEmbeddingsStrategyField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiagentreference/AiAgentReference.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiagentreference/AiAgentReferenceTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiagentspreadsheettool/AiAgentSpreadsheetTool.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiagenttextgen/AiAgentTextGen.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiagenttextgen/AiAgentTextGenTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiask/AiAsk.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiask/AiAskModeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiaskagent/AiAskAgent.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aicitation/AiCitation.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aicitation/AiCitationTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aidialoguehistory/AiDialogueHistory.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiextract/AiExtract.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiextractagent/AiExtractAgent.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiextractresponse/AiExtractResponse.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiextractstructured/AiExtractStructured.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiextractstructured/AiExtractStructuredFieldsField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiextractstructured/AiExtractStructuredFieldsOptionsField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiextractstructured/AiExtractStructuredMetadataTemplateField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiextractstructured/AiExtractStructuredMetadataTemplateTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiextractstructuredagent/AiExtractStructuredAgent.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiextractstructuredresponse/AiExtractStructuredResponse.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiitemask/AiItemAsk.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiitemask/AiItemAskTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiitembase/AiItemBase.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aiitembase/AiItemBaseTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aillmendpointparams/AiLlmEndpointParams.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aillmendpointparamsaws/AiLlmEndpointParamsAws.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aillmendpointparamsaws/AiLlmEndpointParamsAwsTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aillmendpointparamsgoogle/AiLlmEndpointParamsGoogle.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aillmendpointparamsgoogle/AiLlmEndpointParamsGoogleTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aillmendpointparamsibm/AiLlmEndpointParamsIbm.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aillmendpointparamsibm/AiLlmEndpointParamsIbmTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aillmendpointparamsopenai/AiLlmEndpointParamsOpenAi.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aillmendpointparamsopenai/AiLlmEndpointParamsOpenAiTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aimultipleagentresponse/AiMultipleAgentResponse.java create mode 100644 src/main/java/com/box/sdkgen/schemas/airesponse/AiResponse.java create mode 100644 src/main/java/com/box/sdkgen/schemas/airesponsefull/AiResponseFull.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aisingleagentresponse/AiSingleAgentResponse.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aisingleagentresponse/AiSingleAgentResponseTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aisingleagentresponsefull/AiSingleAgentResponseFull.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aistudioagentask/AiStudioAgentAsk.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aistudioagentask/AiStudioAgentAskTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aistudioagentaskresponse/AiStudioAgentAskResponse.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aistudioagentaskresponse/AiStudioAgentAskResponseTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aistudioagentbasicgentool/AiStudioAgentBasicGenTool.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aistudioagentbasicgentoolresponse/AiStudioAgentBasicGenToolResponse.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aistudioagentbasictexttool/AiStudioAgentBasicTextTool.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aistudioagentbasictexttoolresponse/AiStudioAgentBasicTextToolResponse.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aistudioagentextract/AiStudioAgentExtract.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aistudioagentextract/AiStudioAgentExtractTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aistudioagentextractresponse/AiStudioAgentExtractResponse.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aistudioagentextractresponse/AiStudioAgentExtractResponseTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aistudioagentlongtexttool/AiStudioAgentLongTextTool.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aistudioagentlongtexttoolresponse/AiStudioAgentLongTextToolResponse.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aistudioagentspreadsheettool/AiStudioAgentSpreadsheetTool.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aistudioagentspreadsheettoolresponse/AiStudioAgentSpreadsheetToolResponse.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aistudioagenttextgen/AiStudioAgentTextGen.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aistudioagenttextgen/AiStudioAgentTextGenTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aistudioagenttextgenresponse/AiStudioAgentTextGenResponse.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aistudioagenttextgenresponse/AiStudioAgentTextGenResponseTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aitextgen/AiTextGen.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aitextgen/AiTextGenItemsField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aitextgen/AiTextGenItemsTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/aitextgenagent/AiTextGenAgent.java create mode 100644 src/main/java/com/box/sdkgen/schemas/appitem/AppItem.java create mode 100644 src/main/java/com/box/sdkgen/schemas/appitem/AppItemTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/appitemassociateditem/AppItemAssociatedItem.java create mode 100644 src/main/java/com/box/sdkgen/schemas/appitemassociation/AppItemAssociation.java create mode 100644 src/main/java/com/box/sdkgen/schemas/appitemassociation/AppItemAssociationTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/appitemassociations/AppItemAssociations.java create mode 100644 src/main/java/com/box/sdkgen/schemas/appitemeventsource/AppItemEventSource.java create mode 100644 src/main/java/com/box/sdkgen/schemas/appitemeventsource/AppItemEventSourceTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/classification/Classification.java create mode 100644 src/main/java/com/box/sdkgen/schemas/classification/ClassificationTemplateField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/classificationtemplate/ClassificationTemplate.java create mode 100644 src/main/java/com/box/sdkgen/schemas/classificationtemplate/ClassificationTemplateDisplayNameField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/classificationtemplate/ClassificationTemplateFieldsDisplayNameField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/classificationtemplate/ClassificationTemplateFieldsField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/classificationtemplate/ClassificationTemplateFieldsKeyField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/classificationtemplate/ClassificationTemplateFieldsOptionsField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/classificationtemplate/ClassificationTemplateFieldsOptionsStaticConfigClassificationField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/classificationtemplate/ClassificationTemplateFieldsOptionsStaticConfigField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/classificationtemplate/ClassificationTemplateFieldsTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/classificationtemplate/ClassificationTemplateTemplateKeyField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/classificationtemplate/ClassificationTemplateTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/clienterror/ClientError.java create mode 100644 src/main/java/com/box/sdkgen/schemas/clienterror/ClientErrorCodeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/clienterror/ClientErrorTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/collaboration/Collaboration.java create mode 100644 src/main/java/com/box/sdkgen/schemas/collaboration/CollaborationAcceptanceRequirementsStatusField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/collaboration/CollaborationAcceptanceRequirementsStatusStrongPasswordRequirementField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/collaboration/CollaborationAcceptanceRequirementsStatusTermsOfServiceRequirementField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/collaboration/CollaborationAcceptanceRequirementsStatusTwoFactorAuthenticationRequirementField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/collaboration/CollaborationRoleField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/collaboration/CollaborationStatusField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/collaboration/CollaborationTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/collaborationaccessgrantee/CollaborationAccessGrantee.java create mode 100644 src/main/java/com/box/sdkgen/schemas/collaborationallowlistentries/CollaborationAllowlistEntries.java create mode 100644 src/main/java/com/box/sdkgen/schemas/collaborationallowlistentry/CollaborationAllowlistEntry.java create mode 100644 src/main/java/com/box/sdkgen/schemas/collaborationallowlistentry/CollaborationAllowlistEntryDirectionField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/collaborationallowlistentry/CollaborationAllowlistEntryEnterpriseField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/collaborationallowlistentry/CollaborationAllowlistEntryEnterpriseTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/collaborationallowlistentry/CollaborationAllowlistEntryTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/collaborationallowlistexempttarget/CollaborationAllowlistExemptTarget.java create mode 100644 src/main/java/com/box/sdkgen/schemas/collaborationallowlistexempttarget/CollaborationAllowlistExemptTargetEnterpriseField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/collaborationallowlistexempttarget/CollaborationAllowlistExemptTargetEnterpriseTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/collaborationallowlistexempttarget/CollaborationAllowlistExemptTargetTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/collaborationallowlistexempttargets/CollaborationAllowlistExemptTargets.java create mode 100644 src/main/java/com/box/sdkgen/schemas/collaborationitem/CollaborationItem.java create mode 100644 src/main/java/com/box/sdkgen/schemas/collaborations/Collaborations.java create mode 100644 src/main/java/com/box/sdkgen/schemas/collaborationsoffsetpaginated/CollaborationsOffsetPaginated.java create mode 100644 src/main/java/com/box/sdkgen/schemas/collaboratorvariable/CollaboratorVariable.java create mode 100644 src/main/java/com/box/sdkgen/schemas/collaboratorvariable/CollaboratorVariableTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/collaboratorvariable/CollaboratorVariableVariableTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/collaboratorvariable/CollaboratorVariableVariableValueField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/collaboratorvariable/CollaboratorVariableVariableValueTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/collection/Collection.java create mode 100644 src/main/java/com/box/sdkgen/schemas/collection/CollectionCollectionTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/collection/CollectionNameField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/collection/CollectionTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/collections/Collections.java create mode 100644 src/main/java/com/box/sdkgen/schemas/collections/CollectionsOrderDirectionField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/collections/CollectionsOrderField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/comment/Comment.java create mode 100644 src/main/java/com/box/sdkgen/schemas/comment/CommentItemField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/commentbase/CommentBase.java create mode 100644 src/main/java/com/box/sdkgen/schemas/commentbase/CommentBaseTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/commentfull/CommentFull.java create mode 100644 src/main/java/com/box/sdkgen/schemas/comments/Comments.java create mode 100644 src/main/java/com/box/sdkgen/schemas/comments/CommentsOrderDirectionField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/comments/CommentsOrderField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/completionrulevariable/CompletionRuleVariable.java create mode 100644 src/main/java/com/box/sdkgen/schemas/completionrulevariable/CompletionRuleVariableTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/completionrulevariable/CompletionRuleVariableVariableTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/completionrulevariable/CompletionRuleVariableVariableValueField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/conflicterror/ConflictError.java create mode 100644 src/main/java/com/box/sdkgen/schemas/conflicterror/ConflictErrorContextInfoField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/createaiagent/CreateAiAgent.java create mode 100644 src/main/java/com/box/sdkgen/schemas/createaiagent/CreateAiAgentTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/devicepinner/DevicePinner.java create mode 100644 src/main/java/com/box/sdkgen/schemas/devicepinner/DevicePinnerTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/devicepinners/DevicePinners.java create mode 100644 src/main/java/com/box/sdkgen/schemas/devicepinners/DevicePinnersOrderByField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/devicepinners/DevicePinnersOrderDirectionField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/devicepinners/DevicePinnersOrderField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/emailalias/EmailAlias.java create mode 100644 src/main/java/com/box/sdkgen/schemas/emailalias/EmailAliasTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/emailaliases/EmailAliases.java create mode 100644 src/main/java/com/box/sdkgen/schemas/enterprisebase/EnterpriseBase.java create mode 100644 src/main/java/com/box/sdkgen/schemas/enterprisebase/EnterpriseBaseTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/event/Event.java create mode 100644 src/main/java/com/box/sdkgen/schemas/event/EventAdditionalDetailsField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/event/EventEventTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/events/Events.java create mode 100644 src/main/java/com/box/sdkgen/schemas/events/EventsNextStreamPositionField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/eventsource/EventSource.java create mode 100644 src/main/java/com/box/sdkgen/schemas/eventsource/EventSourceClassificationField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/eventsource/EventSourceItemTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/eventsourceresource/EventSourceResource.java create mode 100644 src/main/java/com/box/sdkgen/schemas/file/File.java create mode 100644 src/main/java/com/box/sdkgen/schemas/file/FileItemStatusField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/file/FilePathCollectionField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/file/FileSharedLinkAccessField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/file/FileSharedLinkEffectiveAccessField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/file/FileSharedLinkEffectivePermissionField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/file/FileSharedLinkField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/file/FileSharedLinkPermissionsField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/filebase/FileBase.java create mode 100644 src/main/java/com/box/sdkgen/schemas/filebase/FileBaseTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/fileconflict/FileConflict.java create mode 100644 src/main/java/com/box/sdkgen/schemas/filefull/FileFull.java create mode 100644 src/main/java/com/box/sdkgen/schemas/filefull/FileFullAllowedInviteeRolesField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/filefull/FileFullClassificationField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/filefull/FileFullExpiringEmbedLinkField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/filefull/FileFullExpiringEmbedLinkTokenTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/filefull/FileFullLockAppTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/filefull/FileFullLockField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/filefull/FileFullLockTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/filefull/FileFullMetadataField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/filefull/FileFullPermissionsField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/filefull/FileFullRepresentationsEntriesContentField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/filefull/FileFullRepresentationsEntriesField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/filefull/FileFullRepresentationsEntriesInfoField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/filefull/FileFullRepresentationsEntriesPropertiesField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/filefull/FileFullRepresentationsEntriesStatusField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/filefull/FileFullRepresentationsEntriesStatusStateField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/filefull/FileFullRepresentationsField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/filefull/FileFullSharedLinkPermissionOptionsField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/filefull/FileFullWatermarkInfoField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/filemini/FileMini.java create mode 100644 src/main/java/com/box/sdkgen/schemas/filerequest/FileRequest.java create mode 100644 src/main/java/com/box/sdkgen/schemas/filerequest/FileRequestStatusField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/filerequest/FileRequestTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/filerequestcopyrequest/FileRequestCopyRequest.java create mode 100644 src/main/java/com/box/sdkgen/schemas/filerequestcopyrequest/FileRequestCopyRequestFolderField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/filerequestcopyrequest/FileRequestCopyRequestFolderTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/filerequestupdaterequest/FileRequestUpdateRequest.java create mode 100644 src/main/java/com/box/sdkgen/schemas/filerequestupdaterequest/FileRequestUpdateRequestStatusField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/files/Files.java create mode 100644 src/main/java/com/box/sdkgen/schemas/filesonhold/FilesOnHold.java create mode 100644 src/main/java/com/box/sdkgen/schemas/filesunderretention/FilesUnderRetention.java create mode 100644 src/main/java/com/box/sdkgen/schemas/fileversion/FileVersion.java create mode 100644 src/main/java/com/box/sdkgen/schemas/fileversionbase/FileVersionBase.java create mode 100644 src/main/java/com/box/sdkgen/schemas/fileversionbase/FileVersionBaseTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/fileversionfull/FileVersionFull.java create mode 100644 src/main/java/com/box/sdkgen/schemas/fileversionlegalhold/FileVersionLegalHold.java create mode 100644 src/main/java/com/box/sdkgen/schemas/fileversionlegalhold/FileVersionLegalHoldTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/fileversionlegalholds/FileVersionLegalHolds.java create mode 100644 src/main/java/com/box/sdkgen/schemas/fileversionmini/FileVersionMini.java create mode 100644 src/main/java/com/box/sdkgen/schemas/fileversionretention/FileVersionRetention.java create mode 100644 src/main/java/com/box/sdkgen/schemas/fileversionretention/FileVersionRetentionTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/fileversionretentions/FileVersionRetentions.java create mode 100644 src/main/java/com/box/sdkgen/schemas/fileversions/FileVersions.java create mode 100644 src/main/java/com/box/sdkgen/schemas/fileversions/FileVersionsOrderDirectionField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/fileversions/FileVersionsOrderField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/folder/Folder.java create mode 100644 src/main/java/com/box/sdkgen/schemas/folder/FolderFolderUploadEmailAccessField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/folder/FolderFolderUploadEmailField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/folder/FolderItemStatusField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/folder/FolderPathCollectionField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/folder/FolderSharedLinkAccessField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/folder/FolderSharedLinkEffectiveAccessField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/folder/FolderSharedLinkEffectivePermissionField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/folder/FolderSharedLinkField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/folder/FolderSharedLinkPermissionsField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/folderbase/FolderBase.java create mode 100644 src/main/java/com/box/sdkgen/schemas/folderbase/FolderBaseTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/folderfull/FolderFull.java create mode 100644 src/main/java/com/box/sdkgen/schemas/folderfull/FolderFullAllowedInviteeRolesField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/folderfull/FolderFullAllowedSharedLinkAccessLevelsField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/folderfull/FolderFullClassificationField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/folderfull/FolderFullMetadataField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/folderfull/FolderFullPermissionsField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/folderfull/FolderFullSyncStateField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/folderfull/FolderFullWatermarkInfoField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/folderlock/FolderLock.java create mode 100644 src/main/java/com/box/sdkgen/schemas/folderlock/FolderLockLockedOperationsField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/folderlocks/FolderLocks.java create mode 100644 src/main/java/com/box/sdkgen/schemas/foldermini/FolderMini.java create mode 100644 src/main/java/com/box/sdkgen/schemas/folderreference/FolderReference.java create mode 100644 src/main/java/com/box/sdkgen/schemas/folderreference/FolderReferenceTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/group/Group.java create mode 100644 src/main/java/com/box/sdkgen/schemas/groupbase/GroupBase.java create mode 100644 src/main/java/com/box/sdkgen/schemas/groupbase/GroupBaseTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/groupfull/GroupFull.java create mode 100644 src/main/java/com/box/sdkgen/schemas/groupfull/GroupFullInvitabilityLevelField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/groupfull/GroupFullMemberViewabilityLevelField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/groupfull/GroupFullPermissionsField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/groupmembership/GroupMembership.java create mode 100644 src/main/java/com/box/sdkgen/schemas/groupmembership/GroupMembershipRoleField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/groupmembership/GroupMembershipTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/groupmemberships/GroupMemberships.java create mode 100644 src/main/java/com/box/sdkgen/schemas/groupmemberships/GroupMembershipsOrderDirectionField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/groupmemberships/GroupMembershipsOrderField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/groupmini/GroupMini.java create mode 100644 src/main/java/com/box/sdkgen/schemas/groupmini/GroupMiniGroupTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/groups/Groups.java create mode 100644 src/main/java/com/box/sdkgen/schemas/groups/GroupsOrderDirectionField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/groups/GroupsOrderField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/integrationmapping/IntegrationMapping.java create mode 100644 src/main/java/com/box/sdkgen/schemas/integrationmapping/IntegrationMappingIntegrationTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/integrationmappingbase/IntegrationMappingBase.java create mode 100644 src/main/java/com/box/sdkgen/schemas/integrationmappingbase/IntegrationMappingBaseTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/integrationmappingboxitemslack/IntegrationMappingBoxItemSlack.java create mode 100644 src/main/java/com/box/sdkgen/schemas/integrationmappingboxitemslack/IntegrationMappingBoxItemSlackTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/integrationmappingpartneritemslack/IntegrationMappingPartnerItemSlack.java create mode 100644 src/main/java/com/box/sdkgen/schemas/integrationmappingpartneritemslack/IntegrationMappingPartnerItemSlackTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/integrationmappingpartneritemteams/IntegrationMappingPartnerItemTeams.java create mode 100644 src/main/java/com/box/sdkgen/schemas/integrationmappingpartneritemteams/IntegrationMappingPartnerItemTeamsTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/integrationmappingpartneritemteamscreaterequest/IntegrationMappingPartnerItemTeamsCreateRequest.java create mode 100644 src/main/java/com/box/sdkgen/schemas/integrationmappingpartneritemteamscreaterequest/IntegrationMappingPartnerItemTeamsCreateRequestTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/integrationmappings/IntegrationMappings.java create mode 100644 src/main/java/com/box/sdkgen/schemas/integrationmappingslackcreaterequest/IntegrationMappingSlackCreateRequest.java create mode 100644 src/main/java/com/box/sdkgen/schemas/integrationmappingslackoptions/IntegrationMappingSlackOptions.java create mode 100644 src/main/java/com/box/sdkgen/schemas/integrationmappingsteams/IntegrationMappingsTeams.java create mode 100644 src/main/java/com/box/sdkgen/schemas/integrationmappingteams/IntegrationMappingTeams.java create mode 100644 src/main/java/com/box/sdkgen/schemas/integrationmappingteams/IntegrationMappingTeamsIntegrationTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/integrationmappingteamscreaterequest/IntegrationMappingTeamsCreateRequest.java create mode 100644 src/main/java/com/box/sdkgen/schemas/invite/Invite.java create mode 100644 src/main/java/com/box/sdkgen/schemas/invite/InviteInvitedToField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/invite/InviteInvitedToTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/invite/InviteTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/item/Item.java create mode 100644 src/main/java/com/box/sdkgen/schemas/items/Items.java create mode 100644 src/main/java/com/box/sdkgen/schemas/items/ItemsOrderDirectionField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/items/ItemsOrderField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/itemsoffsetpaginated/ItemsOffsetPaginated.java create mode 100644 src/main/java/com/box/sdkgen/schemas/itemsoffsetpaginated/ItemsOffsetPaginatedOrderDirectionField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/itemsoffsetpaginated/ItemsOffsetPaginatedOrderField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/keywordskillcard/KeywordSkillCard.java create mode 100644 src/main/java/com/box/sdkgen/schemas/keywordskillcard/KeywordSkillCardEntriesField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/keywordskillcard/KeywordSkillCardInvocationField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/keywordskillcard/KeywordSkillCardInvocationTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/keywordskillcard/KeywordSkillCardSkillCardTitleField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/keywordskillcard/KeywordSkillCardSkillCardTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/keywordskillcard/KeywordSkillCardSkillField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/keywordskillcard/KeywordSkillCardSkillTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/keywordskillcard/KeywordSkillCardTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/legalholdpolicies/LegalHoldPolicies.java create mode 100644 src/main/java/com/box/sdkgen/schemas/legalholdpolicy/LegalHoldPolicy.java create mode 100644 src/main/java/com/box/sdkgen/schemas/legalholdpolicy/LegalHoldPolicyAssignmentCountsField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/legalholdpolicy/LegalHoldPolicyStatusField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/legalholdpolicyassigneditem/LegalHoldPolicyAssignedItem.java create mode 100644 src/main/java/com/box/sdkgen/schemas/legalholdpolicyassignment/LegalHoldPolicyAssignment.java create mode 100644 src/main/java/com/box/sdkgen/schemas/legalholdpolicyassignmentbase/LegalHoldPolicyAssignmentBase.java create mode 100644 src/main/java/com/box/sdkgen/schemas/legalholdpolicyassignmentbase/LegalHoldPolicyAssignmentBaseTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/legalholdpolicyassignments/LegalHoldPolicyAssignments.java create mode 100644 src/main/java/com/box/sdkgen/schemas/legalholdpolicymini/LegalHoldPolicyMini.java create mode 100644 src/main/java/com/box/sdkgen/schemas/legalholdpolicymini/LegalHoldPolicyMiniTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/metadata/Metadata.java create mode 100644 src/main/java/com/box/sdkgen/schemas/metadatabase/MetadataBase.java create mode 100644 src/main/java/com/box/sdkgen/schemas/metadatacascadepolicies/MetadataCascadePolicies.java create mode 100644 src/main/java/com/box/sdkgen/schemas/metadatacascadepolicy/MetadataCascadePolicy.java create mode 100644 src/main/java/com/box/sdkgen/schemas/metadatacascadepolicy/MetadataCascadePolicyOwnerEnterpriseField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/metadatacascadepolicy/MetadataCascadePolicyOwnerEnterpriseTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/metadatacascadepolicy/MetadataCascadePolicyParentField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/metadatacascadepolicy/MetadataCascadePolicyParentTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/metadatacascadepolicy/MetadataCascadePolicyTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/metadataerror/MetadataError.java create mode 100644 src/main/java/com/box/sdkgen/schemas/metadatafieldfilterdaterange/MetadataFieldFilterDateRange.java create mode 100644 src/main/java/com/box/sdkgen/schemas/metadatafieldfilterfloatrange/MetadataFieldFilterFloatRange.java create mode 100644 src/main/java/com/box/sdkgen/schemas/metadatafilter/MetadataFilter.java create mode 100644 src/main/java/com/box/sdkgen/schemas/metadatafilter/MetadataFilterScopeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/metadatafiltervalue/MetadataFilterValue.java create mode 100644 src/main/java/com/box/sdkgen/schemas/metadatafull/MetadataFull.java create mode 100644 src/main/java/com/box/sdkgen/schemas/metadatainstancevalue/MetadataInstanceValue.java create mode 100644 src/main/java/com/box/sdkgen/schemas/metadataquery/MetadataQuery.java create mode 100644 src/main/java/com/box/sdkgen/schemas/metadataquery/MetadataQueryOrderByDirectionField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/metadataquery/MetadataQueryOrderByField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/metadataqueryresultitem/MetadataQueryResultItem.java create mode 100644 src/main/java/com/box/sdkgen/schemas/metadataqueryresults/MetadataQueryResults.java create mode 100644 src/main/java/com/box/sdkgen/schemas/metadatas/Metadatas.java create mode 100644 src/main/java/com/box/sdkgen/schemas/metadatatemplate/MetadataTemplate.java create mode 100644 src/main/java/com/box/sdkgen/schemas/metadatatemplate/MetadataTemplateFieldsField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/metadatatemplate/MetadataTemplateFieldsOptionsField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/metadatatemplate/MetadataTemplateFieldsTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/metadatatemplate/MetadataTemplateTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/metadatatemplates/MetadataTemplates.java create mode 100644 src/main/java/com/box/sdkgen/schemas/oauth2error/OAuth2Error.java create mode 100644 src/main/java/com/box/sdkgen/schemas/outcome/Outcome.java create mode 100644 src/main/java/com/box/sdkgen/schemas/postoauth2revoke/PostOAuth2Revoke.java create mode 100644 src/main/java/com/box/sdkgen/schemas/postoauth2token/PostOAuth2Token.java create mode 100644 src/main/java/com/box/sdkgen/schemas/postoauth2token/PostOAuth2TokenActorTokenTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/postoauth2token/PostOAuth2TokenBoxSubjectTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/postoauth2token/PostOAuth2TokenGrantTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/postoauth2token/PostOAuth2TokenSubjectTokenTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/postoauth2tokenrefreshaccesstoken/PostOAuth2TokenRefreshAccessToken.java create mode 100644 src/main/java/com/box/sdkgen/schemas/postoauth2tokenrefreshaccesstoken/PostOAuth2TokenRefreshAccessTokenGrantTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/realtimeserver/RealtimeServer.java create mode 100644 src/main/java/com/box/sdkgen/schemas/realtimeservers/RealtimeServers.java create mode 100644 src/main/java/com/box/sdkgen/schemas/recentitem/RecentItem.java create mode 100644 src/main/java/com/box/sdkgen/schemas/recentitem/RecentItemInteractionTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/recentitemresource/RecentItemResource.java create mode 100644 src/main/java/com/box/sdkgen/schemas/recentitems/RecentItems.java create mode 100644 src/main/java/com/box/sdkgen/schemas/resource/Resource.java create mode 100644 src/main/java/com/box/sdkgen/schemas/resourcescope/ResourceScope.java create mode 100644 src/main/java/com/box/sdkgen/schemas/resourcescope/ResourceScopeScopeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/retentionpolicies/RetentionPolicies.java create mode 100644 src/main/java/com/box/sdkgen/schemas/retentionpolicy/RetentionPolicy.java create mode 100644 src/main/java/com/box/sdkgen/schemas/retentionpolicy/RetentionPolicyAssignmentCountsField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/retentionpolicy/RetentionPolicyPolicyTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/retentionpolicy/RetentionPolicyRetentionTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/retentionpolicy/RetentionPolicyStatusField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/retentionpolicyassignment/RetentionPolicyAssignment.java create mode 100644 src/main/java/com/box/sdkgen/schemas/retentionpolicyassignment/RetentionPolicyAssignmentAssignedToField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/retentionpolicyassignment/RetentionPolicyAssignmentAssignedToTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/retentionpolicyassignment/RetentionPolicyAssignmentFilterFieldsField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/retentionpolicyassignment/RetentionPolicyAssignmentTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/retentionpolicyassignments/RetentionPolicyAssignments.java create mode 100644 src/main/java/com/box/sdkgen/schemas/retentionpolicybase/RetentionPolicyBase.java create mode 100644 src/main/java/com/box/sdkgen/schemas/retentionpolicybase/RetentionPolicyBaseTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/retentionpolicymini/RetentionPolicyMini.java create mode 100644 src/main/java/com/box/sdkgen/schemas/retentionpolicymini/RetentionPolicyMiniDispositionActionField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/rolevariable/RoleVariable.java create mode 100644 src/main/java/com/box/sdkgen/schemas/rolevariable/RoleVariableTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/rolevariable/RoleVariableVariableTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/rolevariable/RoleVariableVariableValueField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/searchresultitem/SearchResultItem.java create mode 100644 src/main/java/com/box/sdkgen/schemas/searchresults/SearchResults.java create mode 100644 src/main/java/com/box/sdkgen/schemas/searchresults/SearchResultsTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/searchresultsresponse/SearchResultsResponse.java create mode 100644 src/main/java/com/box/sdkgen/schemas/searchresultswithsharedlinks/SearchResultsWithSharedLinks.java create mode 100644 src/main/java/com/box/sdkgen/schemas/searchresultswithsharedlinks/SearchResultsWithSharedLinksTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/searchresultwithsharedlink/SearchResultWithSharedLink.java create mode 100644 src/main/java/com/box/sdkgen/schemas/searchresultwithsharedlinkitem/SearchResultWithSharedLinkItem.java create mode 100644 src/main/java/com/box/sdkgen/schemas/sessionterminationmessage/SessionTerminationMessage.java create mode 100644 src/main/java/com/box/sdkgen/schemas/shieldinformationbarrier/ShieldInformationBarrier.java create mode 100644 src/main/java/com/box/sdkgen/schemas/shieldinformationbarrier/ShieldInformationBarrierStatusField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/shieldinformationbarrier/ShieldInformationBarrierTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/shieldinformationbarrierbase/ShieldInformationBarrierBase.java create mode 100644 src/main/java/com/box/sdkgen/schemas/shieldinformationbarrierbase/ShieldInformationBarrierBaseTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/shieldinformationbarrierreference/ShieldInformationBarrierReference.java create mode 100644 src/main/java/com/box/sdkgen/schemas/shieldinformationbarrierreport/ShieldInformationBarrierReport.java create mode 100644 src/main/java/com/box/sdkgen/schemas/shieldinformationbarrierreport/ShieldInformationBarrierReportStatusField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/shieldinformationbarrierreportbase/ShieldInformationBarrierReportBase.java create mode 100644 src/main/java/com/box/sdkgen/schemas/shieldinformationbarrierreportbase/ShieldInformationBarrierReportBaseTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/shieldinformationbarrierreportdetails/ShieldInformationBarrierReportDetails.java create mode 100644 src/main/java/com/box/sdkgen/schemas/shieldinformationbarrierreportdetails/ShieldInformationBarrierReportDetailsDetailsField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/shieldinformationbarrierreports/ShieldInformationBarrierReports.java create mode 100644 src/main/java/com/box/sdkgen/schemas/shieldinformationbarriers/ShieldInformationBarriers.java create mode 100644 src/main/java/com/box/sdkgen/schemas/shieldinformationbarriersegment/ShieldInformationBarrierSegment.java create mode 100644 src/main/java/com/box/sdkgen/schemas/shieldinformationbarriersegment/ShieldInformationBarrierSegmentTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/shieldinformationbarriersegmentmember/ShieldInformationBarrierSegmentMember.java create mode 100644 src/main/java/com/box/sdkgen/schemas/shieldinformationbarriersegmentmember/ShieldInformationBarrierSegmentMemberShieldInformationBarrierSegmentField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/shieldinformationbarriersegmentmember/ShieldInformationBarrierSegmentMemberShieldInformationBarrierSegmentTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/shieldinformationbarriersegmentmemberbase/ShieldInformationBarrierSegmentMemberBase.java create mode 100644 src/main/java/com/box/sdkgen/schemas/shieldinformationbarriersegmentmemberbase/ShieldInformationBarrierSegmentMemberBaseTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/shieldinformationbarriersegmentmembermini/ShieldInformationBarrierSegmentMemberMini.java create mode 100644 src/main/java/com/box/sdkgen/schemas/shieldinformationbarriersegmentmembers/ShieldInformationBarrierSegmentMembers.java create mode 100644 src/main/java/com/box/sdkgen/schemas/shieldinformationbarriersegmentrestriction/ShieldInformationBarrierSegmentRestriction.java create mode 100644 src/main/java/com/box/sdkgen/schemas/shieldinformationbarriersegmentrestrictionbase/ShieldInformationBarrierSegmentRestrictionBase.java create mode 100644 src/main/java/com/box/sdkgen/schemas/shieldinformationbarriersegmentrestrictionbase/ShieldInformationBarrierSegmentRestrictionBaseTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/shieldinformationbarriersegmentrestrictionmini/ShieldInformationBarrierSegmentRestrictionMini.java create mode 100644 src/main/java/com/box/sdkgen/schemas/shieldinformationbarriersegmentrestrictionmini/ShieldInformationBarrierSegmentRestrictionMiniRestrictedSegmentField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/shieldinformationbarriersegmentrestrictionmini/ShieldInformationBarrierSegmentRestrictionMiniRestrictedSegmentTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/shieldinformationbarriersegmentrestrictionmini/ShieldInformationBarrierSegmentRestrictionMiniShieldInformationBarrierSegmentField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/shieldinformationbarriersegmentrestrictionmini/ShieldInformationBarrierSegmentRestrictionMiniShieldInformationBarrierSegmentTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/shieldinformationbarriersegmentrestrictions/ShieldInformationBarrierSegmentRestrictions.java create mode 100644 src/main/java/com/box/sdkgen/schemas/shieldinformationbarriersegments/ShieldInformationBarrierSegments.java create mode 100644 src/main/java/com/box/sdkgen/schemas/signrequest/SignRequest.java create mode 100644 src/main/java/com/box/sdkgen/schemas/signrequest/SignRequestSignFilesField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/signrequest/SignRequestStatusField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/signrequest/SignRequestTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/signrequestbase/SignRequestBase.java create mode 100644 src/main/java/com/box/sdkgen/schemas/signrequestcreaterequest/SignRequestCreateRequest.java create mode 100644 src/main/java/com/box/sdkgen/schemas/signrequestcreaterequest/SignRequestCreateRequestSignatureColorField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/signrequestcreatesigner/SignRequestCreateSigner.java create mode 100644 src/main/java/com/box/sdkgen/schemas/signrequestcreatesigner/SignRequestCreateSignerRoleField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/signrequestprefilltag/SignRequestPrefillTag.java create mode 100644 src/main/java/com/box/sdkgen/schemas/signrequests/SignRequests.java create mode 100644 src/main/java/com/box/sdkgen/schemas/signrequestsigner/SignRequestSigner.java create mode 100644 src/main/java/com/box/sdkgen/schemas/signrequestsigner/SignRequestSignerSignerDecisionField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/signrequestsigner/SignRequestSignerSignerDecisionTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/signrequestsignerinput/SignRequestSignerInput.java create mode 100644 src/main/java/com/box/sdkgen/schemas/signrequestsignerinput/SignRequestSignerInputContentTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/signrequestsignerinput/SignRequestSignerInputTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/signtemplate/SignTemplate.java create mode 100644 src/main/java/com/box/sdkgen/schemas/signtemplate/SignTemplateAdditionalInfoField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/signtemplate/SignTemplateAdditionalInfoNonEditableField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/signtemplate/SignTemplateAdditionalInfoRequiredField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/signtemplate/SignTemplateAdditionalInfoRequiredSignersField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/signtemplate/SignTemplateCustomBrandingField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/signtemplate/SignTemplateReadySignLinkField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/signtemplate/SignTemplateTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/signtemplates/SignTemplates.java create mode 100644 src/main/java/com/box/sdkgen/schemas/skillcard/SkillCard.java create mode 100644 src/main/java/com/box/sdkgen/schemas/skillcardsmetadata/SkillCardsMetadata.java create mode 100644 src/main/java/com/box/sdkgen/schemas/statusskillcard/StatusSkillCard.java create mode 100644 src/main/java/com/box/sdkgen/schemas/statusskillcard/StatusSkillCardInvocationField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/statusskillcard/StatusSkillCardInvocationTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/statusskillcard/StatusSkillCardSkillCardTitleField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/statusskillcard/StatusSkillCardSkillCardTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/statusskillcard/StatusSkillCardSkillField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/statusskillcard/StatusSkillCardSkillTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/statusskillcard/StatusSkillCardStatusCodeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/statusskillcard/StatusSkillCardStatusField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/statusskillcard/StatusSkillCardTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/storagepolicies/StoragePolicies.java create mode 100644 src/main/java/com/box/sdkgen/schemas/storagepolicy/StoragePolicy.java create mode 100644 src/main/java/com/box/sdkgen/schemas/storagepolicyassignment/StoragePolicyAssignment.java create mode 100644 src/main/java/com/box/sdkgen/schemas/storagepolicyassignment/StoragePolicyAssignmentAssignedToField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/storagepolicyassignment/StoragePolicyAssignmentTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/storagepolicyassignments/StoragePolicyAssignments.java create mode 100644 src/main/java/com/box/sdkgen/schemas/storagepolicymini/StoragePolicyMini.java create mode 100644 src/main/java/com/box/sdkgen/schemas/storagepolicymini/StoragePolicyMiniTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/task/Task.java create mode 100644 src/main/java/com/box/sdkgen/schemas/task/TaskActionField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/task/TaskCompletionRuleField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/task/TaskTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/taskassignment/TaskAssignment.java create mode 100644 src/main/java/com/box/sdkgen/schemas/taskassignment/TaskAssignmentResolutionStateField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/taskassignment/TaskAssignmentTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/taskassignments/TaskAssignments.java create mode 100644 src/main/java/com/box/sdkgen/schemas/tasks/Tasks.java create mode 100644 src/main/java/com/box/sdkgen/schemas/templatesigner/TemplateSigner.java create mode 100644 src/main/java/com/box/sdkgen/schemas/templatesigner/TemplateSignerRoleField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/templatesignerinput/TemplateSignerInput.java create mode 100644 src/main/java/com/box/sdkgen/schemas/templatesignerinput/TemplateSignerInputContentTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/templatesignerinput/TemplateSignerInputCoordinatesField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/templatesignerinput/TemplateSignerInputDimensionsField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/templatesignerinput/TemplateSignerInputTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/termsofservice/TermsOfService.java create mode 100644 src/main/java/com/box/sdkgen/schemas/termsofservice/TermsOfServiceEnterpriseField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/termsofservice/TermsOfServiceEnterpriseTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/termsofservice/TermsOfServiceStatusField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/termsofservice/TermsOfServiceTosTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/termsofservicebase/TermsOfServiceBase.java create mode 100644 src/main/java/com/box/sdkgen/schemas/termsofservicebase/TermsOfServiceBaseTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/termsofservices/TermsOfServices.java create mode 100644 src/main/java/com/box/sdkgen/schemas/termsofserviceuserstatus/TermsOfServiceUserStatus.java create mode 100644 src/main/java/com/box/sdkgen/schemas/termsofserviceuserstatus/TermsOfServiceUserStatusTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/termsofserviceuserstatuses/TermsOfServiceUserStatuses.java create mode 100644 src/main/java/com/box/sdkgen/schemas/timelineskillcard/TimelineSkillCard.java create mode 100644 src/main/java/com/box/sdkgen/schemas/timelineskillcard/TimelineSkillCardEntriesAppearsField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/timelineskillcard/TimelineSkillCardEntriesField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/timelineskillcard/TimelineSkillCardInvocationField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/timelineskillcard/TimelineSkillCardInvocationTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/timelineskillcard/TimelineSkillCardSkillCardTitleField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/timelineskillcard/TimelineSkillCardSkillCardTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/timelineskillcard/TimelineSkillCardSkillField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/timelineskillcard/TimelineSkillCardSkillTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/timelineskillcard/TimelineSkillCardTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/trackingcode/TrackingCode.java create mode 100644 src/main/java/com/box/sdkgen/schemas/trackingcode/TrackingCodeTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/transcriptskillcard/TranscriptSkillCard.java create mode 100644 src/main/java/com/box/sdkgen/schemas/transcriptskillcard/TranscriptSkillCardEntriesAppearsField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/transcriptskillcard/TranscriptSkillCardEntriesField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/transcriptskillcard/TranscriptSkillCardInvocationField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/transcriptskillcard/TranscriptSkillCardInvocationTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/transcriptskillcard/TranscriptSkillCardSkillCardTitleField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/transcriptskillcard/TranscriptSkillCardSkillCardTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/transcriptskillcard/TranscriptSkillCardSkillField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/transcriptskillcard/TranscriptSkillCardSkillTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/transcriptskillcard/TranscriptSkillCardTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/trashfile/TrashFile.java create mode 100644 src/main/java/com/box/sdkgen/schemas/trashfile/TrashFileItemStatusField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/trashfile/TrashFilePathCollectionEntriesField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/trashfile/TrashFilePathCollectionEntriesTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/trashfile/TrashFilePathCollectionField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/trashfile/TrashFileTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/trashfilerestored/TrashFileRestored.java create mode 100644 src/main/java/com/box/sdkgen/schemas/trashfilerestored/TrashFileRestoredItemStatusField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/trashfilerestored/TrashFileRestoredPathCollectionField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/trashfilerestored/TrashFileRestoredTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/trashfolder/TrashFolder.java create mode 100644 src/main/java/com/box/sdkgen/schemas/trashfolder/TrashFolderItemStatusField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/trashfolder/TrashFolderPathCollectionEntriesField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/trashfolder/TrashFolderPathCollectionEntriesTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/trashfolder/TrashFolderPathCollectionField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/trashfolder/TrashFolderTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/trashfolderrestored/TrashFolderRestored.java create mode 100644 src/main/java/com/box/sdkgen/schemas/trashfolderrestored/TrashFolderRestoredItemStatusField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/trashfolderrestored/TrashFolderRestoredPathCollectionField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/trashfolderrestored/TrashFolderRestoredTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/trashweblink/TrashWebLink.java create mode 100644 src/main/java/com/box/sdkgen/schemas/trashweblink/TrashWebLinkItemStatusField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/trashweblink/TrashWebLinkPathCollectionEntriesField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/trashweblink/TrashWebLinkPathCollectionEntriesTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/trashweblink/TrashWebLinkPathCollectionField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/trashweblink/TrashWebLinkTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/trashweblinkrestored/TrashWebLinkRestored.java create mode 100644 src/main/java/com/box/sdkgen/schemas/trashweblinkrestored/TrashWebLinkRestoredItemStatusField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/trashweblinkrestored/TrashWebLinkRestoredPathCollectionField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/trashweblinkrestored/TrashWebLinkRestoredTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/uploadedpart/UploadedPart.java create mode 100644 src/main/java/com/box/sdkgen/schemas/uploadpart/UploadPart.java create mode 100644 src/main/java/com/box/sdkgen/schemas/uploadpartmini/UploadPartMini.java create mode 100644 src/main/java/com/box/sdkgen/schemas/uploadparts/UploadParts.java create mode 100644 src/main/java/com/box/sdkgen/schemas/uploadparts/UploadPartsOrderDirectionField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/uploadparts/UploadPartsOrderField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/uploadsession/UploadSession.java create mode 100644 src/main/java/com/box/sdkgen/schemas/uploadsession/UploadSessionSessionEndpointsField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/uploadsession/UploadSessionTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/uploadurl/UploadUrl.java create mode 100644 src/main/java/com/box/sdkgen/schemas/user/User.java create mode 100644 src/main/java/com/box/sdkgen/schemas/user/UserNotificationEmailField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/user/UserStatusField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/useravatar/UserAvatar.java create mode 100644 src/main/java/com/box/sdkgen/schemas/useravatar/UserAvatarPicUrlsField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/userbase/UserBase.java create mode 100644 src/main/java/com/box/sdkgen/schemas/userbase/UserBaseTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/usercollaborations/UserCollaborations.java create mode 100644 src/main/java/com/box/sdkgen/schemas/userfull/UserFull.java create mode 100644 src/main/java/com/box/sdkgen/schemas/userfull/UserFullEnterpriseField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/userfull/UserFullEnterpriseTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/userfull/UserFullRoleField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/userintegrationmappings/UserIntegrationMappings.java create mode 100644 src/main/java/com/box/sdkgen/schemas/usermini/UserMini.java create mode 100644 src/main/java/com/box/sdkgen/schemas/users/Users.java create mode 100644 src/main/java/com/box/sdkgen/schemas/users/UsersOrderDirectionField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/users/UsersOrderField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/archivesv2025r0/ArchivesV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/archivev2025r0/ArchiveV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/archivev2025r0/ArchiveV2025R0TypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/clienterrorv2025r0/ClientErrorV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/clienterrorv2025r0/ClientErrorV2025R0CodeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/clienterrorv2025r0/ClientErrorV2025R0TypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/docgenbatchbasev2025r0/DocGenBatchBaseV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/docgenbatchbasev2025r0/DocGenBatchBaseV2025R0TypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/docgenbatchcreaterequestv2025r0/DocGenBatchCreateRequestV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/docgenbatchcreaterequestv2025r0/DocGenBatchCreateRequestV2025R0DestinationFolderField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/docgenbatchcreaterequestv2025r0/DocGenBatchCreateRequestV2025R0DestinationFolderTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/docgendocumentgenerationdatav2025r0/DocGenDocumentGenerationDataV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/docgenjobbasev2025r0/DocGenJobBaseV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/docgenjobbasev2025r0/DocGenJobBaseV2025R0TypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/docgenjobfullv2025r0/DocGenJobFullV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/docgenjobsfullv2025r0/DocGenJobsFullV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/docgenjobsv2025r0/DocGenJobsV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/docgenjobv2025r0/DocGenJobV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/docgenjobv2025r0/DocGenJobV2025R0StatusField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/docgentagsprocessingmessagev2025r0/DocGenTagsProcessingMessageV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/docgentagsv2025r0/DocGenTagsV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/docgentagv2025r0/DocGenTagV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/docgentagv2025r0/DocGenTagV2025R0TagTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/docgentemplatebasev2025r0/DocGenTemplateBaseV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/docgentemplatecreaterequestv2025r0/DocGenTemplateCreateRequestV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/docgentemplatesv2025r0/DocGenTemplatesV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/docgentemplatev2025r0/DocGenTemplateV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/enterprisereferencev2025r0/EnterpriseReferenceV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/enterprisereferencev2025r0/EnterpriseReferenceV2025R0TypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/externaluserdeletionresultv2025r0/ExternalUserDeletionResultV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/externaluserssubmitdeletejobrequestv2025r0/ExternalUsersSubmitDeleteJobRequestV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/externaluserssubmitdeletejobresponsev2025r0/ExternalUsersSubmitDeleteJobResponseV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/filereferencev2025r0/FileReferenceV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/filereferencev2025r0/FileReferenceV2025R0TypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/fileversionbasev2025r0/FileVersionBaseV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/fileversionbasev2025r0/FileVersionBaseV2025R0TypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/folderreferencev2025r0/FolderReferenceV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/folderreferencev2025r0/FolderReferenceV2025R0TypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/groupbasev2025r0/GroupBaseV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/groupbasev2025r0/GroupBaseV2025R0TypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/groupminiv2025r0/GroupMiniV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/groupminiv2025r0/GroupMiniV2025R0GroupTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/hubaccessgranteev2025r0/HubAccessGranteeV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/hubbasev2025r0/HubBaseV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/hubbasev2025r0/HubBaseV2025R0TypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/hubcollaborationcreaterequestv2025r0/HubCollaborationCreateRequestV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/hubcollaborationcreaterequestv2025r0/HubCollaborationCreateRequestV2025R0AccessibleByField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/hubcollaborationcreaterequestv2025r0/HubCollaborationCreateRequestV2025R0HubField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/hubcollaborationcreaterequestv2025r0/HubCollaborationCreateRequestV2025R0HubTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/hubcollaborationsv2025r0/HubCollaborationsV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/hubcollaborationupdaterequestv2025r0/HubCollaborationUpdateRequestV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/hubcollaborationuserv2025r0/HubCollaborationUserV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/hubcollaborationv2025r0/HubCollaborationV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/hubcollaborationv2025r0/HubCollaborationV2025R0AcceptanceRequirementsStatusField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/hubcollaborationv2025r0/HubCollaborationV2025R0AcceptanceRequirementsStatusStrongPasswordRequirementField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/hubcollaborationv2025r0/HubCollaborationV2025R0AcceptanceRequirementsStatusTermsOfServiceRequirementField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/hubcollaborationv2025r0/HubCollaborationV2025R0AcceptanceRequirementsStatusTwoFactorAuthenticationRequirementField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/hubcollaborationv2025r0/HubCollaborationV2025R0StatusField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/hubcollaborationv2025r0/HubCollaborationV2025R0TypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/hubcopyrequestv2025r0/HubCopyRequestV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/hubcreaterequestv2025r0/HubCreateRequestV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/hubitemoperationresultv2025r0/HubItemOperationResultV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/hubitemoperationv2025r0/HubItemOperationV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/hubitemoperationv2025r0/HubItemOperationV2025R0ActionField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/hubitemreferencev2025r0/HubItemReferenceV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/hubitemsmanagerequestv2025r0/HubItemsManageRequestV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/hubitemsmanageresponsev2025r0/HubItemsManageResponseV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/hubitemsv2025r0/HubItemsV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/hubitemv2025r0/HubItemV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/hubitemv2025r0/HubItemV2025R0TypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/hubsv2025r0/HubsV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/hubupdaterequestv2025r0/HubUpdateRequestV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/hubv2025r0/HubV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/shieldlistcontentcountryv2025r0/ShieldListContentCountryV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/shieldlistcontentcountryv2025r0/ShieldListContentCountryV2025R0TypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/shieldlistcontentdomainv2025r0/ShieldListContentDomainV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/shieldlistcontentdomainv2025r0/ShieldListContentDomainV2025R0TypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/shieldlistcontentemailv2025r0/ShieldListContentEmailV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/shieldlistcontentemailv2025r0/ShieldListContentEmailV2025R0TypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/shieldlistcontentintegrationv2025r0/ShieldListContentIntegrationV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/shieldlistcontentintegrationv2025r0/ShieldListContentIntegrationV2025R0IntegrationsField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/shieldlistcontentintegrationv2025r0/ShieldListContentIntegrationV2025R0TypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/shieldlistcontentipv2025r0/ShieldListContentIpV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/shieldlistcontentipv2025r0/ShieldListContentIpV2025R0TypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/shieldlistcontentrequestv2025r0/ShieldListContentRequestV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/shieldlistcontentv2025r0/ShieldListContentV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/shieldlistminiv2025r0/ShieldListMiniV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/shieldlistminiv2025r0/ShieldListMiniV2025R0ContentField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/shieldlistminiv2025r0/ShieldListMiniV2025R0TypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/shieldlistscreatev2025r0/ShieldListsCreateV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/shieldlistsupdatev2025r0/ShieldListsUpdateV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/shieldlistsv2025r0/ShieldListsV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/shieldlistv2025r0/ShieldListV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/termsofservicebasev2025r0/TermsOfServiceBaseV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/termsofservicebasev2025r0/TermsOfServiceBaseV2025R0TypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/userbasev2025r0/UserBaseV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/userbasev2025r0/UserBaseV2025R0TypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/userminiv2025r0/UserMiniV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/userreferencev2025r0/UserReferenceV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/userreferencev2025r0/UserReferenceV2025R0TypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/weblinkreferencev2025r0/WeblinkReferenceV2025R0.java create mode 100644 src/main/java/com/box/sdkgen/schemas/v2025r0/weblinkreferencev2025r0/WeblinkReferenceV2025R0TypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/watermark/Watermark.java create mode 100644 src/main/java/com/box/sdkgen/schemas/watermark/WatermarkWatermarkField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/webhook/Webhook.java create mode 100644 src/main/java/com/box/sdkgen/schemas/webhook/WebhookTriggersField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/webhookmini/WebhookMini.java create mode 100644 src/main/java/com/box/sdkgen/schemas/webhookmini/WebhookMiniTargetField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/webhookmini/WebhookMiniTargetTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/webhookmini/WebhookMiniTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/webhooks/Webhooks.java create mode 100644 src/main/java/com/box/sdkgen/schemas/weblink/WebLink.java create mode 100644 src/main/java/com/box/sdkgen/schemas/weblink/WebLinkItemStatusField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/weblink/WebLinkPathCollectionField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/weblink/WebLinkSharedLinkAccessField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/weblink/WebLinkSharedLinkEffectiveAccessField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/weblink/WebLinkSharedLinkEffectivePermissionField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/weblink/WebLinkSharedLinkField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/weblink/WebLinkSharedLinkPermissionsField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/weblinkbase/WebLinkBase.java create mode 100644 src/main/java/com/box/sdkgen/schemas/weblinkbase/WebLinkBaseTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/weblinkmini/WebLinkMini.java create mode 100644 src/main/java/com/box/sdkgen/schemas/workflow/Workflow.java create mode 100644 src/main/java/com/box/sdkgen/schemas/workflow/WorkflowFlowsField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/workflow/WorkflowFlowsOutcomesActionTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/workflow/WorkflowFlowsOutcomesField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/workflow/WorkflowFlowsOutcomesIfRejectedActionTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/workflow/WorkflowFlowsOutcomesIfRejectedField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/workflow/WorkflowFlowsOutcomesIfRejectedTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/workflow/WorkflowFlowsOutcomesTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/workflow/WorkflowFlowsTriggerField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/workflow/WorkflowFlowsTriggerScopeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/workflow/WorkflowFlowsTriggerScopeObjectField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/workflow/WorkflowFlowsTriggerScopeObjectTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/workflow/WorkflowFlowsTriggerScopeTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/workflow/WorkflowFlowsTriggerTriggerTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/workflow/WorkflowFlowsTriggerTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/workflow/WorkflowFlowsTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/workflowmini/WorkflowMini.java create mode 100644 src/main/java/com/box/sdkgen/schemas/workflowmini/WorkflowMiniTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/workflows/Workflows.java create mode 100644 src/main/java/com/box/sdkgen/schemas/zipdownload/ZipDownload.java create mode 100644 src/main/java/com/box/sdkgen/schemas/zipdownload/ZipDownloadNameConflictsField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/zipdownload/ZipDownloadNameConflictsTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/zipdownloadrequest/ZipDownloadRequest.java create mode 100644 src/main/java/com/box/sdkgen/schemas/zipdownloadrequest/ZipDownloadRequestItemsField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/zipdownloadrequest/ZipDownloadRequestItemsTypeField.java create mode 100644 src/main/java/com/box/sdkgen/schemas/zipdownloadstatus/ZipDownloadStatus.java create mode 100644 src/main/java/com/box/sdkgen/schemas/zipdownloadstatus/ZipDownloadStatusStateField.java create mode 100644 src/main/java/com/box/sdkgen/serialization/json/EnumWrapper.java create mode 100644 src/main/java/com/box/sdkgen/serialization/json/JsonManager.java create mode 100644 src/main/java/com/box/sdkgen/serialization/json/Valuable.java diff --git a/.codegen.json b/.codegen.json new file mode 100644 index 000000000..4dc9db038 --- /dev/null +++ b/.codegen.json @@ -0,0 +1 @@ +{ "engineHash": "6674fe3", "specHash": "1ed059a", "version": "0.1.0" } diff --git a/docs/sdkgen/Authentication.md b/docs/sdkgen/Authentication.md new file mode 100644 index 000000000..a8fdf1ec0 --- /dev/null +++ b/docs/sdkgen/Authentication.md @@ -0,0 +1,365 @@ +# Authentication + + + + +- [Authentication](#authentication) +- [Authentication methods](#authentication-methods) + - [Developer Token](#developer-token) + - [JWT Auth](#jwt-auth) + - [Authenticate Enterprise](#authenticate-enterprise) + - [Authenticate user](#authenticate-user) + - [Client Credentials Grant](#client-credentials-grant) + - [Obtaining Service Account token](#obtaining-service-account-token) + - [Obtaining User token](#obtaining-user-token) + - [Switching between Service Account and User](#switching-between-service-account-and-user) + - [OAuth 2.0 Auth](#oauth-20-auth) + - [Authentication with OAuth2](#authentication-with-oauth2) + - [Injecting existing token into BoxOAuth](#injecting-existing-token-into-boxoauth) +- [Retrieve current access token](#retrieve-current-access-token) +- [Refresh access token](#refresh-access-token) +- [Revoke token](#revoke-token) +- [Downscope token](#downscope-token) +- [Token storage](#token-storage) + - [In-memory token storage](#in-memory-token-storage) + - [Custom storage](#custom-storage) + + + +# Authentication methods + +## Developer Token + +The fastest way to get started using the API is with developer token. A +developer token is simply a short-lived access token that cannot be refreshed +and can only be used with your own account. Therefore, they're only useful for +testing an app and aren't suitable for production. You can obtain a developer +token from your application's [developer console][dev_console] page. + +To create a `BoxClient` with a developer token, construct an `BoxDeveloperTokenAuth` +object with the `token` set to the developer token and construct the client with that. + + + +```java +BoxDeveloperTokenAuth auth = new BoxDeveloperTokenAuth("YOUR-DEVELOPER-TOKEN"); +BoxClient client = new BoxClient(auth); +``` + +[dev_console]: https://app.box.com/developers/console + +## JWT Auth + +Before using JWT Auth make sure you set up correctly your Box platform app. +The guide with all required steps can be found here: [Setup with JWT][jwt_guide] + +### Authenticate Enterprise + +JWT auth allows your application to authenticate itself with the Box API +for a given enterprise. By default, your application has a [Service Account][service_account] +that represents it and can perform API calls. The Service Account is separate +from the Box accounts of the application developer and the enterprise admin of +any enterprise that has authorized the app — files stored in that account are +not accessible in any other account by default, and vice versa. + +If you generated your public and private keys automatically through the +[Box Developer Console][dev_console], you can use the JSON file created there +to configure your SDK instance and create a client to make calls as the +Service Account. Call one of static `BoxJwtAuth` method: +`JWTConfig.fromConfigFile("PATH_TO_CONFIG_FILE")` and pass JSON file local path +or `JWTConfig.fromConfigJsonString(CONFIG_JSON_STRING)` and pass JSON config file content as string. + +```java +JWTConfig config = JWTConfig.fromConfigFile("src/example/config/config.json"); +BoxJWTAuth auth = new BoxJWTAuth(config); +BoxClient client = new BoxClient(auth); +``` + +Otherwise, you'll need to provide the necessary configuration fields directly to the `JWTConfig` constructor: + +```java +JWTConfig config = new JWTConfig.Builder("YOUR_CLIENT_ID", "YOUR_CLIENT_SECRET", "JWT_KEY_ID", "PRIVATE_KEY", "PRIVATE_KEY_PASSWORD") + .enterpriseId("123456") + .build(); +BoxJWTAuth auth = new BoxJWTAuth(config); +BoxClient client = new BoxClient(auth); +``` + +### Authenticate user + +App auth applications also often have associated [App Users][app_user], which are +created and managed directly by the application — they do not have normal login credentials, +and can only be accessed through the Box API by the application that created them. +You may authenticate as the Service Account to provision and manage users, or as an individual app user to +make calls as that user. See the [API documentation](https://developer.box.com/) +for detailed instructions on how to use app auth. + +Clients for making calls as an App User can be created with the same JSON JWT config file generated through the +[Box Developer Console][dev_console]. Calling `jwtAuth.withUserSubject('USER_ID')` method will return a new auth object, +which is authenticated as the user with provided id, leaving the original object unchanged. + +```java +JWTConfig config = JWTConfig.fromConfigFile("src/example/config/config.json"); +BoxJWTAuth auth = new BoxJWTAuth(config); +BoxJWTAuth userAuth = auth.withUserSubject("USER_ID"); +BoxClient userClient = new BoxClient(userAuth); +``` + +Alternatively, clients for making calls as an App User can be created with the same `JWTConfig` +constructor as in the above examples, similarly to creating a Service Account client. Simply pass the +`userId` instead of `enterpriseId` when constructing the auth config instance: + +```java +JWTConfig config = new JWTConfig.Builder("YOUR_CLIENT_ID", "YOUR_CLIENT_SECRET", "JWT_KEY_ID", "PRIVATE_KEY", "PRIVATE_KEY_PASSWORD") + .userId("123456") + .build(); +BoxJWTAuth auth = new BoxJWTAuth(config); +BoxClient client = new BoxClient(auth); +``` + +[jwt_guide]: https://developer.box.com/guides/authentication/jwt/jwt-setup/ +[service_account]: https://developer.box.com/guides/getting-started/user-types/service-account/ +[app_user]: https://developer.box.com/guides/getting-started/user-types/app-users/ + +## Client Credentials Grant + +Before using Client Credentials Grant Auth make sure you set up correctly your Box platform app. +The guide with all required steps can be found here: [Setup with Client Credentials Grant][ccg_guide] + +Client Credentials Grant Auth method allows you to obtain an access token by having client credentials +and secret with enterprise or user ID, which allows you to work using service or user account. + +You can use `CCGAuth` to initialize a client object the same way as for other authentication types: + +```java +CCGConfig config = new CCGConfig.Builder("YOUR_CLIENT", "YOUR_CLIENT_SECRET") + .userId("USER_ID") + .build(); +BoxCCGAuth auth = new BoxCCGAuth(config); +BoxClient client = new BoxClient(auth); + +UserFull user = client.users.getUserMe(); +System.out.println(user.getName()); +``` + +Obtained token is valid for specified amount of time, it will be refreshed automatically by default. + +### Obtaining Service Account token + +The [Service Account](https://developer.box.com/guides/getting-started/user-types/service-account//) +is separate from the Box accounts of the application developer and the +enterprise admin of any enterprise that has authorized the app — files stored in that account +are not accessible in any other account by default, and vice versa. +To obtain service account you will have to provide enterprise ID with client id and secret: + +```java +CCGConfig config = new CCGConfig.Builder("YOUR_CLIENT", "YOUR_CLIENT_SECRET") + .enterpriseId("ENTERPRISE_ID") + .build(); +BoxCCGAuth auth = new BoxCCGAuth(config); +BoxClient client = new BoxClient(auth); +``` + +### Obtaining User token + +In order to enable obtaining user token you have to go to your application configuration that can be found +[here][dev_console]. In `Configuration` tab, in section `Advanced Features` +select `Generate user access tokens`. Do not forget to re-authorize application if it was already authorized. + +To obtain user account you will have to provide user ID with client id and secret. + +```java +CCGConfig config = new CCGConfig.Builder("YOUR_CLIENT", "YOUR_CLIENT_SECRET") + .userId("USER_ID") + .build(); +BoxCCGAuth auth = new BoxCCGAuth(config); +BoxClient client = new BoxClient(auth); +``` + +### Switching between Service Account and User + +You can easily switch to be authenticated as a Service Account or as a User. +To create a new auth object authenticated as Service Account you can call: + +```java +BoxCCGAuth enterpriseAuth = auth.withEnterpriseSubject("ENTERPRISE_ID"); +BoxClient enterpriseClient = new BoxClient(enterpriseAuth); +``` + +To authenticate with user subject call: + +```java +BoxCCGAuth userAuth = auth.withUserSubject("USER_ID"); +BoxClient userClient = new BoxClient(userAuth); +``` + +The new token will be automatically fetched with a next API call. + +[ccg_guide]: https://developer.box.com/guides/authentication/client-credentials/client-credentials-setup/ + +## OAuth 2.0 Auth + +### Authentication with OAuth2 + +If your application needs to integrate with existing Box users who will provide +their login credentials to grant your application access to their account, you +will need to go through the standard OAuth2 login flow. A detailed guide for +this process is available in the +[Authentication with OAuth API documentation](https://developer.box.com/en/guides/authentication/oauth2/). + +Using an auth code is the most common way of authenticating with the Box API for +existing Box users, to integrate with their accounts. +Your application must provide a way for the user to login to Box (usually with a +browser or web view) in order to obtain an auth code. + + + +```java +BoxOAuth oauth = new OAuthConfig("CLIENT_ID", "CLIENT_SECRET"); +String authorizationUrl = auoauthth.getAuthorizeUrl(); +``` + +After a user logs in and grants your application access to their Box account, +they will be redirected to your application's `redirect_uri` which will contain +an auth code. This auth code can then be used along with your client ID and +client secret to establish an API connection. +You need to provide the auth code to the SDK to obtain an access token. +Calling `oauth.getTokensAuthorizationCodeGrant('code')` will exchange the auth code for an access token +and save it in the `BoxOAuth` token storage. The SDK will automatically refresh the token when needed. +All you need to do is create a client object with the `BoxOAuth` object and start making API calls. + + + +```java +auth.getTokensAuthorizationCodeGrant("AUTHORIZATION_CODE"); +BoxClient client = new BoxClient(auth); +``` + +### Injecting existing token into BoxOAuth + +If you already have an access token and refresh token, you can inject them into the `BoxOAuth` token storage +to avoid repeating the authentication process. This can be useful when you want to reuse the token +between runs of your application. + +```java +AccessToken accessToken = new AccessToken.Builder() + .accessToken("ACCESS_TOKEN") + .refreshToken("REFRESH_TOKEN") + .build(); +auth.getTokenStorage().store(accessToken); +BoxClient client = new BoxClient(auth); +``` + +Alternatively, you can create a custom implementation of `TokenStorage` interface and pass it to the `BoxOAuth` object. +See the [Custom storage](#custom-storage) section for more information. + +# Retrieve current access token + +After initializing the authentication object, the SDK will be able to retrieve the access token. +To retrieve the current access token you can use the following code: + + + +```java +auth.retrieveToken(); +``` + +# Refresh access token + +Access tokens are short-lived and need to be refreshed periodically. The SDK will automatically refresh the token when needed. +If you want to manually refresh the token, you can use the following code: + + + +```java +auth.refreshToken(); +``` + +# Revoke token + +Access tokens for a client can be revoked when needed. This call invalidates old token. +For BoxCcgAuth and BoxJwtAuth you can still reuse the `auth` object to retrieve a new token. +If you make any new call after revoking the token, a new token will be automatically retrieved. +For BoxOAuth it would be necessary to manually go through the authentication process again. +For BoxDeveloperTokenAuth, it is necessary to provide a DeveloperTokenConfig during initialization, +containing the client ID and client secret. + +To revoke current client's tokens in the storage use the following code: + + + +```java +auth.revokeToken(); +// client's tokens have been revoked +``` + +# Downscope token + +You can exchange a client's access token for one with a lower scope, in order +to restrict the permissions for a child client or to pass to a less secure +location (e.g. a browser-based app). + +A downscoped token does not include a refresh token. +In such a scenario, to obtain a new downscoped token, refresh the original token +and utilize the newly acquired token to obtain the downscoped token. + +More information about downscoping tokens can be found [here](https://developer.box.com/guides/authentication/tokens/downscope/). +If you want to learn more about available scopes please go [here](https://developer.box.com/guides/api-calls/permissions-and-errors/scopes/#scopes-for-downscoping). + +For example to get a new token with only `item_preview` scope, restricted to a single file, suitable for the +[Content Preview UI Element](https://developer.box.com/en/guides/embed/ui-elements/preview/) you can use the following code. +You can also initialize `BoxDeveloperTokenAuth` with the retrieved access token and use it to create a new Client. + + + +```java +String resource = "https://api.box.com/2.0/files/123456789"; +List scopes = List.of("item_preview"); +AccessToken downscopedToken = auth.downscopeToken(scopes, resource, null, null); +BoxDeveloperTokenAuth downscopedAuth = new BoxDeveloperTokenAuth(downscopedToken.getAccessToken()); +BoxClient downscopedClient = new BoxClient(downscopedAuth); +``` + +# Token storage + +## In-memory token storage + +By default, the SDK stores the access token in volatile memory. When rerunning your application, +the access token won't be reused from the previous run; a new token has to be obtained again. +To use in-memory token storage, you don't need to do anything more than +create an Auth class using AuthConfig, for example, for OAuth: + +```java +OAuthConfig config = new OAuthConfig("CLIENT_ID", "CLIENT_SECRET"); +BoxOAuth auth = new BoxOAuth(config); +``` + +## Custom storage + +You can also provide a custom token storage class. All you need to do is create a class that implements `TokenStorage` +interface and pass an instance of your class to the AuthConfig constructor. + +```java +TokenStorage customTokenStorage = new TokenStorage() { + @Override + public void store(AccessToken accessToken) { + // Store the access token + } + + @Override + public AccessToken get() { + // Retrieve the access token + return null; + } + + @Override + public void clear() { + // Clear the access token + } +}; + +OAuthConfig config = new OAuthConfig.Builder("CLIENT_ID", "CLIENT_SECRET") + .tokenStorage(customTokenStorage) + .build(); +BoxOAuth auth = new BoxOAuth(config); +``` diff --git a/docs/sdkgen/Client.md b/docs/sdkgen/Client.md new file mode 100644 index 000000000..9a871d55e --- /dev/null +++ b/docs/sdkgen/Client.md @@ -0,0 +1,194 @@ +# Client + +This is the central entrypoint for all SDK interaction. The BoxClient houses all the API endpoints +divided across resource managers. + + + + +- [Client](#client) +- [Make custom HTTP request](#make-custom-http-request) + - [JSON request](#json-request) + - [Multi-part request](#multi-part-request) + - [Binary response](#binary-response) +- [Additional headers](#additional-headers) + - [As-User header](#as-user-header) + - [Suppress notifications](#suppress-notifications) + - [Custom headers](#custom-headers) +- [Custom Base URLs](#custom-base-urls) +- [Interceptors](#interceptors) +- [Use Proxy for API calls](#use-proxy-for-api-calls) + + + +# Make custom HTTP request + +You can make custom HTTP requests using the `client.makeRequest()` method. +This method allows you to make any HTTP request to the Box API. It will automatically use authentication and +network configuration settings from the client. +The method accepts a `FetchOptions` object as an argument and returns a `FetchResponse` object. + +## JSON request + +The following example demonstrates how to make a custom POST request to create a new folder in the root folder. + +```java +FetchOptions fetchOptions = new FetchOptions.Builder("https://api.box.com/2.0/users/me", "GET") + .params(new HashMap<>() {{ + put("fields", "name"); + }}) + .build(); +FetchResponse response = client.makeRequest(fetchOptions); +System.out.println("Status code: " + response.getStatus()); +System.out.println("Response body: " + response.getContent()); +``` + +## Multi-part request + +The following example demonstrates how to make a custom multipart request that uploads a file to a folder. + +```java +List multipartItems = List.of( + new MultipartItem.Builder("attributes") + .data(JsonManager.serialize("{\"name\": \"newFileName\", \"parent\": { \"id\": \"0\" }}")) + .build(), + new MultipartItem.Builder("file") + .fileStream(new FileInputStream(new File("file.txt"))) + .build() +); +FetchOptions fetchOptions = new FetchOptions.Builder("https://upload.box.com/api/2.0/files/content", "POST") + .contentType("multipart/form-data") + .multipartData(multipartItems) + .build(); + +FetchResponse response = client.makeRequest(fetchOptions); +System.out.println("Status code: " + response.getStatus()); +System.out.println("Response body: " + response.getContent()); +``` + +## Binary response + +The following example demonstrates how to make a custom request that expects a binary response. +It is required to specify the `responseFormat` parameter in the `FetchOptions` object to "binary". + +```java +FetchOptions fetchOptions = new FetchOptions.Builder("https://upload.box.com/api/2.0/files/12345/content", "GET") + .responseFormat(ResponseFormat.BINARY) + .build(); +FetchResponse response = client.makeRequest(fetchOptions); +System.out.println("Status code: " + response.getStatus()); +System.out.println("Response body: " + response.getContent()); +``` + +# Additional headers + +BoxClient provides a convenient methods, which allow passing additional headers, which will be included +in every API call made by the client. + +## As-User header + +The As-User header is used by enterprise admins to make API calls on behalf of their enterprise's users. +This requires the API request to pass an As-User: USER-ID header. For more details see the [documentation on As-User](https://developer.box.com/en/guides/authentication/oauth2/as-user/). + +The following example assume that the client has been instantiated with an access token belonging to an admin-level user +or Service Account with appropriate privileges to make As-User calls. + +Calling the `client.withAsUserHeader()` method creates a new client to impersonate user with the provided ID. +All calls made with the new client will be made in context of the impersonated user, leaving the original client unmodified. + + + +```java +BoxClient userClient = client.withAsUserHeader('1234567'); +``` + +## Suppress notifications + +If you are making administrative API calls (that is, your application has “Manage an Enterprise” +scope, and the user signing in is a co-admin with the correct "Edit settings for your company" +permission) then you can suppress both email and webhook notifications. This can be used, for +example, for a virus-scanning tool to download copies of everyone’s files in an enterprise, +without every collaborator on the file getting an email. All actions will still appear in users' +updates feed and audit logs. + +> **Note:** This functionality is only available for approved applications. + +Calling the `client.withSuppressedNotifications()` method creates a new client. +For all calls made with the new client the notifications will be suppressed. + +```java +BoxClient newClient = client.withSuppressedNotifications(); +``` + +## Custom headers + +You can also specify the custom set of headers, which will be included in every API call made by client. +Calling the `client.withExtraHeaders()` method creates a new client, leaving the original client unmodified. + +```java +BoxClient newClient = client.withExtraHeaders(new HashMap<>() {{ + put("X-My-Header", "124"); +}}); +``` + +# Custom Base URLs + +You can also specify the custom base URLs, which will be used for API calls made by client. +Calling the `client.withCustomBaseUrls()` method creates a new client, leaving the original client unmodified. + +```java +BaseUrls baseUrls = new BaseUrls.Builder() + .baseUrl("https://new-base-url.com") + .uploadUrl("https://my-company-upload-url.com") + .oauth2Url("https://my-company.com/oauth2") + .build(); +BoxClient clientWithCustomBaseUrl = client.withCustomBaseUrls(baseUrls); +``` + +# Interceptors + +You can specify custom interceptors - methods that will be called just before making a request and right after +receiving a response from the server. Using these function allows you to modify the request payload and response. +Interceptor interface accepts two methods with the following signatures: + +```java +FetchOptions beforeRequest(FetchOptions fetchOptions) +FetchResponse afterRequest(FetchResponse fetchResponse) +``` + +You can apply more than one interceptor to the client by passing a list of interceptors to apply. +Calling the `client.withInterceptors()` method creates a new client, leaving the original client unmodified. + +```java +List interceptors = new ArrayList<>() { + { + add(new Interceptor() { + @Override + public FetchOptions beforeRequest(FetchOptions fetchOptions) { + return fetchOptions; + } + + @Override + public FetchResponse afterRequest(FetchResponse fetchResponse) { + return fetchResponse; + } + }); + } +}; +BoxClient clientWithInterceptor = client.withInterceptors(interceptors); +``` + +# Use Proxy for API calls + +In order to use a proxy for API calls, calling the `client.withProxy(proxyConfig)` method creates a new client, leaving the original client unmodified, with the username and password being optional. We only support adding proxy for BoxNetworkClient. If you are using your own implementation of NetworkClient, you would need to configure proxy on your own. + +**Note:** We are only supporting http/s proxies with basic authentication. NTLM and other authentication methods are not supported. + +```java +ProxyConfig proxyConfig = new ProxyConfig("http://127.0.0.1:3128"); +newClient = client.withProxy(proxyConfig); + +//Using Basic Auth with username and password +ProxyConfig proxyConfig = new ProxyConfig.Builder("http://127.0.0.1:3128").username("username").password("password").build(); +newClient = client.withProxy(proxyConfig); +``` diff --git a/docs/sdkgen/Configuration.md b/docs/sdkgen/Configuration.md new file mode 100644 index 000000000..ab18f97a8 --- /dev/null +++ b/docs/sdkgen/Configuration.md @@ -0,0 +1,51 @@ +# Configuration + + + + +- [Configuration](#configuration) + - [Max retry attempts](#max-retry-attempts) + - [Custom retry strategy](#custom-retry-strategy) + + + +## Max retry attempts + +The default maximum number of retries in case of failed API call is 5. +To change this number you should initialize `BoxRetryStrategy` with the new value and pass it to `NetworkSession`. + +```java +BoxDeveloperTokenAuth auth = new BoxDeveloperTokenAuth("DEVELOPER_TOKEN"); +NetworkSession session = new NetworkSession.Builder() + .retryStrategy(new BoxRetryStrategy.Builder().maxAttempts(3).build()) + .build(); +BoxClient client = new BoxClient.Builder(auth) + .networkSession(session) + .build(); +``` + +## Custom retry strategy + +You can also implement your own retry strategy by subclassing `RetryStrategy` and overriding `shouldRetry` and `retryAfter` methods. +This example shows how to set custom strategy that retries on 5xx status codes and waits 1 second between retries. + +```java +BoxDeveloperTokenAuth auth = new BoxDeveloperTokenAuth("DEVELOPER_TOKEN"); +RetryStrategy customRetryStrategy = new RetryStrategy() { + @Override + public boolean shouldRetry(FetchOptions fetchOptions, FetchResponse fetchResponse, int attemptNumber) { + return fetchResponse.status >= 500; + } + + @Override + public double retryAfter(FetchOptions fetchOptions, FetchResponse fetchResponse, int attemptNumber) { + return 1.0; + } +}; +NetworkSession session = new NetworkSession.Builder() + .retryStrategy(customRetryStrategy) + .build(); +BoxClient client = new BoxClient.Builder(auth) + .networkSession(session) + .build(); +``` diff --git a/docs/sdkgen/EventStream.md b/docs/sdkgen/EventStream.md new file mode 100644 index 000000000..a91eef21f --- /dev/null +++ b/docs/sdkgen/EventStream.md @@ -0,0 +1,29 @@ +# Event Stream + +The Event Stream class utilizes long-polling to receive real-time events from Box. The SDK provides an easy way to set up and manage the event stream which returns an iterable object and yields events as they are received. + + + + +- [Event Stream](#event-stream) + - [Listening to the Event Stream](#listening-to-the-event-stream) + - [Deduplication](#deduplication) + + + +## Listening to the Event Stream + +When the `EventStream` is started, it will begin long-polling asynchronously. Events received from the API are then yielded to the caller. + +```java +EventStream stream = client.getEvents().getEventStream(); +for (Event event : stream) { + System.out.printf( + "Received event: ID=%s, Type=%s, CreatedAt=%s%n\n",event.getEventId(),event.getEventType(),event.getCreatedAt()); +} + +``` + +## Deduplication + +The `EventStream` class automatically deduplicates events based on their `eventId`. This means that if the same event is received multiple times, it will only be emitted once to the listeners. diff --git a/docs/sdkgen/README.md b/docs/sdkgen/README.md new file mode 100644 index 000000000..f33f1ff46 --- /dev/null +++ b/docs/sdkgen/README.md @@ -0,0 +1,87 @@ +# Documentation + +## High-level Documentation + +General explanations of the available functionality and examples of how to use +the SDK are available by topic: + +* [Ai](ai.md) +* [Aistudio](aistudio.md) +* [Appitemassociations](appitemassociations.md) +* [Archives](archives.md) +* [Authorization](authorization.md) +* [Avatars](avatars.md) +* [Chunkeduploads](chunkeduploads.md) +* [Classifications](classifications.md) +* [Collaborationallowlistentries](collaborationallowlistentries.md) +* [Collaborationallowlistexempttargets](collaborationallowlistexempttargets.md) +* [Collections](collections.md) +* [Comments](comments.md) +* [Devicepinners](devicepinners.md) +* [Docgen](docgen.md) +* [Docgentemplate](docgentemplate.md) +* [Downloads](downloads.md) +* [Emailaliases](emailaliases.md) +* [Events](events.md) +* [Externalusers](externalusers.md) +* [Fileclassifications](fileclassifications.md) +* [Filemetadata](filemetadata.md) +* [Filerequests](filerequests.md) +* [Files](files.md) +* [Fileversionlegalholds](fileversionlegalholds.md) +* [Fileversionretentions](fileversionretentions.md) +* [Fileversions](fileversions.md) +* [Filewatermarks](filewatermarks.md) +* [Folderclassifications](folderclassifications.md) +* [Folderlocks](folderlocks.md) +* [Foldermetadata](foldermetadata.md) +* [Folders](folders.md) +* [Folderwatermarks](folderwatermarks.md) +* [Groups](groups.md) +* [Hubcollaborations](hubcollaborations.md) +* [Hubitems](hubitems.md) +* [Hubs](hubs.md) +* [Integrationmappings](integrationmappings.md) +* [Invites](invites.md) +* [Legalholdpolicies](legalholdpolicies.md) +* [Legalholdpolicyassignments](legalholdpolicyassignments.md) +* [Listcollaborations](listcollaborations.md) +* [Memberships](memberships.md) +* [Metadatacascadepolicies](metadatacascadepolicies.md) +* [Metadatatemplates](metadatatemplates.md) +* [Recentitems](recentitems.md) +* [Retentionpolicies](retentionpolicies.md) +* [Retentionpolicyassignments](retentionpolicyassignments.md) +* [Search](search.md) +* [Sessiontermination](sessiontermination.md) +* [Sharedlinksappitems](sharedlinksappitems.md) +* [Sharedlinksfiles](sharedlinksfiles.md) +* [Sharedlinksfolders](sharedlinksfolders.md) +* [Sharedlinksweblinks](sharedlinksweblinks.md) +* [Shieldinformationbarrierreports](shieldinformationbarrierreports.md) +* [Shieldinformationbarriers](shieldinformationbarriers.md) +* [Shieldinformationbarriersegmentmembers](shieldinformationbarriersegmentmembers.md) +* [Shieldinformationbarriersegmentrestrictions](shieldinformationbarriersegmentrestrictions.md) +* [Shieldinformationbarriersegments](shieldinformationbarriersegments.md) +* [Shieldlists](shieldlists.md) +* [Signrequests](signrequests.md) +* [Signtemplates](signtemplates.md) +* [Skills](skills.md) +* [Storagepolicies](storagepolicies.md) +* [Storagepolicyassignments](storagepolicyassignments.md) +* [Taskassignments](taskassignments.md) +* [Tasks](tasks.md) +* [Termsofservices](termsofservices.md) +* [Termsofserviceuserstatuses](termsofserviceuserstatuses.md) +* [Transfer](transfer.md) +* [Trashedfiles](trashedfiles.md) +* [Trashedfolders](trashedfolders.md) +* [Trasheditems](trasheditems.md) +* [Trashedweblinks](trashedweblinks.md) +* [Uploads](uploads.md) +* [Usercollaborations](usercollaborations.md) +* [Users](users.md) +* [Webhooks](webhooks.md) +* [Weblinks](weblinks.md) +* [Workflows](workflows.md) +* [Zipdownloads](zipdownloads.md) diff --git a/docs/sdkgen/ai.md b/docs/sdkgen/ai.md new file mode 100644 index 000000000..a8b3cef23 --- /dev/null +++ b/docs/sdkgen/ai.md @@ -0,0 +1,166 @@ +# AiManager + + +- [Ask question](#ask-question) +- [Generate text](#generate-text) +- [Get AI agent default configuration](#get-ai-agent-default-configuration) +- [Extract metadata (freeform)](#extract-metadata-freeform) +- [Extract metadata (structured)](#extract-metadata-structured) + +## Ask question + +Sends an AI request to supported LLMs and returns an answer specifically focused on the user's question given the provided context. + +This operation is performed by calling function `createAiAsk`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-ai-ask/). + + +``` +client.getAi().createAiAsk(new AiAsk.Builder(AiAskModeField.SINGLE_ITEM_QA, "which direction sun rises", Arrays.asList(new AiItemAsk.Builder(fileToAsk.getId(), AiItemAskTypeField.FILE).content("Sun rises in the East").build())).aiAgent(aiAskAgentConfig).build()) +``` + +### Arguments + +- requestBody `AiAsk` + - Request body of createAiAsk method +- headers `CreateAiAskHeaders` + - Headers of createAiAsk method + + +### Returns + +This function returns a value of type `AiResponseFull`. + +A successful response including the answer from the LLM.No content is available to answer the question. This is returned when the request item is a hub, but content in the hubs is not indexed. To ensure content in the hub is indexed, make sure Box AI for Hubs in the Admin Console was enabled before hub creation. + + +## Generate text + +Sends an AI request to supported Large Language Models (LLMs) and returns generated text based on the provided prompt. + +This operation is performed by calling function `createAiTextGen`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-ai-text-gen/). + + +``` +client.getAi().createAiTextGen(new AiTextGen.Builder("Parapharse the document.s", Arrays.asList(new AiTextGenItemsField.Builder(fileToAsk.getId()).type(AiTextGenItemsTypeField.FILE).content("The Earth goes around the sun. Sun rises in the East in the morning.").build())).dialogueHistory(Arrays.asList(new AiDialogueHistory.Builder().prompt("What does the earth go around?").answer("The sun").createdAt(dateTimeFromString("2021-01-01T00:00:00Z")).build(), new AiDialogueHistory.Builder().prompt("On Earth, where does the sun rise?").answer("East").createdAt(dateTimeFromString("2021-01-01T00:00:00Z")).build())).aiAgent(aiTextGenAgentConfig).build()) +``` + +### Arguments + +- requestBody `AiTextGen` + - Request body of createAiTextGen method +- headers `CreateAiTextGenHeaders` + - Headers of createAiTextGen method + + +### Returns + +This function returns a value of type `AiResponse`. + +A successful response including the answer from the LLM. + + +## Get AI agent default configuration + +Get the AI agent default config. + +This operation is performed by calling function `getAiAgentDefaultConfig`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-ai-agent-default/). + + +``` +client.getAi().getAiAgentDefaultConfig(new GetAiAgentDefaultConfigQueryParams.Builder(GetAiAgentDefaultConfigQueryParamsModeField.ASK).language("en-US").build()) +``` + +### Arguments + +- queryParams `GetAiAgentDefaultConfigQueryParams` + - Query parameters of getAiAgentDefaultConfig method +- headers `GetAiAgentDefaultConfigHeaders` + - Headers of getAiAgentDefaultConfig method + + +### Returns + +This function returns a value of type `AiAgent`. + +A successful response including the default agent configuration. +This response can be one of the following four objects: +* AI agent for questions +* AI agent for text generation +* AI agent for freeform metadata extraction +* AI agent for structured metadata extraction. +The response depends on the agent configuration requested in this endpoint. + + +## Extract metadata (freeform) + +Sends an AI request to supported Large Language Models (LLMs) and extracts metadata in form of key-value pairs. +In this request, both the prompt and the output can be freeform. +Metadata template setup before sending the request is not required. + +This operation is performed by calling function `createAiExtract`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-ai-extract/). + + +``` +client.getAi().createAiExtract(new AiExtract.Builder("firstName, lastName, location, yearOfBirth, company", Arrays.asList(new AiItemBase(file.getId()))).aiAgent(agentIgnoringOverridingEmbeddingsModel).build()) +``` + +### Arguments + +- requestBody `AiExtract` + - Request body of createAiExtract method +- headers `CreateAiExtractHeaders` + - Headers of createAiExtract method + + +### Returns + +This function returns a value of type `AiResponse`. + +A response including the answer from the LLM. + + +## Extract metadata (structured) + +Sends an AI request to supported Large Language Models (LLMs) and returns extracted metadata as a set of key-value pairs. +For this request, you either need a metadata template or a list of fields you want to extract. +Input is **either** a metadata template or a list of fields to ensure the structure. +To learn more about creating templates, see [Creating metadata templates in the Admin Console](https://support.box.com/hc/en-us/articles/360044194033-Customizing-Metadata-Templates) +or use the [metadata template API](g://metadata/templates/create). This endpoint also supports [Enhanced Extract Agent](g://box-ai/ai-tutorials/extract-metadata-structured/#enhanced-extract-agent). + +This operation is performed by calling function `createAiExtractStructured`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-ai-extract-structured/). + + +``` +client.getAi().createAiExtractStructured(new AiExtractStructured.Builder(Arrays.asList(new AiItemBase(file.getId()))).fields(Arrays.asList(new AiExtractStructuredFieldsField.Builder("firstName").description("Person first name").displayName("First name").prompt("What is the your first name?").type("string").build(), new AiExtractStructuredFieldsField.Builder("lastName").description("Person last name").displayName("Last name").prompt("What is the your last name?").type("string").build(), new AiExtractStructuredFieldsField.Builder("dateOfBirth").description("Person date of birth").displayName("Birth date").prompt("What is the date of your birth?").type("date").build(), new AiExtractStructuredFieldsField.Builder("age").description("Person age").displayName("Age").prompt("How old are you?").type("float").build(), new AiExtractStructuredFieldsField.Builder("hobby").description("Person hobby").displayName("Hobby").prompt("What is your hobby?").type("multiSelect").options(Arrays.asList(new AiExtractStructuredFieldsOptionsField("guitar"), new AiExtractStructuredFieldsOptionsField("books"))).build())).aiAgent(agentIgnoringOverridingEmbeddingsModel).build()) +``` + +### Arguments + +- requestBody `AiExtractStructured` + - Request body of createAiExtractStructured method +- headers `CreateAiExtractStructuredHeaders` + - Headers of createAiExtractStructured method + + +### Returns + +This function returns a value of type `AiExtractStructuredResponse`. + +A successful response including the answer from the LLM. + + diff --git a/docs/sdkgen/aistudio.md b/docs/sdkgen/aistudio.md new file mode 100644 index 000000000..2313462ff --- /dev/null +++ b/docs/sdkgen/aistudio.md @@ -0,0 +1,158 @@ +# AiStudioManager + + +- [List AI agents](#list-ai-agents) +- [Create AI agent](#create-ai-agent) +- [Update AI agent](#update-ai-agent) +- [Get AI agent by agent ID](#get-ai-agent-by-agent-id) +- [Delete AI agent](#delete-ai-agent) + +## List AI agents + +Lists AI agents based on the provided parameters. + +This operation is performed by calling function `getAiAgents`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-ai-agents/). + + +``` +client.getAiStudio().getAiAgents() +``` + +### Arguments + +- queryParams `GetAiAgentsQueryParams` + - Query parameters of getAiAgents method +- headers `GetAiAgentsHeaders` + - Headers of getAiAgents method + + +### Returns + +This function returns a value of type `AiMultipleAgentResponse`. + +A successful response including the agents list. + + +## Create AI agent + +Creates an AI agent. At least one of the following capabilities must be provided: `ask`, `text_gen`, `extract`. + +This operation is performed by calling function `createAiAgent`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-ai-agents/). + + +``` +client.getAiStudio().createAiAgent(new CreateAiAgent.Builder(agentName, "enabled").ask(new AiStudioAgentAsk("enabled", "desc1")).build()) +``` + +### Arguments + +- requestBody `CreateAiAgent` + - Request body of createAiAgent method +- headers `CreateAiAgentHeaders` + - Headers of createAiAgent method + + +### Returns + +This function returns a value of type `AiSingleAgentResponseFull`. + +Definition of created AI agent. + + +## Update AI agent + +Updates an AI agent. + +This operation is performed by calling function `updateAiAgentById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-ai-agents-id/). + + +``` +client.getAiStudio().updateAiAgentById(createdAgent.getId(), new CreateAiAgent.Builder(agentName, "enabled").ask(new AiStudioAgentAsk("disabled", "desc2")).build()) +``` + +### Arguments + +- agentId `String` + - The ID of the agent to update. Example: "1234" +- requestBody `CreateAiAgent` + - Request body of updateAiAgentById method +- headers `UpdateAiAgentByIdHeaders` + - Headers of updateAiAgentById method + + +### Returns + +This function returns a value of type `AiSingleAgentResponseFull`. + +Definition of created AI agent. + + +## Get AI agent by agent ID + +Gets an AI Agent using the `agent_id` parameter. + +This operation is performed by calling function `getAiAgentById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-ai-agents-id/). + + +``` +client.getAiStudio().getAiAgentById(createdAgent.getId(), new GetAiAgentByIdQueryParams.Builder().fields(Arrays.asList("ask")).build()) +``` + +### Arguments + +- agentId `String` + - The agent id to get. Example: "1234" +- queryParams `GetAiAgentByIdQueryParams` + - Query parameters of getAiAgentById method +- headers `GetAiAgentByIdHeaders` + - Headers of getAiAgentById method + + +### Returns + +This function returns a value of type `AiSingleAgentResponseFull`. + +A successful response including the agent. + + +## Delete AI agent + +Deletes an AI agent using the provided parameters. + +This operation is performed by calling function `deleteAiAgentById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-ai-agents-id/). + + +``` +client.getAiStudio().deleteAiAgentById(createdAgent.getId()) +``` + +### Arguments + +- agentId `String` + - The ID of the agent to delete. Example: "1234" +- headers `DeleteAiAgentByIdHeaders` + - Headers of deleteAiAgentById method + + +### Returns + +This function returns a value of type `void`. + +A successful response with no content. + + diff --git a/docs/sdkgen/appitemassociations.md b/docs/sdkgen/appitemassociations.md new file mode 100644 index 000000000..cc8a99bc2 --- /dev/null +++ b/docs/sdkgen/appitemassociations.md @@ -0,0 +1,80 @@ +# AppItemAssociationsManager + + +- [List file app item associations](#list-file-app-item-associations) +- [List folder app item associations](#list-folder-app-item-associations) + +## List file app item associations + +**This is a beta feature, which means that its availability might be limited.** +Returns all app items the file is associated with. This includes app items +associated with ancestors of the file. Assuming the context user has access +to the file, the type/ids are revealed even if the context user does not +have **View** permission on the app item. + +This operation is performed by calling function `getFileAppItemAssociations`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-files-id-app-item-associations/). + + +``` +client.getAppItemAssociations().getFileAppItemAssociations(fileId) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- queryParams `GetFileAppItemAssociationsQueryParams` + - Query parameters of getFileAppItemAssociations method +- headers `GetFileAppItemAssociationsHeaders` + - Headers of getFileAppItemAssociations method + + +### Returns + +This function returns a value of type `AppItemAssociations`. + +Returns a collection of app item objects. If there are no +app items on this file, an empty collection will be returned. +This list includes app items on ancestors of this File. + + +## List folder app item associations + +**This is a beta feature, which means that its availability might be limited.** +Returns all app items the folder is associated with. This includes app items +associated with ancestors of the folder. Assuming the context user has access +to the folder, the type/ids are revealed even if the context user does not +have **View** permission on the app item. + +This operation is performed by calling function `getFolderAppItemAssociations`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-folders-id-app-item-associations/). + + +``` +client.getAppItemAssociations().getFolderAppItemAssociations(folderId) +``` + +### Arguments + +- folderId `String` + - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" +- queryParams `GetFolderAppItemAssociationsQueryParams` + - Query parameters of getFolderAppItemAssociations method +- headers `GetFolderAppItemAssociationsHeaders` + - Headers of getFolderAppItemAssociations method + + +### Returns + +This function returns a value of type `AppItemAssociations`. + +Returns a collection of app item objects. If there are no +app items on this folder an empty collection will be returned. +This list includes app items on ancestors of this folder. + + diff --git a/docs/sdkgen/archives.md b/docs/sdkgen/archives.md new file mode 100644 index 000000000..173edd0c6 --- /dev/null +++ b/docs/sdkgen/archives.md @@ -0,0 +1,100 @@ +# ArchivesManager + + +- [List archives](#list-archives) +- [Create archive](#create-archive) +- [Delete archive](#delete-archive) + +## List archives + +Retrieves archives for an enterprise. + +To learn more about the archive APIs, see the [Archive API Guide](g://archives). + +This operation is performed by calling function `getArchivesV2025R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2025.0/get-archives/). + + +``` +client.getArchives().getArchivesV2025R0(new GetArchivesV2025R0QueryParams.Builder().limit(100L).build()) +``` + +### Arguments + +- queryParams `GetArchivesV2025R0QueryParams` + - Query parameters of getArchivesV2025R0 method +- headers `GetArchivesV2025R0Headers` + - Headers of getArchivesV2025R0 method + + +### Returns + +This function returns a value of type `ArchivesV2025R0`. + +Returns a list of archives in the enterprise. + + +## Create archive + +Creates an archive. + +To learn more about the archive APIs, see the [Archive API Guide](g://archives). + +This operation is performed by calling function `createArchiveV2025R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2025.0/post-archives/). + + +``` +client.getArchives().createArchiveV2025R0(new CreateArchiveV2025R0RequestBody(archiveName)) +``` + +### Arguments + +- requestBody `CreateArchiveV2025R0RequestBody` + - Request body of createArchiveV2025R0 method +- headers `CreateArchiveV2025R0Headers` + - Headers of createArchiveV2025R0 method + + +### Returns + +This function returns a value of type `ArchiveV2025R0`. + +Returns a new archive object. + + +## Delete archive + +Permanently deletes an archive. + +To learn more about the archive APIs, see the [Archive API Guide](g://archives). + +This operation is performed by calling function `deleteArchiveByIdV2025R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2025.0/delete-archives-id/). + + +``` +client.getArchives().deleteArchiveByIdV2025R0(archive.getId()) +``` + +### Arguments + +- archiveId `String` + - The ID of the archive. Example: "982312" +- headers `DeleteArchiveByIdV2025R0Headers` + - Headers of deleteArchiveByIdV2025R0 method + + +### Returns + +This function returns a value of type `void`. + +Returns an empty response when the archive has been deleted. + + diff --git a/docs/sdkgen/authorization.md b/docs/sdkgen/authorization.md new file mode 100644 index 000000000..b2be220ec --- /dev/null +++ b/docs/sdkgen/authorization.md @@ -0,0 +1,134 @@ +# AuthorizationManager + + +- [Authorize user](#authorize-user) +- [Request access token](#request-access-token) +- [Refresh access token](#refresh-access-token) +- [Revoke access token](#revoke-access-token) + +## Authorize user + +Authorize a user by sending them through the [Box](https://box.com) +website and request their permission to act on their behalf. + +This is the first step when authenticating a user using +OAuth 2.0. To request a user's authorization to use the Box APIs +on their behalf you will need to send a user to the URL with this +format. + +This operation is performed by calling function `authorizeUser`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-authorize/). + +*Currently we don't have an example for calling `authorizeUser` in integration tests* + +### Arguments + +- queryParams `AuthorizeUserQueryParams` + - Query parameters of authorizeUser method +- headers `AuthorizeUserHeaders` + - Headers of authorizeUser method + + +### Returns + +This function returns a value of type `void`. + +Does not return any data, but rather should be used in the browser. + + +## Request access token + +Request an Access Token using either a client-side obtained OAuth 2.0 +authorization code or a server-side JWT assertion. + +An Access Token is a string that enables Box to verify that a +request belongs to an authorized session. In the normal order of +operations you will begin by requesting authentication from the +[authorize](#get-authorize) endpoint and Box will send you an +authorization code. + +You will then send this code to this endpoint to exchange it for +an Access Token. The returned Access Token can then be used to to make +Box API calls. + +This operation is performed by calling function `requestAccessToken`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-oauth2-token/). + +*Currently we don't have an example for calling `requestAccessToken` in integration tests* + +### Arguments + +- requestBody `PostOAuth2Token` + - Request body of requestAccessToken method +- headers `RequestAccessTokenHeaders` + - Headers of requestAccessToken method + + +### Returns + +This function returns a value of type `AccessToken`. + +Returns a new Access Token that can be used to make authenticated +API calls by passing along the token in a authorization header as +follows `Authorization: Bearer `. + + +## Refresh access token + +Refresh an Access Token using its client ID, secret, and refresh token. + +This operation is performed by calling function `refreshAccessToken`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-oauth2-token--refresh/). + +*Currently we don't have an example for calling `refreshAccessToken` in integration tests* + +### Arguments + +- requestBody `PostOAuth2TokenRefreshAccessToken` + - Request body of refreshAccessToken method +- headers `RefreshAccessTokenHeaders` + - Headers of refreshAccessToken method + + +### Returns + +This function returns a value of type `AccessToken`. + +Returns a new Access Token that can be used to make authenticated +API calls by passing along the token in a authorization header as +follows `Authorization: Bearer `. + + +## Revoke access token + +Revoke an active Access Token, effectively logging a user out +that has been previously authenticated. + +This operation is performed by calling function `revokeAccessToken`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-oauth2-revoke/). + +*Currently we don't have an example for calling `revokeAccessToken` in integration tests* + +### Arguments + +- requestBody `PostOAuth2Revoke` + - Request body of revokeAccessToken method +- headers `RevokeAccessTokenHeaders` + - Headers of revokeAccessToken method + + +### Returns + +This function returns a value of type `void`. + +Returns an empty response when the token was successfully revoked. + + diff --git a/docs/sdkgen/avatars.md b/docs/sdkgen/avatars.md new file mode 100644 index 000000000..902fffd58 --- /dev/null +++ b/docs/sdkgen/avatars.md @@ -0,0 +1,101 @@ +# AvatarsManager + + +- [Get user avatar](#get-user-avatar) +- [Add or update user avatar](#add-or-update-user-avatar) +- [Delete user avatar](#delete-user-avatar) + +## Get user avatar + +Retrieves an image of a the user's avatar. + +This operation is performed by calling function `getUserAvatar`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-users-id-avatar/). + + +``` +client.getAvatars().getUserAvatar(user.getId()) +``` + +### Arguments + +- userId `String` + - The ID of the user. Example: "12345" +- headers `GetUserAvatarHeaders` + - Headers of getUserAvatar method + + +### Returns + +This function returns a value of type `InputStream`. + +When an avatar can be found for the user the +image data will be returned in the body of the +response. + + +## Add or update user avatar + +Adds or updates a user avatar. + +This operation is performed by calling function `createUserAvatar`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-users-id-avatar/). + + +``` +client.getAvatars().createUserAvatar(user.getId(), new CreateUserAvatarRequestBody.Builder(decodeBase64ByteStream("iVBORw0KGgoAAAANSUhEUgAAAQAAAAEAAQMAAABmvDolAAAAA1BMVEW10NBjBBbqAAAAH0lEQVRoge3BAQ0AAADCoPdPbQ43oAAAAAAAAAAAvg0hAAABmmDh1QAAAABJRU5ErkJggg==")).picFileName("avatar.png").picContentType("image/png").build()) +``` + +### Arguments + +- userId `String` + - The ID of the user. Example: "12345" +- requestBody `CreateUserAvatarRequestBody` + - Request body of createUserAvatar method +- headers `CreateUserAvatarHeaders` + - Headers of createUserAvatar method + + +### Returns + +This function returns a value of type `UserAvatar`. + +`ok`: Returns the `pic_urls` object with URLs to existing +user avatars that were updated.`created`: Returns the `pic_urls` object with URLS to user avatars +uploaded to Box with the request. + + +## Delete user avatar + +Removes an existing user avatar. +You cannot reverse this operation. + +This operation is performed by calling function `deleteUserAvatar`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-users-id-avatar/). + + +``` +client.getAvatars().deleteUserAvatar(user.getId()) +``` + +### Arguments + +- userId `String` + - The ID of the user. Example: "12345" +- headers `DeleteUserAvatarHeaders` + - Headers of deleteUserAvatar method + + +### Returns + +This function returns a value of type `void`. + +`no_content`: Removes the avatar and returns an empty response. + + diff --git a/docs/sdkgen/chunkeduploads.md b/docs/sdkgen/chunkeduploads.md new file mode 100644 index 000000000..5b8136599 --- /dev/null +++ b/docs/sdkgen/chunkeduploads.md @@ -0,0 +1,450 @@ +# ChunkedUploadsManager + +This is a manager for chunked uploads (allowed for files at least 20MB). + +- [Create upload session](#create-upload-session) +- [Create upload session for existing file](#create-upload-session-for-existing-file) +- [Get upload session by URL](#get-upload-session-by-url) +- [Get upload session](#get-upload-session) +- [Upload part of file by URL](#upload-part-of-file-by-url) +- [Upload part of file](#upload-part-of-file) +- [Remove upload session by URL](#remove-upload-session-by-url) +- [Remove upload session](#remove-upload-session) +- [List parts by URL](#list-parts-by-url) +- [List parts](#list-parts) +- [Commit upload session by URL](#commit-upload-session-by-url) +- [Commit upload session](#commit-upload-session) +- [Upload big file](#upload-big-file) + +## Create upload session + +Creates an upload session for a new file. + +This operation is performed by calling function `createFileUploadSession`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-files-upload-sessions/). + + +``` +client.getChunkedUploads().createFileUploadSession(new CreateFileUploadSessionRequestBody(parentFolderId, fileSize, fileName)) +``` + +### Arguments + +- requestBody `CreateFileUploadSessionRequestBody` + - Request body of createFileUploadSession method +- headers `CreateFileUploadSessionHeaders` + - Headers of createFileUploadSession method + + +### Returns + +This function returns a value of type `UploadSession`. + +Returns a new upload session. + + +## Create upload session for existing file + +Creates an upload session for an existing file. + +This operation is performed by calling function `createFileUploadSessionForExistingFile`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-files-id-upload-sessions/). + +*Currently we don't have an example for calling `createFileUploadSessionForExistingFile` in integration tests* + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- requestBody `CreateFileUploadSessionForExistingFileRequestBody` + - Request body of createFileUploadSessionForExistingFile method +- headers `CreateFileUploadSessionForExistingFileHeaders` + - Headers of createFileUploadSessionForExistingFile method + + +### Returns + +This function returns a value of type `UploadSession`. + +Returns a new upload session. + + +## Get upload session by URL + +Return information about an upload session. + +The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) endpoint. + +This operation is performed by calling function `getFileUploadSessionByUrl`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-files-upload-sessions-id/). + + +``` +client.getChunkedUploads().getFileUploadSessionByUrl(statusUrl) +``` + +### Arguments + +- url `String` + - URL of getFileUploadSessionById method +- headers `GetFileUploadSessionByUrlHeaders` + - Headers of getFileUploadSessionById method + + +### Returns + +This function returns a value of type `UploadSession`. + +Returns an upload session object. + + +## Get upload session + +Return information about an upload session. + +The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) endpoint. + +This operation is performed by calling function `getFileUploadSessionById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-files-upload-sessions-id/). + + +``` +client.getChunkedUploads().getFileUploadSessionById(uploadSessionId) +``` + +### Arguments + +- uploadSessionId `String` + - The ID of the upload session. Example: "D5E3F7A" +- headers `GetFileUploadSessionByIdHeaders` + - Headers of getFileUploadSessionById method + + +### Returns + +This function returns a value of type `UploadSession`. + +Returns an upload session object. + + +## Upload part of file by URL + +Uploads a chunk of a file for an upload session. + +The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) +and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. + +This operation is performed by calling function `uploadFilePartByUrl`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-files-upload-sessions-id/). + + +``` +client.getChunkedUploads().uploadFilePartByUrl(acc.getUploadPartUrl(), generateByteStreamFromBuffer(chunkBuffer), new UploadFilePartByUrlHeaders(digest, contentRange)) +``` + +### Arguments + +- url `String` + - URL of uploadFilePart method +- requestBody `InputStream` + - Request body of uploadFilePart method +- headers `UploadFilePartByUrlHeaders` + - Headers of uploadFilePart method + + +### Returns + +This function returns a value of type `UploadedPart`. + +Chunk has been uploaded successfully. + + +## Upload part of file + +Uploads a chunk of a file for an upload session. + +The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) +and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. + +This operation is performed by calling function `uploadFilePart`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-files-upload-sessions-id/). + + +``` +client.getChunkedUploads().uploadFilePart(acc.getUploadSessionId(), generateByteStreamFromBuffer(chunkBuffer), new UploadFilePartHeaders(digest, contentRange)) +``` + +### Arguments + +- uploadSessionId `String` + - The ID of the upload session. Example: "D5E3F7A" +- requestBody `InputStream` + - Request body of uploadFilePart method +- headers `UploadFilePartHeaders` + - Headers of uploadFilePart method + + +### Returns + +This function returns a value of type `UploadedPart`. + +Chunk has been uploaded successfully. + + +## Remove upload session by URL + +Abort an upload session and discard all data uploaded. + +This cannot be reversed. + +The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) +and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. + +This operation is performed by calling function `deleteFileUploadSessionByUrl`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-files-upload-sessions-id/). + + +``` +client.getChunkedUploads().deleteFileUploadSessionByUrl(abortUrl) +``` + +### Arguments + +- url `String` + - URL of deleteFileUploadSessionById method +- headers `DeleteFileUploadSessionByUrlHeaders` + - Headers of deleteFileUploadSessionById method + + +### Returns + +This function returns a value of type `void`. + +A blank response is returned if the session was +successfully aborted. + + +## Remove upload session + +Abort an upload session and discard all data uploaded. + +This cannot be reversed. + +The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) +and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. + +This operation is performed by calling function `deleteFileUploadSessionById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-files-upload-sessions-id/). + + +``` +client.getChunkedUploads().deleteFileUploadSessionById(uploadSessionId) +``` + +### Arguments + +- uploadSessionId `String` + - The ID of the upload session. Example: "D5E3F7A" +- headers `DeleteFileUploadSessionByIdHeaders` + - Headers of deleteFileUploadSessionById method + + +### Returns + +This function returns a value of type `void`. + +A blank response is returned if the session was +successfully aborted. + + +## List parts by URL + +Return a list of the chunks uploaded to the upload session so far. + +The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) +and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. + +This operation is performed by calling function `getFileUploadSessionPartsByUrl`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-files-upload-sessions-id-parts/). + + +``` +client.getChunkedUploads().getFileUploadSessionPartsByUrl(listPartsUrl) +``` + +### Arguments + +- url `String` + - URL of getFileUploadSessionParts method +- queryParams `GetFileUploadSessionPartsByUrlQueryParams` + - Query parameters of getFileUploadSessionParts method +- headers `GetFileUploadSessionPartsByUrlHeaders` + - Headers of getFileUploadSessionParts method + + +### Returns + +This function returns a value of type `UploadParts`. + +Returns a list of parts that have been uploaded. + + +## List parts + +Return a list of the chunks uploaded to the upload session so far. + +The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) +and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. + +This operation is performed by calling function `getFileUploadSessionParts`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-files-upload-sessions-id-parts/). + + +``` +client.getChunkedUploads().getFileUploadSessionParts(uploadSessionId) +``` + +### Arguments + +- uploadSessionId `String` + - The ID of the upload session. Example: "D5E3F7A" +- queryParams `GetFileUploadSessionPartsQueryParams` + - Query parameters of getFileUploadSessionParts method +- headers `GetFileUploadSessionPartsHeaders` + - Headers of getFileUploadSessionParts method + + +### Returns + +This function returns a value of type `UploadParts`. + +Returns a list of parts that have been uploaded. + + +## Commit upload session by URL + +Close an upload session and create a file from the uploaded chunks. + +The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) +and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. + +This operation is performed by calling function `createFileUploadSessionCommitByUrl`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-files-upload-sessions-id-commit/). + + +``` +client.getChunkedUploads().createFileUploadSessionCommitByUrl(commitUrl, new CreateFileUploadSessionCommitByUrlRequestBody(parts), new CreateFileUploadSessionCommitByUrlHeaders(digest)) +``` + +### Arguments + +- url `String` + - URL of createFileUploadSessionCommit method +- requestBody `CreateFileUploadSessionCommitByUrlRequestBody` + - Request body of createFileUploadSessionCommit method +- headers `CreateFileUploadSessionCommitByUrlHeaders` + - Headers of createFileUploadSessionCommit method + + +### Returns + +This function returns a value of type `Files`. + +Returns the file object in a list.Returns when all chunks have been uploaded but not yet processed. + +Inspect the upload session to get more information about the +progress of processing the chunks, then retry committing the file +when all chunks have processed. + + +## Commit upload session + +Close an upload session and create a file from the uploaded chunks. + +The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) +and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. + +This operation is performed by calling function `createFileUploadSessionCommit`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-files-upload-sessions-id-commit/). + + +``` +client.getChunkedUploads().createFileUploadSessionCommit(uploadSessionId, new CreateFileUploadSessionCommitRequestBody(parts), new CreateFileUploadSessionCommitHeaders(digest)) +``` + +### Arguments + +- uploadSessionId `String` + - The ID of the upload session. Example: "D5E3F7A" +- requestBody `CreateFileUploadSessionCommitRequestBody` + - Request body of createFileUploadSessionCommit method +- headers `CreateFileUploadSessionCommitHeaders` + - Headers of createFileUploadSessionCommit method + + +### Returns + +This function returns a value of type `Files`. + +Returns the file object in a list.Returns when all chunks have been uploaded but not yet processed. + +Inspect the upload session to get more information about the +progress of processing the chunks, then retry committing the file +when all chunks have processed. + + +## Upload big file + +Starts the process of chunk uploading a big file. Should return a File object representing uploaded file. + +This operation is performed by calling function `uploadBigFile`. + + + +``` +client.getChunkedUploads().uploadBigFile(fileByteStream, fileName, fileSize, parentFolderId) +``` + +### Arguments + +- file `InputStream` + - The stream of the file to upload. +- fileName `String` + - The name of the file, which will be used for storage in Box. +- fileSize `long` + - The total size of the file for the chunked upload in bytes. +- parentFolderId `String` + - The ID of the folder where the file should be uploaded. + + +### Returns + +This function returns a value of type `FileFull`. + + + + diff --git a/docs/sdkgen/classifications.md b/docs/sdkgen/classifications.md new file mode 100644 index 000000000..6f3139fbe --- /dev/null +++ b/docs/sdkgen/classifications.md @@ -0,0 +1,148 @@ +# ClassificationsManager + + +- [List all classifications](#list-all-classifications) +- [Add classification](#add-classification) +- [Update classification](#update-classification) +- [Add initial classifications](#add-initial-classifications) + +## List all classifications + +Retrieves the classification metadata template and lists all the +classifications available to this enterprise. + +This API can also be called by including the enterprise ID in the +URL explicitly, for example +`/metadata_templates/enterprise_12345/securityClassification-6VMVochwUWo/schema`. + +This operation is performed by calling function `getClassificationTemplate`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-metadata-templates-enterprise-securityClassification-6VMVochwUWo-schema/). + + +``` +client.getClassifications().getClassificationTemplate() +``` + +### Arguments + +- headers `GetClassificationTemplateHeaders` + - Headers of getClassificationTemplate method + + +### Returns + +This function returns a value of type `ClassificationTemplate`. + +Returns the `securityClassification` metadata template, which contains +a `Box__Security__Classification__Key` field that lists all the +classifications available to this enterprise. + + +## Add classification + +Adds one or more new classifications to the list of classifications +available to the enterprise. + +This API can also be called by including the enterprise ID in the +URL explicitly, for example +`/metadata_templates/enterprise_12345/securityClassification-6VMVochwUWo/schema`. + +This operation is performed by calling function `addClassification`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-metadata-templates-enterprise-securityClassification-6VMVochwUWo-schema--add/). + + +``` +client.getClassifications().addClassification(Arrays.asList(new AddClassificationRequestBody(new AddClassificationRequestBodyDataField.Builder(getUuid()).staticConfig(new AddClassificationRequestBodyDataStaticConfigField.Builder().classification(new AddClassificationRequestBodyDataStaticConfigClassificationField.Builder().classificationDefinition("Other description").colorId(4L).build()).build()).build()))) +``` + +### Arguments + +- requestBody `List` + - Request body of addClassification method +- headers `AddClassificationHeaders` + - Headers of addClassification method + + +### Returns + +This function returns a value of type `ClassificationTemplate`. + +Returns the updated `securityClassification` metadata template, which +contains a `Box__Security__Classification__Key` field that lists all +the classifications available to this enterprise. + + +## Update classification + +Updates the labels and descriptions of one or more classifications +available to the enterprise. + +This API can also be called by including the enterprise ID in the +URL explicitly, for example +`/metadata_templates/enterprise_12345/securityClassification-6VMVochwUWo/schema`. + +This operation is performed by calling function `updateClassification`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-metadata-templates-enterprise-securityClassification-6VMVochwUWo-schema--update/). + + +``` +client.getClassifications().updateClassification(Arrays.asList(new UpdateClassificationRequestBody(classification.getKey(), new UpdateClassificationRequestBodyDataField.Builder(updatedClassificationName).staticConfig(new UpdateClassificationRequestBodyDataStaticConfigField.Builder().classification(new UpdateClassificationRequestBodyDataStaticConfigClassificationField.Builder().classificationDefinition(updatedClassificationDescription).colorId(2L).build()).build()).build()))) +``` + +### Arguments + +- requestBody `List` + - Request body of updateClassification method +- headers `UpdateClassificationHeaders` + - Headers of updateClassification method + + +### Returns + +This function returns a value of type `ClassificationTemplate`. + +Returns the updated `securityClassification` metadata template, which +contains a `Box__Security__Classification__Key` field that lists all +the classifications available to this enterprise. + + +## Add initial classifications + +When an enterprise does not yet have any classifications, this API call +initializes the classification template with an initial set of +classifications. + +If an enterprise already has a classification, the template will already +exist and instead an API call should be made to add additional +classifications. + +This operation is performed by calling function `createClassificationTemplate`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-metadata-templates-schema--classifications/). + +*Currently we don't have an example for calling `createClassificationTemplate` in integration tests* + +### Arguments + +- requestBody `CreateClassificationTemplateRequestBody` + - Request body of createClassificationTemplate method +- headers `CreateClassificationTemplateHeaders` + - Headers of createClassificationTemplate method + + +### Returns + +This function returns a value of type `ClassificationTemplate`. + +Returns a new `securityClassification` metadata template, which +contains a `Box__Security__Classification__Key` field that lists all +the classifications available to this enterprise. + + diff --git a/docs/sdkgen/collaborationallowlistentries.md b/docs/sdkgen/collaborationallowlistentries.md new file mode 100644 index 000000000..20aa3c70b --- /dev/null +++ b/docs/sdkgen/collaborationallowlistentries.md @@ -0,0 +1,129 @@ +# CollaborationAllowlistEntriesManager + + +- [List allowed collaboration domains](#list-allowed-collaboration-domains) +- [Add domain to list of allowed collaboration domains](#add-domain-to-list-of-allowed-collaboration-domains) +- [Get allowed collaboration domain](#get-allowed-collaboration-domain) +- [Remove domain from list of allowed collaboration domains](#remove-domain-from-list-of-allowed-collaboration-domains) + +## List allowed collaboration domains + +Returns the list domains that have been deemed safe to create collaborations +for within the current enterprise. + +This operation is performed by calling function `getCollaborationWhitelistEntries`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-collaboration-whitelist-entries/). + + +``` +client.getCollaborationAllowlistEntries().getCollaborationWhitelistEntries() +``` + +### Arguments + +- queryParams `GetCollaborationWhitelistEntriesQueryParams` + - Query parameters of getCollaborationWhitelistEntries method +- headers `GetCollaborationWhitelistEntriesHeaders` + - Headers of getCollaborationWhitelistEntries method + + +### Returns + +This function returns a value of type `CollaborationAllowlistEntries`. + +Returns a collection of domains that are allowed for collaboration. + + +## Add domain to list of allowed collaboration domains + +Creates a new entry in the list of allowed domains to allow +collaboration for. + +This operation is performed by calling function `createCollaborationWhitelistEntry`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-collaboration-whitelist-entries/). + + +``` +client.getCollaborationAllowlistEntries().createCollaborationWhitelistEntry(new CreateCollaborationWhitelistEntryRequestBody(domain, CreateCollaborationWhitelistEntryRequestBodyDirectionField.INBOUND)) +``` + +### Arguments + +- requestBody `CreateCollaborationWhitelistEntryRequestBody` + - Request body of createCollaborationWhitelistEntry method +- headers `CreateCollaborationWhitelistEntryHeaders` + - Headers of createCollaborationWhitelistEntry method + + +### Returns + +This function returns a value of type `CollaborationAllowlistEntry`. + +Returns a new entry on the list of allowed domains. + + +## Get allowed collaboration domain + +Returns a domain that has been deemed safe to create collaborations +for within the current enterprise. + +This operation is performed by calling function `getCollaborationWhitelistEntryById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-collaboration-whitelist-entries-id/). + + +``` +client.getCollaborationAllowlistEntries().getCollaborationWhitelistEntryById(newEntry.getId()) +``` + +### Arguments + +- collaborationWhitelistEntryId `String` + - The ID of the entry in the list. Example: "213123" +- headers `GetCollaborationWhitelistEntryByIdHeaders` + - Headers of getCollaborationWhitelistEntryById method + + +### Returns + +This function returns a value of type `CollaborationAllowlistEntry`. + +Returns an entry on the list of allowed domains. + + +## Remove domain from list of allowed collaboration domains + +Removes a domain from the list of domains that have been deemed safe to create +collaborations for within the current enterprise. + +This operation is performed by calling function `deleteCollaborationWhitelistEntryById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-collaboration-whitelist-entries-id/). + + +``` +client.getCollaborationAllowlistEntries().deleteCollaborationWhitelistEntryById(entry.getId()) +``` + +### Arguments + +- collaborationWhitelistEntryId `String` + - The ID of the entry in the list. Example: "213123" +- headers `DeleteCollaborationWhitelistEntryByIdHeaders` + - Headers of deleteCollaborationWhitelistEntryById method + + +### Returns + +This function returns a value of type `void`. + +A blank response is returned if the entry was +successfully deleted. + + diff --git a/docs/sdkgen/collaborationallowlistexempttargets.md b/docs/sdkgen/collaborationallowlistexempttargets.md new file mode 100644 index 000000000..a96a3790c --- /dev/null +++ b/docs/sdkgen/collaborationallowlistexempttargets.md @@ -0,0 +1,129 @@ +# CollaborationAllowlistExemptTargetsManager + + +- [List users exempt from collaboration domain restrictions](#list-users-exempt-from-collaboration-domain-restrictions) +- [Create user exemption from collaboration domain restrictions](#create-user-exemption-from-collaboration-domain-restrictions) +- [Get user exempt from collaboration domain restrictions](#get-user-exempt-from-collaboration-domain-restrictions) +- [Remove user from list of users exempt from domain restrictions](#remove-user-from-list-of-users-exempt-from-domain-restrictions) + +## List users exempt from collaboration domain restrictions + +Returns a list of users who have been exempt from the collaboration +domain restrictions. + +This operation is performed by calling function `getCollaborationWhitelistExemptTargets`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-collaboration-whitelist-exempt-targets/). + + +``` +client.getCollaborationAllowlistExemptTargets().getCollaborationWhitelistExemptTargets() +``` + +### Arguments + +- queryParams `GetCollaborationWhitelistExemptTargetsQueryParams` + - Query parameters of getCollaborationWhitelistExemptTargets method +- headers `GetCollaborationWhitelistExemptTargetsHeaders` + - Headers of getCollaborationWhitelistExemptTargets method + + +### Returns + +This function returns a value of type `CollaborationAllowlistExemptTargets`. + +Returns a collection of user exemptions. + + +## Create user exemption from collaboration domain restrictions + +Exempts a user from the restrictions set out by the allowed list of domains +for collaborations. + +This operation is performed by calling function `createCollaborationWhitelistExemptTarget`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-collaboration-whitelist-exempt-targets/). + + +``` +client.getCollaborationAllowlistExemptTargets().createCollaborationWhitelistExemptTarget(new CreateCollaborationWhitelistExemptTargetRequestBody(new CreateCollaborationWhitelistExemptTargetRequestBodyUserField(user.getId()))) +``` + +### Arguments + +- requestBody `CreateCollaborationWhitelistExemptTargetRequestBody` + - Request body of createCollaborationWhitelistExemptTarget method +- headers `CreateCollaborationWhitelistExemptTargetHeaders` + - Headers of createCollaborationWhitelistExemptTarget method + + +### Returns + +This function returns a value of type `CollaborationAllowlistExemptTarget`. + +Returns a new exemption entry. + + +## Get user exempt from collaboration domain restrictions + +Returns a users who has been exempt from the collaboration +domain restrictions. + +This operation is performed by calling function `getCollaborationWhitelistExemptTargetById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-collaboration-whitelist-exempt-targets-id/). + + +``` +client.getCollaborationAllowlistExemptTargets().getCollaborationWhitelistExemptTargetById(newExemptTarget.getId()) +``` + +### Arguments + +- collaborationWhitelistExemptTargetId `String` + - The ID of the exemption to the list. Example: "984923" +- headers `GetCollaborationWhitelistExemptTargetByIdHeaders` + - Headers of getCollaborationWhitelistExemptTargetById method + + +### Returns + +This function returns a value of type `CollaborationAllowlistExemptTarget`. + +Returns the user's exempted from the list of collaboration domains. + + +## Remove user from list of users exempt from domain restrictions + +Removes a user's exemption from the restrictions set out by the allowed list +of domains for collaborations. + +This operation is performed by calling function `deleteCollaborationWhitelistExemptTargetById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-collaboration-whitelist-exempt-targets-id/). + + +``` +client.getCollaborationAllowlistExemptTargets().deleteCollaborationWhitelistExemptTargetById(exemptTarget.getId()) +``` + +### Arguments + +- collaborationWhitelistExemptTargetId `String` + - The ID of the exemption to the list. Example: "984923" +- headers `DeleteCollaborationWhitelistExemptTargetByIdHeaders` + - Headers of deleteCollaborationWhitelistExemptTargetById method + + +### Returns + +This function returns a value of type `void`. + +A blank response is returned if the exemption was +successfully deleted. + + diff --git a/docs/sdkgen/collections.md b/docs/sdkgen/collections.md new file mode 100644 index 000000000..dabe7ba5d --- /dev/null +++ b/docs/sdkgen/collections.md @@ -0,0 +1,91 @@ +# CollectionsManager + + +- [List all collections](#list-all-collections) +- [List collection items](#list-collection-items) +- [Get collection by ID](#get-collection-by-id) + +## List all collections + +Retrieves all collections for a given user. + +Currently, only the `favorites` collection +is supported. + +This operation is performed by calling function `getCollections`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-collections/). + +*Currently we don't have an example for calling `getCollections` in integration tests* + +### Arguments + +- queryParams `GetCollectionsQueryParams` + - Query parameters of getCollections method +- headers `GetCollectionsHeaders` + - Headers of getCollections method + + +### Returns + +This function returns a value of type `Collections`. + +Returns all collections for the given user. + + +## List collection items + +Retrieves the files and/or folders contained within +this collection. + +This operation is performed by calling function `getCollectionItems`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-collections-id-items/). + +*Currently we don't have an example for calling `getCollectionItems` in integration tests* + +### Arguments + +- collectionId `String` + - The ID of the collection. Example: "926489" +- queryParams `GetCollectionItemsQueryParams` + - Query parameters of getCollectionItems method +- headers `GetCollectionItemsHeaders` + - Headers of getCollectionItems method + + +### Returns + +This function returns a value of type `ItemsOffsetPaginated`. + +Returns an array of items in the collection. + + +## Get collection by ID + +Retrieves a collection by its ID. + +This operation is performed by calling function `getCollectionById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-collections-id/). + +*Currently we don't have an example for calling `getCollectionById` in integration tests* + +### Arguments + +- collectionId `String` + - The ID of the collection. Example: "926489" +- headers `GetCollectionByIdHeaders` + - Headers of getCollectionById method + + +### Returns + +This function returns a value of type `Collection`. + +Returns an array of items in the collection. + + diff --git a/docs/sdkgen/comments.md b/docs/sdkgen/comments.md new file mode 100644 index 000000000..4691d323e --- /dev/null +++ b/docs/sdkgen/comments.md @@ -0,0 +1,171 @@ +# CommentsManager + + +- [List file comments](#list-file-comments) +- [Get comment](#get-comment) +- [Update comment](#update-comment) +- [Remove comment](#remove-comment) +- [Create comment](#create-comment) + +## List file comments + +Retrieves a list of comments for a file. + +This operation is performed by calling function `getFileComments`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-files-id-comments/). + + +``` +client.getComments().getFileComments(fileId) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- queryParams `GetFileCommentsQueryParams` + - Query parameters of getFileComments method +- headers `GetFileCommentsHeaders` + - Headers of getFileComments method + + +### Returns + +This function returns a value of type `Comments`. + +Returns a collection of comment objects. If there are no +comments on this file an empty collection will be returned. + + +## Get comment + +Retrieves the message and metadata for a specific comment, as well +as information on the user who created the comment. + +This operation is performed by calling function `getCommentById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-comments-id/). + + +``` +client.getComments().getCommentById(newComment.getId()) +``` + +### Arguments + +- commentId `String` + - The ID of the comment. Example: "12345" +- queryParams `GetCommentByIdQueryParams` + - Query parameters of getCommentById method +- headers `GetCommentByIdHeaders` + - Headers of getCommentById method + + +### Returns + +This function returns a value of type `CommentFull`. + +Returns a full comment object. + + +## Update comment + +Update the message of a comment. + +This operation is performed by calling function `updateCommentById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-comments-id/). + + +``` +client.getComments().updateCommentById(newReplyComment.getId(), new UpdateCommentByIdRequestBody.Builder().message(newMessage).build()) +``` + +### Arguments + +- commentId `String` + - The ID of the comment. Example: "12345" +- requestBody `UpdateCommentByIdRequestBody` + - Request body of updateCommentById method +- queryParams `UpdateCommentByIdQueryParams` + - Query parameters of updateCommentById method +- headers `UpdateCommentByIdHeaders` + - Headers of updateCommentById method + + +### Returns + +This function returns a value of type `CommentFull`. + +Returns the updated comment object. + + +## Remove comment + +Permanently deletes a comment. + +This operation is performed by calling function `deleteCommentById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-comments-id/). + + +``` +client.getComments().deleteCommentById(newComment.getId()) +``` + +### Arguments + +- commentId `String` + - The ID of the comment. Example: "12345" +- headers `DeleteCommentByIdHeaders` + - Headers of deleteCommentById method + + +### Returns + +This function returns a value of type `void`. + +Returns an empty response when the comment has been deleted. + + +## Create comment + +Adds a comment by the user to a specific file, or +as a reply to an other comment. + +This operation is performed by calling function `createComment`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-comments/). + + +``` +client.getComments().createComment(new CreateCommentRequestBody(message, new CreateCommentRequestBodyItemField(fileId, CreateCommentRequestBodyItemTypeField.FILE))) +``` + +### Arguments + +- requestBody `CreateCommentRequestBody` + - Request body of createComment method +- queryParams `CreateCommentQueryParams` + - Query parameters of createComment method +- headers `CreateCommentHeaders` + - Headers of createComment method + + +### Returns + +This function returns a value of type `CommentFull`. + +Returns the newly created comment object. + +Not all available fields are returned by default. Use the +[fields](#param-fields) query parameter to explicitly request +any specific fields. + + diff --git a/docs/sdkgen/devicepinners.md b/docs/sdkgen/devicepinners.md new file mode 100644 index 000000000..06078a729 --- /dev/null +++ b/docs/sdkgen/devicepinners.md @@ -0,0 +1,99 @@ +# DevicePinnersManager + + +- [Get device pin](#get-device-pin) +- [Remove device pin](#remove-device-pin) +- [List enterprise device pins](#list-enterprise-device-pins) + +## Get device pin + +Retrieves information about an individual device pin. + +This operation is performed by calling function `getDevicePinnerById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-device-pinners-id/). + + +``` +client.getDevicePinners().getDevicePinnerById(devicePinnerId) +``` + +### Arguments + +- devicePinnerId `String` + - The ID of the device pin. Example: "2324234" +- headers `GetDevicePinnerByIdHeaders` + - Headers of getDevicePinnerById method + + +### Returns + +This function returns a value of type `DevicePinner`. + +Returns information about a single device pin. + + +## Remove device pin + +Deletes an individual device pin. + +This operation is performed by calling function `deleteDevicePinnerById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-device-pinners-id/). + + +``` +client.getDevicePinners().deleteDevicePinnerById(devicePinnerId) +``` + +### Arguments + +- devicePinnerId `String` + - The ID of the device pin. Example: "2324234" +- headers `DeleteDevicePinnerByIdHeaders` + - Headers of deleteDevicePinnerById method + + +### Returns + +This function returns a value of type `void`. + +Returns an empty response when the pin has been deleted. + + +## List enterprise device pins + +Retrieves all the device pins within an enterprise. + +The user must have admin privileges, and the application +needs the "manage enterprise" scope to make this call. + +This operation is performed by calling function `getEnterpriseDevicePinners`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-enterprises-id-device-pinners/). + + +``` +client.getDevicePinners().getEnterpriseDevicePinners(enterpriseId) +``` + +### Arguments + +- enterpriseId `String` + - The ID of the enterprise. Example: "3442311" +- queryParams `GetEnterpriseDevicePinnersQueryParams` + - Query parameters of getEnterpriseDevicePinners method +- headers `GetEnterpriseDevicePinnersHeaders` + - Headers of getEnterpriseDevicePinners method + + +### Returns + +This function returns a value of type `DevicePinners`. + +Returns a list of device pins for a given enterprise. + + diff --git a/docs/sdkgen/docgen.md b/docs/sdkgen/docgen.md new file mode 100644 index 000000000..ad7ad936f --- /dev/null +++ b/docs/sdkgen/docgen.md @@ -0,0 +1,126 @@ +# DocgenManager + + +- [Get Box Doc Gen job by ID](#get-box-doc-gen-job-by-id) +- [List all Box Doc Gen jobs](#list-all-box-doc-gen-jobs) +- [Get Box Doc Gen jobs by batch ID](#get-box-doc-gen-jobs-by-batch-id) +- [Generate document using Box Doc Gen template](#generate-document-using-box-doc-gen-template) + +## Get Box Doc Gen job by ID + +Get details of the Box Doc Gen job. + +This operation is performed by calling function `getDocgenJobByIdV2025R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2025.0/get-docgen-jobs-id/). + + +``` +client.getDocgen().getDocgenJobByIdV2025R0(docgenJobItemFromList.getId()) +``` + +### Arguments + +- jobId `String` + - Box Doc Gen job ID. Example: 123 +- headers `GetDocgenJobByIdV2025R0Headers` + - Headers of getDocgenJobByIdV2025R0 method + + +### Returns + +This function returns a value of type `DocGenJobV2025R0`. + +Details of the Box Doc Gen job. + + +## List all Box Doc Gen jobs + +Lists all Box Doc Gen jobs for a user. + +This operation is performed by calling function `getDocgenJobsV2025R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2025.0/get-docgen-jobs/). + + +``` +client.getDocgen().getDocgenJobsV2025R0(new GetDocgenJobsV2025R0QueryParams.Builder().limit(10000L).build()) +``` + +### Arguments + +- queryParams `GetDocgenJobsV2025R0QueryParams` + - Query parameters of getDocgenJobsV2025R0 method +- headers `GetDocgenJobsV2025R0Headers` + - Headers of getDocgenJobsV2025R0 method + + +### Returns + +This function returns a value of type `DocGenJobsFullV2025R0`. + +A list of Box Doc Gen jobs. + + +## Get Box Doc Gen jobs by batch ID + +Lists Box Doc Gen jobs in a batch. + +This operation is performed by calling function `getDocgenBatchJobByIdV2025R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2025.0/get-docgen-batch-jobs-id/). + + +``` +client.getDocgen().getDocgenBatchJobByIdV2025R0(docgenBatch.getId()) +``` + +### Arguments + +- batchId `String` + - Box Doc Gen batch ID. Example: 123 +- queryParams `GetDocgenBatchJobByIdV2025R0QueryParams` + - Query parameters of getDocgenBatchJobByIdV2025R0 method +- headers `GetDocgenBatchJobByIdV2025R0Headers` + - Headers of getDocgenBatchJobByIdV2025R0 method + + +### Returns + +This function returns a value of type `DocGenJobsV2025R0`. + +Returns a list of Box Doc Gen jobs in a Box Doc Gen batch. + + +## Generate document using Box Doc Gen template + +Generates a document using a Box Doc Gen template. + +This operation is performed by calling function `createDocgenBatchV2025R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2025.0/post-docgen-batches/). + + +``` +client.getDocgen().createDocgenBatchV2025R0(new DocGenBatchCreateRequestV2025R0(new FileReferenceV2025R0(uploadedFile.getId()), "api", new DocGenBatchCreateRequestV2025R0DestinationFolderField(folder.getId()), "pdf", Arrays.asList(new DocGenDocumentGenerationDataV2025R0("test", mapOf(entryOf("abc", "xyz")))))) +``` + +### Arguments + +- requestBody `DocGenBatchCreateRequestV2025R0` + - Request body of createDocgenBatchV2025R0 method +- headers `CreateDocgenBatchV2025R0Headers` + - Headers of createDocgenBatchV2025R0 method + + +### Returns + +This function returns a value of type `DocGenBatchBaseV2025R0`. + +The created Batch ID. + + diff --git a/docs/sdkgen/docgentemplate.md b/docs/sdkgen/docgentemplate.md new file mode 100644 index 000000000..c427b2af6 --- /dev/null +++ b/docs/sdkgen/docgentemplate.md @@ -0,0 +1,188 @@ +# DocgenTemplateManager + + +- [Create Box Doc Gen template](#create-box-doc-gen-template) +- [List Box Doc Gen templates](#list-box-doc-gen-templates) +- [Delete Box Doc Gen template](#delete-box-doc-gen-template) +- [Get Box Doc Gen template by ID](#get-box-doc-gen-template-by-id) +- [List all Box Doc Gen template tags in template](#list-all-box-doc-gen-template-tags-in-template) +- [Get list of all Box Doc Gen jobs for template](#get-list-of-all-box-doc-gen-jobs-for-template) + +## Create Box Doc Gen template + +Marks a file as a Box Doc Gen template. + +This operation is performed by calling function `createDocgenTemplateV2025R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2025.0/post-docgen-templates/). + + +``` +client.getDocgenTemplate().createDocgenTemplateV2025R0(new DocGenTemplateCreateRequestV2025R0(new FileReferenceV2025R0(file.getId()))) +``` + +### Arguments + +- requestBody `DocGenTemplateCreateRequestV2025R0` + - Request body of createDocgenTemplateV2025R0 method +- headers `CreateDocgenTemplateV2025R0Headers` + - Headers of createDocgenTemplateV2025R0 method + + +### Returns + +This function returns a value of type `DocGenTemplateBaseV2025R0`. + +The file which has now been marked as a Box Doc Gen template. + + +## List Box Doc Gen templates + +Lists Box Doc Gen templates on which the user is a collaborator. + +This operation is performed by calling function `getDocgenTemplatesV2025R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2025.0/get-docgen-templates/). + + +``` +client.getDocgenTemplate().getDocgenTemplatesV2025R0() +``` + +### Arguments + +- queryParams `GetDocgenTemplatesV2025R0QueryParams` + - Query parameters of getDocgenTemplatesV2025R0 method +- headers `GetDocgenTemplatesV2025R0Headers` + - Headers of getDocgenTemplatesV2025R0 method + + +### Returns + +This function returns a value of type `DocGenTemplatesV2025R0`. + +Returns a collection of templates. + + +## Delete Box Doc Gen template + +Unmarks file as Box Doc Gen template. + +This operation is performed by calling function `deleteDocgenTemplateByIdV2025R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2025.0/delete-docgen-templates-id/). + + +``` +client.getDocgenTemplate().deleteDocgenTemplateByIdV2025R0(createdDocgenTemplate.getFile().getId()) +``` + +### Arguments + +- templateId `String` + - ID of the file which will no longer be marked as a Box Doc Gen template. Example: "123" +- headers `DeleteDocgenTemplateByIdV2025R0Headers` + - Headers of deleteDocgenTemplateByIdV2025R0 method + + +### Returns + +This function returns a value of type `void`. + +Returns an empty response when a file is no longer marked as a Box Doc Gen template. + + +## Get Box Doc Gen template by ID + +Lists details of a specific Box Doc Gen template. + +This operation is performed by calling function `getDocgenTemplateByIdV2025R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2025.0/get-docgen-templates-id/). + + +``` +client.getDocgenTemplate().getDocgenTemplateByIdV2025R0(createdDocgenTemplate.getFile().getId()) +``` + +### Arguments + +- templateId `String` + - The ID of a Box Doc Gen template. Example: 123 +- headers `GetDocgenTemplateByIdV2025R0Headers` + - Headers of getDocgenTemplateByIdV2025R0 method + + +### Returns + +This function returns a value of type `DocGenTemplateV2025R0`. + +Returns a template. + + +## List all Box Doc Gen template tags in template + +Lists all tags in a Box Doc Gen template. + +This operation is performed by calling function `getDocgenTemplateTagsV2025R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2025.0/get-docgen-templates-id-tags/). + + +``` +client.getDocgenTemplate().getDocgenTemplateTagsV2025R0(fetchedDocgenTemplate.getFile().getId()) +``` + +### Arguments + +- templateId `String` + - ID of template. Example: 123 +- queryParams `GetDocgenTemplateTagsV2025R0QueryParams` + - Query parameters of getDocgenTemplateTagsV2025R0 method +- headers `GetDocgenTemplateTagsV2025R0Headers` + - Headers of getDocgenTemplateTagsV2025R0 method + + +### Returns + +This function returns a value of type `DocGenTagsV2025R0`. + +A list of document generation template tags.Processing tags for the file. + + +## Get list of all Box Doc Gen jobs for template + +Lists the users jobs which use this template. + +This operation is performed by calling function `getDocgenTemplateJobByIdV2025R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2025.0/get-docgen-template-jobs-id/). + + +``` +client.getDocgenTemplate().getDocgenTemplateJobByIdV2025R0(fetchedDocgenTemplate.getFile().getId()) +``` + +### Arguments + +- templateId `String` + - Id of template to fetch jobs for. Example: 123 +- queryParams `GetDocgenTemplateJobByIdV2025R0QueryParams` + - Query parameters of getDocgenTemplateJobByIdV2025R0 method +- headers `GetDocgenTemplateJobByIdV2025R0Headers` + - Headers of getDocgenTemplateJobByIdV2025R0 method + + +### Returns + +This function returns a value of type `DocGenJobsV2025R0`. + +A single Box Doc Gen template. + + diff --git a/docs/sdkgen/downloads.md b/docs/sdkgen/downloads.md new file mode 100644 index 000000000..c4b4489c4 --- /dev/null +++ b/docs/sdkgen/downloads.md @@ -0,0 +1,120 @@ +# DownloadsManager + + +- [Download file URL](#download-file-url) +- [Download file](#download-file) +- [Download file](#download-file) + +## Download file URL + +Get the download URL without downloading the content. + +This operation is performed by calling function `getDownloadFileUrl`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-files-id-content/). + + +``` +client.getDownloads().getDownloadFileUrl(uploadedFile.getId()) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- queryParams `GetDownloadFileUrlQueryParams` + - Query parameters of downloadFile method +- headers `GetDownloadFileUrlHeaders` + - Headers of downloadFile method + + +### Returns + +This function returns a value of type `String`. + +Returns the requested file if the client has the **follow +redirects** setting enabled to automatically +follow HTTP `3xx` responses as redirects. If not, the request +will return `302` instead. +For details, see +the [download file guide](g://downloads/file#download-url).If the file is not ready to be downloaded yet `Retry-After` header will +be returned indicating the time in seconds after which the file will +be available for the client to download. + +This response can occur when the file was uploaded immediately before the +download request. + + +## Download file + +Returns the contents of a file in binary format. + +This operation is performed by calling function `downloadFile`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-files-id-content/). + + +``` +client.getDownloads().downloadFile(uploadedFile.getId()) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- queryParams `DownloadFileQueryParams` + - Query parameters of downloadFile method +- headers `DownloadFileHeaders` + - Headers of downloadFile method + + +### Returns + +This function returns a value of type `InputStream`. + +Returns the requested file if the client has the **follow +redirects** setting enabled to automatically +follow HTTP `3xx` responses as redirects. If not, the request +will return `302` instead. +For details, see +the [download file guide](g://downloads/file#download-url).If the file is not ready to be downloaded yet `Retry-After` header will +be returned indicating the time in seconds after which the file will +be available for the client to download. + +This response can occur when the file was uploaded immediately before the +download request. + + +## Download file + +Download file to a given output stream + +This operation is performed by calling function `downloadFileToOutputStream`. + + + +``` +client.getDownloads().downloadFileToOutputStream(uploadedFile.getId(), fileOutputStream) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- outputStream `OutputStream` + - Download file to a given output stream +- queryParams `DownloadFileToOutputStreamQueryParams` + - Query parameters of downloadFile method +- headers `DownloadFileToOutputStreamHeaders` + - Headers of downloadFile method + + +### Returns + +This function returns a value of type `void`. + + + + diff --git a/docs/sdkgen/emailaliases.md b/docs/sdkgen/emailaliases.md new file mode 100644 index 000000000..2046bf577 --- /dev/null +++ b/docs/sdkgen/emailaliases.md @@ -0,0 +1,99 @@ +# EmailAliasesManager + + +- [List user's email aliases](#list-users-email-aliases) +- [Create email alias](#create-email-alias) +- [Remove email alias](#remove-email-alias) + +## List user's email aliases + +Retrieves all email aliases for a user. The collection +does not include the primary login for the user. + +This operation is performed by calling function `getUserEmailAliases`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-users-id-email-aliases/). + + +``` +client.getEmailAliases().getUserEmailAliases(newUser.getId()) +``` + +### Arguments + +- userId `String` + - The ID of the user. Example: "12345" +- headers `GetUserEmailAliasesHeaders` + - Headers of getUserEmailAliases method + + +### Returns + +This function returns a value of type `EmailAliases`. + +Returns a collection of email aliases. + + +## Create email alias + +Adds a new email alias to a user account.. + +This operation is performed by calling function `createUserEmailAlias`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-users-id-email-aliases/). + + +``` +client.getEmailAliases().createUserEmailAlias(newUser.getId(), new CreateUserEmailAliasRequestBody(newAliasEmail)) +``` + +### Arguments + +- userId `String` + - The ID of the user. Example: "12345" +- requestBody `CreateUserEmailAliasRequestBody` + - Request body of createUserEmailAlias method +- headers `CreateUserEmailAliasHeaders` + - Headers of createUserEmailAlias method + + +### Returns + +This function returns a value of type `EmailAlias`. + +Returns the newly created email alias object. + + +## Remove email alias + +Removes an email alias from a user. + +This operation is performed by calling function `deleteUserEmailAliasById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-users-id-email-aliases-id/). + + +``` +client.getEmailAliases().deleteUserEmailAliasById(newUser.getId(), newAlias.getId()) +``` + +### Arguments + +- userId `String` + - The ID of the user. Example: "12345" +- emailAliasId `String` + - The ID of the email alias. Example: "23432" +- headers `DeleteUserEmailAliasByIdHeaders` + - Headers of deleteUserEmailAliasById method + + +### Returns + +This function returns a value of type `void`. + +Removes the alias and returns an empty response. + + diff --git a/docs/sdkgen/events.md b/docs/sdkgen/events.md new file mode 100644 index 000000000..94013cc64 --- /dev/null +++ b/docs/sdkgen/events.md @@ -0,0 +1,137 @@ +# EventsManager + + +- [Get events long poll endpoint](#get-events-long-poll-endpoint) +- [List user and enterprise events](#list-user-and-enterprise-events) +- [Get event stream](#get-event-stream) + +## Get events long poll endpoint + +Returns a list of real-time servers that can be used for long-polling updates +to the [event stream](#get-events). + +Long polling is the concept where a HTTP request is kept open until the +server sends a response, then repeating the process over and over to receive +updated responses. + +Long polling the event stream can only be used for user events, not for +enterprise events. + +To use long polling, first use this endpoint to retrieve a list of long poll +URLs. Next, make a long poll request to any of the provided URLs. + +When an event occurs in monitored account a response with the value +`new_change` will be sent. The response contains no other details as +it only serves as a prompt to take further action such as sending a +request to the [events endpoint](#get-events) with the last known +`stream_position`. + +After the server sends this response it closes the connection. You must now +repeat the long poll process to begin listening for events again. + +If no events occur for a while and the connection times out you will +receive a response with the value `reconnect`. When you receive this response +you’ll make another call to this endpoint to restart the process. + +If you receive no events in `retry_timeout` seconds then you will need to +make another request to the real-time server (one of the URLs in the response +for this endpoint). This might be necessary due to network errors. + +Finally, if you receive a `max_retries` error when making a request to the +real-time server, you should start over by making a call to this endpoint +first. + +This operation is performed by calling function `getEventsWithLongPolling`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/options-events/). + + +``` +client.getEvents().getEventsWithLongPolling() +``` + +### Arguments + +- headers `GetEventsWithLongPollingHeaders` + - Headers of getEventsWithLongPolling method + + +### Returns + +This function returns a value of type `RealtimeServers`. + +Returns a paginated array of servers that can be used +instead of the regular endpoints for long-polling events. + + +## List user and enterprise events + +Returns up to a year of past events for a given user +or for the entire enterprise. + +By default this returns events for the authenticated user. To retrieve events +for the entire enterprise, set the `stream_type` to `admin_logs_streaming` +for live monitoring of new events, or `admin_logs` for querying across +historical events. The user making the API call will +need to have admin privileges, and the application will need to have the +scope `manage enterprise properties` checked. + +This operation is performed by calling function `getEvents`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-events/). + + +``` +client.getEvents().getEvents() +``` + +### Arguments + +- queryParams `GetEventsQueryParams` + - Query parameters of getEvents method +- headers `GetEventsHeaders` + - Headers of getEvents method + + +### Returns + +This function returns a value of type `Events`. + +Returns a list of event objects. + +Events objects are returned in pages, with each page (chunk) +including a list of event objects. The response includes a +`chunk_size` parameter indicating how many events were returned in this +chunk, as well as the next `stream_position` that can be +queried. + + +## Get event stream + +Get an event stream for the Box API + +This operation is performed by calling function `getEventStream`. + + + +``` +client.getEvents().getEventStream() +``` + +### Arguments + +- queryParams `GetEventStreamQueryParams` + - Query parameters of getEvents method +- headers `GetEventStreamHeaders` + - Headers of getEvents method + + +### Returns + +This function returns a value of type `EventStream`. + + + + diff --git a/docs/sdkgen/externalusers.md b/docs/sdkgen/externalusers.md new file mode 100644 index 000000000..295e94197 --- /dev/null +++ b/docs/sdkgen/externalusers.md @@ -0,0 +1,35 @@ +# ExternalUsersManager + + +- [Submit job to delete external users](#submit-job-to-delete-external-users) + +## Submit job to delete external users + +Delete external users from current user enterprise. This will remove each +external user from all invited collaborations within the current enterprise. + +This operation is performed by calling function `submitJobToDeleteExternalUsersV2025R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2025.0/post-external-users-submit-delete-job/). + + +``` +client.getExternalUsers().submitJobToDeleteExternalUsersV2025R0(new ExternalUsersSubmitDeleteJobRequestV2025R0(Arrays.asList(new UserReferenceV2025R0(getEnvVar("BOX_EXTERNAL_USER_ID"))))) +``` + +### Arguments + +- requestBody `ExternalUsersSubmitDeleteJobRequestV2025R0` + - Request body of submitJobToDeleteExternalUsersV2025R0 method +- headers `SubmitJobToDeleteExternalUsersV2025R0Headers` + - Headers of submitJobToDeleteExternalUsersV2025R0 method + + +### Returns + +This function returns a value of type `ExternalUsersSubmitDeleteJobResponseV2025R0`. + + + + diff --git a/docs/sdkgen/fileclassifications.md b/docs/sdkgen/fileclassifications.md new file mode 100644 index 000000000..dd386ad46 --- /dev/null +++ b/docs/sdkgen/fileclassifications.md @@ -0,0 +1,151 @@ +# FileClassificationsManager + + +- [Get classification on file](#get-classification-on-file) +- [Add classification to file](#add-classification-to-file) +- [Update classification on file](#update-classification-on-file) +- [Remove classification from file](#remove-classification-from-file) + +## Get classification on file + +Retrieves the classification metadata instance that +has been applied to a file. + +This API can also be called by including the enterprise ID in the +URL explicitly, for example +`/files/:id//enterprise_12345/securityClassification-6VMVochwUWo`. + +This operation is performed by calling function `getClassificationOnFile`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-files-id-metadata-enterprise-securityClassification-6VMVochwUWo/). + + +``` +client.getFileClassifications().getClassificationOnFile(file.getId()) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- headers `GetClassificationOnFileHeaders` + - Headers of getClassificationOnFile method + + +### Returns + +This function returns a value of type `Classification`. + +Returns an instance of the `securityClassification` metadata +template, which contains a `Box__Security__Classification__Key` +field that lists all the classifications available to this +enterprise. + + +## Add classification to file + +Adds a classification to a file by specifying the label of the +classification to add. + +This API can also be called by including the enterprise ID in the +URL explicitly, for example +`/files/:id//enterprise_12345/securityClassification-6VMVochwUWo`. + +This operation is performed by calling function `addClassificationToFile`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-files-id-metadata-enterprise-securityClassification-6VMVochwUWo/). + + +``` +client.getFileClassifications().addClassificationToFile(file.getId(), new AddClassificationToFileRequestBody.Builder().boxSecurityClassificationKey(classification.getKey()).build()) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- requestBody `AddClassificationToFileRequestBody` + - Request body of addClassificationToFile method +- headers `AddClassificationToFileHeaders` + - Headers of addClassificationToFile method + + +### Returns + +This function returns a value of type `Classification`. + +Returns the classification template instance +that was applied to the file. + + +## Update classification on file + +Updates a classification on a file. + +The classification can only be updated if a classification has already been +applied to the file before. When editing classifications, only values are +defined for the enterprise will be accepted. + +This operation is performed by calling function `updateClassificationOnFile`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-files-id-metadata-enterprise-securityClassification-6VMVochwUWo/). + + +``` +client.getFileClassifications().updateClassificationOnFile(file.getId(), Arrays.asList(new UpdateClassificationOnFileRequestBody(secondClassification.getKey()))) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- requestBody `List` + - Request body of updateClassificationOnFile method +- headers `UpdateClassificationOnFileHeaders` + - Headers of updateClassificationOnFile method + + +### Returns + +This function returns a value of type `Classification`. + +Returns the updated classification metadata template instance. + + +## Remove classification from file + +Removes any classifications from a file. + +This API can also be called by including the enterprise ID in the +URL explicitly, for example +`/files/:id//enterprise_12345/securityClassification-6VMVochwUWo`. + +This operation is performed by calling function `deleteClassificationFromFile`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-files-id-metadata-enterprise-securityClassification-6VMVochwUWo/). + + +``` +client.getFileClassifications().deleteClassificationFromFile(file.getId()) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- headers `DeleteClassificationFromFileHeaders` + - Headers of deleteClassificationFromFile method + + +### Returns + +This function returns a value of type `void`. + +Returns an empty response when the classification is +successfully deleted. + + diff --git a/docs/sdkgen/filemetadata.md b/docs/sdkgen/filemetadata.md new file mode 100644 index 000000000..4a55f9c32 --- /dev/null +++ b/docs/sdkgen/filemetadata.md @@ -0,0 +1,194 @@ +# FileMetadataManager + + +- [List metadata instances on file](#list-metadata-instances-on-file) +- [Get metadata instance on file](#get-metadata-instance-on-file) +- [Create metadata instance on file](#create-metadata-instance-on-file) +- [Update metadata instance on file](#update-metadata-instance-on-file) +- [Remove metadata instance from file](#remove-metadata-instance-from-file) + +## List metadata instances on file + +Retrieves all metadata for a given file. + +This operation is performed by calling function `getFileMetadata`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-files-id-metadata/). + + +``` +client.getFileMetadata().getFileMetadata(file.getId()) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- headers `GetFileMetadataHeaders` + - Headers of getFileMetadata method + + +### Returns + +This function returns a value of type `Metadatas`. + +Returns all the metadata associated with a file. + +This API does not support pagination and will therefore always return +all of the metadata associated to the file. + + +## Get metadata instance on file + +Retrieves the instance of a metadata template that has been applied to a +file. + +This operation is performed by calling function `getFileMetadataById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-files-id-metadata-id-id/). + + +``` +client.getFileMetadata().getFileMetadataById(file.getId(), GetFileMetadataByIdScope.GLOBAL, "properties") +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- scope `GetFileMetadataByIdScope` + - The scope of the metadata template. Example: "global" +- templateKey `String` + - The name of the metadata template. Example: "properties" +- headers `GetFileMetadataByIdHeaders` + - Headers of getFileMetadataById method + + +### Returns + +This function returns a value of type `MetadataFull`. + +An instance of the metadata template that includes +additional "key:value" pairs defined by the user or +an application. + + +## Create metadata instance on file + +Applies an instance of a metadata template to a file. + +In most cases only values that are present in the metadata template +will be accepted, except for the `global.properties` template which accepts +any key-value pair. + +This operation is performed by calling function `createFileMetadataById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-files-id-metadata-id-id/). + + +``` +client.getFileMetadata().createFileMetadataById(file.getId(), CreateFileMetadataByIdScope.ENTERPRISE, templateKey, mapOf(entryOf("name", "John"), entryOf("age", 23), entryOf("birthDate", "2001-01-03T02:20:50.520Z"), entryOf("countryCode", "US"), entryOf("sports", Arrays.asList("basketball", "tennis")))) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- scope `CreateFileMetadataByIdScope` + - The scope of the metadata template. Example: "global" +- templateKey `String` + - The name of the metadata template. Example: "properties" +- requestBody `Map` + - Request body of createFileMetadataById method +- headers `CreateFileMetadataByIdHeaders` + - Headers of createFileMetadataById method + + +### Returns + +This function returns a value of type `MetadataFull`. + +Returns the instance of the template that was applied to the file, +including the data that was applied to the template. + + +## Update metadata instance on file + +Updates a piece of metadata on a file. + +The metadata instance can only be updated if the template has already been +applied to the file before. When editing metadata, only values that match +the metadata template schema will be accepted. + +The update is applied atomically. If any errors occur during the +application of the operations, the metadata instance will not be changed. + +This operation is performed by calling function `updateFileMetadataById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-files-id-metadata-id-id/). + + +``` +client.getFileMetadata().updateFileMetadataById(file.getId(), UpdateFileMetadataByIdScope.ENTERPRISE, templateKey, Arrays.asList(new UpdateFileMetadataByIdRequestBody.Builder().op(UpdateFileMetadataByIdRequestBodyOpField.REPLACE).path("/name").value("Jack").build(), new UpdateFileMetadataByIdRequestBody.Builder().op(UpdateFileMetadataByIdRequestBodyOpField.REPLACE).path("/age").value(24L).build(), new UpdateFileMetadataByIdRequestBody.Builder().op(UpdateFileMetadataByIdRequestBodyOpField.REPLACE).path("/birthDate").value("2000-01-03T02:20:50.520Z").build(), new UpdateFileMetadataByIdRequestBody.Builder().op(UpdateFileMetadataByIdRequestBodyOpField.REPLACE).path("/countryCode").value("CA").build(), new UpdateFileMetadataByIdRequestBody.Builder().op(UpdateFileMetadataByIdRequestBodyOpField.REPLACE).path("/sports").value(Arrays.asList("football")).build())) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- scope `UpdateFileMetadataByIdScope` + - The scope of the metadata template. Example: "global" +- templateKey `String` + - The name of the metadata template. Example: "properties" +- requestBody `List` + - Request body of updateFileMetadataById method +- headers `UpdateFileMetadataByIdHeaders` + - Headers of updateFileMetadataById method + + +### Returns + +This function returns a value of type `MetadataFull`. + +Returns the updated metadata template instance, with the +custom template data included. + + +## Remove metadata instance from file + +Deletes a piece of file metadata. + +This operation is performed by calling function `deleteFileMetadataById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-files-id-metadata-id-id/). + + +``` +client.getFileMetadata().deleteFileMetadataById(file.getId(), DeleteFileMetadataByIdScope.ENTERPRISE, templateKey) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- scope `DeleteFileMetadataByIdScope` + - The scope of the metadata template. Example: "global" +- templateKey `String` + - The name of the metadata template. Example: "properties" +- headers `DeleteFileMetadataByIdHeaders` + - Headers of deleteFileMetadataById method + + +### Returns + +This function returns a value of type `void`. + +Returns an empty response when the metadata is +successfully deleted. + + diff --git a/docs/sdkgen/filerequests.md b/docs/sdkgen/filerequests.md new file mode 100644 index 000000000..169912eb5 --- /dev/null +++ b/docs/sdkgen/filerequests.md @@ -0,0 +1,131 @@ +# FileRequestsManager + + +- [Get file request](#get-file-request) +- [Update file request](#update-file-request) +- [Delete file request](#delete-file-request) +- [Copy file request](#copy-file-request) + +## Get file request + +Retrieves the information about a file request. + +This operation is performed by calling function `getFileRequestById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-file-requests-id/). + + +``` +client.getFileRequests().getFileRequestById(fileRequestId) +``` + +### Arguments + +- fileRequestId `String` + - The unique identifier that represent a file request. The ID for any file request can be determined by visiting a file request builder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/filerequest/123` the `file_request_id` is `123`. Example: "123" +- headers `GetFileRequestByIdHeaders` + - Headers of getFileRequestById method + + +### Returns + +This function returns a value of type `FileRequest`. + +Returns a file request object. + + +## Update file request + +Updates a file request. This can be used to activate or +deactivate a file request. + +This operation is performed by calling function `updateFileRequestById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-file-requests-id/). + + +``` +client.getFileRequests().updateFileRequestById(copiedFileRequest.getId(), new FileRequestUpdateRequest.Builder().title("updated title").description("updated description").build()) +``` + +### Arguments + +- fileRequestId `String` + - The unique identifier that represent a file request. The ID for any file request can be determined by visiting a file request builder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/filerequest/123` the `file_request_id` is `123`. Example: "123" +- requestBody `FileRequestUpdateRequest` + - Request body of updateFileRequestById method +- headers `UpdateFileRequestByIdHeaders` + - Headers of updateFileRequestById method + + +### Returns + +This function returns a value of type `FileRequest`. + +Returns the updated file request object. + + +## Delete file request + +Deletes a file request permanently. + +This operation is performed by calling function `deleteFileRequestById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-file-requests-id/). + + +``` +client.getFileRequests().deleteFileRequestById(updatedFileRequest.getId()) +``` + +### Arguments + +- fileRequestId `String` + - The unique identifier that represent a file request. The ID for any file request can be determined by visiting a file request builder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/filerequest/123` the `file_request_id` is `123`. Example: "123" +- headers `DeleteFileRequestByIdHeaders` + - Headers of deleteFileRequestById method + + +### Returns + +This function returns a value of type `void`. + +Returns an empty response when the file request has been successfully +deleted. + + +## Copy file request + +Copies an existing file request that is already present on one folder, +and applies it to another folder. + +This operation is performed by calling function `createFileRequestCopy`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-file-requests-id-copy/). + + +``` +client.getFileRequests().createFileRequestCopy(fileRequestId, new FileRequestCopyRequest(new FileRequestCopyRequestFolderField.Builder(fileRequest.getFolder().getId()).type(FileRequestCopyRequestFolderTypeField.FOLDER).build())) +``` + +### Arguments + +- fileRequestId `String` + - The unique identifier that represent a file request. The ID for any file request can be determined by visiting a file request builder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/filerequest/123` the `file_request_id` is `123`. Example: "123" +- requestBody `FileRequestCopyRequest` + - Request body of createFileRequestCopy method +- headers `CreateFileRequestCopyHeaders` + - Headers of createFileRequestCopy method + + +### Returns + +This function returns a value of type `FileRequest`. + +Returns updated file request object. + + diff --git a/docs/sdkgen/files.md b/docs/sdkgen/files.md new file mode 100644 index 000000000..bcb48a240 --- /dev/null +++ b/docs/sdkgen/files.md @@ -0,0 +1,245 @@ +# FilesManager + + +- [Get file information](#get-file-information) +- [Update file](#update-file) +- [Delete file](#delete-file) +- [Copy file](#copy-file) +- [Get file thumbnail URL](#get-file-thumbnail-url) +- [Get file thumbnail](#get-file-thumbnail) + +## Get file information + +Retrieves the details about a file. + +This operation is performed by calling function `getFileById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-files-id/). + + +``` +client.getFiles().getFileById(uploadedFile.getId(), new GetFileByIdQueryParams.Builder().fields(Arrays.asList("is_externally_owned", "has_collaborations")).build()) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- queryParams `GetFileByIdQueryParams` + - Query parameters of getFileById method +- headers `GetFileByIdHeaders` + - Headers of getFileById method + + +### Returns + +This function returns a value of type `FileFull`. + +Returns a file object. + +Not all available fields are returned by default. Use the +[fields](#param-fields) query parameter to explicitly request +any specific fields. + + +## Update file + +Updates a file. This can be used to rename or move a file, +create a shared link, or lock a file. + +This operation is performed by calling function `updateFileById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-files-id/). + + +``` +client.getFiles().updateFileById(fileToUpdate.getId(), new UpdateFileByIdRequestBody.Builder().name(updatedName).description("Updated description").build()) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- requestBody `UpdateFileByIdRequestBody` + - Request body of updateFileById method +- queryParams `UpdateFileByIdQueryParams` + - Query parameters of updateFileById method +- headers `UpdateFileByIdHeaders` + - Headers of updateFileById method + + +### Returns + +This function returns a value of type `FileFull`. + +Returns a file object. + +Not all available fields are returned by default. Use the +[fields](#param-fields) query parameter to explicitly request +any specific fields. + + +## Delete file + +Deletes a file, either permanently or by moving it to +the trash. + +The enterprise settings determine whether the item will +be permanently deleted from Box or moved to the trash. + +This operation is performed by calling function `deleteFileById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-files-id/). + + +``` +client.getFiles().deleteFileById(thumbnailFile.getId()) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- headers `DeleteFileByIdHeaders` + - Headers of deleteFileById method + + +### Returns + +This function returns a value of type `void`. + +Returns an empty response when the file has been successfully +deleted. + + +## Copy file + +Creates a copy of a file. + +This operation is performed by calling function `copyFile`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-files-id-copy/). + + +``` +client.getFiles().copyFile(fileOrigin.getId(), new CopyFileRequestBody.Builder(new CopyFileRequestBodyParentField("0")).name(copiedFileName).build()) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- requestBody `CopyFileRequestBody` + - Request body of copyFile method +- queryParams `CopyFileQueryParams` + - Query parameters of copyFile method +- headers `CopyFileHeaders` + - Headers of copyFile method + + +### Returns + +This function returns a value of type `FileFull`. + +Returns a new file object representing the copied file. + +Not all available fields are returned by default. Use the +[fields](#param-fields) query parameter to explicitly request +any specific fields. + + +## Get file thumbnail URL + +Get the download URL without downloading the content. + +This operation is performed by calling function `getFileThumbnailUrl`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-files-id-thumbnail-id/). + + +``` +client.getFiles().getFileThumbnailUrl(thumbnailFile.getId(), GetFileThumbnailUrlExtension.PNG) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- extension `GetFileThumbnailUrlExtension` + - The file format for the thumbnail. Example: "png" +- queryParams `GetFileThumbnailUrlQueryParams` + - Query parameters of getFileThumbnailById method +- headers `GetFileThumbnailUrlHeaders` + - Headers of getFileThumbnailById method + + +### Returns + +This function returns a value of type `String`. + +When a thumbnail can be created the thumbnail data will be +returned in the body of the response.Sometimes generating a thumbnail can take a few seconds. In these +situations the API returns a `Location`-header pointing to a +placeholder graphic for this file type. + +The placeholder graphic can be used in a user interface until the +thumbnail generation has completed. The `Retry-After`-header indicates +when to the thumbnail will be ready. At that time, retry this endpoint +to retrieve the thumbnail. + + +## Get file thumbnail + +Retrieves a thumbnail, or smaller image representation, of a file. + +Sizes of `32x32`,`64x64`, `128x128`, and `256x256` can be returned in +the `.png` format and sizes of `32x32`, `160x160`, and `320x320` +can be returned in the `.jpg` format. + +Thumbnails can be generated for the image and video file formats listed +[found on our community site][1]. + +[1]: https://community.box.com/t5/Migrating-and-Previewing-Content/File-Types-and-Fonts-Supported-in-Box-Content-Preview/ta-p/327 + +This operation is performed by calling function `getFileThumbnailById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-files-id-thumbnail-id/). + + +``` +client.getFiles().getFileThumbnailById(thumbnailFile.getId(), GetFileThumbnailByIdExtension.PNG) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- extension `GetFileThumbnailByIdExtension` + - The file format for the thumbnail. Example: "png" +- queryParams `GetFileThumbnailByIdQueryParams` + - Query parameters of getFileThumbnailById method +- headers `GetFileThumbnailByIdHeaders` + - Headers of getFileThumbnailById method + + +### Returns + +This function returns a value of type `InputStream`. + +When a thumbnail can be created the thumbnail data will be +returned in the body of the response.Sometimes generating a thumbnail can take a few seconds. In these +situations the API returns a `Location`-header pointing to a +placeholder graphic for this file type. + +The placeholder graphic can be used in a user interface until the +thumbnail generation has completed. The `Retry-After`-header indicates +when to the thumbnail will be ready. At that time, retry this endpoint +to retrieve the thumbnail. + + diff --git a/docs/sdkgen/fileversionlegalholds.md b/docs/sdkgen/fileversionlegalholds.md new file mode 100644 index 000000000..eecfa32cb --- /dev/null +++ b/docs/sdkgen/fileversionlegalholds.md @@ -0,0 +1,85 @@ +# FileVersionLegalHoldsManager + + +- [Get file version legal hold](#get-file-version-legal-hold) +- [List file version legal holds](#list-file-version-legal-holds) + +## Get file version legal hold + +Retrieves information about the legal hold policies +assigned to a file version. + +This operation is performed by calling function `getFileVersionLegalHoldById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-file-version-legal-holds-id/). + + +``` +client.getFileVersionLegalHolds().getFileVersionLegalHoldById(fileVersionLegalHoldId) +``` + +### Arguments + +- fileVersionLegalHoldId `String` + - The ID of the file version legal hold. Example: "2348213" +- headers `GetFileVersionLegalHoldByIdHeaders` + - Headers of getFileVersionLegalHoldById method + + +### Returns + +This function returns a value of type `FileVersionLegalHold`. + +Returns the legal hold policy assignments for the file version. + + +## List file version legal holds + +Get a list of file versions on legal hold for a legal hold +assignment. + +Due to ongoing re-architecture efforts this API might not return all file +versions for this policy ID. + +Instead, this API will only return file versions held in the legacy +architecture. Two new endpoints will available to request any file versions +held in the new architecture. + +For file versions held in the new architecture, the `GET +/legal_hold_policy_assignments/:id/file_versions_on_hold` API can be used to +return all past file versions available for this policy assignment, and the +`GET /legal_hold_policy_assignments/:id/files_on_hold` API can be used to +return any current (latest) versions of a file under legal hold. + +The `GET /legal_hold_policy_assignments?policy_id={id}` API can be used to +find a list of policy assignments for a given policy ID. + +Once the re-architecture is completed this API will be deprecated. + +This operation is performed by calling function `getFileVersionLegalHolds`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-file-version-legal-holds/). + + +``` +client.getFileVersionLegalHolds().getFileVersionLegalHolds(new GetFileVersionLegalHoldsQueryParams(policyId)) +``` + +### Arguments + +- queryParams `GetFileVersionLegalHoldsQueryParams` + - Query parameters of getFileVersionLegalHolds method +- headers `GetFileVersionLegalHoldsHeaders` + - Headers of getFileVersionLegalHolds method + + +### Returns + +This function returns a value of type `FileVersionLegalHolds`. + +Returns the list of file version legal holds for a specific legal +hold policy. + + diff --git a/docs/sdkgen/fileversionretentions.md b/docs/sdkgen/fileversionretentions.md new file mode 100644 index 000000000..ac1c8ff18 --- /dev/null +++ b/docs/sdkgen/fileversionretentions.md @@ -0,0 +1,74 @@ +# FileVersionRetentionsManager + + +- [List file version retentions](#list-file-version-retentions) +- [Get retention on file](#get-retention-on-file) + +## List file version retentions + +Retrieves all file version retentions for the given enterprise. + +**Note**: +File retention API is now **deprecated**. +To get information about files and file versions under retention, +see [files under retention](e://get-retention-policy-assignments-id-files-under-retention) or [file versions under retention](e://get-retention-policy-assignments-id-file-versions-under-retention) endpoints. + +This operation is performed by calling function `getFileVersionRetentions`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-file-version-retentions/). + + +``` +client.getFileVersionRetentions().getFileVersionRetentions() +``` + +### Arguments + +- queryParams `GetFileVersionRetentionsQueryParams` + - Query parameters of getFileVersionRetentions method +- headers `GetFileVersionRetentionsHeaders` + - Headers of getFileVersionRetentions method + + +### Returns + +This function returns a value of type `FileVersionRetentions`. + +Returns a list of all file version retentions for the enterprise. + + +## Get retention on file + +Returns information about a file version retention. + +**Note**: +File retention API is now **deprecated**. +To get information about files and file versions under retention, +see [files under retention](e://get-retention-policy-assignments-id-files-under-retention) or [file versions under retention](e://get-retention-policy-assignments-id-file-versions-under-retention) endpoints. + +This operation is performed by calling function `getFileVersionRetentionById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-file-version-retentions-id/). + + +``` +client.getFileVersionRetentions().getFileVersionRetentionById(fileVersionRetention.getId()) +``` + +### Arguments + +- fileVersionRetentionId `String` + - The ID of the file version retention. Example: "3424234" +- headers `GetFileVersionRetentionByIdHeaders` + - Headers of getFileVersionRetentionById method + + +### Returns + +This function returns a value of type `FileVersionRetention`. + +Returns a file version retention object. + + diff --git a/docs/sdkgen/fileversions.md b/docs/sdkgen/fileversions.md new file mode 100644 index 000000000..3f9153904 --- /dev/null +++ b/docs/sdkgen/fileversions.md @@ -0,0 +1,200 @@ +# FileVersionsManager + + +- [List all file versions](#list-all-file-versions) +- [Get file version](#get-file-version) +- [Remove file version](#remove-file-version) +- [Restore file version](#restore-file-version) +- [Promote file version](#promote-file-version) + +## List all file versions + +Retrieve a list of the past versions for a file. + +Versions are only tracked by Box users with premium accounts. To fetch the ID +of the current version of a file, use the `GET /file/:id` API. + +This operation is performed by calling function `getFileVersions`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-files-id-versions/). + + +``` +client.getFileVersions().getFileVersions(file.getId()) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- queryParams `GetFileVersionsQueryParams` + - Query parameters of getFileVersions method +- headers `GetFileVersionsHeaders` + - Headers of getFileVersions method + + +### Returns + +This function returns a value of type `FileVersions`. + +Returns an array of past versions for this file. + + +## Get file version + +Retrieve a specific version of a file. + +Versions are only tracked for Box users with premium accounts. + +This operation is performed by calling function `getFileVersionById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-files-id-versions-id/). + + +``` +client.getFileVersions().getFileVersionById(file.getId(), fileVersions.getEntries().get(0).getId()) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- fileVersionId `String` + - The ID of the file version. Example: "1234" +- queryParams `GetFileVersionByIdQueryParams` + - Query parameters of getFileVersionById method +- headers `GetFileVersionByIdHeaders` + - Headers of getFileVersionById method + + +### Returns + +This function returns a value of type `FileVersionFull`. + +Returns a specific version of a file. + +Not all available fields are returned by default. Use the +[fields](#param-fields) query parameter to explicitly request +any specific fields. + + +## Remove file version + +Move a file version to the trash. + +Versions are only tracked for Box users with premium accounts. + +This operation is performed by calling function `deleteFileVersionById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-files-id-versions-id/). + + +``` +client.getFileVersions().deleteFileVersionById(file.getId(), fileVersion.getId()) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- fileVersionId `String` + - The ID of the file version. Example: "1234" +- headers `DeleteFileVersionByIdHeaders` + - Headers of deleteFileVersionById method + + +### Returns + +This function returns a value of type `void`. + +Returns an empty response when the file has been successfully +deleted. + + +## Restore file version + +Restores a specific version of a file after it was deleted. +Don't use this endpoint to restore Box Notes, +as it works with file formats such as PDF, DOC, +PPTX or similar. + +This operation is performed by calling function `updateFileVersionById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-files-id-versions-id/). + + +``` +client.getFileVersions().updateFileVersionById(file.getId(), fileVersion.getId(), new UpdateFileVersionByIdRequestBody.Builder().trashedAt(null).build()) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- fileVersionId `String` + - The ID of the file version. Example: "1234" +- requestBody `UpdateFileVersionByIdRequestBody` + - Request body of updateFileVersionById method +- headers `UpdateFileVersionByIdHeaders` + - Headers of updateFileVersionById method + + +### Returns + +This function returns a value of type `FileVersionFull`. + +Returns a restored file version object. + + +## Promote file version + +Promote a specific version of a file. + +If previous versions exist, this method can be used to +promote one of the older versions to the top of the version history. + +This creates a new copy of the old version and puts it at the +top of the versions history. The file will have the exact same contents +as the older version, with the same hash digest, `etag`, and +name as the original. + +Other properties such as comments do not get updated to their +former values. + +Don't use this endpoint to restore Box Notes, +as it works with file formats such as PDF, DOC, +PPTX or similar. + +This operation is performed by calling function `promoteFileVersion`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-files-id-versions-current/). + + +``` +client.getFileVersions().promoteFileVersion(file.getId(), new PromoteFileVersionRequestBody.Builder().id(fileVersions.getEntries().get(0).getId()).type(PromoteFileVersionRequestBodyTypeField.FILE_VERSION).build()) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- requestBody `PromoteFileVersionRequestBody` + - Request body of promoteFileVersion method +- queryParams `PromoteFileVersionQueryParams` + - Query parameters of promoteFileVersion method +- headers `PromoteFileVersionHeaders` + - Headers of promoteFileVersion method + + +### Returns + +This function returns a value of type `FileVersionFull`. + +Returns a newly created file version object. + + diff --git a/docs/sdkgen/filewatermarks.md b/docs/sdkgen/filewatermarks.md new file mode 100644 index 000000000..fd94bbd8b --- /dev/null +++ b/docs/sdkgen/filewatermarks.md @@ -0,0 +1,99 @@ +# FileWatermarksManager + + +- [Get watermark on file](#get-watermark-on-file) +- [Apply watermark to file](#apply-watermark-to-file) +- [Remove watermark from file](#remove-watermark-from-file) + +## Get watermark on file + +Retrieve the watermark for a file. + +This operation is performed by calling function `getFileWatermark`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-files-id-watermark/). + + +``` +client.getFileWatermarks().getFileWatermark(file.getId()) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- headers `GetFileWatermarkHeaders` + - Headers of getFileWatermark method + + +### Returns + +This function returns a value of type `Watermark`. + +Returns an object containing information about the +watermark associated for to this file. + + +## Apply watermark to file + +Applies or update a watermark on a file. + +This operation is performed by calling function `updateFileWatermark`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-files-id-watermark/). + + +``` +client.getFileWatermarks().updateFileWatermark(file.getId(), new UpdateFileWatermarkRequestBody(new UpdateFileWatermarkRequestBodyWatermarkField.Builder().imprint(UpdateFileWatermarkRequestBodyWatermarkImprintField.DEFAULT).build())) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- requestBody `UpdateFileWatermarkRequestBody` + - Request body of updateFileWatermark method +- headers `UpdateFileWatermarkHeaders` + - Headers of updateFileWatermark method + + +### Returns + +This function returns a value of type `Watermark`. + +Returns an updated watermark if a watermark already +existed on this file.Returns a new watermark if no watermark existed on +this file yet. + + +## Remove watermark from file + +Removes the watermark from a file. + +This operation is performed by calling function `deleteFileWatermark`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-files-id-watermark/). + + +``` +client.getFileWatermarks().deleteFileWatermark(file.getId()) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- headers `DeleteFileWatermarkHeaders` + - Headers of deleteFileWatermark method + + +### Returns + +This function returns a value of type `void`. + +Removes the watermark and returns an empty response. + + diff --git a/docs/sdkgen/folderclassifications.md b/docs/sdkgen/folderclassifications.md new file mode 100644 index 000000000..5a887a3fb --- /dev/null +++ b/docs/sdkgen/folderclassifications.md @@ -0,0 +1,151 @@ +# FolderClassificationsManager + + +- [Get classification on folder](#get-classification-on-folder) +- [Add classification to folder](#add-classification-to-folder) +- [Update classification on folder](#update-classification-on-folder) +- [Remove classification from folder](#remove-classification-from-folder) + +## Get classification on folder + +Retrieves the classification metadata instance that +has been applied to a folder. + +This API can also be called by including the enterprise ID in the +URL explicitly, for example +`/folders/:id/enterprise_12345/securityClassification-6VMVochwUWo`. + +This operation is performed by calling function `getClassificationOnFolder`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-folders-id-metadata-enterprise-securityClassification-6VMVochwUWo/). + + +``` +client.getFolderClassifications().getClassificationOnFolder(folder.getId()) +``` + +### Arguments + +- folderId `String` + - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" +- headers `GetClassificationOnFolderHeaders` + - Headers of getClassificationOnFolder method + + +### Returns + +This function returns a value of type `Classification`. + +Returns an instance of the `securityClassification` metadata +template, which contains a `Box__Security__Classification__Key` +field that lists all the classifications available to this +enterprise. + + +## Add classification to folder + +Adds a classification to a folder by specifying the label of the +classification to add. + +This API can also be called by including the enterprise ID in the +URL explicitly, for example +`/folders/:id/enterprise_12345/securityClassification-6VMVochwUWo`. + +This operation is performed by calling function `addClassificationToFolder`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-folders-id-metadata-enterprise-securityClassification-6VMVochwUWo/). + + +``` +client.getFolderClassifications().addClassificationToFolder(folder.getId(), new AddClassificationToFolderRequestBody.Builder().boxSecurityClassificationKey(classification.getKey()).build()) +``` + +### Arguments + +- folderId `String` + - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" +- requestBody `AddClassificationToFolderRequestBody` + - Request body of addClassificationToFolder method +- headers `AddClassificationToFolderHeaders` + - Headers of addClassificationToFolder method + + +### Returns + +This function returns a value of type `Classification`. + +Returns the classification template instance +that was applied to the folder. + + +## Update classification on folder + +Updates a classification on a folder. + +The classification can only be updated if a classification has already been +applied to the folder before. When editing classifications, only values are +defined for the enterprise will be accepted. + +This operation is performed by calling function `updateClassificationOnFolder`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-folders-id-metadata-enterprise-securityClassification-6VMVochwUWo/). + + +``` +client.getFolderClassifications().updateClassificationOnFolder(folder.getId(), Arrays.asList(new UpdateClassificationOnFolderRequestBody(secondClassification.getKey()))) +``` + +### Arguments + +- folderId `String` + - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" +- requestBody `List` + - Request body of updateClassificationOnFolder method +- headers `UpdateClassificationOnFolderHeaders` + - Headers of updateClassificationOnFolder method + + +### Returns + +This function returns a value of type `Classification`. + +Returns the updated classification metadata template instance. + + +## Remove classification from folder + +Removes any classifications from a folder. + +This API can also be called by including the enterprise ID in the +URL explicitly, for example +`/folders/:id/enterprise_12345/securityClassification-6VMVochwUWo`. + +This operation is performed by calling function `deleteClassificationFromFolder`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-folders-id-metadata-enterprise-securityClassification-6VMVochwUWo/). + + +``` +client.getFolderClassifications().deleteClassificationFromFolder(folder.getId()) +``` + +### Arguments + +- folderId `String` + - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" +- headers `DeleteClassificationFromFolderHeaders` + - Headers of deleteClassificationFromFolder method + + +### Returns + +This function returns a value of type `void`. + +Returns an empty response when the classification is +successfully deleted. + + diff --git a/docs/sdkgen/folderlocks.md b/docs/sdkgen/folderlocks.md new file mode 100644 index 000000000..6c050d597 --- /dev/null +++ b/docs/sdkgen/folderlocks.md @@ -0,0 +1,106 @@ +# FolderLocksManager + + +- [List folder locks](#list-folder-locks) +- [Create folder lock](#create-folder-lock) +- [Delete folder lock](#delete-folder-lock) + +## List folder locks + +Retrieves folder lock details for a given folder. + +You must be authenticated as the owner or co-owner of the folder to +use this endpoint. + +This operation is performed by calling function `getFolderLocks`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-folder-locks/). + + +``` +client.getFolderLocks().getFolderLocks(new GetFolderLocksQueryParams(folder.getId())) +``` + +### Arguments + +- queryParams `GetFolderLocksQueryParams` + - Query parameters of getFolderLocks method +- headers `GetFolderLocksHeaders` + - Headers of getFolderLocks method + + +### Returns + +This function returns a value of type `FolderLocks`. + +Returns details for all folder locks applied to the folder, including the +lock type and user that applied the lock. + + +## Create folder lock + +Creates a folder lock on a folder, preventing it from being moved and/or +deleted. + +You must be authenticated as the owner or co-owner of the folder to +use this endpoint. + +This operation is performed by calling function `createFolderLock`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-folder-locks/). + + +``` +client.getFolderLocks().createFolderLock(new CreateFolderLockRequestBody.Builder(new CreateFolderLockRequestBodyFolderField("folder", folder.getId())).lockedOperations(new CreateFolderLockRequestBodyLockedOperationsField(true, true)).build()) +``` + +### Arguments + +- requestBody `CreateFolderLockRequestBody` + - Request body of createFolderLock method +- headers `CreateFolderLockHeaders` + - Headers of createFolderLock method + + +### Returns + +This function returns a value of type `FolderLock`. + +Returns the instance of the folder lock that was applied to the folder, +including the user that applied the lock and the operations set. + + +## Delete folder lock + +Deletes a folder lock on a given folder. + +You must be authenticated as the owner or co-owner of the folder to +use this endpoint. + +This operation is performed by calling function `deleteFolderLockById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-folder-locks-id/). + + +``` +client.getFolderLocks().deleteFolderLockById(folderLock.getId()) +``` + +### Arguments + +- folderLockId `String` + - The ID of the folder lock. Example: "12345" +- headers `DeleteFolderLockByIdHeaders` + - Headers of deleteFolderLockById method + + +### Returns + +This function returns a value of type `void`. + +Returns an empty response when the folder lock is successfully deleted. + + diff --git a/docs/sdkgen/foldermetadata.md b/docs/sdkgen/foldermetadata.md new file mode 100644 index 000000000..307d252f7 --- /dev/null +++ b/docs/sdkgen/foldermetadata.md @@ -0,0 +1,199 @@ +# FolderMetadataManager + + +- [List metadata instances on folder](#list-metadata-instances-on-folder) +- [Get metadata instance on folder](#get-metadata-instance-on-folder) +- [Create metadata instance on folder](#create-metadata-instance-on-folder) +- [Update metadata instance on folder](#update-metadata-instance-on-folder) +- [Remove metadata instance from folder](#remove-metadata-instance-from-folder) + +## List metadata instances on folder + +Retrieves all metadata for a given folder. This can not be used on the root +folder with ID `0`. + +This operation is performed by calling function `getFolderMetadata`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-folders-id-metadata/). + + +``` +client.getFolderMetadata().getFolderMetadata(folder.getId()) +``` + +### Arguments + +- folderId `String` + - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" +- headers `GetFolderMetadataHeaders` + - Headers of getFolderMetadata method + + +### Returns + +This function returns a value of type `Metadatas`. + +Returns all the metadata associated with a folder. + +This API does not support pagination and will therefore always return +all of the metadata associated to the folder. + + +## Get metadata instance on folder + +Retrieves the instance of a metadata template that has been applied to a +folder. This can not be used on the root folder with ID `0`. + +This operation is performed by calling function `getFolderMetadataById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-folders-id-metadata-id-id/). + + +``` +client.getFolderMetadata().getFolderMetadataById(folder.getId(), GetFolderMetadataByIdScope.GLOBAL, "properties") +``` + +### Arguments + +- folderId `String` + - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" +- scope `GetFolderMetadataByIdScope` + - The scope of the metadata template. Example: "global" +- templateKey `String` + - The name of the metadata template. Example: "properties" +- headers `GetFolderMetadataByIdHeaders` + - Headers of getFolderMetadataById method + + +### Returns + +This function returns a value of type `MetadataFull`. + +An instance of the metadata template that includes +additional "key:value" pairs defined by the user or +an application. + + +## Create metadata instance on folder + +Applies an instance of a metadata template to a folder. + +In most cases only values that are present in the metadata template +will be accepted, except for the `global.properties` template which accepts +any key-value pair. + +To display the metadata template in the Box web app the enterprise needs to be +configured to enable **Cascading Folder Level Metadata** for the user in the +admin console. + +This operation is performed by calling function `createFolderMetadataById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-folders-id-metadata-id-id/). + + +``` +client.getFolderMetadata().createFolderMetadataById(folder.getId(), CreateFolderMetadataByIdScope.ENTERPRISE, templateKey, mapOf(entryOf("name", "John"), entryOf("age", 23), entryOf("birthDate", "2001-01-03T02:20:50.520Z"), entryOf("countryCode", "US"), entryOf("sports", Arrays.asList("basketball", "tennis")))) +``` + +### Arguments + +- folderId `String` + - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" +- scope `CreateFolderMetadataByIdScope` + - The scope of the metadata template. Example: "global" +- templateKey `String` + - The name of the metadata template. Example: "properties" +- requestBody `Map` + - Request body of createFolderMetadataById method +- headers `CreateFolderMetadataByIdHeaders` + - Headers of createFolderMetadataById method + + +### Returns + +This function returns a value of type `MetadataFull`. + +Returns the instance of the template that was applied to the folder, +including the data that was applied to the template. + + +## Update metadata instance on folder + +Updates a piece of metadata on a folder. + +The metadata instance can only be updated if the template has already been +applied to the folder before. When editing metadata, only values that match +the metadata template schema will be accepted. + +The update is applied atomically. If any errors occur during the +application of the operations, the metadata instance will not be changed. + +This operation is performed by calling function `updateFolderMetadataById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-folders-id-metadata-id-id/). + + +``` +client.getFolderMetadata().updateFolderMetadataById(folder.getId(), UpdateFolderMetadataByIdScope.ENTERPRISE, templateKey, Arrays.asList(new UpdateFolderMetadataByIdRequestBody.Builder().op(UpdateFolderMetadataByIdRequestBodyOpField.REPLACE).path("/name").value("Jack").build(), new UpdateFolderMetadataByIdRequestBody.Builder().op(UpdateFolderMetadataByIdRequestBodyOpField.REPLACE).path("/age").value(24L).build(), new UpdateFolderMetadataByIdRequestBody.Builder().op(UpdateFolderMetadataByIdRequestBodyOpField.REPLACE).path("/birthDate").value("2000-01-03T02:20:50.520Z").build(), new UpdateFolderMetadataByIdRequestBody.Builder().op(UpdateFolderMetadataByIdRequestBodyOpField.REPLACE).path("/countryCode").value("CA").build(), new UpdateFolderMetadataByIdRequestBody.Builder().op(UpdateFolderMetadataByIdRequestBodyOpField.REPLACE).path("/sports").value(Arrays.asList("football")).build())) +``` + +### Arguments + +- folderId `String` + - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" +- scope `UpdateFolderMetadataByIdScope` + - The scope of the metadata template. Example: "global" +- templateKey `String` + - The name of the metadata template. Example: "properties" +- requestBody `List` + - Request body of updateFolderMetadataById method +- headers `UpdateFolderMetadataByIdHeaders` + - Headers of updateFolderMetadataById method + + +### Returns + +This function returns a value of type `MetadataFull`. + +Returns the updated metadata template instance, with the +custom template data included. + + +## Remove metadata instance from folder + +Deletes a piece of folder metadata. + +This operation is performed by calling function `deleteFolderMetadataById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-folders-id-metadata-id-id/). + + +``` +client.getFolderMetadata().deleteFolderMetadataById(folder.getId(), DeleteFolderMetadataByIdScope.ENTERPRISE, templateKey) +``` + +### Arguments + +- folderId `String` + - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" +- scope `DeleteFolderMetadataByIdScope` + - The scope of the metadata template. Example: "global" +- templateKey `String` + - The name of the metadata template. Example: "properties" +- headers `DeleteFolderMetadataByIdHeaders` + - Headers of deleteFolderMetadataById method + + +### Returns + +This function returns a value of type `void`. + +Returns an empty response when the metadata is +successfully deleted. + + diff --git a/docs/sdkgen/folders.md b/docs/sdkgen/folders.md new file mode 100644 index 000000000..0ab79c9fd --- /dev/null +++ b/docs/sdkgen/folders.md @@ -0,0 +1,245 @@ +# FoldersManager + + +- [Get folder information](#get-folder-information) +- [Update folder](#update-folder) +- [Delete folder](#delete-folder) +- [List items in folder](#list-items-in-folder) +- [Create folder](#create-folder) +- [Copy folder](#copy-folder) + +## Get folder information + +Retrieves details for a folder, including the first 100 entries +in the folder. + +Passing `sort`, `direction`, `offset`, and `limit` +parameters in query allows you to manage the +list of returned +[folder items](r://folder--full#param-item-collection). + +To fetch more items within the folder, use the +[Get items in a folder](e://get-folders-id-items) endpoint. + +This operation is performed by calling function `getFolderById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-folders-id/). + + +``` +client.getFolders().getFolderById("0") +``` + +### Arguments + +- folderId `String` + - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" +- queryParams `GetFolderByIdQueryParams` + - Query parameters of getFolderById method +- headers `GetFolderByIdHeaders` + - Headers of getFolderById method + + +### Returns + +This function returns a value of type `FolderFull`. + +Returns a folder, including the first 100 entries in the folder. +If you used query parameters like +`sort`, `direction`, `offset`, or `limit` +the *folder items list* will be affected accordingly. + +To fetch more items within the folder, use the +[Get items in a folder](e://get-folders-id-items)) endpoint. + +Not all available fields are returned by default. Use the +[fields](#param-fields) query parameter to explicitly request +any specific fields. + + +## Update folder + +Updates a folder. This can be also be used to move the folder, +create shared links, update collaborations, and more. + +This operation is performed by calling function `updateFolderById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-folders-id/). + + +``` +client.getFolders().updateFolderById(folderToUpdate.getId(), new UpdateFolderByIdRequestBody.Builder().name(updatedName).description("Updated description").build()) +``` + +### Arguments + +- folderId `String` + - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" +- requestBody `UpdateFolderByIdRequestBody` + - Request body of updateFolderById method +- queryParams `UpdateFolderByIdQueryParams` + - Query parameters of updateFolderById method +- headers `UpdateFolderByIdHeaders` + - Headers of updateFolderById method + + +### Returns + +This function returns a value of type `FolderFull`. + +Returns a folder object for the updated folder + +Not all available fields are returned by default. Use the +[fields](#param-fields) query parameter to explicitly request +any specific fields. + +If the user is moving folders with a large number of items in all of +their descendants, the call will be run asynchronously. If the +operation is not completed within 10 minutes, the user will receive +a 200 OK response, and the operation will continue running. + + +## Delete folder + +Deletes a folder, either permanently or by moving it to +the trash. + +This operation is performed by calling function `deleteFolderById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-folders-id/). + + +``` +client.getFolders().deleteFolderById(newFolder.getId()) +``` + +### Arguments + +- folderId `String` + - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" +- queryParams `DeleteFolderByIdQueryParams` + - Query parameters of deleteFolderById method +- headers `DeleteFolderByIdHeaders` + - Headers of deleteFolderById method + + +### Returns + +This function returns a value of type `void`. + +Returns an empty response when the folder is successfully deleted +or moved to the trash. + + +## List items in folder + +Retrieves a page of items in a folder. These items can be files, +folders, and web links. + +To request more information about the folder itself, like its size, +use the [Get a folder](#get-folders-id) endpoint instead. + +This operation is performed by calling function `getFolderItems`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-folders-id-items/). + + +``` +client.getFolders().getFolderItems(folderOrigin.getId()) +``` + +### Arguments + +- folderId `String` + - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" +- queryParams `GetFolderItemsQueryParams` + - Query parameters of getFolderItems method +- headers `GetFolderItemsHeaders` + - Headers of getFolderItems method + + +### Returns + +This function returns a value of type `Items`. + +Returns a collection of files, folders, and web links contained in a folder. + + +## Create folder + +Creates a new empty folder within the specified parent folder. + +This operation is performed by calling function `createFolder`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-folders/). + + +``` +client.getFolders().createFolder(new CreateFolderRequestBody(newFolderName, new CreateFolderRequestBodyParentField("0"))) +``` + +### Arguments + +- requestBody `CreateFolderRequestBody` + - Request body of createFolder method +- queryParams `CreateFolderQueryParams` + - Query parameters of createFolder method +- headers `CreateFolderHeaders` + - Headers of createFolder method + + +### Returns + +This function returns a value of type `FolderFull`. + +Returns a folder object. + +Not all available fields are returned by default. Use the +[fields](#param-fields) query parameter to explicitly request +any specific fields. + + +## Copy folder + +Creates a copy of a folder within a destination folder. + +The original folder will not be changed. + +This operation is performed by calling function `copyFolder`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-folders-id-copy/). + + +``` +client.getFolders().copyFolder(folderOrigin.getId(), new CopyFolderRequestBody.Builder(new CopyFolderRequestBodyParentField("0")).name(copiedFolderName).build()) +``` + +### Arguments + +- folderId `String` + - The unique identifier of the folder to copy. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder with the ID `0` can not be copied. Example: "0" +- requestBody `CopyFolderRequestBody` + - Request body of copyFolder method +- queryParams `CopyFolderQueryParams` + - Query parameters of copyFolder method +- headers `CopyFolderHeaders` + - Headers of copyFolder method + + +### Returns + +This function returns a value of type `FolderFull`. + +Returns a new folder object representing the copied folder. + +Not all available fields are returned by default. Use the +[fields](#param-fields) query parameter to explicitly request +any specific fields. + + diff --git a/docs/sdkgen/folderwatermarks.md b/docs/sdkgen/folderwatermarks.md new file mode 100644 index 000000000..323f45ef8 --- /dev/null +++ b/docs/sdkgen/folderwatermarks.md @@ -0,0 +1,100 @@ +# FolderWatermarksManager + + +- [Get watermark for folder](#get-watermark-for-folder) +- [Apply watermark to folder](#apply-watermark-to-folder) +- [Remove watermark from folder](#remove-watermark-from-folder) + +## Get watermark for folder + +Retrieve the watermark for a folder. + +This operation is performed by calling function `getFolderWatermark`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-folders-id-watermark/). + + +``` +client.getFolderWatermarks().getFolderWatermark(folder.getId()) +``` + +### Arguments + +- folderId `String` + - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" +- headers `GetFolderWatermarkHeaders` + - Headers of getFolderWatermark method + + +### Returns + +This function returns a value of type `Watermark`. + +Returns an object containing information about the +watermark associated for to this folder. + + +## Apply watermark to folder + +Applies or update a watermark on a folder. + +This operation is performed by calling function `updateFolderWatermark`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-folders-id-watermark/). + + +``` +client.getFolderWatermarks().updateFolderWatermark(folder.getId(), new UpdateFolderWatermarkRequestBody(new UpdateFolderWatermarkRequestBodyWatermarkField.Builder().imprint(UpdateFolderWatermarkRequestBodyWatermarkImprintField.DEFAULT).build())) +``` + +### Arguments + +- folderId `String` + - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" +- requestBody `UpdateFolderWatermarkRequestBody` + - Request body of updateFolderWatermark method +- headers `UpdateFolderWatermarkHeaders` + - Headers of updateFolderWatermark method + + +### Returns + +This function returns a value of type `Watermark`. + +Returns an updated watermark if a watermark already +existed on this folder.Returns a new watermark if no watermark existed on +this folder yet. + + +## Remove watermark from folder + +Removes the watermark from a folder. + +This operation is performed by calling function `deleteFolderWatermark`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-folders-id-watermark/). + + +``` +client.getFolderWatermarks().deleteFolderWatermark(folder.getId()) +``` + +### Arguments + +- folderId `String` + - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" +- headers `DeleteFolderWatermarkHeaders` + - Headers of deleteFolderWatermark method + + +### Returns + +This function returns a value of type `void`. + +An empty response will be returned when the watermark +was successfully deleted. + + diff --git a/docs/sdkgen/groups.md b/docs/sdkgen/groups.md new file mode 100644 index 000000000..5e66b2d5f --- /dev/null +++ b/docs/sdkgen/groups.md @@ -0,0 +1,171 @@ +# GroupsManager + + +- [List groups for enterprise](#list-groups-for-enterprise) +- [Create group](#create-group) +- [Get group](#get-group) +- [Update group](#update-group) +- [Remove group](#remove-group) + +## List groups for enterprise + +Retrieves all of the groups for a given enterprise. The user +must have admin permissions to inspect enterprise's groups. + +This operation is performed by calling function `getGroups`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-groups/). + + +``` +client.getGroups().getGroups() +``` + +### Arguments + +- queryParams `GetGroupsQueryParams` + - Query parameters of getGroups method +- headers `GetGroupsHeaders` + - Headers of getGroups method + + +### Returns + +This function returns a value of type `Groups`. + +Returns a collection of group objects. If there are no groups, an +empty collection will be returned. + + +## Create group + +Creates a new group of users in an enterprise. Only users with admin +permissions can create new groups. + +This operation is performed by calling function `createGroup`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-groups/). + + +``` +client.getGroups().createGroup(new CreateGroupRequestBody.Builder(groupName).description(groupDescription).build()) +``` + +### Arguments + +- requestBody `CreateGroupRequestBody` + - Request body of createGroup method +- queryParams `CreateGroupQueryParams` + - Query parameters of createGroup method +- headers `CreateGroupHeaders` + - Headers of createGroup method + + +### Returns + +This function returns a value of type `GroupFull`. + +Returns the new group object. + + +## Get group + +Retrieves information about a group. Only members of this +group or users with admin-level permissions will be able to +use this API. + +This operation is performed by calling function `getGroupById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-groups-id/). + + +``` +client.getGroups().getGroupById(group.getId(), new GetGroupByIdQueryParams.Builder().fields(Arrays.asList("id", "name", "description", "group_type")).build()) +``` + +### Arguments + +- groupId `String` + - The ID of the group. Example: "57645" +- queryParams `GetGroupByIdQueryParams` + - Query parameters of getGroupById method +- headers `GetGroupByIdHeaders` + - Headers of getGroupById method + + +### Returns + +This function returns a value of type `GroupFull`. + +Returns the group object. + + +## Update group + +Updates a specific group. Only admins of this +group or users with admin-level permissions will be able to +use this API. + +This operation is performed by calling function `updateGroupById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-groups-id/). + + +``` +client.getGroups().updateGroupById(group.getId(), new UpdateGroupByIdRequestBody.Builder().name(updatedGroupName).build()) +``` + +### Arguments + +- groupId `String` + - The ID of the group. Example: "57645" +- requestBody `UpdateGroupByIdRequestBody` + - Request body of updateGroupById method +- queryParams `UpdateGroupByIdQueryParams` + - Query parameters of updateGroupById method +- headers `UpdateGroupByIdHeaders` + - Headers of updateGroupById method + + +### Returns + +This function returns a value of type `GroupFull`. + +Returns the updated group object. + + +## Remove group + +Permanently deletes a group. Only users with +admin-level permissions will be able to use this API. + +This operation is performed by calling function `deleteGroupById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-groups-id/). + + +``` +client.getGroups().deleteGroupById(group.getId()) +``` + +### Arguments + +- groupId `String` + - The ID of the group. Example: "57645" +- headers `DeleteGroupByIdHeaders` + - Headers of deleteGroupById method + + +### Returns + +This function returns a value of type `void`. + +A blank response is returned if the group was +successfully deleted. + + diff --git a/docs/sdkgen/hubcollaborations.md b/docs/sdkgen/hubcollaborations.md new file mode 100644 index 000000000..609b5e572 --- /dev/null +++ b/docs/sdkgen/hubcollaborations.md @@ -0,0 +1,160 @@ +# HubCollaborationsManager + + +- [Get Box Hub collaborations](#get-box-hub-collaborations) +- [Create Box Hub collaboration](#create-box-hub-collaboration) +- [Get Box Hub collaboration by collaboration ID](#get-box-hub-collaboration-by-collaboration-id) +- [Update Box Hub collaboration](#update-box-hub-collaboration) +- [Remove Box Hub collaboration](#remove-box-hub-collaboration) + +## Get Box Hub collaborations + +Retrieves all collaborations for a Box Hub. + +This operation is performed by calling function `getHubCollaborationsV2025R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2025.0/get-hub-collaborations/). + + +``` +client.getHubCollaborations().getHubCollaborationsV2025R0(new GetHubCollaborationsV2025R0QueryParams(hub.getId())) +``` + +### Arguments + +- queryParams `GetHubCollaborationsV2025R0QueryParams` + - Query parameters of getHubCollaborationsV2025R0 method +- headers `GetHubCollaborationsV2025R0Headers` + - Headers of getHubCollaborationsV2025R0 method + + +### Returns + +This function returns a value of type `HubCollaborationsV2025R0`. + +Retrieves the collaborations associated with the specified Box Hub. + + +## Create Box Hub collaboration + +Adds a collaboration for a single user or a single group to a Box Hub. + +Collaborations can be created using email address, user IDs, or group IDs. + +This operation is performed by calling function `createHubCollaborationV2025R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2025.0/post-hub-collaborations/). + + +``` +client.getHubCollaborations().createHubCollaborationV2025R0(new HubCollaborationCreateRequestV2025R0(new HubCollaborationCreateRequestV2025R0HubField(hub.getId()), new HubCollaborationCreateRequestV2025R0AccessibleByField.Builder("user").id(user.getId()).build(), "viewer")) +``` + +### Arguments + +- requestBody `HubCollaborationCreateRequestV2025R0` + - Request body of createHubCollaborationV2025R0 method +- headers `CreateHubCollaborationV2025R0Headers` + - Headers of createHubCollaborationV2025R0 method + + +### Returns + +This function returns a value of type `HubCollaborationV2025R0`. + +Returns a new Box Hub collaboration object. + + +## Get Box Hub collaboration by collaboration ID + +Retrieves details for a Box Hub collaboration by collaboration ID. + +This operation is performed by calling function `getHubCollaborationByIdV2025R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2025.0/get-hub-collaborations-id/). + + +``` +client.getHubCollaborations().getHubCollaborationByIdV2025R0(createdCollaboration.getId()) +``` + +### Arguments + +- hubCollaborationId `String` + - The ID of the hub collaboration. Example: "1234" +- headers `GetHubCollaborationByIdV2025R0Headers` + - Headers of getHubCollaborationByIdV2025R0 method + + +### Returns + +This function returns a value of type `HubCollaborationV2025R0`. + +Returns a Box Hub collaboration object. + + +## Update Box Hub collaboration + +Updates a Box Hub collaboration. +Can be used to change the Box Hub role. + +This operation is performed by calling function `updateHubCollaborationByIdV2025R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2025.0/put-hub-collaborations-id/). + + +``` +client.getHubCollaborations().updateHubCollaborationByIdV2025R0(createdCollaboration.getId(), new HubCollaborationUpdateRequestV2025R0.Builder().role("editor").build()) +``` + +### Arguments + +- hubCollaborationId `String` + - The ID of the hub collaboration. Example: "1234" +- requestBody `HubCollaborationUpdateRequestV2025R0` + - Request body of updateHubCollaborationByIdV2025R0 method +- headers `UpdateHubCollaborationByIdV2025R0Headers` + - Headers of updateHubCollaborationByIdV2025R0 method + + +### Returns + +This function returns a value of type `HubCollaborationV2025R0`. + +Returns an updated Box Hub collaboration object. + + +## Remove Box Hub collaboration + +Deletes a single Box Hub collaboration. + +This operation is performed by calling function `deleteHubCollaborationByIdV2025R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2025.0/delete-hub-collaborations-id/). + + +``` +client.getHubCollaborations().deleteHubCollaborationByIdV2025R0(createdCollaboration.getId()) +``` + +### Arguments + +- hubCollaborationId `String` + - The ID of the hub collaboration. Example: "1234" +- headers `DeleteHubCollaborationByIdV2025R0Headers` + - Headers of deleteHubCollaborationByIdV2025R0 method + + +### Returns + +This function returns a value of type `void`. + +A blank response is returned if the Box Hub collaboration was +successfully deleted. + + diff --git a/docs/sdkgen/hubitems.md b/docs/sdkgen/hubitems.md new file mode 100644 index 000000000..b826422e4 --- /dev/null +++ b/docs/sdkgen/hubitems.md @@ -0,0 +1,66 @@ +# HubItemsManager + + +- [Get Box Hub items](#get-box-hub-items) +- [Manage Box Hub items](#manage-box-hub-items) + +## Get Box Hub items + +Retrieves all items associated with a Box Hub. + +This operation is performed by calling function `getHubItemsV2025R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2025.0/get-hub-items/). + + +``` +client.getHubItems().getHubItemsV2025R0(new GetHubItemsV2025R0QueryParams(createdHub.getId())) +``` + +### Arguments + +- queryParams `GetHubItemsV2025R0QueryParams` + - Query parameters of getHubItemsV2025R0 method +- headers `GetHubItemsV2025R0Headers` + - Headers of getHubItemsV2025R0 method + + +### Returns + +This function returns a value of type `HubItemsV2025R0`. + +Retrieves the items associated with the specified Box Hub. + + +## Manage Box Hub items + +Adds and/or removes Box Hub items from a Box Hub. + +This operation is performed by calling function `manageHubItemsV2025R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2025.0/post-hubs-id-manage-items/). + + +``` +client.getHubItems().manageHubItemsV2025R0(createdHub.getId(), new HubItemsManageRequestV2025R0.Builder().operations(Arrays.asList(new HubItemOperationV2025R0(HubItemOperationV2025R0ActionField.ADD, new FolderReferenceV2025R0(folder.getId())))).build()) +``` + +### Arguments + +- hubId `String` + - The unique identifier that represent a hub. The ID for any hub can be determined by visiting this hub in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/hubs/123` the `hub_id` is `123`. Example: "12345" +- requestBody `HubItemsManageRequestV2025R0` + - Request body of manageHubItemsV2025R0 method +- headers `ManageHubItemsV2025R0Headers` + - Headers of manageHubItemsV2025R0 method + + +### Returns + +This function returns a value of type `HubItemsManageResponseV2025R0`. + + + + diff --git a/docs/sdkgen/hubs.md b/docs/sdkgen/hubs.md new file mode 100644 index 000000000..45f7182e6 --- /dev/null +++ b/docs/sdkgen/hubs.md @@ -0,0 +1,224 @@ +# HubsManager + + +- [List all Box Hubs](#list-all-box-hubs) +- [Create Box Hub](#create-box-hub) +- [List all Box Hubs for requesting enterprise](#list-all-box-hubs-for-requesting-enterprise) +- [Get Box Hub information by ID](#get-box-hub-information-by-id) +- [Update Box Hub information by ID](#update-box-hub-information-by-id) +- [Delete Box Hub](#delete-box-hub) +- [Copy Box Hub](#copy-box-hub) + +## List all Box Hubs + +Retrieves all Box Hubs for requesting user. + +This operation is performed by calling function `getHubsV2025R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2025.0/get-hubs/). + + +``` +client.getHubs().getHubsV2025R0(new GetHubsV2025R0QueryParams.Builder().scope("all").sort("name").direction(GetHubsV2025R0QueryParamsDirectionField.ASC).build()) +``` + +### Arguments + +- queryParams `GetHubsV2025R0QueryParams` + - Query parameters of getHubsV2025R0 method +- headers `GetHubsV2025R0Headers` + - Headers of getHubsV2025R0 method + + +### Returns + +This function returns a value of type `HubsV2025R0`. + +Returns all Box Hubs for the given user or enterprise. + + +## Create Box Hub + +Creates a new Box Hub. + +This operation is performed by calling function `createHubV2025R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2025.0/post-hubs/). + + +``` +client.getHubs().createHubV2025R0(new HubCreateRequestV2025R0.Builder(hubTitle).description(hubDescription).build()) +``` + +### Arguments + +- requestBody `HubCreateRequestV2025R0` + - Request body of createHubV2025R0 method +- headers `CreateHubV2025R0Headers` + - Headers of createHubV2025R0 method + + +### Returns + +This function returns a value of type `HubV2025R0`. + +Returns a new Hub object. + + +## List all Box Hubs for requesting enterprise + +Retrieves all Box Hubs for a given enterprise. + +Admins or Hub Co-admins of an enterprise +with GCM scope can make this call. + +This operation is performed by calling function `getEnterpriseHubsV2025R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2025.0/get-enterprise-hubs/). + + +``` +client.getHubs().getEnterpriseHubsV2025R0(new GetEnterpriseHubsV2025R0QueryParams.Builder().sort("name").direction(GetEnterpriseHubsV2025R0QueryParamsDirectionField.ASC).build()) +``` + +### Arguments + +- queryParams `GetEnterpriseHubsV2025R0QueryParams` + - Query parameters of getEnterpriseHubsV2025R0 method +- headers `GetEnterpriseHubsV2025R0Headers` + - Headers of getEnterpriseHubsV2025R0 method + + +### Returns + +This function returns a value of type `HubsV2025R0`. + +Returns all Box Hubs for the given user or enterprise. + + +## Get Box Hub information by ID + +Retrieves details for a Box Hub by its ID. + +This operation is performed by calling function `getHubByIdV2025R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2025.0/get-hubs-id/). + + +``` +client.getHubs().getHubByIdV2025R0(hubId) +``` + +### Arguments + +- hubId `String` + - The unique identifier that represent a hub. The ID for any hub can be determined by visiting this hub in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/hubs/123` the `hub_id` is `123`. Example: "12345" +- headers `GetHubByIdV2025R0Headers` + - Headers of getHubByIdV2025R0 method + + +### Returns + +This function returns a value of type `HubV2025R0`. + +Returns a hub object. + + +## Update Box Hub information by ID + +Updates a Box Hub. Can be used to change title, description, or Box Hub settings. + +This operation is performed by calling function `updateHubByIdV2025R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2025.0/put-hubs-id/). + + +``` +client.getHubs().updateHubByIdV2025R0(hubId, new HubUpdateRequestV2025R0.Builder().title(newHubTitle).description(newHubDescription).build()) +``` + +### Arguments + +- hubId `String` + - The unique identifier that represent a hub. The ID for any hub can be determined by visiting this hub in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/hubs/123` the `hub_id` is `123`. Example: "12345" +- requestBody `HubUpdateRequestV2025R0` + - Request body of updateHubByIdV2025R0 method +- headers `UpdateHubByIdV2025R0Headers` + - Headers of updateHubByIdV2025R0 method + + +### Returns + +This function returns a value of type `HubV2025R0`. + +Returns a Hub object. + + +## Delete Box Hub + +Deletes a single Box Hub. + +This operation is performed by calling function `deleteHubByIdV2025R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2025.0/delete-hubs-id/). + + +``` +client.getHubs().deleteHubByIdV2025R0(hubId) +``` + +### Arguments + +- hubId `String` + - The unique identifier that represent a hub. The ID for any hub can be determined by visiting this hub in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/hubs/123` the `hub_id` is `123`. Example: "12345" +- headers `DeleteHubByIdV2025R0Headers` + - Headers of deleteHubByIdV2025R0 method + + +### Returns + +This function returns a value of type `void`. + +A blank response is returned if the hub was +successfully deleted. + + +## Copy Box Hub + +Creates a copy of a Box Hub. + +The original Box Hub will not be modified. + +This operation is performed by calling function `copyHubV2025R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2025.0/post-hubs-id-copy/). + + +``` +client.getHubs().copyHubV2025R0(createdHub.getId(), new HubCopyRequestV2025R0.Builder().title(copiedHubTitle).description(copiedHubDescription).build()) +``` + +### Arguments + +- hubId `String` + - The unique identifier that represent a hub. The ID for any hub can be determined by visiting this hub in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/hubs/123` the `hub_id` is `123`. Example: "12345" +- requestBody `HubCopyRequestV2025R0` + - Request body of copyHubV2025R0 method +- headers `CopyHubV2025R0Headers` + - Headers of copyHubV2025R0 method + + +### Returns + +This function returns a value of type `HubV2025R0`. + +Returns a new Hub object. + + diff --git a/docs/sdkgen/integrationmappings.md b/docs/sdkgen/integrationmappings.md new file mode 100644 index 000000000..d05be5194 --- /dev/null +++ b/docs/sdkgen/integrationmappings.md @@ -0,0 +1,273 @@ +# IntegrationMappingsManager + + +- [List Slack integration mappings](#list-slack-integration-mappings) +- [Create Slack integration mapping](#create-slack-integration-mapping) +- [Update Slack integration mapping](#update-slack-integration-mapping) +- [Delete Slack integration mapping](#delete-slack-integration-mapping) +- [List Teams integration mappings](#list-teams-integration-mappings) +- [Create Teams integration mapping](#create-teams-integration-mapping) +- [Update Teams integration mapping](#update-teams-integration-mapping) +- [Delete Teams integration mapping](#delete-teams-integration-mapping) + +## List Slack integration mappings + +Lists [Slack integration mappings](https://support.box.com/hc/en-us/articles/4415585987859-Box-as-the-Content-Layer-for-Slack) in a users' enterprise. + +You need Admin or Co-Admin role to +use this endpoint. + +This operation is performed by calling function `getSlackIntegrationMapping`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-integration-mappings-slack/). + + +``` +userClient.getIntegrationMappings().getSlackIntegrationMapping() +``` + +### Arguments + +- queryParams `GetSlackIntegrationMappingQueryParams` + - Query parameters of getSlackIntegrationMapping method +- headers `GetSlackIntegrationMappingHeaders` + - Headers of getSlackIntegrationMapping method + + +### Returns + +This function returns a value of type `IntegrationMappings`. + +Returns a collection of integration mappings. + + +## Create Slack integration mapping + +Creates a [Slack integration mapping](https://support.box.com/hc/en-us/articles/4415585987859-Box-as-the-Content-Layer-for-Slack) +by mapping a Slack channel to a Box item. + +You need Admin or Co-Admin role to +use this endpoint. + +This operation is performed by calling function `createSlackIntegrationMapping`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-integration-mappings-slack/). + + +``` +userClient.getIntegrationMappings().createSlackIntegrationMapping(new IntegrationMappingSlackCreateRequest(new IntegrationMappingPartnerItemSlack.Builder(slackPartnerItemId).slackOrgId(slackOrgId).build(), new IntegrationMappingBoxItemSlack(folder.getId()))) +``` + +### Arguments + +- requestBody `IntegrationMappingSlackCreateRequest` + - Request body of createSlackIntegrationMapping method +- headers `CreateSlackIntegrationMappingHeaders` + - Headers of createSlackIntegrationMapping method + + +### Returns + +This function returns a value of type `IntegrationMapping`. + +Returns the created integration mapping. + + +## Update Slack integration mapping + +Updates a [Slack integration mapping](https://support.box.com/hc/en-us/articles/4415585987859-Box-as-the-Content-Layer-for-Slack). +Supports updating the Box folder ID and options. + +You need Admin or Co-Admin role to +use this endpoint. + +This operation is performed by calling function `updateSlackIntegrationMappingById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-integration-mappings-slack-id/). + + +``` +userClient.getIntegrationMappings().updateSlackIntegrationMappingById(slackIntegrationMapping.getId(), new UpdateSlackIntegrationMappingByIdRequestBody.Builder().boxItem(new IntegrationMappingBoxItemSlack(folder.getId())).build()) +``` + +### Arguments + +- integrationMappingId `String` + - An ID of an integration mapping. Example: "11235432" +- requestBody `UpdateSlackIntegrationMappingByIdRequestBody` + - Request body of updateSlackIntegrationMappingById method +- headers `UpdateSlackIntegrationMappingByIdHeaders` + - Headers of updateSlackIntegrationMappingById method + + +### Returns + +This function returns a value of type `IntegrationMapping`. + +Returns the updated integration mapping object. + + +## Delete Slack integration mapping + +Deletes a [Slack integration mapping](https://support.box.com/hc/en-us/articles/4415585987859-Box-as-the-Content-Layer-for-Slack). + + +You need Admin or Co-Admin role to +use this endpoint. + +This operation is performed by calling function `deleteSlackIntegrationMappingById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-integration-mappings-slack-id/). + + +``` +userClient.getIntegrationMappings().deleteSlackIntegrationMappingById(slackIntegrationMapping.getId()) +``` + +### Arguments + +- integrationMappingId `String` + - An ID of an integration mapping. Example: "11235432" +- headers `DeleteSlackIntegrationMappingByIdHeaders` + - Headers of deleteSlackIntegrationMappingById method + + +### Returns + +This function returns a value of type `void`. + +Empty body in response. + + +## List Teams integration mappings + +Lists [Teams integration mappings](https://support.box.com/hc/en-us/articles/360044681474-Using-Box-for-Teams) in a users' enterprise. +You need Admin or Co-Admin role to +use this endpoint. + +This operation is performed by calling function `getTeamsIntegrationMapping`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-integration-mappings-teams/). + + +``` +userClient.getIntegrationMappings().getTeamsIntegrationMapping() +``` + +### Arguments + +- queryParams `GetTeamsIntegrationMappingQueryParams` + - Query parameters of getTeamsIntegrationMapping method +- headers `GetTeamsIntegrationMappingHeaders` + - Headers of getTeamsIntegrationMapping method + + +### Returns + +This function returns a value of type `IntegrationMappingsTeams`. + +Returns a collection of integration mappings. + + +## Create Teams integration mapping + +Creates a [Teams integration mapping](https://support.box.com/hc/en-us/articles/360044681474-Using-Box-for-Teams) +by mapping a Teams channel to a Box item. +You need Admin or Co-Admin role to +use this endpoint. + +This operation is performed by calling function `createTeamsIntegrationMapping`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-integration-mappings-teams/). + + +``` +userClient.getIntegrationMappings().createTeamsIntegrationMapping(new IntegrationMappingTeamsCreateRequest(new IntegrationMappingPartnerItemTeamsCreateRequest(IntegrationMappingPartnerItemTeamsCreateRequestTypeField.CHANNEL, partnerItemId, tenantId, teamId), new FolderReference(folder.getId()))) +``` + +### Arguments + +- requestBody `IntegrationMappingTeamsCreateRequest` + - Request body of createTeamsIntegrationMapping method +- headers `CreateTeamsIntegrationMappingHeaders` + - Headers of createTeamsIntegrationMapping method + + +### Returns + +This function returns a value of type `IntegrationMappingTeams`. + +Returns the created integration mapping. + + +## Update Teams integration mapping + +Updates a [Teams integration mapping](https://support.box.com/hc/en-us/articles/360044681474-Using-Box-for-Teams). +Supports updating the Box folder ID and options. +You need Admin or Co-Admin role to +use this endpoint. + +This operation is performed by calling function `updateTeamsIntegrationMappingById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-integration-mappings-teams-id/). + + +``` +userClient.getIntegrationMappings().updateTeamsIntegrationMappingById(integrationMappingId, new UpdateTeamsIntegrationMappingByIdRequestBody.Builder().boxItem(new FolderReference("1234567")).build()) +``` + +### Arguments + +- integrationMappingId `String` + - An ID of an integration mapping. Example: "11235432" +- requestBody `UpdateTeamsIntegrationMappingByIdRequestBody` + - Request body of updateTeamsIntegrationMappingById method +- headers `UpdateTeamsIntegrationMappingByIdHeaders` + - Headers of updateTeamsIntegrationMappingById method + + +### Returns + +This function returns a value of type `IntegrationMappingTeams`. + +Returns the updated integration mapping object. + + +## Delete Teams integration mapping + +Deletes a [Teams integration mapping](https://support.box.com/hc/en-us/articles/360044681474-Using-Box-for-Teams). +You need Admin or Co-Admin role to +use this endpoint. + +This operation is performed by calling function `deleteTeamsIntegrationMappingById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-integration-mappings-teams-id/). + + +``` +userClient.getIntegrationMappings().deleteTeamsIntegrationMappingById(integrationMappingId) +``` + +### Arguments + +- integrationMappingId `String` + - An ID of an integration mapping. Example: "11235432" +- headers `DeleteTeamsIntegrationMappingByIdHeaders` + - Headers of deleteTeamsIntegrationMappingById method + + +### Returns + +This function returns a value of type `void`. + +Empty body in response. + + diff --git a/docs/sdkgen/invites.md b/docs/sdkgen/invites.md new file mode 100644 index 000000000..e1a89b263 --- /dev/null +++ b/docs/sdkgen/invites.md @@ -0,0 +1,76 @@ +# InvitesManager + + +- [Create user invite](#create-user-invite) +- [Get user invite status](#get-user-invite-status) + +## Create user invite + +Invites an existing external user to join an enterprise. + +The existing user can not be part of another enterprise and +must already have a Box account. Once invited, the user will receive an +email and are prompted to accept the invitation within the +Box web application. + +This method requires the "Manage An Enterprise" scope enabled for +the application, which can be enabled within the developer console. + +This operation is performed by calling function `createInvite`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-invites/). + + +``` +client.getInvites().createInvite(new CreateInviteRequestBody(new CreateInviteRequestBodyEnterpriseField(currentUser.getEnterprise().getId()), new CreateInviteRequestBodyActionableByField.Builder().login(email).build())) +``` + +### Arguments + +- requestBody `CreateInviteRequestBody` + - Request body of createInvite method +- queryParams `CreateInviteQueryParams` + - Query parameters of createInvite method +- headers `CreateInviteHeaders` + - Headers of createInvite method + + +### Returns + +This function returns a value of type `Invite`. + +Returns a new invite object. + + +## Get user invite status + +Returns the status of a user invite. + +This operation is performed by calling function `getInviteById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-invites-id/). + + +``` +client.getInvites().getInviteById(invitation.getId()) +``` + +### Arguments + +- inviteId `String` + - The ID of an invite. Example: "213723" +- queryParams `GetInviteByIdQueryParams` + - Query parameters of getInviteById method +- headers `GetInviteByIdHeaders` + - Headers of getInviteById method + + +### Returns + +This function returns a value of type `Invite`. + +Returns an invite object. + + diff --git a/docs/sdkgen/legalholdpolicies.md b/docs/sdkgen/legalholdpolicies.md new file mode 100644 index 000000000..dff0d51ef --- /dev/null +++ b/docs/sdkgen/legalholdpolicies.md @@ -0,0 +1,161 @@ +# LegalHoldPoliciesManager + + +- [List all legal hold policies](#list-all-legal-hold-policies) +- [Create legal hold policy](#create-legal-hold-policy) +- [Get legal hold policy](#get-legal-hold-policy) +- [Update legal hold policy](#update-legal-hold-policy) +- [Remove legal hold policy](#remove-legal-hold-policy) + +## List all legal hold policies + +Retrieves a list of legal hold policies that belong to +an enterprise. + +This operation is performed by calling function `getLegalHoldPolicies`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-legal-hold-policies/). + + +``` +client.getLegalHoldPolicies().getLegalHoldPolicies() +``` + +### Arguments + +- queryParams `GetLegalHoldPoliciesQueryParams` + - Query parameters of getLegalHoldPolicies method +- headers `GetLegalHoldPoliciesHeaders` + - Headers of getLegalHoldPolicies method + + +### Returns + +This function returns a value of type `LegalHoldPolicies`. + +Returns a list of legal hold policies. + + +## Create legal hold policy + +Create a new legal hold policy. + +This operation is performed by calling function `createLegalHoldPolicy`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-legal-hold-policies/). + + +``` +client.getLegalHoldPolicies().createLegalHoldPolicy(new CreateLegalHoldPolicyRequestBody.Builder(legalHoldPolicyName).description(legalHoldDescription).filterStartedAt(filterStartedAt).filterEndedAt(filterEndedAt).isOngoing(false).build()) +``` + +### Arguments + +- requestBody `CreateLegalHoldPolicyRequestBody` + - Request body of createLegalHoldPolicy method +- headers `CreateLegalHoldPolicyHeaders` + - Headers of createLegalHoldPolicy method + + +### Returns + +This function returns a value of type `LegalHoldPolicy`. + +Returns a new legal hold policy object. + + +## Get legal hold policy + +Retrieve a legal hold policy. + +This operation is performed by calling function `getLegalHoldPolicyById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-legal-hold-policies-id/). + + +``` +client.getLegalHoldPolicies().getLegalHoldPolicyById(legalHoldPolicyId) +``` + +### Arguments + +- legalHoldPolicyId `String` + - The ID of the legal hold policy. Example: "324432" +- headers `GetLegalHoldPolicyByIdHeaders` + - Headers of getLegalHoldPolicyById method + + +### Returns + +This function returns a value of type `LegalHoldPolicy`. + +Returns a legal hold policy object. + + +## Update legal hold policy + +Update legal hold policy. + +This operation is performed by calling function `updateLegalHoldPolicyById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-legal-hold-policies-id/). + + +``` +client.getLegalHoldPolicies().updateLegalHoldPolicyById(legalHoldPolicyId, new UpdateLegalHoldPolicyByIdRequestBody.Builder().policyName(updatedLegalHoldPolicyName).build()) +``` + +### Arguments + +- legalHoldPolicyId `String` + - The ID of the legal hold policy. Example: "324432" +- requestBody `UpdateLegalHoldPolicyByIdRequestBody` + - Request body of updateLegalHoldPolicyById method +- headers `UpdateLegalHoldPolicyByIdHeaders` + - Headers of updateLegalHoldPolicyById method + + +### Returns + +This function returns a value of type `LegalHoldPolicy`. + +Returns a new legal hold policy object. + + +## Remove legal hold policy + +Delete an existing legal hold policy. + +This is an asynchronous process. The policy will not be +fully deleted yet when the response returns. + +This operation is performed by calling function `deleteLegalHoldPolicyById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-legal-hold-policies-id/). + + +``` +client.getLegalHoldPolicies().deleteLegalHoldPolicyById(legalHoldPolicy.getId()) +``` + +### Arguments + +- legalHoldPolicyId `String` + - The ID of the legal hold policy. Example: "324432" +- headers `DeleteLegalHoldPolicyByIdHeaders` + - Headers of deleteLegalHoldPolicyById method + + +### Returns + +This function returns a value of type `void`. + +A blank response is returned if the policy was +successfully deleted. + + diff --git a/docs/sdkgen/legalholdpolicyassignments.md b/docs/sdkgen/legalholdpolicyassignments.md new file mode 100644 index 000000000..0717f1c4c --- /dev/null +++ b/docs/sdkgen/legalholdpolicyassignments.md @@ -0,0 +1,179 @@ +# LegalHoldPolicyAssignmentsManager + + +- [List legal hold policy assignments](#list-legal-hold-policy-assignments) +- [Assign legal hold policy](#assign-legal-hold-policy) +- [Get legal hold policy assignment](#get-legal-hold-policy-assignment) +- [Unassign legal hold policy](#unassign-legal-hold-policy) +- [List files with current file versions for legal hold policy assignment](#list-files-with-current-file-versions-for-legal-hold-policy-assignment) + +## List legal hold policy assignments + +Retrieves a list of items a legal hold policy has been assigned to. + +This operation is performed by calling function `getLegalHoldPolicyAssignments`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-legal-hold-policy-assignments/). + + +``` +client.getLegalHoldPolicyAssignments().getLegalHoldPolicyAssignments(new GetLegalHoldPolicyAssignmentsQueryParams(legalHoldPolicyId)) +``` + +### Arguments + +- queryParams `GetLegalHoldPolicyAssignmentsQueryParams` + - Query parameters of getLegalHoldPolicyAssignments method +- headers `GetLegalHoldPolicyAssignmentsHeaders` + - Headers of getLegalHoldPolicyAssignments method + + +### Returns + +This function returns a value of type `LegalHoldPolicyAssignments`. + +Returns a list of legal hold policy assignments. + + +## Assign legal hold policy + +Assign a legal hold to a file, file version, folder, or user. + +This operation is performed by calling function `createLegalHoldPolicyAssignment`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-legal-hold-policy-assignments/). + + +``` +client.getLegalHoldPolicyAssignments().createLegalHoldPolicyAssignment(new CreateLegalHoldPolicyAssignmentRequestBody(legalHoldPolicyId, new CreateLegalHoldPolicyAssignmentRequestBodyAssignToField(CreateLegalHoldPolicyAssignmentRequestBodyAssignToTypeField.FILE, fileId))) +``` + +### Arguments + +- requestBody `CreateLegalHoldPolicyAssignmentRequestBody` + - Request body of createLegalHoldPolicyAssignment method +- headers `CreateLegalHoldPolicyAssignmentHeaders` + - Headers of createLegalHoldPolicyAssignment method + + +### Returns + +This function returns a value of type `LegalHoldPolicyAssignment`. + +Returns a new legal hold policy assignment. + + +## Get legal hold policy assignment + +Retrieve a legal hold policy assignment. + +This operation is performed by calling function `getLegalHoldPolicyAssignmentById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-legal-hold-policy-assignments-id/). + + +``` +client.getLegalHoldPolicyAssignments().getLegalHoldPolicyAssignmentById(legalHoldPolicyAssignmentId) +``` + +### Arguments + +- legalHoldPolicyAssignmentId `String` + - The ID of the legal hold policy assignment. Example: "753465" +- headers `GetLegalHoldPolicyAssignmentByIdHeaders` + - Headers of getLegalHoldPolicyAssignmentById method + + +### Returns + +This function returns a value of type `LegalHoldPolicyAssignment`. + +Returns a legal hold policy object. + + +## Unassign legal hold policy + +Remove a legal hold from an item. + +This is an asynchronous process. The policy will not be +fully removed yet when the response returns. + +This operation is performed by calling function `deleteLegalHoldPolicyAssignmentById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-legal-hold-policy-assignments-id/). + + +``` +client.getLegalHoldPolicyAssignments().deleteLegalHoldPolicyAssignmentById(legalHoldPolicyAssignmentId) +``` + +### Arguments + +- legalHoldPolicyAssignmentId `String` + - The ID of the legal hold policy assignment. Example: "753465" +- headers `DeleteLegalHoldPolicyAssignmentByIdHeaders` + - Headers of deleteLegalHoldPolicyAssignmentById method + + +### Returns + +This function returns a value of type `void`. + +A blank response is returned if the assignment was +successfully deleted. + + +## List files with current file versions for legal hold policy assignment + +Get a list of files with current file versions for a legal hold +assignment. + +In some cases you may want to get previous file versions instead. In these +cases, use the `GET /legal_hold_policy_assignments/:id/file_versions_on_hold` +API instead to return any previous versions of a file for this legal hold +policy assignment. + +Due to ongoing re-architecture efforts this API might not return all file +versions held for this policy ID. Instead, this API will only return the +latest file version held in the newly developed architecture. The `GET +/file_version_legal_holds` API can be used to fetch current and past versions +of files held within the legacy architecture. + +This endpoint does not support returning any content that is on hold due to +a Custodian collaborating on a Hub. + +The `GET /legal_hold_policy_assignments?policy_id={id}` API can be used to +find a list of policy assignments for a given policy ID. + +This operation is performed by calling function `getLegalHoldPolicyAssignmentFileOnHold`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-legal-hold-policy-assignments-id-files-on-hold/). + + +``` +client.getLegalHoldPolicyAssignments().getLegalHoldPolicyAssignmentFileOnHold(legalHoldPolicyAssignmentId) +``` + +### Arguments + +- legalHoldPolicyAssignmentId `String` + - The ID of the legal hold policy assignment. Example: "753465" +- queryParams `GetLegalHoldPolicyAssignmentFileOnHoldQueryParams` + - Query parameters of getLegalHoldPolicyAssignmentFileOnHold method +- headers `GetLegalHoldPolicyAssignmentFileOnHoldHeaders` + - Headers of getLegalHoldPolicyAssignmentFileOnHold method + + +### Returns + +This function returns a value of type `FilesOnHold`. + +Returns the list of current file versions held under legal hold for a +specific legal hold policy assignment. + + diff --git a/docs/sdkgen/listcollaborations.md b/docs/sdkgen/listcollaborations.md new file mode 100644 index 000000000..a3d691d3d --- /dev/null +++ b/docs/sdkgen/listcollaborations.md @@ -0,0 +1,152 @@ +# ListCollaborationsManager + + +- [List file collaborations](#list-file-collaborations) +- [List folder collaborations](#list-folder-collaborations) +- [List pending collaborations](#list-pending-collaborations) +- [List group collaborations](#list-group-collaborations) + +## List file collaborations + +Retrieves a list of pending and active collaborations for a +file. This returns all the users that have access to the file +or have been invited to the file. + +This operation is performed by calling function `getFileCollaborations`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-files-id-collaborations/). + + +``` +client.getListCollaborations().getFileCollaborations(file.getId()) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- queryParams `GetFileCollaborationsQueryParams` + - Query parameters of getFileCollaborations method +- headers `GetFileCollaborationsHeaders` + - Headers of getFileCollaborations method + + +### Returns + +This function returns a value of type `Collaborations`. + +Returns a collection of collaboration objects. If there are no +collaborations on this file an empty collection will be returned. + +This list includes pending collaborations, for which the `status` +is set to `pending`, indicating invitations that have been sent but not +yet accepted. + + +## List folder collaborations + +Retrieves a list of pending and active collaborations for a +folder. This returns all the users that have access to the folder +or have been invited to the folder. + +This operation is performed by calling function `getFolderCollaborations`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-folders-id-collaborations/). + + +``` +client.getListCollaborations().getFolderCollaborations(folder.getId()) +``` + +### Arguments + +- folderId `String` + - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. Example: "12345" +- queryParams `GetFolderCollaborationsQueryParams` + - Query parameters of getFolderCollaborations method +- headers `GetFolderCollaborationsHeaders` + - Headers of getFolderCollaborations method + + +### Returns + +This function returns a value of type `Collaborations`. + +Returns a collection of collaboration objects. If there are no +collaborations on this folder an empty collection will be returned. + +This list includes pending collaborations, for which the `status` +is set to `pending`, indicating invitations that have been sent but not +yet accepted. + + +## List pending collaborations + +Retrieves all pending collaboration invites for this user. + +This operation is performed by calling function `getCollaborations`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-collaborations/). + + +``` +client.getListCollaborations().getCollaborations(new GetCollaborationsQueryParams(GetCollaborationsQueryParamsStatusField.PENDING)) +``` + +### Arguments + +- queryParams `GetCollaborationsQueryParams` + - Query parameters of getCollaborations method +- headers `GetCollaborationsHeaders` + - Headers of getCollaborations method + + +### Returns + +This function returns a value of type `CollaborationsOffsetPaginated`. + +Returns a collection of pending collaboration objects. + +If the user has no pending collaborations, the collection +will be empty. + + +## List group collaborations + +Retrieves all the collaborations for a group. The user +must have admin permissions to inspect enterprise's groups. + +Each collaboration object has details on which files or +folders the group has access to and with what role. + +This operation is performed by calling function `getGroupCollaborations`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-groups-id-collaborations/). + + +``` +client.getListCollaborations().getGroupCollaborations(group.getId()) +``` + +### Arguments + +- groupId `String` + - The ID of the group. Example: "57645" +- queryParams `GetGroupCollaborationsQueryParams` + - Query parameters of getGroupCollaborations method +- headers `GetGroupCollaborationsHeaders` + - Headers of getGroupCollaborations method + + +### Returns + +This function returns a value of type `CollaborationsOffsetPaginated`. + +Returns a collection of collaboration objects. If there are no +collaborations, an empty collection will be returned. + + diff --git a/docs/sdkgen/memberships.md b/docs/sdkgen/memberships.md new file mode 100644 index 000000000..39fd5df40 --- /dev/null +++ b/docs/sdkgen/memberships.md @@ -0,0 +1,210 @@ +# MembershipsManager + + +- [List user's groups](#list-users-groups) +- [List members of group](#list-members-of-group) +- [Add user to group](#add-user-to-group) +- [Get group membership](#get-group-membership) +- [Update group membership](#update-group-membership) +- [Remove user from group](#remove-user-from-group) + +## List user's groups + +Retrieves all the groups for a user. Only members of this +group or users with admin-level permissions will be able to +use this API. + +This operation is performed by calling function `getUserMemberships`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-users-id-memberships/). + + +``` +client.getMemberships().getUserMemberships(user.getId()) +``` + +### Arguments + +- userId `String` + - The ID of the user. Example: "12345" +- queryParams `GetUserMembershipsQueryParams` + - Query parameters of getUserMemberships method +- headers `GetUserMembershipsHeaders` + - Headers of getUserMemberships method + + +### Returns + +This function returns a value of type `GroupMemberships`. + +Returns a collection of membership objects. If there are no +memberships, an empty collection will be returned. + + +## List members of group + +Retrieves all the members for a group. Only members of this +group or users with admin-level permissions will be able to +use this API. + +This operation is performed by calling function `getGroupMemberships`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-groups-id-memberships/). + + +``` +client.getMemberships().getGroupMemberships(group.getId()) +``` + +### Arguments + +- groupId `String` + - The ID of the group. Example: "57645" +- queryParams `GetGroupMembershipsQueryParams` + - Query parameters of getGroupMemberships method +- headers `GetGroupMembershipsHeaders` + - Headers of getGroupMemberships method + + +### Returns + +This function returns a value of type `GroupMemberships`. + +Returns a collection of membership objects. If there are no +memberships, an empty collection will be returned. + + +## Add user to group + +Creates a group membership. Only users with +admin-level permissions will be able to use this API. + +This operation is performed by calling function `createGroupMembership`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-group-memberships/). + + +``` +client.getMemberships().createGroupMembership(new CreateGroupMembershipRequestBody(new CreateGroupMembershipRequestBodyUserField(user.getId()), new CreateGroupMembershipRequestBodyGroupField(group.getId()))) +``` + +### Arguments + +- requestBody `CreateGroupMembershipRequestBody` + - Request body of createGroupMembership method +- queryParams `CreateGroupMembershipQueryParams` + - Query parameters of createGroupMembership method +- headers `CreateGroupMembershipHeaders` + - Headers of createGroupMembership method + + +### Returns + +This function returns a value of type `GroupMembership`. + +Returns a new group membership object. + + +## Get group membership + +Retrieves a specific group membership. Only admins of this +group or users with admin-level permissions will be able to +use this API. + +This operation is performed by calling function `getGroupMembershipById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-group-memberships-id/). + + +``` +client.getMemberships().getGroupMembershipById(groupMembership.getId()) +``` + +### Arguments + +- groupMembershipId `String` + - The ID of the group membership. Example: "434534" +- queryParams `GetGroupMembershipByIdQueryParams` + - Query parameters of getGroupMembershipById method +- headers `GetGroupMembershipByIdHeaders` + - Headers of getGroupMembershipById method + + +### Returns + +This function returns a value of type `GroupMembership`. + +Returns the group membership object. + + +## Update group membership + +Updates a user's group membership. Only admins of this +group or users with admin-level permissions will be able to +use this API. + +This operation is performed by calling function `updateGroupMembershipById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-group-memberships-id/). + + +``` +client.getMemberships().updateGroupMembershipById(groupMembership.getId(), new UpdateGroupMembershipByIdRequestBody.Builder().role(UpdateGroupMembershipByIdRequestBodyRoleField.ADMIN).build()) +``` + +### Arguments + +- groupMembershipId `String` + - The ID of the group membership. Example: "434534" +- requestBody `UpdateGroupMembershipByIdRequestBody` + - Request body of updateGroupMembershipById method +- queryParams `UpdateGroupMembershipByIdQueryParams` + - Query parameters of updateGroupMembershipById method +- headers `UpdateGroupMembershipByIdHeaders` + - Headers of updateGroupMembershipById method + + +### Returns + +This function returns a value of type `GroupMembership`. + +Returns a new group membership object. + + +## Remove user from group + +Deletes a specific group membership. Only admins of this +group or users with admin-level permissions will be able to +use this API. + +This operation is performed by calling function `deleteGroupMembershipById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-group-memberships-id/). + + +``` +client.getMemberships().deleteGroupMembershipById(groupMembership.getId()) +``` + +### Arguments + +- groupMembershipId `String` + - The ID of the group membership. Example: "434534" +- headers `DeleteGroupMembershipByIdHeaders` + - Headers of deleteGroupMembershipById method + + +### Returns + +This function returns a value of type `void`. + +A blank response is returned if the membership was +successfully deleted. + + diff --git a/docs/sdkgen/metadatacascadepolicies.md b/docs/sdkgen/metadatacascadepolicies.md new file mode 100644 index 000000000..5542a8820 --- /dev/null +++ b/docs/sdkgen/metadatacascadepolicies.md @@ -0,0 +1,172 @@ +# MetadataCascadePoliciesManager + + +- [List metadata cascade policies](#list-metadata-cascade-policies) +- [Create metadata cascade policy](#create-metadata-cascade-policy) +- [Get metadata cascade policy](#get-metadata-cascade-policy) +- [Remove metadata cascade policy](#remove-metadata-cascade-policy) +- [Force-apply metadata cascade policy to folder](#force-apply-metadata-cascade-policy-to-folder) + +## List metadata cascade policies + +Retrieves a list of all the metadata cascade policies +that are applied to a given folder. This can not be used on the root +folder with ID `0`. + +This operation is performed by calling function `getMetadataCascadePolicies`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-metadata-cascade-policies/). + + +``` +client.getMetadataCascadePolicies().getMetadataCascadePolicies(new GetMetadataCascadePoliciesQueryParams(folder.getId())) +``` + +### Arguments + +- queryParams `GetMetadataCascadePoliciesQueryParams` + - Query parameters of getMetadataCascadePolicies method +- headers `GetMetadataCascadePoliciesHeaders` + - Headers of getMetadataCascadePolicies method + + +### Returns + +This function returns a value of type `MetadataCascadePolicies`. + +Returns a list of metadata cascade policies. + + +## Create metadata cascade policy + +Creates a new metadata cascade policy that applies a given +metadata template to a given folder and automatically +cascades it down to any files within that folder. + +In order for the policy to be applied a metadata instance must first +be applied to the folder the policy is to be applied to. + +This operation is performed by calling function `createMetadataCascadePolicy`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-metadata-cascade-policies/). + + +``` +client.getMetadataCascadePolicies().createMetadataCascadePolicy(new CreateMetadataCascadePolicyRequestBody(folder.getId(), CreateMetadataCascadePolicyRequestBodyScopeField.ENTERPRISE, templateKey)) +``` + +### Arguments + +- requestBody `CreateMetadataCascadePolicyRequestBody` + - Request body of createMetadataCascadePolicy method +- headers `CreateMetadataCascadePolicyHeaders` + - Headers of createMetadataCascadePolicy method + + +### Returns + +This function returns a value of type `MetadataCascadePolicy`. + +Returns a new of metadata cascade policy. + + +## Get metadata cascade policy + +Retrieve a specific metadata cascade policy assigned to a folder. + +This operation is performed by calling function `getMetadataCascadePolicyById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-metadata-cascade-policies-id/). + + +``` +client.getMetadataCascadePolicies().getMetadataCascadePolicyById(cascadePolicyId) +``` + +### Arguments + +- metadataCascadePolicyId `String` + - The ID of the metadata cascade policy. Example: "6fd4ff89-8fc1-42cf-8b29-1890dedd26d7" +- headers `GetMetadataCascadePolicyByIdHeaders` + - Headers of getMetadataCascadePolicyById method + + +### Returns + +This function returns a value of type `MetadataCascadePolicy`. + +Returns a metadata cascade policy. + + +## Remove metadata cascade policy + +Deletes a metadata cascade policy. + +This operation is performed by calling function `deleteMetadataCascadePolicyById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-metadata-cascade-policies-id/). + + +``` +client.getMetadataCascadePolicies().deleteMetadataCascadePolicyById(cascadePolicyId) +``` + +### Arguments + +- metadataCascadePolicyId `String` + - The ID of the metadata cascade policy. Example: "6fd4ff89-8fc1-42cf-8b29-1890dedd26d7" +- headers `DeleteMetadataCascadePolicyByIdHeaders` + - Headers of deleteMetadataCascadePolicyById method + + +### Returns + +This function returns a value of type `void`. + +Returns an empty response when the policy +is successfully deleted. + + +## Force-apply metadata cascade policy to folder + +Force the metadata on a folder with a metadata cascade policy to be applied to +all of its children. This can be used after creating a new cascade policy to +enforce the metadata to be cascaded down to all existing files within that +folder. + +This operation is performed by calling function `applyMetadataCascadePolicy`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-metadata-cascade-policies-id-apply/). + + +``` +client.getMetadataCascadePolicies().applyMetadataCascadePolicy(cascadePolicyId, new ApplyMetadataCascadePolicyRequestBody(ApplyMetadataCascadePolicyRequestBodyConflictResolutionField.OVERWRITE)) +``` + +### Arguments + +- metadataCascadePolicyId `String` + - The ID of the cascade policy to force-apply. Example: "6fd4ff89-8fc1-42cf-8b29-1890dedd26d7" +- requestBody `ApplyMetadataCascadePolicyRequestBody` + - Request body of applyMetadataCascadePolicy method +- headers `ApplyMetadataCascadePolicyHeaders` + - Headers of applyMetadataCascadePolicy method + + +### Returns + +This function returns a value of type `void`. + +Returns an empty response when the API call was successful. The metadata +cascade operation will be performed asynchronously. + +The API call will return directly, before the cascade operation +is complete. There is currently no API to check for the status of this +operation. + + diff --git a/docs/sdkgen/metadatatemplates.md b/docs/sdkgen/metadatatemplates.md new file mode 100644 index 000000000..e56609056 --- /dev/null +++ b/docs/sdkgen/metadatatemplates.md @@ -0,0 +1,272 @@ +# MetadataTemplatesManager + + +- [Find metadata template by instance ID](#find-metadata-template-by-instance-id) +- [Get metadata template by name](#get-metadata-template-by-name) +- [Update metadata template](#update-metadata-template) +- [Remove metadata template](#remove-metadata-template) +- [Get metadata template by ID](#get-metadata-template-by-id) +- [List all global metadata templates](#list-all-global-metadata-templates) +- [List all metadata templates for enterprise](#list-all-metadata-templates-for-enterprise) +- [Create metadata template](#create-metadata-template) + +## Find metadata template by instance ID + +Finds a metadata template by searching for the ID of an instance of the +template. + +This operation is performed by calling function `getMetadataTemplatesByInstanceId`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-metadata-templates/). + + +``` +client.getMetadataTemplates().getMetadataTemplatesByInstanceId(new GetMetadataTemplatesByInstanceIdQueryParams(createdMetadataInstance.getId())) +``` + +### Arguments + +- queryParams `GetMetadataTemplatesByInstanceIdQueryParams` + - Query parameters of getMetadataTemplatesByInstanceId method +- headers `GetMetadataTemplatesByInstanceIdHeaders` + - Headers of getMetadataTemplatesByInstanceId method + + +### Returns + +This function returns a value of type `MetadataTemplates`. + +Returns a list containing the 1 metadata template that matches the +instance ID. + + +## Get metadata template by name + +Retrieves a metadata template by its `scope` and `templateKey` values. + +To find the `scope` and `templateKey` for a template, list all templates for +an enterprise or globally, or list all templates applied to a file or folder. + +This operation is performed by calling function `getMetadataTemplate`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-metadata-templates-id-id-schema/). + + +``` +client.getMetadataTemplates().getMetadataTemplate(GetMetadataTemplateScope.ENTERPRISE, template.getTemplateKey()) +``` + +### Arguments + +- scope `GetMetadataTemplateScope` + - The scope of the metadata template. Example: "global" +- templateKey `String` + - The name of the metadata template. Example: "properties" +- headers `GetMetadataTemplateHeaders` + - Headers of getMetadataTemplate method + + +### Returns + +This function returns a value of type `MetadataTemplate`. + +Returns the metadata template matching the `scope` +and `template` name. + + +## Update metadata template + +Updates a metadata template. + +The metadata template can only be updated if the template +already exists. + +The update is applied atomically. If any errors occur during the +application of the operations, the metadata template will not be changed. + +This operation is performed by calling function `updateMetadataTemplate`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-metadata-templates-id-id-schema/). + + +``` +client.getMetadataTemplates().updateMetadataTemplate(UpdateMetadataTemplateScope.ENTERPRISE, templateKey, Arrays.asList(new UpdateMetadataTemplateRequestBody.Builder(UpdateMetadataTemplateRequestBodyOpField.ADDFIELD).data(mapOf(entryOf("type", "string"), entryOf("displayName", "newFieldName"))).fieldKey("newfieldname").build())) +``` + +### Arguments + +- scope `UpdateMetadataTemplateScope` + - The scope of the metadata template. Example: "global" +- templateKey `String` + - The name of the metadata template. Example: "properties" +- requestBody `List` + - Request body of updateMetadataTemplate method +- headers `UpdateMetadataTemplateHeaders` + - Headers of updateMetadataTemplate method + + +### Returns + +This function returns a value of type `MetadataTemplate`. + +Returns the updated metadata template, with the +custom template data included. + + +## Remove metadata template + +Delete a metadata template and its instances. +This deletion is permanent and can not be reversed. + +This operation is performed by calling function `deleteMetadataTemplate`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-metadata-templates-id-id-schema/). + + +``` +client.getMetadataTemplates().deleteMetadataTemplate(DeleteMetadataTemplateScope.ENTERPRISE, template.getTemplateKey()) +``` + +### Arguments + +- scope `DeleteMetadataTemplateScope` + - The scope of the metadata template. Example: "global" +- templateKey `String` + - The name of the metadata template. Example: "properties" +- headers `DeleteMetadataTemplateHeaders` + - Headers of deleteMetadataTemplate method + + +### Returns + +This function returns a value of type `void`. + +Returns an empty response when the metadata +template is successfully deleted. + + +## Get metadata template by ID + +Retrieves a metadata template by its ID. + +This operation is performed by calling function `getMetadataTemplateById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-metadata-templates-id/). + + +``` +client.getMetadataTemplates().getMetadataTemplateById(template.getId()) +``` + +### Arguments + +- templateId `String` + - The ID of the template. Example: "f7a9891f" +- headers `GetMetadataTemplateByIdHeaders` + - Headers of getMetadataTemplateById method + + +### Returns + +This function returns a value of type `MetadataTemplate`. + +Returns the metadata template that matches the ID. + + +## List all global metadata templates + +Used to retrieve all generic, global metadata templates available to all +enterprises using Box. + +This operation is performed by calling function `getGlobalMetadataTemplates`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-metadata-templates-global/). + + +``` +client.getMetadataTemplates().getGlobalMetadataTemplates() +``` + +### Arguments + +- queryParams `GetGlobalMetadataTemplatesQueryParams` + - Query parameters of getGlobalMetadataTemplates method +- headers `GetGlobalMetadataTemplatesHeaders` + - Headers of getGlobalMetadataTemplates method + + +### Returns + +This function returns a value of type `MetadataTemplates`. + +Returns all of the metadata templates available to all enterprises +and their corresponding schema. + + +## List all metadata templates for enterprise + +Used to retrieve all metadata templates created to be used specifically within +the user's enterprise. + +This operation is performed by calling function `getEnterpriseMetadataTemplates`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-metadata-templates-enterprise/). + + +``` +client.getMetadataTemplates().getEnterpriseMetadataTemplates() +``` + +### Arguments + +- queryParams `GetEnterpriseMetadataTemplatesQueryParams` + - Query parameters of getEnterpriseMetadataTemplates method +- headers `GetEnterpriseMetadataTemplatesHeaders` + - Headers of getEnterpriseMetadataTemplates method + + +### Returns + +This function returns a value of type `MetadataTemplates`. + +Returns all of the metadata templates within an enterprise +and their corresponding schema. + + +## Create metadata template + +Creates a new metadata template that can be applied to +files and folders. + +This operation is performed by calling function `createMetadataTemplate`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-metadata-templates-schema/). + + +``` +client.getMetadataTemplates().createMetadataTemplate(new CreateMetadataTemplateRequestBody.Builder("enterprise", templateKey).templateKey(templateKey).fields(Arrays.asList(new CreateMetadataTemplateRequestBodyFieldsField(CreateMetadataTemplateRequestBodyFieldsTypeField.STRING, "testName", "testName"), new CreateMetadataTemplateRequestBodyFieldsField(CreateMetadataTemplateRequestBodyFieldsTypeField.FLOAT, "age", "age"), new CreateMetadataTemplateRequestBodyFieldsField(CreateMetadataTemplateRequestBodyFieldsTypeField.DATE, "birthDate", "birthDate"), new CreateMetadataTemplateRequestBodyFieldsField.Builder(CreateMetadataTemplateRequestBodyFieldsTypeField.ENUM, "countryCode", "countryCode").options(Arrays.asList(new CreateMetadataTemplateRequestBodyFieldsOptionsField("US"), new CreateMetadataTemplateRequestBodyFieldsOptionsField("CA"))).build(), new CreateMetadataTemplateRequestBodyFieldsField.Builder(CreateMetadataTemplateRequestBodyFieldsTypeField.MULTISELECT, "sports", "sports").options(Arrays.asList(new CreateMetadataTemplateRequestBodyFieldsOptionsField("basketball"), new CreateMetadataTemplateRequestBodyFieldsOptionsField("football"), new CreateMetadataTemplateRequestBodyFieldsOptionsField("tennis"))).build())).build()) +``` + +### Arguments + +- requestBody `CreateMetadataTemplateRequestBody` + - Request body of createMetadataTemplate method +- headers `CreateMetadataTemplateHeaders` + - Headers of createMetadataTemplate method + + +### Returns + +This function returns a value of type `MetadataTemplate`. + +The schema representing the metadata template created. + + diff --git a/docs/sdkgen/recentitems.md b/docs/sdkgen/recentitems.md new file mode 100644 index 000000000..bb76f26a4 --- /dev/null +++ b/docs/sdkgen/recentitems.md @@ -0,0 +1,36 @@ +# RecentItemsManager + + +- [List recently accessed items](#list-recently-accessed-items) + +## List recently accessed items + +Returns information about the recent items accessed +by a user, either in the last 90 days or up to the last +1000 items accessed. + +This operation is performed by calling function `getRecentItems`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-recent-items/). + + +``` +client.getRecentItems().getRecentItems() +``` + +### Arguments + +- queryParams `GetRecentItemsQueryParams` + - Query parameters of getRecentItems method +- headers `GetRecentItemsHeaders` + - Headers of getRecentItems method + + +### Returns + +This function returns a value of type `RecentItems`. + +Returns a list recent items access by a user. + + diff --git a/docs/sdkgen/retentionpolicies.md b/docs/sdkgen/retentionpolicies.md new file mode 100644 index 000000000..e82f25545 --- /dev/null +++ b/docs/sdkgen/retentionpolicies.md @@ -0,0 +1,158 @@ +# RetentionPoliciesManager + + +- [List retention policies](#list-retention-policies) +- [Create retention policy](#create-retention-policy) +- [Get retention policy](#get-retention-policy) +- [Update retention policy](#update-retention-policy) +- [Delete retention policy](#delete-retention-policy) + +## List retention policies + +Retrieves all of the retention policies for an enterprise. + +This operation is performed by calling function `getRetentionPolicies`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-retention-policies/). + + +``` +client.getRetentionPolicies().getRetentionPolicies() +``` + +### Arguments + +- queryParams `GetRetentionPoliciesQueryParams` + - Query parameters of getRetentionPolicies method +- headers `GetRetentionPoliciesHeaders` + - Headers of getRetentionPolicies method + + +### Returns + +This function returns a value of type `RetentionPolicies`. + +Returns a list retention policies in the enterprise. + + +## Create retention policy + +Creates a retention policy. + +This operation is performed by calling function `createRetentionPolicy`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-retention-policies/). + + +``` +client.getRetentionPolicies().createRetentionPolicy(new CreateRetentionPolicyRequestBody.Builder(retentionPolicyName, CreateRetentionPolicyRequestBodyPolicyTypeField.FINITE, CreateRetentionPolicyRequestBodyDispositionActionField.REMOVE_RETENTION).description(retentionDescription).retentionLength("1").retentionType(CreateRetentionPolicyRequestBodyRetentionTypeField.MODIFIABLE).canOwnerExtendRetention(true).areOwnersNotified(true).build()) +``` + +### Arguments + +- requestBody `CreateRetentionPolicyRequestBody` + - Request body of createRetentionPolicy method +- headers `CreateRetentionPolicyHeaders` + - Headers of createRetentionPolicy method + + +### Returns + +This function returns a value of type `RetentionPolicy`. + +Returns a new retention policy object. + + +## Get retention policy + +Retrieves a retention policy. + +This operation is performed by calling function `getRetentionPolicyById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-retention-policies-id/). + + +``` +client.getRetentionPolicies().getRetentionPolicyById(retentionPolicy.getId()) +``` + +### Arguments + +- retentionPolicyId `String` + - The ID of the retention policy. Example: "982312" +- queryParams `GetRetentionPolicyByIdQueryParams` + - Query parameters of getRetentionPolicyById method +- headers `GetRetentionPolicyByIdHeaders` + - Headers of getRetentionPolicyById method + + +### Returns + +This function returns a value of type `RetentionPolicy`. + +Returns the retention policy object. + + +## Update retention policy + +Updates a retention policy. + +This operation is performed by calling function `updateRetentionPolicyById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-retention-policies-id/). + + +``` +client.getRetentionPolicies().updateRetentionPolicyById(retentionPolicy.getId(), new UpdateRetentionPolicyByIdRequestBody.Builder().policyName(updatedRetentionPolicyName).build()) +``` + +### Arguments + +- retentionPolicyId `String` + - The ID of the retention policy. Example: "982312" +- requestBody `UpdateRetentionPolicyByIdRequestBody` + - Request body of updateRetentionPolicyById method +- headers `UpdateRetentionPolicyByIdHeaders` + - Headers of updateRetentionPolicyById method + + +### Returns + +This function returns a value of type `RetentionPolicy`. + +Returns the updated retention policy object. + + +## Delete retention policy + +Permanently deletes a retention policy. + +This operation is performed by calling function `deleteRetentionPolicyById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-retention-policies-id/). + + +``` +client.getRetentionPolicies().deleteRetentionPolicyById(retentionPolicy.getId()) +``` + +### Arguments + +- retentionPolicyId `String` + - The ID of the retention policy. Example: "982312" +- headers `DeleteRetentionPolicyByIdHeaders` + - Headers of deleteRetentionPolicyById method + + +### Returns + +This function returns a value of type `void`. + +Returns an empty response when the policy has been deleted. + + diff --git a/docs/sdkgen/retentionpolicyassignments.md b/docs/sdkgen/retentionpolicyassignments.md new file mode 100644 index 000000000..3ebfe1e50 --- /dev/null +++ b/docs/sdkgen/retentionpolicyassignments.md @@ -0,0 +1,165 @@ +# RetentionPolicyAssignmentsManager + + +- [List retention policy assignments](#list-retention-policy-assignments) +- [Assign retention policy](#assign-retention-policy) +- [Get retention policy assignment](#get-retention-policy-assignment) +- [Remove retention policy assignment](#remove-retention-policy-assignment) +- [Get files under retention](#get-files-under-retention) + +## List retention policy assignments + +Returns a list of all retention policy assignments associated with a specified +retention policy. + +This operation is performed by calling function `getRetentionPolicyAssignments`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-retention-policies-id-assignments/). + + +``` +client.getRetentionPolicyAssignments().getRetentionPolicyAssignments(retentionPolicy.getId()) +``` + +### Arguments + +- retentionPolicyId `String` + - The ID of the retention policy. Example: "982312" +- queryParams `GetRetentionPolicyAssignmentsQueryParams` + - Query parameters of getRetentionPolicyAssignments method +- headers `GetRetentionPolicyAssignmentsHeaders` + - Headers of getRetentionPolicyAssignments method + + +### Returns + +This function returns a value of type `RetentionPolicyAssignments`. + +Returns a list of the retention policy assignments associated with the +specified retention policy. + + +## Assign retention policy + +Assigns a retention policy to an item. + +This operation is performed by calling function `createRetentionPolicyAssignment`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-retention-policy-assignments/). + + +``` +client.getRetentionPolicyAssignments().createRetentionPolicyAssignment(new CreateRetentionPolicyAssignmentRequestBody(retentionPolicy.getId(), new CreateRetentionPolicyAssignmentRequestBodyAssignToField.Builder(CreateRetentionPolicyAssignmentRequestBodyAssignToTypeField.FOLDER).id(folder.getId()).build())) +``` + +### Arguments + +- requestBody `CreateRetentionPolicyAssignmentRequestBody` + - Request body of createRetentionPolicyAssignment method +- headers `CreateRetentionPolicyAssignmentHeaders` + - Headers of createRetentionPolicyAssignment method + + +### Returns + +This function returns a value of type `RetentionPolicyAssignment`. + +Returns a new retention policy assignment object. + + +## Get retention policy assignment + +Retrieves a retention policy assignment. + +This operation is performed by calling function `getRetentionPolicyAssignmentById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-retention-policy-assignments-id/). + + +``` +client.getRetentionPolicyAssignments().getRetentionPolicyAssignmentById(retentionPolicyAssignment.getId()) +``` + +### Arguments + +- retentionPolicyAssignmentId `String` + - The ID of the retention policy assignment. Example: "1233123" +- queryParams `GetRetentionPolicyAssignmentByIdQueryParams` + - Query parameters of getRetentionPolicyAssignmentById method +- headers `GetRetentionPolicyAssignmentByIdHeaders` + - Headers of getRetentionPolicyAssignmentById method + + +### Returns + +This function returns a value of type `RetentionPolicyAssignment`. + +Returns the retention policy assignment object. + + +## Remove retention policy assignment + +Removes a retention policy assignment +applied to content. + +This operation is performed by calling function `deleteRetentionPolicyAssignmentById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-retention-policy-assignments-id/). + + +``` +client.getRetentionPolicyAssignments().deleteRetentionPolicyAssignmentById(retentionPolicyAssignment.getId()) +``` + +### Arguments + +- retentionPolicyAssignmentId `String` + - The ID of the retention policy assignment. Example: "1233123" +- headers `DeleteRetentionPolicyAssignmentByIdHeaders` + - Headers of deleteRetentionPolicyAssignmentById method + + +### Returns + +This function returns a value of type `void`. + +Returns an empty response when the policy assignment +is successfully deleted. + + +## Get files under retention + +Returns a list of files under retention for a retention policy assignment. + +This operation is performed by calling function `getFilesUnderRetentionPolicyAssignment`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-retention-policy-assignments-id-files-under-retention/). + + +``` +client.getRetentionPolicyAssignments().getFilesUnderRetentionPolicyAssignment(retentionPolicyAssignment.getId()) +``` + +### Arguments + +- retentionPolicyAssignmentId `String` + - The ID of the retention policy assignment. Example: "1233123" +- queryParams `GetFilesUnderRetentionPolicyAssignmentQueryParams` + - Query parameters of getFilesUnderRetentionPolicyAssignment method +- headers `GetFilesUnderRetentionPolicyAssignmentHeaders` + - Headers of getFilesUnderRetentionPolicyAssignment method + + +### Returns + +This function returns a value of type `FilesUnderRetention`. + +Returns a list of files under retention that are associated with the +specified retention policy assignment. + + diff --git a/docs/sdkgen/search.md b/docs/sdkgen/search.md new file mode 100644 index 000000000..be7116fff --- /dev/null +++ b/docs/sdkgen/search.md @@ -0,0 +1,71 @@ +# SearchManager + + +- [Query files/folders by metadata](#query-files-folders-by-metadata) +- [Search for content](#search-for-content) + +## Query files/folders by metadata + +Create a search using SQL-like syntax to return items that match specific +metadata. + +By default, this endpoint returns only the most basic info about the items for +which the query matches. To get additional fields for each item, including any +of the metadata, use the `fields` attribute in the query. + +This operation is performed by calling function `searchByMetadataQuery`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-metadata-queries-execute-read/). + + +``` +client.getSearch().searchByMetadataQuery(new MetadataQuery.Builder(searchFrom, "0").query("name = :name AND age < :age AND birthDate >= :birthDate AND countryCode = :countryCode AND sports = :sports").queryParams(mapOf(entryOf("name", "John"), entryOf("age", 50), entryOf("birthDate", "2001-01-01T02:20:10.120Z"), entryOf("countryCode", "US"), entryOf("sports", Arrays.asList("basketball", "tennis")))).build()) +``` + +### Arguments + +- requestBody `MetadataQuery` + - Request body of searchByMetadataQuery method +- headers `SearchByMetadataQueryHeaders` + - Headers of searchByMetadataQuery method + + +### Returns + +This function returns a value of type `MetadataQueryResults`. + +Returns a list of files and folders that match this metadata query. + + +## Search for content + +Searches for files, folders, web links, and shared files across the +users content or across the entire enterprise. + +This operation is performed by calling function `searchForContent`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-search/). + + +``` +client.getSearch().searchForContent(new SearchForContentQueryParams.Builder().ancestorFolderIds(Arrays.asList("0")).mdfilters(Arrays.asList(new MetadataFilter.Builder().scope(MetadataFilterScopeField.ENTERPRISE).templateKey(templateKey).filters(searchFilters).build())).build()) +``` + +### Arguments + +- queryParams `SearchForContentQueryParams` + - Query parameters of searchForContent method +- headers `SearchForContentHeaders` + - Headers of searchForContent method + + +### Returns + +This function returns a value of type `SearchResultsResponse`. + +Returns a collection of search results. If there are no matching +search results, the `entries` array will be empty. + + diff --git a/docs/sdkgen/sessiontermination.md b/docs/sdkgen/sessiontermination.md new file mode 100644 index 000000000..72f701acf --- /dev/null +++ b/docs/sdkgen/sessiontermination.md @@ -0,0 +1,70 @@ +# SessionTerminationManager + + +- [Create jobs to terminate users session](#create-jobs-to-terminate-users-session) +- [Create jobs to terminate user group session](#create-jobs-to-terminate-user-group-session) + +## Create jobs to terminate users session + +Validates the roles and permissions of the user, +and creates asynchronous jobs +to terminate the user's sessions. +Returns the status for the POST request. + +This operation is performed by calling function `terminateUsersSessions`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-users-terminate-sessions/). + + +``` +client.getSessionTermination().terminateUsersSessions(new TerminateUsersSessionsRequestBody(Arrays.asList(getEnvVar("USER_ID")), Arrays.asList(user.getLogin()))) +``` + +### Arguments + +- requestBody `TerminateUsersSessionsRequestBody` + - Request body of terminateUsersSessions method +- headers `TerminateUsersSessionsHeaders` + - Headers of terminateUsersSessions method + + +### Returns + +This function returns a value of type `SessionTerminationMessage`. + +Returns a message about the request status. + + +## Create jobs to terminate user group session + +Validates the roles and permissions of the group, +and creates asynchronous jobs +to terminate the group's sessions. +Returns the status for the POST request. + +This operation is performed by calling function `terminateGroupsSessions`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-groups-terminate-sessions/). + + +``` +client.getSessionTermination().terminateGroupsSessions(new TerminateGroupsSessionsRequestBody(Arrays.asList(group.getId()))) +``` + +### Arguments + +- requestBody `TerminateGroupsSessionsRequestBody` + - Request body of terminateGroupsSessions method +- headers `TerminateGroupsSessionsHeaders` + - Headers of terminateGroupsSessions method + + +### Returns + +This function returns a value of type `SessionTerminationMessage`. + +Returns a message about the request status. + + diff --git a/docs/sdkgen/sharedlinksappitems.md b/docs/sdkgen/sharedlinksappitems.md new file mode 100644 index 000000000..434a25ad7 --- /dev/null +++ b/docs/sdkgen/sharedlinksappitems.md @@ -0,0 +1,35 @@ +# SharedLinksAppItemsManager + + +- [Find app item for shared link](#find-app-item-for-shared-link) + +## Find app item for shared link + +Returns the app item represented by a shared link. + +The link can originate from the current enterprise or another. + +This operation is performed by calling function `findAppItemForSharedLink`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-shared-items--app-items/). + + +``` +client.getSharedLinksAppItems().findAppItemForSharedLink(new FindAppItemForSharedLinkHeaders(String.join("", "shared_link=", appItemSharedLink))) +``` + +### Arguments + +- headers `FindAppItemForSharedLinkHeaders` + - Headers of findAppItemForSharedLink method + + +### Returns + +This function returns a value of type `AppItem`. + +Returns a full app item resource if the shared link is valid and +the user has access to it. + + diff --git a/docs/sdkgen/sharedlinksfiles.md b/docs/sdkgen/sharedlinksfiles.md new file mode 100644 index 000000000..2503d0c77 --- /dev/null +++ b/docs/sdkgen/sharedlinksfiles.md @@ -0,0 +1,181 @@ +# SharedLinksFilesManager + + +- [Find file for shared link](#find-file-for-shared-link) +- [Get shared link for file](#get-shared-link-for-file) +- [Add shared link to file](#add-shared-link-to-file) +- [Update shared link on file](#update-shared-link-on-file) +- [Remove shared link from file](#remove-shared-link-from-file) + +## Find file for shared link + +Returns the file represented by a shared link. + +A shared file can be represented by a shared link, +which can originate within the current enterprise or within another. + +This endpoint allows an application to retrieve information about a +shared file when only given a shared link. + +The `shared_link_permission_options` array field can be returned +by requesting it in the `fields` query parameter. + +This operation is performed by calling function `findFileForSharedLink`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-shared-items/). + + +``` +userClient.getSharedLinksFiles().findFileForSharedLink(new FindFileForSharedLinkQueryParams(), new FindFileForSharedLinkHeaders(String.join("", "shared_link=", fileFromApi.getSharedLink().getUrl(), "&shared_link_password=Secret123@"))) +``` + +### Arguments + +- queryParams `FindFileForSharedLinkQueryParams` + - Query parameters of findFileForSharedLink method +- headers `FindFileForSharedLinkHeaders` + - Headers of findFileForSharedLink method + + +### Returns + +This function returns a value of type `FileFull`. + +Returns a full file resource if the shared link is valid and +the user has access to it. + + +## Get shared link for file + +Gets the information for a shared link on a file. + +This operation is performed by calling function `getSharedLinkForFile`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-files-id--get-shared-link/). + + +``` +client.getSharedLinksFiles().getSharedLinkForFile(fileId, new GetSharedLinkForFileQueryParams("shared_link")) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- queryParams `GetSharedLinkForFileQueryParams` + - Query parameters of getSharedLinkForFile method +- headers `GetSharedLinkForFileHeaders` + - Headers of getSharedLinkForFile method + + +### Returns + +This function returns a value of type `FileFull`. + +Returns the base representation of a file with the +additional shared link information. + + +## Add shared link to file + +Adds a shared link to a file. + +This operation is performed by calling function `addShareLinkToFile`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-files-id--add-shared-link/). + + +``` +client.getSharedLinksFiles().addShareLinkToFile(fileId, new AddShareLinkToFileRequestBody.Builder().sharedLink(new AddShareLinkToFileRequestBodySharedLinkField.Builder().access(AddShareLinkToFileRequestBodySharedLinkAccessField.OPEN).password("Secret123@").build()).build(), new AddShareLinkToFileQueryParams("shared_link")) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- requestBody `AddShareLinkToFileRequestBody` + - Request body of addShareLinkToFile method +- queryParams `AddShareLinkToFileQueryParams` + - Query parameters of addShareLinkToFile method +- headers `AddShareLinkToFileHeaders` + - Headers of addShareLinkToFile method + + +### Returns + +This function returns a value of type `FileFull`. + +Returns the base representation of a file with a new shared +link attached. + + +## Update shared link on file + +Updates a shared link on a file. + +This operation is performed by calling function `updateSharedLinkOnFile`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-files-id--update-shared-link/). + + +``` +client.getSharedLinksFiles().updateSharedLinkOnFile(fileId, new UpdateSharedLinkOnFileRequestBody.Builder().sharedLink(new UpdateSharedLinkOnFileRequestBodySharedLinkField.Builder().access(UpdateSharedLinkOnFileRequestBodySharedLinkAccessField.COLLABORATORS).build()).build(), new UpdateSharedLinkOnFileQueryParams("shared_link")) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- requestBody `UpdateSharedLinkOnFileRequestBody` + - Request body of updateSharedLinkOnFile method +- queryParams `UpdateSharedLinkOnFileQueryParams` + - Query parameters of updateSharedLinkOnFile method +- headers `UpdateSharedLinkOnFileHeaders` + - Headers of updateSharedLinkOnFile method + + +### Returns + +This function returns a value of type `FileFull`. + +Returns a basic representation of the file, with the updated shared +link attached. + + +## Remove shared link from file + +Removes a shared link from a file. + +This operation is performed by calling function `removeSharedLinkFromFile`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-files-id--remove-shared-link/). + + +``` +client.getSharedLinksFiles().removeSharedLinkFromFile(fileId, new RemoveSharedLinkFromFileRequestBody.Builder().sharedLink(null).build(), new RemoveSharedLinkFromFileQueryParams("shared_link")) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- requestBody `RemoveSharedLinkFromFileRequestBody` + - Request body of removeSharedLinkFromFile method +- queryParams `RemoveSharedLinkFromFileQueryParams` + - Query parameters of removeSharedLinkFromFile method +- headers `RemoveSharedLinkFromFileHeaders` + - Headers of removeSharedLinkFromFile method + + +### Returns + +This function returns a value of type `FileFull`. + +Returns a basic representation of a file, with the shared link removed. + + diff --git a/docs/sdkgen/sharedlinksfolders.md b/docs/sdkgen/sharedlinksfolders.md new file mode 100644 index 000000000..7119c05ec --- /dev/null +++ b/docs/sdkgen/sharedlinksfolders.md @@ -0,0 +1,178 @@ +# SharedLinksFoldersManager + + +- [Find folder for shared link](#find-folder-for-shared-link) +- [Get shared link for folder](#get-shared-link-for-folder) +- [Add shared link to folder](#add-shared-link-to-folder) +- [Update shared link on folder](#update-shared-link-on-folder) +- [Remove shared link from folder](#remove-shared-link-from-folder) + +## Find folder for shared link + +Return the folder represented by a shared link. + +A shared folder can be represented by a shared link, +which can originate within the current enterprise or within another. + +This endpoint allows an application to retrieve information about a +shared folder when only given a shared link. + +This operation is performed by calling function `findFolderForSharedLink`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-shared-items--folders/). + + +``` +userClient.getSharedLinksFolders().findFolderForSharedLink(new FindFolderForSharedLinkQueryParams(), new FindFolderForSharedLinkHeaders(String.join("", "shared_link=", folderFromApi.getSharedLink().getUrl(), "&shared_link_password=Secret123@"))) +``` + +### Arguments + +- queryParams `FindFolderForSharedLinkQueryParams` + - Query parameters of findFolderForSharedLink method +- headers `FindFolderForSharedLinkHeaders` + - Headers of findFolderForSharedLink method + + +### Returns + +This function returns a value of type `FolderFull`. + +Returns a full folder resource if the shared link is valid and +the user has access to it. + + +## Get shared link for folder + +Gets the information for a shared link on a folder. + +This operation is performed by calling function `getSharedLinkForFolder`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-folders-id--get-shared-link/). + + +``` +client.getSharedLinksFolders().getSharedLinkForFolder(folder.getId(), new GetSharedLinkForFolderQueryParams("shared_link")) +``` + +### Arguments + +- folderId `String` + - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" +- queryParams `GetSharedLinkForFolderQueryParams` + - Query parameters of getSharedLinkForFolder method +- headers `GetSharedLinkForFolderHeaders` + - Headers of getSharedLinkForFolder method + + +### Returns + +This function returns a value of type `FolderFull`. + +Returns the base representation of a folder with the +additional shared link information. + + +## Add shared link to folder + +Adds a shared link to a folder. + +This operation is performed by calling function `addShareLinkToFolder`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-folders-id--add-shared-link/). + + +``` +client.getSharedLinksFolders().addShareLinkToFolder(folder.getId(), new AddShareLinkToFolderRequestBody.Builder().sharedLink(new AddShareLinkToFolderRequestBodySharedLinkField.Builder().access(AddShareLinkToFolderRequestBodySharedLinkAccessField.OPEN).password("Secret123@").build()).build(), new AddShareLinkToFolderQueryParams("shared_link")) +``` + +### Arguments + +- folderId `String` + - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" +- requestBody `AddShareLinkToFolderRequestBody` + - Request body of addShareLinkToFolder method +- queryParams `AddShareLinkToFolderQueryParams` + - Query parameters of addShareLinkToFolder method +- headers `AddShareLinkToFolderHeaders` + - Headers of addShareLinkToFolder method + + +### Returns + +This function returns a value of type `FolderFull`. + +Returns the base representation of a folder with a new shared +link attached. + + +## Update shared link on folder + +Updates a shared link on a folder. + +This operation is performed by calling function `updateSharedLinkOnFolder`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-folders-id--update-shared-link/). + + +``` +client.getSharedLinksFolders().updateSharedLinkOnFolder(folder.getId(), new UpdateSharedLinkOnFolderRequestBody.Builder().sharedLink(new UpdateSharedLinkOnFolderRequestBodySharedLinkField.Builder().access(UpdateSharedLinkOnFolderRequestBodySharedLinkAccessField.COLLABORATORS).build()).build(), new UpdateSharedLinkOnFolderQueryParams("shared_link")) +``` + +### Arguments + +- folderId `String` + - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" +- requestBody `UpdateSharedLinkOnFolderRequestBody` + - Request body of updateSharedLinkOnFolder method +- queryParams `UpdateSharedLinkOnFolderQueryParams` + - Query parameters of updateSharedLinkOnFolder method +- headers `UpdateSharedLinkOnFolderHeaders` + - Headers of updateSharedLinkOnFolder method + + +### Returns + +This function returns a value of type `FolderFull`. + +Returns a basic representation of the folder, with the updated shared +link attached. + + +## Remove shared link from folder + +Removes a shared link from a folder. + +This operation is performed by calling function `removeSharedLinkFromFolder`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-folders-id--remove-shared-link/). + + +``` +client.getSharedLinksFolders().removeSharedLinkFromFolder(folder.getId(), new RemoveSharedLinkFromFolderRequestBody.Builder().sharedLink(null).build(), new RemoveSharedLinkFromFolderQueryParams("shared_link")) +``` + +### Arguments + +- folderId `String` + - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" +- requestBody `RemoveSharedLinkFromFolderRequestBody` + - Request body of removeSharedLinkFromFolder method +- queryParams `RemoveSharedLinkFromFolderQueryParams` + - Query parameters of removeSharedLinkFromFolder method +- headers `RemoveSharedLinkFromFolderHeaders` + - Headers of removeSharedLinkFromFolder method + + +### Returns + +This function returns a value of type `FolderFull`. + +Returns a basic representation of a folder, with the shared link removed. + + diff --git a/docs/sdkgen/sharedlinksweblinks.md b/docs/sdkgen/sharedlinksweblinks.md new file mode 100644 index 000000000..e192a73fb --- /dev/null +++ b/docs/sdkgen/sharedlinksweblinks.md @@ -0,0 +1,179 @@ +# SharedLinksWebLinksManager + + +- [Find web link for shared link](#find-web-link-for-shared-link) +- [Get shared link for web link](#get-shared-link-for-web-link) +- [Add shared link to web link](#add-shared-link-to-web-link) +- [Update shared link on web link](#update-shared-link-on-web-link) +- [Remove shared link from web link](#remove-shared-link-from-web-link) + +## Find web link for shared link + +Returns the web link represented by a shared link. + +A shared web link can be represented by a shared link, +which can originate within the current enterprise or within another. + +This endpoint allows an application to retrieve information about a +shared web link when only given a shared link. + +This operation is performed by calling function `findWebLinkForSharedLink`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-shared-items--web-links/). + + +``` +userClient.getSharedLinksWebLinks().findWebLinkForSharedLink(new FindWebLinkForSharedLinkQueryParams(), new FindWebLinkForSharedLinkHeaders(String.join("", "shared_link=", webLinkFromApi.getSharedLink().getUrl(), "&shared_link_password=Secret123@"))) +``` + +### Arguments + +- queryParams `FindWebLinkForSharedLinkQueryParams` + - Query parameters of findWebLinkForSharedLink method +- headers `FindWebLinkForSharedLinkHeaders` + - Headers of findWebLinkForSharedLink method + + +### Returns + +This function returns a value of type `WebLink`. + +Returns a full web link resource if the shared link is valid and +the user has access to it. + + +## Get shared link for web link + +Gets the information for a shared link on a web link. + +This operation is performed by calling function `getSharedLinkForWebLink`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-web-links-id--get-shared-link/). + + +``` +client.getSharedLinksWebLinks().getSharedLinkForWebLink(webLinkId, new GetSharedLinkForWebLinkQueryParams("shared_link")) +``` + +### Arguments + +- webLinkId `String` + - The ID of the web link. Example: "12345" +- queryParams `GetSharedLinkForWebLinkQueryParams` + - Query parameters of getSharedLinkForWebLink method +- headers `GetSharedLinkForWebLinkHeaders` + - Headers of getSharedLinkForWebLink method + + +### Returns + +This function returns a value of type `WebLink`. + +Returns the base representation of a web link with the +additional shared link information. + + +## Add shared link to web link + +Adds a shared link to a web link. + +This operation is performed by calling function `addShareLinkToWebLink`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-web-links-id--add-shared-link/). + + +``` +client.getSharedLinksWebLinks().addShareLinkToWebLink(webLinkId, new AddShareLinkToWebLinkRequestBody.Builder().sharedLink(new AddShareLinkToWebLinkRequestBodySharedLinkField.Builder().access(AddShareLinkToWebLinkRequestBodySharedLinkAccessField.OPEN).password("Secret123@").build()).build(), new AddShareLinkToWebLinkQueryParams("shared_link")) +``` + +### Arguments + +- webLinkId `String` + - The ID of the web link. Example: "12345" +- requestBody `AddShareLinkToWebLinkRequestBody` + - Request body of addShareLinkToWebLink method +- queryParams `AddShareLinkToWebLinkQueryParams` + - Query parameters of addShareLinkToWebLink method +- headers `AddShareLinkToWebLinkHeaders` + - Headers of addShareLinkToWebLink method + + +### Returns + +This function returns a value of type `WebLink`. + +Returns the base representation of a web link with a new shared +link attached. + + +## Update shared link on web link + +Updates a shared link on a web link. + +This operation is performed by calling function `updateSharedLinkOnWebLink`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-web-links-id--update-shared-link/). + + +``` +client.getSharedLinksWebLinks().updateSharedLinkOnWebLink(webLinkId, new UpdateSharedLinkOnWebLinkRequestBody.Builder().sharedLink(new UpdateSharedLinkOnWebLinkRequestBodySharedLinkField.Builder().access(UpdateSharedLinkOnWebLinkRequestBodySharedLinkAccessField.COLLABORATORS).build()).build(), new UpdateSharedLinkOnWebLinkQueryParams("shared_link")) +``` + +### Arguments + +- webLinkId `String` + - The ID of the web link. Example: "12345" +- requestBody `UpdateSharedLinkOnWebLinkRequestBody` + - Request body of updateSharedLinkOnWebLink method +- queryParams `UpdateSharedLinkOnWebLinkQueryParams` + - Query parameters of updateSharedLinkOnWebLink method +- headers `UpdateSharedLinkOnWebLinkHeaders` + - Headers of updateSharedLinkOnWebLink method + + +### Returns + +This function returns a value of type `WebLink`. + +Returns a basic representation of the web link, with the updated shared +link attached. + + +## Remove shared link from web link + +Removes a shared link from a web link. + +This operation is performed by calling function `removeSharedLinkFromWebLink`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-web-links-id--remove-shared-link/). + + +``` +client.getSharedLinksWebLinks().removeSharedLinkFromWebLink(webLinkId, new RemoveSharedLinkFromWebLinkRequestBody.Builder().sharedLink(null).build(), new RemoveSharedLinkFromWebLinkQueryParams("shared_link")) +``` + +### Arguments + +- webLinkId `String` + - The ID of the web link. Example: "12345" +- requestBody `RemoveSharedLinkFromWebLinkRequestBody` + - Request body of removeSharedLinkFromWebLink method +- queryParams `RemoveSharedLinkFromWebLinkQueryParams` + - Query parameters of removeSharedLinkFromWebLink method +- headers `RemoveSharedLinkFromWebLinkHeaders` + - Headers of removeSharedLinkFromWebLink method + + +### Returns + +This function returns a value of type `WebLink`. + +Returns a basic representation of a web link, with the +shared link removed. + + diff --git a/docs/sdkgen/shieldinformationbarrierreports.md b/docs/sdkgen/shieldinformationbarrierreports.md new file mode 100644 index 000000000..542409705 --- /dev/null +++ b/docs/sdkgen/shieldinformationbarrierreports.md @@ -0,0 +1,94 @@ +# ShieldInformationBarrierReportsManager + + +- [List shield information barrier reports](#list-shield-information-barrier-reports) +- [Create shield information barrier report](#create-shield-information-barrier-report) +- [Get shield information barrier report by ID](#get-shield-information-barrier-report-by-id) + +## List shield information barrier reports + +Lists shield information barrier reports. + +This operation is performed by calling function `getShieldInformationBarrierReports`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-shield-information-barrier-reports/). + + +``` +client.getShieldInformationBarrierReports().getShieldInformationBarrierReports(new GetShieldInformationBarrierReportsQueryParams(barrierId)) +``` + +### Arguments + +- queryParams `GetShieldInformationBarrierReportsQueryParams` + - Query parameters of getShieldInformationBarrierReports method +- headers `GetShieldInformationBarrierReportsHeaders` + - Headers of getShieldInformationBarrierReports method + + +### Returns + +This function returns a value of type `ShieldInformationBarrierReports`. + +Returns a paginated list of shield information barrier report objects. + + +## Create shield information barrier report + +Creates a shield information barrier report for a given barrier. + +This operation is performed by calling function `createShieldInformationBarrierReport`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-shield-information-barrier-reports/). + + +``` +client.getShieldInformationBarrierReports().createShieldInformationBarrierReport(new ShieldInformationBarrierReference.Builder().shieldInformationBarrier(new ShieldInformationBarrierBase.Builder().id(barrierId).type(ShieldInformationBarrierBaseTypeField.SHIELD_INFORMATION_BARRIER).build()).build()) +``` + +### Arguments + +- requestBody `ShieldInformationBarrierReference` + - Request body of createShieldInformationBarrierReport method +- headers `CreateShieldInformationBarrierReportHeaders` + - Headers of createShieldInformationBarrierReport method + + +### Returns + +This function returns a value of type `ShieldInformationBarrierReport`. + +Returns the shield information barrier report information object. + + +## Get shield information barrier report by ID + +Retrieves a shield information barrier report by its ID. + +This operation is performed by calling function `getShieldInformationBarrierReportById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-shield-information-barrier-reports-id/). + + +``` +client.getShieldInformationBarrierReports().getShieldInformationBarrierReportById(createdReport.getId()) +``` + +### Arguments + +- shieldInformationBarrierReportId `String` + - The ID of the shield information barrier Report. Example: "3423" +- headers `GetShieldInformationBarrierReportByIdHeaders` + - Headers of getShieldInformationBarrierReportById method + + +### Returns + +This function returns a value of type `ShieldInformationBarrierReport`. + +Returns the shield information barrier report object. + + diff --git a/docs/sdkgen/shieldinformationbarriers.md b/docs/sdkgen/shieldinformationbarriers.md new file mode 100644 index 000000000..fe561fbb7 --- /dev/null +++ b/docs/sdkgen/shieldinformationbarriers.md @@ -0,0 +1,129 @@ +# ShieldInformationBarriersManager + + +- [Get shield information barrier with specified ID](#get-shield-information-barrier-with-specified-id) +- [Add changed status of shield information barrier with specified ID](#add-changed-status-of-shield-information-barrier-with-specified-id) +- [List shield information barriers](#list-shield-information-barriers) +- [Create shield information barrier](#create-shield-information-barrier) + +## Get shield information barrier with specified ID + +Get shield information barrier based on provided ID. + +This operation is performed by calling function `getShieldInformationBarrierById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-shield-information-barriers-id/). + + +``` +client.getShieldInformationBarriers().getShieldInformationBarrierById(barrierId) +``` + +### Arguments + +- shieldInformationBarrierId `String` + - The ID of the shield information barrier. Example: "1910967" +- headers `GetShieldInformationBarrierByIdHeaders` + - Headers of getShieldInformationBarrierById method + + +### Returns + +This function returns a value of type `ShieldInformationBarrier`. + +Returns the shield information barrier object. + + +## Add changed status of shield information barrier with specified ID + +Change status of shield information barrier with the specified ID. + +This operation is performed by calling function `updateShieldInformationBarrierStatus`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-shield-information-barriers-change-status/). + + +``` +client.getShieldInformationBarriers().updateShieldInformationBarrierStatus(new UpdateShieldInformationBarrierStatusRequestBody(barrierId, UpdateShieldInformationBarrierStatusRequestBodyStatusField.DISABLED)) +``` + +### Arguments + +- requestBody `UpdateShieldInformationBarrierStatusRequestBody` + - Request body of updateShieldInformationBarrierStatus method +- headers `UpdateShieldInformationBarrierStatusHeaders` + - Headers of updateShieldInformationBarrierStatus method + + +### Returns + +This function returns a value of type `ShieldInformationBarrier`. + +Returns the updated shield information barrier object. + + +## List shield information barriers + +Retrieves a list of shield information barrier objects +for the enterprise of JWT. + +This operation is performed by calling function `getShieldInformationBarriers`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-shield-information-barriers/). + + +``` +client.getShieldInformationBarriers().getShieldInformationBarriers() +``` + +### Arguments + +- queryParams `GetShieldInformationBarriersQueryParams` + - Query parameters of getShieldInformationBarriers method +- headers `GetShieldInformationBarriersHeaders` + - Headers of getShieldInformationBarriers method + + +### Returns + +This function returns a value of type `ShieldInformationBarriers`. + +Returns a paginated list of +shield information barrier objects, +empty list if currently no barrier. + + +## Create shield information barrier + +Creates a shield information barrier to +separate individuals/groups within the same +firm and prevents confidential information passing between them. + +This operation is performed by calling function `createShieldInformationBarrier`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-shield-information-barriers/). + + +``` +client.getShieldInformationBarriers().createShieldInformationBarrier(new CreateShieldInformationBarrierRequestBody(new EnterpriseBase.Builder().id(enterpriseId).build())) +``` + +### Arguments + +- requestBody `CreateShieldInformationBarrierRequestBody` + - Request body of createShieldInformationBarrier method +- headers `CreateShieldInformationBarrierHeaders` + - Headers of createShieldInformationBarrier method + + +### Returns + +This function returns a value of type `ShieldInformationBarrier`. + +Returns a new shield information barrier object. + + diff --git a/docs/sdkgen/shieldinformationbarriersegmentmembers.md b/docs/sdkgen/shieldinformationbarriersegmentmembers.md new file mode 100644 index 000000000..5ff9dd6c9 --- /dev/null +++ b/docs/sdkgen/shieldinformationbarriersegmentmembers.md @@ -0,0 +1,129 @@ +# ShieldInformationBarrierSegmentMembersManager + + +- [Get shield information barrier segment member by ID](#get-shield-information-barrier-segment-member-by-id) +- [Delete shield information barrier segment member by ID](#delete-shield-information-barrier-segment-member-by-id) +- [List shield information barrier segment members](#list-shield-information-barrier-segment-members) +- [Create shield information barrier segment member](#create-shield-information-barrier-segment-member) + +## Get shield information barrier segment member by ID + +Retrieves a shield information barrier +segment member by its ID. + +This operation is performed by calling function `getShieldInformationBarrierSegmentMemberById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-shield-information-barrier-segment-members-id/). + + +``` +client.getShieldInformationBarrierSegmentMembers().getShieldInformationBarrierSegmentMemberById(segmentMember.getId()) +``` + +### Arguments + +- shieldInformationBarrierSegmentMemberId `String` + - The ID of the shield information barrier segment Member. Example: "7815" +- headers `GetShieldInformationBarrierSegmentMemberByIdHeaders` + - Headers of getShieldInformationBarrierSegmentMemberById method + + +### Returns + +This function returns a value of type `ShieldInformationBarrierSegmentMember`. + +Returns the shield information barrier segment member object. + + +## Delete shield information barrier segment member by ID + +Deletes a shield information barrier +segment member based on provided ID. + +This operation is performed by calling function `deleteShieldInformationBarrierSegmentMemberById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-shield-information-barrier-segment-members-id/). + + +``` +client.getShieldInformationBarrierSegmentMembers().deleteShieldInformationBarrierSegmentMemberById(segmentMember.getId()) +``` + +### Arguments + +- shieldInformationBarrierSegmentMemberId `String` + - The ID of the shield information barrier segment Member. Example: "7815" +- headers `DeleteShieldInformationBarrierSegmentMemberByIdHeaders` + - Headers of deleteShieldInformationBarrierSegmentMemberById method + + +### Returns + +This function returns a value of type `void`. + +Returns an empty response if the +segment member was deleted successfully. + + +## List shield information barrier segment members + +Lists shield information barrier segment members +based on provided segment IDs. + +This operation is performed by calling function `getShieldInformationBarrierSegmentMembers`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-shield-information-barrier-segment-members/). + + +``` +client.getShieldInformationBarrierSegmentMembers().getShieldInformationBarrierSegmentMembers(new GetShieldInformationBarrierSegmentMembersQueryParams(segment.getId())) +``` + +### Arguments + +- queryParams `GetShieldInformationBarrierSegmentMembersQueryParams` + - Query parameters of getShieldInformationBarrierSegmentMembers method +- headers `GetShieldInformationBarrierSegmentMembersHeaders` + - Headers of getShieldInformationBarrierSegmentMembers method + + +### Returns + +This function returns a value of type `ShieldInformationBarrierSegmentMembers`. + +Returns a paginated list of +shield information barrier segment member objects. + + +## Create shield information barrier segment member + +Creates a new shield information barrier segment member. + +This operation is performed by calling function `createShieldInformationBarrierSegmentMember`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-shield-information-barrier-segment-members/). + + +``` +client.getShieldInformationBarrierSegmentMembers().createShieldInformationBarrierSegmentMember(new CreateShieldInformationBarrierSegmentMemberRequestBody(new CreateShieldInformationBarrierSegmentMemberRequestBodyShieldInformationBarrierSegmentField.Builder().id(segment.getId()).type(CreateShieldInformationBarrierSegmentMemberRequestBodyShieldInformationBarrierSegmentTypeField.SHIELD_INFORMATION_BARRIER_SEGMENT).build(), new UserBase(getEnvVar("USER_ID")))) +``` + +### Arguments + +- requestBody `CreateShieldInformationBarrierSegmentMemberRequestBody` + - Request body of createShieldInformationBarrierSegmentMember method +- headers `CreateShieldInformationBarrierSegmentMemberHeaders` + - Headers of createShieldInformationBarrierSegmentMember method + + +### Returns + +This function returns a value of type `ShieldInformationBarrierSegmentMember`. + +Returns a new shield information barrier segment member object. + + diff --git a/docs/sdkgen/shieldinformationbarriersegmentrestrictions.md b/docs/sdkgen/shieldinformationbarriersegmentrestrictions.md new file mode 100644 index 000000000..ab9fbb2bc --- /dev/null +++ b/docs/sdkgen/shieldinformationbarriersegmentrestrictions.md @@ -0,0 +1,131 @@ +# ShieldInformationBarrierSegmentRestrictionsManager + + +- [Get shield information barrier segment restriction by ID](#get-shield-information-barrier-segment-restriction-by-id) +- [Delete shield information barrier segment restriction by ID](#delete-shield-information-barrier-segment-restriction-by-id) +- [List shield information barrier segment restrictions](#list-shield-information-barrier-segment-restrictions) +- [Create shield information barrier segment restriction](#create-shield-information-barrier-segment-restriction) + +## Get shield information barrier segment restriction by ID + +Retrieves a shield information barrier segment +restriction based on provided ID. + +This operation is performed by calling function `getShieldInformationBarrierSegmentRestrictionById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-shield-information-barrier-segment-restrictions-id/). + + +``` +client.getShieldInformationBarrierSegmentRestrictions().getShieldInformationBarrierSegmentRestrictionById(segmentRestrictionId) +``` + +### Arguments + +- shieldInformationBarrierSegmentRestrictionId `String` + - The ID of the shield information barrier segment Restriction. Example: "4563" +- headers `GetShieldInformationBarrierSegmentRestrictionByIdHeaders` + - Headers of getShieldInformationBarrierSegmentRestrictionById method + + +### Returns + +This function returns a value of type `ShieldInformationBarrierSegmentRestriction`. + +Returns the shield information barrier segment +restriction object. + + +## Delete shield information barrier segment restriction by ID + +Delete shield information barrier segment restriction +based on provided ID. + +This operation is performed by calling function `deleteShieldInformationBarrierSegmentRestrictionById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-shield-information-barrier-segment-restrictions-id/). + + +``` +client.getShieldInformationBarrierSegmentRestrictions().deleteShieldInformationBarrierSegmentRestrictionById(segmentRestrictionId) +``` + +### Arguments + +- shieldInformationBarrierSegmentRestrictionId `String` + - The ID of the shield information barrier segment Restriction. Example: "4563" +- headers `DeleteShieldInformationBarrierSegmentRestrictionByIdHeaders` + - Headers of deleteShieldInformationBarrierSegmentRestrictionById method + + +### Returns + +This function returns a value of type `void`. + +Empty body in response. + + +## List shield information barrier segment restrictions + +Lists shield information barrier segment restrictions +based on provided segment ID. + +This operation is performed by calling function `getShieldInformationBarrierSegmentRestrictions`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-shield-information-barrier-segment-restrictions/). + + +``` +client.getShieldInformationBarrierSegmentRestrictions().getShieldInformationBarrierSegmentRestrictions(new GetShieldInformationBarrierSegmentRestrictionsQueryParams(segmentId)) +``` + +### Arguments + +- queryParams `GetShieldInformationBarrierSegmentRestrictionsQueryParams` + - Query parameters of getShieldInformationBarrierSegmentRestrictions method +- headers `GetShieldInformationBarrierSegmentRestrictionsHeaders` + - Headers of getShieldInformationBarrierSegmentRestrictions method + + +### Returns + +This function returns a value of type `ShieldInformationBarrierSegmentRestrictions`. + +Returns a paginated list of +shield information barrier segment restriction objects. + + +## Create shield information barrier segment restriction + +Creates a shield information barrier +segment restriction object. + +This operation is performed by calling function `createShieldInformationBarrierSegmentRestriction`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-shield-information-barrier-segment-restrictions/). + + +``` +client.getShieldInformationBarrierSegmentRestrictions().createShieldInformationBarrierSegmentRestriction(new CreateShieldInformationBarrierSegmentRestrictionRequestBody.Builder(new CreateShieldInformationBarrierSegmentRestrictionRequestBodyShieldInformationBarrierSegmentField.Builder().id(segmentId).type(CreateShieldInformationBarrierSegmentRestrictionRequestBodyShieldInformationBarrierSegmentTypeField.SHIELD_INFORMATION_BARRIER_SEGMENT).build(), new CreateShieldInformationBarrierSegmentRestrictionRequestBodyRestrictedSegmentField.Builder().id(segmentToRestrictId).type(CreateShieldInformationBarrierSegmentRestrictionRequestBodyRestrictedSegmentTypeField.SHIELD_INFORMATION_BARRIER_SEGMENT).build()).type(CreateShieldInformationBarrierSegmentRestrictionRequestBodyTypeField.SHIELD_INFORMATION_BARRIER_SEGMENT_RESTRICTION).build()) +``` + +### Arguments + +- requestBody `CreateShieldInformationBarrierSegmentRestrictionRequestBody` + - Request body of createShieldInformationBarrierSegmentRestriction method +- headers `CreateShieldInformationBarrierSegmentRestrictionHeaders` + - Headers of createShieldInformationBarrierSegmentRestriction method + + +### Returns + +This function returns a value of type `ShieldInformationBarrierSegmentRestriction`. + +Returns the newly created Shield +Information Barrier Segment Restriction object. + + diff --git a/docs/sdkgen/shieldinformationbarriersegments.md b/docs/sdkgen/shieldinformationbarriersegments.md new file mode 100644 index 000000000..99af74127 --- /dev/null +++ b/docs/sdkgen/shieldinformationbarriersegments.md @@ -0,0 +1,158 @@ +# ShieldInformationBarrierSegmentsManager + + +- [Get shield information barrier segment with specified ID](#get-shield-information-barrier-segment-with-specified-id) +- [Delete shield information barrier segment](#delete-shield-information-barrier-segment) +- [Update shield information barrier segment with specified ID](#update-shield-information-barrier-segment-with-specified-id) +- [List shield information barrier segments](#list-shield-information-barrier-segments) +- [Create shield information barrier segment](#create-shield-information-barrier-segment) + +## Get shield information barrier segment with specified ID + +Retrieves shield information barrier segment based on provided ID.. + +This operation is performed by calling function `getShieldInformationBarrierSegmentById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-shield-information-barrier-segments-id/). + + +``` +client.getShieldInformationBarrierSegments().getShieldInformationBarrierSegmentById(segmentId) +``` + +### Arguments + +- shieldInformationBarrierSegmentId `String` + - The ID of the shield information barrier segment. Example: "3423" +- headers `GetShieldInformationBarrierSegmentByIdHeaders` + - Headers of getShieldInformationBarrierSegmentById method + + +### Returns + +This function returns a value of type `ShieldInformationBarrierSegment`. + +Returns the shield information barrier segment object. + + +## Delete shield information barrier segment + +Deletes the shield information barrier segment +based on provided ID. + +This operation is performed by calling function `deleteShieldInformationBarrierSegmentById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-shield-information-barrier-segments-id/). + + +``` +client.getShieldInformationBarrierSegments().deleteShieldInformationBarrierSegmentById(segmentId) +``` + +### Arguments + +- shieldInformationBarrierSegmentId `String` + - The ID of the shield information barrier segment. Example: "3423" +- headers `DeleteShieldInformationBarrierSegmentByIdHeaders` + - Headers of deleteShieldInformationBarrierSegmentById method + + +### Returns + +This function returns a value of type `void`. + +Empty body in response. + + +## Update shield information barrier segment with specified ID + +Updates the shield information barrier segment based on provided ID.. + +This operation is performed by calling function `updateShieldInformationBarrierSegmentById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-shield-information-barrier-segments-id/). + + +``` +client.getShieldInformationBarrierSegments().updateShieldInformationBarrierSegmentById(segmentId, new UpdateShieldInformationBarrierSegmentByIdRequestBody.Builder().description(updatedSegmentDescription).build()) +``` + +### Arguments + +- shieldInformationBarrierSegmentId `String` + - The ID of the shield information barrier segment. Example: "3423" +- requestBody `UpdateShieldInformationBarrierSegmentByIdRequestBody` + - Request body of updateShieldInformationBarrierSegmentById method +- headers `UpdateShieldInformationBarrierSegmentByIdHeaders` + - Headers of updateShieldInformationBarrierSegmentById method + + +### Returns + +This function returns a value of type `ShieldInformationBarrierSegment`. + +Returns the updated shield information barrier segment object. + + +## List shield information barrier segments + +Retrieves a list of shield information barrier segment objects +for the specified Information Barrier ID. + +This operation is performed by calling function `getShieldInformationBarrierSegments`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-shield-information-barrier-segments/). + + +``` +client.getShieldInformationBarrierSegments().getShieldInformationBarrierSegments(new GetShieldInformationBarrierSegmentsQueryParams(barrierId)) +``` + +### Arguments + +- queryParams `GetShieldInformationBarrierSegmentsQueryParams` + - Query parameters of getShieldInformationBarrierSegments method +- headers `GetShieldInformationBarrierSegmentsHeaders` + - Headers of getShieldInformationBarrierSegments method + + +### Returns + +This function returns a value of type `ShieldInformationBarrierSegments`. + +Returns a paginated list of shield information barrier segment objects. + + +## Create shield information barrier segment + +Creates a shield information barrier segment. + +This operation is performed by calling function `createShieldInformationBarrierSegment`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-shield-information-barrier-segments/). + + +``` +client.getShieldInformationBarrierSegments().createShieldInformationBarrierSegment(new CreateShieldInformationBarrierSegmentRequestBody.Builder(new ShieldInformationBarrierBase.Builder().id(barrierId).type(ShieldInformationBarrierBaseTypeField.SHIELD_INFORMATION_BARRIER).build(), segmentName).description(segmentDescription).build()) +``` + +### Arguments + +- requestBody `CreateShieldInformationBarrierSegmentRequestBody` + - Request body of createShieldInformationBarrierSegment method +- headers `CreateShieldInformationBarrierSegmentHeaders` + - Headers of createShieldInformationBarrierSegment method + + +### Returns + +This function returns a value of type `ShieldInformationBarrierSegment`. + +Returns a new shield information barrier segment object. + + diff --git a/docs/sdkgen/shieldlists.md b/docs/sdkgen/shieldlists.md new file mode 100644 index 000000000..0be407ce9 --- /dev/null +++ b/docs/sdkgen/shieldlists.md @@ -0,0 +1,154 @@ +# ShieldListsManager + + +- [Get all shield lists in enterprise](#get-all-shield-lists-in-enterprise) +- [Create shield list](#create-shield-list) +- [Get single shield list by shield list id](#get-single-shield-list-by-shield-list-id) +- [Delete single shield list by shield list id](#delete-single-shield-list-by-shield-list-id) +- [Update shield list](#update-shield-list) + +## Get all shield lists in enterprise + +Retrieves all shield lists in the enterprise. + +This operation is performed by calling function `getShieldListsV2025R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2025.0/get-shield-lists/). + + +``` +client.getShieldLists().getShieldListsV2025R0() +``` + +### Arguments + +- headers `GetShieldListsV2025R0Headers` + - Headers of getShieldListsV2025R0 method + + +### Returns + +This function returns a value of type `ShieldListsV2025R0`. + +Returns the list of shield list objects. + + +## Create shield list + +Creates a shield list. + +This operation is performed by calling function `createShieldListV2025R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2025.0/post-shield-lists/). + + +``` +client.getShieldLists().createShieldListV2025R0(new ShieldListsCreateV2025R0.Builder(shieldListCountryName, new ShieldListContentCountryV2025R0.Builder(Arrays.asList("US", "PL")).type(ShieldListContentCountryV2025R0TypeField.COUNTRY).build()).description("A list of things that are shielded").build()) +``` + +### Arguments + +- requestBody `ShieldListsCreateV2025R0` + - Request body of createShieldListV2025R0 method +- headers `CreateShieldListV2025R0Headers` + - Headers of createShieldListV2025R0 method + + +### Returns + +This function returns a value of type `ShieldListV2025R0`. + +Returns the shield list object. + + +## Get single shield list by shield list id + +Retrieves a single shield list by its ID. + +This operation is performed by calling function `getShieldListByIdV2025R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2025.0/get-shield-lists-id/). + + +``` +client.getShieldLists().getShieldListByIdV2025R0(shieldListCountry.getId()) +``` + +### Arguments + +- shieldListId `String` + - The unique identifier that represents a shield list. The ID for any Shield List can be determined by the response from the endpoint fetching all shield lists for the enterprise. Example: "90fb0e17-c332-40ed-b4f9-fa8908fbbb24 " +- headers `GetShieldListByIdV2025R0Headers` + - Headers of getShieldListByIdV2025R0 method + + +### Returns + +This function returns a value of type `ShieldListV2025R0`. + +Returns the shield list object. + + +## Delete single shield list by shield list id + +Delete a single shield list by its ID. + +This operation is performed by calling function `deleteShieldListByIdV2025R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2025.0/delete-shield-lists-id/). + + +``` +client.getShieldLists().deleteShieldListByIdV2025R0(shieldListCountry.getId()) +``` + +### Arguments + +- shieldListId `String` + - The unique identifier that represents a shield list. The ID for any Shield List can be determined by the response from the endpoint fetching all shield lists for the enterprise. Example: "90fb0e17-c332-40ed-b4f9-fa8908fbbb24 " +- headers `DeleteShieldListByIdV2025R0Headers` + - Headers of deleteShieldListByIdV2025R0 method + + +### Returns + +This function returns a value of type `void`. + +Shield List correctly removed. No content in response. + + +## Update shield list + +Updates a shield list. + +This operation is performed by calling function `updateShieldListByIdV2025R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2025.0/put-shield-lists-id/). + + +``` +client.getShieldLists().updateShieldListByIdV2025R0(shieldListCountry.getId(), new ShieldListsUpdateV2025R0.Builder(shieldListCountryName, new ShieldListContentCountryV2025R0.Builder(Arrays.asList("US")).type(ShieldListContentCountryV2025R0TypeField.COUNTRY).build()).description("Updated description").build()) +``` + +### Arguments + +- shieldListId `String` + - The unique identifier that represents a shield list. The ID for any Shield List can be determined by the response from the endpoint fetching all shield lists for the enterprise. Example: "90fb0e17-c332-40ed-b4f9-fa8908fbbb24 " +- requestBody `ShieldListsUpdateV2025R0` + - Request body of updateShieldListByIdV2025R0 method +- headers `UpdateShieldListByIdV2025R0Headers` + - Headers of updateShieldListByIdV2025R0 method + + +### Returns + +This function returns a value of type `ShieldListV2025R0`. + +Returns the shield list object. + + diff --git a/docs/sdkgen/signrequests.md b/docs/sdkgen/signrequests.md new file mode 100644 index 000000000..c9227c875 --- /dev/null +++ b/docs/sdkgen/signrequests.md @@ -0,0 +1,154 @@ +# SignRequestsManager + + +- [Cancel Box Sign request](#cancel-box-sign-request) +- [Resend Box Sign request](#resend-box-sign-request) +- [Get Box Sign request by ID](#get-box-sign-request-by-id) +- [List Box Sign requests](#list-box-sign-requests) +- [Create Box Sign request](#create-box-sign-request) + +## Cancel Box Sign request + +Cancels a sign request. + +This operation is performed by calling function `cancelSignRequest`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-sign-requests-id-cancel/). + + +``` +client.getSignRequests().cancelSignRequest(createdSignRequest.getId()) +``` + +### Arguments + +- signRequestId `String` + - The ID of the signature request. Example: "33243242" +- headers `CancelSignRequestHeaders` + - Headers of cancelSignRequest method + + +### Returns + +This function returns a value of type `SignRequest`. + +Returns a Sign Request object. + + +## Resend Box Sign request + +Resends a signature request email to all outstanding signers. + +This operation is performed by calling function `resendSignRequest`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-sign-requests-id-resend/). + +*Currently we don't have an example for calling `resendSignRequest` in integration tests* + +### Arguments + +- signRequestId `String` + - The ID of the signature request. Example: "33243242" +- headers `ResendSignRequestHeaders` + - Headers of resendSignRequest method + + +### Returns + +This function returns a value of type `void`. + +Returns an empty response when the API call was successful. +The email notifications will be sent asynchronously. + + +## Get Box Sign request by ID + +Gets a sign request by ID. + +This operation is performed by calling function `getSignRequestById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-sign-requests-id/). + + +``` +client.getSignRequests().getSignRequestById(createdSignRequest.getId()) +``` + +### Arguments + +- signRequestId `String` + - The ID of the signature request. Example: "33243242" +- headers `GetSignRequestByIdHeaders` + - Headers of getSignRequestById method + + +### Returns + +This function returns a value of type `SignRequest`. + +Returns a signature request. + + +## List Box Sign requests + +Gets signature requests created by a user. If the `sign_files` and/or +`parent_folder` are deleted, the signature request will not return in the list. + +This operation is performed by calling function `getSignRequests`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-sign-requests/). + + +``` +client.getSignRequests().getSignRequests() +``` + +### Arguments + +- queryParams `GetSignRequestsQueryParams` + - Query parameters of getSignRequests method +- headers `GetSignRequestsHeaders` + - Headers of getSignRequests method + + +### Returns + +This function returns a value of type `SignRequests`. + +Returns a collection of sign requests. + + +## Create Box Sign request + +Creates a signature request. This involves preparing a document for signing and +sending the signature request to signers. + +This operation is performed by calling function `createSignRequest`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-sign-requests/). + + +``` +client.getSignRequests().createSignRequest(new SignRequestCreateRequest.Builder(Arrays.asList(new SignRequestCreateSigner.Builder().email(signerEmail).role(SignRequestCreateSignerRoleField.SIGNER).isInPerson(false).embedUrlExternalUserId("123").declinedRedirectUrl("https://www.box.com").loginRequired(false).password("password").suppressNotifications(true).build())).sourceFiles(Arrays.asList(new FileBase(fileToSign.getId()))).parentFolder(new FolderMini(destinationFolder.getId())).isDocumentPreparationNeeded(false).redirectUrl("https://www.box.com").declinedRedirectUrl("https://www.box.com").areTextSignaturesEnabled(true).emailSubject("Sign this document").emailMessage("Please sign this document").areRemindersEnabled(true).name("Sign Request").prefillTags(Arrays.asList(new SignRequestPrefillTag.Builder().documentTagId("0").dateValue(dateFromString("2035-01-01")).build())).daysValid(30L).externalId("123").externalSystemName("BoxSignIntegration").build()) +``` + +### Arguments + +- requestBody `SignRequestCreateRequest` + - Request body of createSignRequest method +- headers `CreateSignRequestHeaders` + - Headers of createSignRequest method + + +### Returns + +This function returns a value of type `SignRequest`. + +Returns a Box Sign request object. + + diff --git a/docs/sdkgen/signtemplates.md b/docs/sdkgen/signtemplates.md new file mode 100644 index 000000000..7c4c1e878 --- /dev/null +++ b/docs/sdkgen/signtemplates.md @@ -0,0 +1,64 @@ +# SignTemplatesManager + + +- [List Box Sign templates](#list-box-sign-templates) +- [Get Box Sign template by ID](#get-box-sign-template-by-id) + +## List Box Sign templates + +Gets Box Sign templates created by a user. + +This operation is performed by calling function `getSignTemplates`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-sign-templates/). + + +``` +client.getSignTemplates().getSignTemplates(new GetSignTemplatesQueryParams.Builder().limit(2L).build()) +``` + +### Arguments + +- queryParams `GetSignTemplatesQueryParams` + - Query parameters of getSignTemplates method +- headers `GetSignTemplatesHeaders` + - Headers of getSignTemplates method + + +### Returns + +This function returns a value of type `SignTemplates`. + +Returns a collection of templates. + + +## Get Box Sign template by ID + +Fetches details of a specific Box Sign template. + +This operation is performed by calling function `getSignTemplateById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-sign-templates-id/). + + +``` +client.getSignTemplates().getSignTemplateById(signTemplates.getEntries().get(0).getId()) +``` + +### Arguments + +- templateId `String` + - The ID of a Box Sign template. Example: "123075213-7d117509-8f05-42e4-a5ef-5190a319d41d" +- headers `GetSignTemplateByIdHeaders` + - Headers of getSignTemplateById method + + +### Returns + +This function returns a value of type `SignTemplate`. + +Returns details of a template. + + diff --git a/docs/sdkgen/skills.md b/docs/sdkgen/skills.md new file mode 100644 index 000000000..8fb35a51d --- /dev/null +++ b/docs/sdkgen/skills.md @@ -0,0 +1,164 @@ +# SkillsManager + + +- [List Box Skill cards on file](#list-box-skill-cards-on-file) +- [Create Box Skill cards on file](#create-box-skill-cards-on-file) +- [Update Box Skill cards on file](#update-box-skill-cards-on-file) +- [Remove Box Skill cards from file](#remove-box-skill-cards-from-file) +- [Update all Box Skill cards on file](#update-all-box-skill-cards-on-file) + +## List Box Skill cards on file + +List the Box Skills metadata cards that are attached to a file. + +This operation is performed by calling function `getBoxSkillCardsOnFile`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-files-id-metadata-global-boxSkillsCards/). + + +``` +client.getSkills().getBoxSkillCardsOnFile(file.getId()) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- headers `GetBoxSkillCardsOnFileHeaders` + - Headers of getBoxSkillCardsOnFile method + + +### Returns + +This function returns a value of type `SkillCardsMetadata`. + +Returns all the metadata associated with a file. + +This API does not support pagination and will therefore always return +all of the metadata associated to the file. + + +## Create Box Skill cards on file + +Applies one or more Box Skills metadata cards to a file. + +This operation is performed by calling function `createBoxSkillCardsOnFile`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-files-id-metadata-global-boxSkillsCards/). + + +``` +client.getSkills().createBoxSkillCardsOnFile(file.getId(), new CreateBoxSkillCardsOnFileRequestBody(cardsToCreate)) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- requestBody `CreateBoxSkillCardsOnFileRequestBody` + - Request body of createBoxSkillCardsOnFile method +- headers `CreateBoxSkillCardsOnFileHeaders` + - Headers of createBoxSkillCardsOnFile method + + +### Returns + +This function returns a value of type `SkillCardsMetadata`. + +Returns the instance of the template that was applied to the file, +including the data that was applied to the template. + + +## Update Box Skill cards on file + +Updates one or more Box Skills metadata cards to a file. + +This operation is performed by calling function `updateBoxSkillCardsOnFile`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-files-id-metadata-global-boxSkillsCards/). + + +``` +client.getSkills().updateBoxSkillCardsOnFile(file.getId(), Arrays.asList(new UpdateBoxSkillCardsOnFileRequestBody.Builder().op(UpdateBoxSkillCardsOnFileRequestBodyOpField.REPLACE).path("/cards/0").value(cardToUpdate).build())) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- requestBody `List` + - Request body of updateBoxSkillCardsOnFile method +- headers `UpdateBoxSkillCardsOnFileHeaders` + - Headers of updateBoxSkillCardsOnFile method + + +### Returns + +This function returns a value of type `SkillCardsMetadata`. + +Returns the updated metadata template, with the +custom template data included. + + +## Remove Box Skill cards from file + +Removes any Box Skills cards metadata from a file. + +This operation is performed by calling function `deleteBoxSkillCardsFromFile`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-files-id-metadata-global-boxSkillsCards/). + + +``` +client.getSkills().deleteBoxSkillCardsFromFile(file.getId()) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- headers `DeleteBoxSkillCardsFromFileHeaders` + - Headers of deleteBoxSkillCardsFromFile method + + +### Returns + +This function returns a value of type `void`. + +Returns an empty response when the cards are +successfully deleted. + + +## Update all Box Skill cards on file + +An alternative method that can be used to overwrite and update all Box Skill +metadata cards on a file. + +This operation is performed by calling function `updateAllSkillCardsOnFile`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-skill-invocations-id/). + +*Currently we don't have an example for calling `updateAllSkillCardsOnFile` in integration tests* + +### Arguments + +- skillId `String` + - The ID of the skill to apply this metadata for. Example: "33243242" +- requestBody `UpdateAllSkillCardsOnFileRequestBody` + - Request body of updateAllSkillCardsOnFile method +- headers `UpdateAllSkillCardsOnFileHeaders` + - Headers of updateAllSkillCardsOnFile method + + +### Returns + +This function returns a value of type `void`. + +Returns an empty response when the card has been successfully updated. + + diff --git a/docs/sdkgen/storagepolicies.md b/docs/sdkgen/storagepolicies.md new file mode 100644 index 000000000..552cdd5ed --- /dev/null +++ b/docs/sdkgen/storagepolicies.md @@ -0,0 +1,64 @@ +# StoragePoliciesManager + + +- [List storage policies](#list-storage-policies) +- [Get storage policy](#get-storage-policy) + +## List storage policies + +Fetches all the storage policies in the enterprise. + +This operation is performed by calling function `getStoragePolicies`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-storage-policies/). + + +``` +client.getStoragePolicies().getStoragePolicies() +``` + +### Arguments + +- queryParams `GetStoragePoliciesQueryParams` + - Query parameters of getStoragePolicies method +- headers `GetStoragePoliciesHeaders` + - Headers of getStoragePolicies method + + +### Returns + +This function returns a value of type `StoragePolicies`. + +Returns a collection of storage policies. + + +## Get storage policy + +Fetches a specific storage policy. + +This operation is performed by calling function `getStoragePolicyById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-storage-policies-id/). + + +``` +client.getStoragePolicies().getStoragePolicyById(storagePolicy.getId()) +``` + +### Arguments + +- storagePolicyId `String` + - The ID of the storage policy. Example: "34342" +- headers `GetStoragePolicyByIdHeaders` + - Headers of getStoragePolicyById method + + +### Returns + +This function returns a value of type `StoragePolicy`. + +Returns a storage policy object. + + diff --git a/docs/sdkgen/storagepolicyassignments.md b/docs/sdkgen/storagepolicyassignments.md new file mode 100644 index 000000000..a28a8a554 --- /dev/null +++ b/docs/sdkgen/storagepolicyassignments.md @@ -0,0 +1,165 @@ +# StoragePolicyAssignmentsManager + + +- [List storage policy assignments](#list-storage-policy-assignments) +- [Assign storage policy](#assign-storage-policy) +- [Get storage policy assignment](#get-storage-policy-assignment) +- [Update storage policy assignment](#update-storage-policy-assignment) +- [Unassign storage policy](#unassign-storage-policy) + +## List storage policy assignments + +Fetches all the storage policy assignment for an enterprise or user. + +This operation is performed by calling function `getStoragePolicyAssignments`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-storage-policy-assignments/). + + +``` +client.getStoragePolicyAssignments().getStoragePolicyAssignments(new GetStoragePolicyAssignmentsQueryParams(GetStoragePolicyAssignmentsQueryParamsResolvedForTypeField.USER, userId)) +``` + +### Arguments + +- queryParams `GetStoragePolicyAssignmentsQueryParams` + - Query parameters of getStoragePolicyAssignments method +- headers `GetStoragePolicyAssignmentsHeaders` + - Headers of getStoragePolicyAssignments method + + +### Returns + +This function returns a value of type `StoragePolicyAssignments`. + +Returns a collection of storage policies for +the enterprise or user. + + +## Assign storage policy + +Creates a storage policy assignment for an enterprise or user. + +This operation is performed by calling function `createStoragePolicyAssignment`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-storage-policy-assignments/). + + +``` +client.getStoragePolicyAssignments().createStoragePolicyAssignment(new CreateStoragePolicyAssignmentRequestBody(new CreateStoragePolicyAssignmentRequestBodyStoragePolicyField(policyId), new CreateStoragePolicyAssignmentRequestBodyAssignedToField(CreateStoragePolicyAssignmentRequestBodyAssignedToTypeField.USER, userId))) +``` + +### Arguments + +- requestBody `CreateStoragePolicyAssignmentRequestBody` + - Request body of createStoragePolicyAssignment method +- headers `CreateStoragePolicyAssignmentHeaders` + - Headers of createStoragePolicyAssignment method + + +### Returns + +This function returns a value of type `StoragePolicyAssignment`. + +Returns the new storage policy assignment created. + + +## Get storage policy assignment + +Fetches a specific storage policy assignment. + +This operation is performed by calling function `getStoragePolicyAssignmentById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-storage-policy-assignments-id/). + + +``` +client.getStoragePolicyAssignments().getStoragePolicyAssignmentById(storagePolicyAssignment.getId()) +``` + +### Arguments + +- storagePolicyAssignmentId `String` + - The ID of the storage policy assignment. Example: "932483" +- headers `GetStoragePolicyAssignmentByIdHeaders` + - Headers of getStoragePolicyAssignmentById method + + +### Returns + +This function returns a value of type `StoragePolicyAssignment`. + +Returns a storage policy assignment object. + + +## Update storage policy assignment + +Updates a specific storage policy assignment. + +This operation is performed by calling function `updateStoragePolicyAssignmentById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-storage-policy-assignments-id/). + + +``` +client.getStoragePolicyAssignments().updateStoragePolicyAssignmentById(storagePolicyAssignment.getId(), new UpdateStoragePolicyAssignmentByIdRequestBody(new UpdateStoragePolicyAssignmentByIdRequestBodyStoragePolicyField(storagePolicy2.getId()))) +``` + +### Arguments + +- storagePolicyAssignmentId `String` + - The ID of the storage policy assignment. Example: "932483" +- requestBody `UpdateStoragePolicyAssignmentByIdRequestBody` + - Request body of updateStoragePolicyAssignmentById method +- headers `UpdateStoragePolicyAssignmentByIdHeaders` + - Headers of updateStoragePolicyAssignmentById method + + +### Returns + +This function returns a value of type `StoragePolicyAssignment`. + +Returns an updated storage policy assignment object. + + +## Unassign storage policy + +Delete a storage policy assignment. + +Deleting a storage policy assignment on a user +will have the user inherit the enterprise's default +storage policy. + +There is a rate limit for calling this endpoint of only +twice per user in a 24 hour time frame. + +This operation is performed by calling function `deleteStoragePolicyAssignmentById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-storage-policy-assignments-id/). + + +``` +client.getStoragePolicyAssignments().deleteStoragePolicyAssignmentById(storagePolicyAssignment.getId()) +``` + +### Arguments + +- storagePolicyAssignmentId `String` + - The ID of the storage policy assignment. Example: "932483" +- headers `DeleteStoragePolicyAssignmentByIdHeaders` + - Headers of deleteStoragePolicyAssignmentById method + + +### Returns + +This function returns a value of type `void`. + +Returns an empty response when the storage policy +assignment is successfully deleted. + + diff --git a/docs/sdkgen/taskassignments.md b/docs/sdkgen/taskassignments.md new file mode 100644 index 000000000..bd90913c9 --- /dev/null +++ b/docs/sdkgen/taskassignments.md @@ -0,0 +1,163 @@ +# TaskAssignmentsManager + + +- [List task assignments](#list-task-assignments) +- [Assign task](#assign-task) +- [Get task assignment](#get-task-assignment) +- [Update task assignment](#update-task-assignment) +- [Unassign task](#unassign-task) + +## List task assignments + +Lists all of the assignments for a given task. + +This operation is performed by calling function `getTaskAssignments`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-tasks-id-assignments/). + + +``` +client.getTaskAssignments().getTaskAssignments(task.getId()) +``` + +### Arguments + +- taskId `String` + - The ID of the task. Example: "12345" +- headers `GetTaskAssignmentsHeaders` + - Headers of getTaskAssignments method + + +### Returns + +This function returns a value of type `TaskAssignments`. + +Returns a collection of task assignment defining what task on +a file has been assigned to which users and by who. + + +## Assign task + +Assigns a task to a user. + +A task can be assigned to more than one user by creating multiple +assignments. + +This operation is performed by calling function `createTaskAssignment`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-task-assignments/). + + +``` +client.getTaskAssignments().createTaskAssignment(new CreateTaskAssignmentRequestBody(new CreateTaskAssignmentRequestBodyTaskField.Builder(task.getId()).type(CreateTaskAssignmentRequestBodyTaskTypeField.TASK).build(), new CreateTaskAssignmentRequestBodyAssignToField.Builder().id(currentUser.getId()).build())) +``` + +### Arguments + +- requestBody `CreateTaskAssignmentRequestBody` + - Request body of createTaskAssignment method +- headers `CreateTaskAssignmentHeaders` + - Headers of createTaskAssignment method + + +### Returns + +This function returns a value of type `TaskAssignment`. + +Returns a new task assignment object. + + +## Get task assignment + +Retrieves information about a task assignment. + +This operation is performed by calling function `getTaskAssignmentById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-task-assignments-id/). + + +``` +client.getTaskAssignments().getTaskAssignmentById(taskAssignment.getId()) +``` + +### Arguments + +- taskAssignmentId `String` + - The ID of the task assignment. Example: "12345" +- headers `GetTaskAssignmentByIdHeaders` + - Headers of getTaskAssignmentById method + + +### Returns + +This function returns a value of type `TaskAssignment`. + +Returns a task assignment, specifying who the task has been assigned to +and by whom. + + +## Update task assignment + +Updates a task assignment. This endpoint can be +used to update the state of a task assigned to a user. + +This operation is performed by calling function `updateTaskAssignmentById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-task-assignments-id/). + + +``` +client.getTaskAssignments().updateTaskAssignmentById(taskAssignment.getId(), new UpdateTaskAssignmentByIdRequestBody.Builder().message("updated message").resolutionState(UpdateTaskAssignmentByIdRequestBodyResolutionStateField.APPROVED).build()) +``` + +### Arguments + +- taskAssignmentId `String` + - The ID of the task assignment. Example: "12345" +- requestBody `UpdateTaskAssignmentByIdRequestBody` + - Request body of updateTaskAssignmentById method +- headers `UpdateTaskAssignmentByIdHeaders` + - Headers of updateTaskAssignmentById method + + +### Returns + +This function returns a value of type `TaskAssignment`. + +Returns the updated task assignment object. + + +## Unassign task + +Deletes a specific task assignment. + +This operation is performed by calling function `deleteTaskAssignmentById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-task-assignments-id/). + + +``` +client.getTaskAssignments().deleteTaskAssignmentById(taskAssignment.getId()) +``` + +### Arguments + +- taskAssignmentId `String` + - The ID of the task assignment. Example: "12345" +- headers `DeleteTaskAssignmentByIdHeaders` + - Headers of deleteTaskAssignmentById method + + +### Returns + +This function returns a value of type `void`. + +Returns an empty response when the task +assignment was successfully deleted. + + diff --git a/docs/sdkgen/tasks.md b/docs/sdkgen/tasks.md new file mode 100644 index 000000000..2f11bf40b --- /dev/null +++ b/docs/sdkgen/tasks.md @@ -0,0 +1,162 @@ +# TasksManager + + +- [List tasks on file](#list-tasks-on-file) +- [Create task](#create-task) +- [Get task](#get-task) +- [Update task](#update-task) +- [Remove task](#remove-task) + +## List tasks on file + +Retrieves a list of all the tasks for a file. This +endpoint does not support pagination. + +This operation is performed by calling function `getFileTasks`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-files-id-tasks/). + + +``` +client.getTasks().getFileTasks(file.getId()) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- headers `GetFileTasksHeaders` + - Headers of getFileTasks method + + +### Returns + +This function returns a value of type `Tasks`. + +Returns a list of tasks on a file. + +If there are no tasks on this file an empty collection is returned +instead. + + +## Create task + +Creates a single task on a file. This task is not assigned to any user and +will need to be assigned separately. + +This operation is performed by calling function `createTask`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-tasks/). + + +``` +client.getTasks().createTask(new CreateTaskRequestBody.Builder(new CreateTaskRequestBodyItemField.Builder().id(file.getId()).type(CreateTaskRequestBodyItemTypeField.FILE).build()).action(CreateTaskRequestBodyActionField.REVIEW).message("test message").dueAt(dateTime).completionRule(CreateTaskRequestBodyCompletionRuleField.ALL_ASSIGNEES).build()) +``` + +### Arguments + +- requestBody `CreateTaskRequestBody` + - Request body of createTask method +- headers `CreateTaskHeaders` + - Headers of createTask method + + +### Returns + +This function returns a value of type `Task`. + +Returns the newly created task. + + +## Get task + +Retrieves information about a specific task. + +This operation is performed by calling function `getTaskById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-tasks-id/). + + +``` +client.getTasks().getTaskById(task.getId()) +``` + +### Arguments + +- taskId `String` + - The ID of the task. Example: "12345" +- headers `GetTaskByIdHeaders` + - Headers of getTaskById method + + +### Returns + +This function returns a value of type `Task`. + +Returns a task object. + + +## Update task + +Updates a task. This can be used to update a task's configuration, or to +update its completion state. + +This operation is performed by calling function `updateTaskById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-tasks-id/). + + +``` +client.getTasks().updateTaskById(task.getId(), new UpdateTaskByIdRequestBody.Builder().message("updated message").build()) +``` + +### Arguments + +- taskId `String` + - The ID of the task. Example: "12345" +- requestBody `UpdateTaskByIdRequestBody` + - Request body of updateTaskById method +- headers `UpdateTaskByIdHeaders` + - Headers of updateTaskById method + + +### Returns + +This function returns a value of type `Task`. + +Returns the updated task object. + + +## Remove task + +Removes a task from a file. + +This operation is performed by calling function `deleteTaskById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-tasks-id/). + + +``` +client.getTasks().deleteTaskById(task.getId()) +``` + +### Arguments + +- taskId `String` + - The ID of the task. Example: "12345" +- headers `DeleteTaskByIdHeaders` + - Headers of deleteTaskById method + + +### Returns + +This function returns a value of type `void`. + +Returns an empty response when the task was successfully deleted. + + diff --git a/docs/sdkgen/termsofservices.md b/docs/sdkgen/termsofservices.md new file mode 100644 index 000000000..700ef5a6c --- /dev/null +++ b/docs/sdkgen/termsofservices.md @@ -0,0 +1,126 @@ +# TermsOfServicesManager + + +- [List terms of services](#list-terms-of-services) +- [Create terms of service](#create-terms-of-service) +- [Get terms of service](#get-terms-of-service) +- [Update terms of service](#update-terms-of-service) + +## List terms of services + +Returns the current terms of service text and settings +for the enterprise. + +This operation is performed by calling function `getTermsOfService`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-terms-of-services/). + + +``` +client.getTermsOfServices().getTermsOfService() +``` + +### Arguments + +- queryParams `GetTermsOfServiceQueryParams` + - Query parameters of getTermsOfService method +- headers `GetTermsOfServiceHeaders` + - Headers of getTermsOfService method + + +### Returns + +This function returns a value of type `TermsOfServices`. + +Returns a collection of terms of service text and settings for the +enterprise. + + +## Create terms of service + +Creates a terms of service for a given enterprise +and type of user. + +This operation is performed by calling function `createTermsOfService`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-terms-of-services/). + + +``` +client.getTermsOfServices().createTermsOfService(new CreateTermsOfServiceRequestBody.Builder(CreateTermsOfServiceRequestBodyStatusField.DISABLED, "Test TOS").tosType(CreateTermsOfServiceRequestBodyTosTypeField.MANAGED).build()) +``` + +### Arguments + +- requestBody `CreateTermsOfServiceRequestBody` + - Request body of createTermsOfService method +- headers `CreateTermsOfServiceHeaders` + - Headers of createTermsOfService method + + +### Returns + +This function returns a value of type `TermsOfService`. + +Returns a new task object. + + +## Get terms of service + +Fetches a specific terms of service. + +This operation is performed by calling function `getTermsOfServiceById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-terms-of-services-id/). + +*Currently we don't have an example for calling `getTermsOfServiceById` in integration tests* + +### Arguments + +- termsOfServiceId `String` + - The ID of the terms of service. Example: "324234" +- headers `GetTermsOfServiceByIdHeaders` + - Headers of getTermsOfServiceById method + + +### Returns + +This function returns a value of type `TermsOfService`. + +Returns a terms of service object. + + +## Update terms of service + +Updates a specific terms of service. + +This operation is performed by calling function `updateTermsOfServiceById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-terms-of-services-id/). + + +``` +client.getTermsOfServices().updateTermsOfServiceById(tos.getId(), new UpdateTermsOfServiceByIdRequestBody(UpdateTermsOfServiceByIdRequestBodyStatusField.DISABLED, "TOS")) +``` + +### Arguments + +- termsOfServiceId `String` + - The ID of the terms of service. Example: "324234" +- requestBody `UpdateTermsOfServiceByIdRequestBody` + - Request body of updateTermsOfServiceById method +- headers `UpdateTermsOfServiceByIdHeaders` + - Headers of updateTermsOfServiceById method + + +### Returns + +This function returns a value of type `TermsOfService`. + +Returns an updated terms of service object. + + diff --git a/docs/sdkgen/termsofserviceuserstatuses.md b/docs/sdkgen/termsofserviceuserstatuses.md new file mode 100644 index 000000000..3a2fa17df --- /dev/null +++ b/docs/sdkgen/termsofserviceuserstatuses.md @@ -0,0 +1,98 @@ +# TermsOfServiceUserStatusesManager + + +- [List terms of service user statuses](#list-terms-of-service-user-statuses) +- [Create terms of service status for new user](#create-terms-of-service-status-for-new-user) +- [Update terms of service status for existing user](#update-terms-of-service-status-for-existing-user) + +## List terms of service user statuses + +Retrieves an overview of users and their status for a +terms of service, including Whether they have accepted +the terms and when. + +This operation is performed by calling function `getTermsOfServiceUserStatuses`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-terms-of-service-user-statuses/). + + +``` +client.getTermsOfServiceUserStatuses().getTermsOfServiceUserStatuses(new GetTermsOfServiceUserStatusesQueryParams.Builder(tos.getId()).userId(user.getId()).build()) +``` + +### Arguments + +- queryParams `GetTermsOfServiceUserStatusesQueryParams` + - Query parameters of getTermsOfServiceUserStatuses method +- headers `GetTermsOfServiceUserStatusesHeaders` + - Headers of getTermsOfServiceUserStatuses method + + +### Returns + +This function returns a value of type `TermsOfServiceUserStatuses`. + +Returns a list of terms of service statuses. + + +## Create terms of service status for new user + +Sets the status for a terms of service for a user. + +This operation is performed by calling function `createTermsOfServiceStatusForUser`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-terms-of-service-user-statuses/). + + +``` +client.getTermsOfServiceUserStatuses().createTermsOfServiceStatusForUser(new CreateTermsOfServiceStatusForUserRequestBody(new CreateTermsOfServiceStatusForUserRequestBodyTosField(tos.getId()), new CreateTermsOfServiceStatusForUserRequestBodyUserField(user.getId()), false)) +``` + +### Arguments + +- requestBody `CreateTermsOfServiceStatusForUserRequestBody` + - Request body of createTermsOfServiceStatusForUser method +- headers `CreateTermsOfServiceStatusForUserHeaders` + - Headers of createTermsOfServiceStatusForUser method + + +### Returns + +This function returns a value of type `TermsOfServiceUserStatus`. + +Returns a terms of service status object. + + +## Update terms of service status for existing user + +Updates the status for a terms of service for a user. + +This operation is performed by calling function `updateTermsOfServiceStatusForUserById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-terms-of-service-user-statuses-id/). + + +``` +client.getTermsOfServiceUserStatuses().updateTermsOfServiceStatusForUserById(createdTosUserStatus.getId(), new UpdateTermsOfServiceStatusForUserByIdRequestBody(true)) +``` + +### Arguments + +- termsOfServiceUserStatusId `String` + - The ID of the terms of service status. Example: "324234" +- requestBody `UpdateTermsOfServiceStatusForUserByIdRequestBody` + - Request body of updateTermsOfServiceStatusForUserById method +- headers `UpdateTermsOfServiceStatusForUserByIdHeaders` + - Headers of updateTermsOfServiceStatusForUserById method + + +### Returns + +This function returns a value of type `TermsOfServiceUserStatus`. + +Returns the updated terms of service status object. + + diff --git a/docs/sdkgen/transfer.md b/docs/sdkgen/transfer.md new file mode 100644 index 000000000..039d67195 --- /dev/null +++ b/docs/sdkgen/transfer.md @@ -0,0 +1,72 @@ +# TransferManager + + +- [Transfer owned folders](#transfer-owned-folders) + +## Transfer owned folders + +Move all of the items (files, folders and workflows) owned by a user into +another user's account + +Only the root folder (`0`) can be transferred. + +Folders can only be moved across users by users with administrative +permissions. + +All existing shared links and folder-level collaborations are transferred +during the operation. Please note that while collaborations at the individual +file-level are transferred during the operation, the collaborations are +deleted when the original user is deleted. + +If the user has a large number of items across all folders, the call will +be run asynchronously. If the operation is not completed within 10 minutes, +the user will receive a 200 OK response, and the operation will continue running. + +If the destination path has a metadata cascade policy attached to any of +the parent folders, a metadata cascade operation will be kicked off +asynchronously. + +There is currently no way to check for when this operation is finished. + +The destination folder's name will be in the format `{User}'s Files and +Folders`, where `{User}` is the display name of the user. + +To make this API call your application will need to have the "Read and write +all files and folders stored in Box" scope enabled. + +Please make sure the destination user has access to `Relay` or `Relay Lite`, +and has access to the files and folders involved in the workflows being +transferred. + +Admins will receive an email when the operation is completed. + +This operation is performed by calling function `transferOwnedFolder`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-users-id-folders-0/). + + +``` +client.getTransfer().transferOwnedFolder(sourceUser.getId(), new TransferOwnedFolderRequestBody(new TransferOwnedFolderRequestBodyOwnedByField(targetUser.getId())), new TransferOwnedFolderQueryParams.Builder().notify(false).build()) +``` + +### Arguments + +- userId `String` + - The ID of the user. Example: "12345" +- requestBody `TransferOwnedFolderRequestBody` + - Request body of transferOwnedFolder method +- queryParams `TransferOwnedFolderQueryParams` + - Query parameters of transferOwnedFolder method +- headers `TransferOwnedFolderHeaders` + - Headers of transferOwnedFolder method + + +### Returns + +This function returns a value of type `FolderFull`. + +Returns the information for the newly created +destination folder. + + diff --git a/docs/sdkgen/trashedfiles.md b/docs/sdkgen/trashedfiles.md new file mode 100644 index 000000000..90ed51ec4 --- /dev/null +++ b/docs/sdkgen/trashedfiles.md @@ -0,0 +1,117 @@ +# TrashedFilesManager + + +- [Restore file](#restore-file) +- [Get trashed file](#get-trashed-file) +- [Permanently remove file](#permanently-remove-file) + +## Restore file + +Restores a file that has been moved to the trash. + +An optional new parent ID can be provided to restore the file to in case the +original folder has been deleted. + +This operation is performed by calling function `restoreFileFromTrash`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-files-id/). + + +``` +client.getTrashedFiles().restoreFileFromTrash(file.getId()) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- requestBody `RestoreFileFromTrashRequestBody` + - Request body of restoreFileFromTrash method +- queryParams `RestoreFileFromTrashQueryParams` + - Query parameters of restoreFileFromTrash method +- headers `RestoreFileFromTrashHeaders` + - Headers of restoreFileFromTrash method + + +### Returns + +This function returns a value of type `TrashFileRestored`. + +Returns a file object when the file has been restored. + + +## Get trashed file + +Retrieves a file that has been moved to the trash. + +Please note that only if the file itself has been moved to the +trash can it be retrieved with this API call. If instead one of +its parent folders was moved to the trash, only that folder +can be inspected using the +[`GET /folders/:id/trash`](e://get_folders_id_trash) API. + +To list all items that have been moved to the trash, please +use the [`GET /folders/trash/items`](e://get-folders-trash-items/) +API. + +This operation is performed by calling function `getTrashedFileById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-files-id-trash/). + + +``` +client.getTrashedFiles().getTrashedFileById(file.getId()) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- queryParams `GetTrashedFileByIdQueryParams` + - Query parameters of getTrashedFileById method +- headers `GetTrashedFileByIdHeaders` + - Headers of getTrashedFileById method + + +### Returns + +This function returns a value of type `TrashFile`. + +Returns the file that was trashed, +including information about when the it +was moved to the trash. + + +## Permanently remove file + +Permanently deletes a file that is in the trash. +This action cannot be undone. + +This operation is performed by calling function `deleteTrashedFileById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-files-id-trash/). + + +``` +client.getTrashedFiles().deleteTrashedFileById(file.getId()) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- headers `DeleteTrashedFileByIdHeaders` + - Headers of deleteTrashedFileById method + + +### Returns + +This function returns a value of type `void`. + +Returns an empty response when the file was +permanently deleted. + + diff --git a/docs/sdkgen/trashedfolders.md b/docs/sdkgen/trashedfolders.md new file mode 100644 index 000000000..906508c2f --- /dev/null +++ b/docs/sdkgen/trashedfolders.md @@ -0,0 +1,124 @@ +# TrashedFoldersManager + + +- [Restore folder](#restore-folder) +- [Get trashed folder](#get-trashed-folder) +- [Permanently remove folder](#permanently-remove-folder) + +## Restore folder + +Restores a folder that has been moved to the trash. + +An optional new parent ID can be provided to restore the folder to in case the +original folder has been deleted. + +During this operation, part of the file tree will be locked, mainly +the source folder and all of its descendants, as well as the destination +folder. + +For the duration of the operation, no other move, copy, delete, or restore +operation can performed on any of the locked folders. + +This operation is performed by calling function `restoreFolderFromTrash`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-folders-id/). + + +``` +client.getTrashedFolders().restoreFolderFromTrash(folder.getId()) +``` + +### Arguments + +- folderId `String` + - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" +- requestBody `RestoreFolderFromTrashRequestBody` + - Request body of restoreFolderFromTrash method +- queryParams `RestoreFolderFromTrashQueryParams` + - Query parameters of restoreFolderFromTrash method +- headers `RestoreFolderFromTrashHeaders` + - Headers of restoreFolderFromTrash method + + +### Returns + +This function returns a value of type `TrashFolderRestored`. + +Returns a folder object when the folder has been restored. + + +## Get trashed folder + +Retrieves a folder that has been moved to the trash. + +Please note that only if the folder itself has been moved to the +trash can it be retrieved with this API call. If instead one of +its parent folders was moved to the trash, only that folder +can be inspected using the +[`GET /folders/:id/trash`](e://get_folders_id_trash) API. + +To list all items that have been moved to the trash, please +use the [`GET /folders/trash/items`](e://get-folders-trash-items/) +API. + +This operation is performed by calling function `getTrashedFolderById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-folders-id-trash/). + + +``` +client.getTrashedFolders().getTrashedFolderById(folder.getId()) +``` + +### Arguments + +- folderId `String` + - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" +- queryParams `GetTrashedFolderByIdQueryParams` + - Query parameters of getTrashedFolderById method +- headers `GetTrashedFolderByIdHeaders` + - Headers of getTrashedFolderById method + + +### Returns + +This function returns a value of type `TrashFolder`. + +Returns the folder that was trashed, +including information about when the it +was moved to the trash. + + +## Permanently remove folder + +Permanently deletes a folder that is in the trash. +This action cannot be undone. + +This operation is performed by calling function `deleteTrashedFolderById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-folders-id-trash/). + + +``` +client.getTrashedFolders().deleteTrashedFolderById(folder.getId()) +``` + +### Arguments + +- folderId `String` + - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" +- headers `DeleteTrashedFolderByIdHeaders` + - Headers of deleteTrashedFolderById method + + +### Returns + +This function returns a value of type `void`. + +Returns an empty response when the folder was +permanently deleted. + + diff --git a/docs/sdkgen/trasheditems.md b/docs/sdkgen/trasheditems.md new file mode 100644 index 000000000..1643b531d --- /dev/null +++ b/docs/sdkgen/trasheditems.md @@ -0,0 +1,42 @@ +# TrashedItemsManager + + +- [List trashed items](#list-trashed-items) + +## List trashed items + +Retrieves the files and folders that have been moved +to the trash. + +Any attribute in the full files or folders objects can be passed +in with the `fields` parameter to retrieve those specific +attributes that are not returned by default. + +This endpoint defaults to use offset-based pagination, yet also supports +marker-based pagination using the `marker` parameter. + +This operation is performed by calling function `getTrashedItems`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-folders-trash-items/). + + +``` +client.getTrashedItems().getTrashedItems() +``` + +### Arguments + +- queryParams `GetTrashedItemsQueryParams` + - Query parameters of getTrashedItems method +- headers `GetTrashedItemsHeaders` + - Headers of getTrashedItems method + + +### Returns + +This function returns a value of type `Items`. + +Returns a list of items that have been deleted. + + diff --git a/docs/sdkgen/trashedweblinks.md b/docs/sdkgen/trashedweblinks.md new file mode 100644 index 000000000..6a3e4b919 --- /dev/null +++ b/docs/sdkgen/trashedweblinks.md @@ -0,0 +1,107 @@ +# TrashedWebLinksManager + + +- [Restore web link](#restore-web-link) +- [Get trashed web link](#get-trashed-web-link) +- [Permanently remove web link](#permanently-remove-web-link) + +## Restore web link + +Restores a web link that has been moved to the trash. + +An optional new parent ID can be provided to restore the web link to in case +the original folder has been deleted. + +This operation is performed by calling function `restoreWeblinkFromTrash`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-web-links-id/). + + +``` +client.getTrashedWebLinks().restoreWeblinkFromTrash(weblink.getId()) +``` + +### Arguments + +- webLinkId `String` + - The ID of the web link. Example: "12345" +- requestBody `RestoreWeblinkFromTrashRequestBody` + - Request body of restoreWeblinkFromTrash method +- queryParams `RestoreWeblinkFromTrashQueryParams` + - Query parameters of restoreWeblinkFromTrash method +- headers `RestoreWeblinkFromTrashHeaders` + - Headers of restoreWeblinkFromTrash method + + +### Returns + +This function returns a value of type `TrashWebLinkRestored`. + +Returns a web link object when it has been restored. + + +## Get trashed web link + +Retrieves a web link that has been moved to the trash. + +This operation is performed by calling function `getTrashedWebLinkById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-web-links-id-trash/). + + +``` +client.getTrashedWebLinks().getTrashedWebLinkById(weblink.getId()) +``` + +### Arguments + +- webLinkId `String` + - The ID of the web link. Example: "12345" +- queryParams `GetTrashedWebLinkByIdQueryParams` + - Query parameters of getTrashedWebLinkById method +- headers `GetTrashedWebLinkByIdHeaders` + - Headers of getTrashedWebLinkById method + + +### Returns + +This function returns a value of type `TrashWebLink`. + +Returns the web link that was trashed, +including information about when the it +was moved to the trash. + + +## Permanently remove web link + +Permanently deletes a web link that is in the trash. +This action cannot be undone. + +This operation is performed by calling function `deleteTrashedWebLinkById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-web-links-id-trash/). + + +``` +client.getTrashedWebLinks().deleteTrashedWebLinkById(weblink.getId()) +``` + +### Arguments + +- webLinkId `String` + - The ID of the web link. Example: "12345" +- headers `DeleteTrashedWebLinkByIdHeaders` + - Headers of deleteTrashedWebLinkById method + + +### Returns + +This function returns a value of type `void`. + +Returns an empty response when the web link was +permanently deleted. + + diff --git a/docs/sdkgen/uploads.md b/docs/sdkgen/uploads.md new file mode 100644 index 000000000..a3eb4721f --- /dev/null +++ b/docs/sdkgen/uploads.md @@ -0,0 +1,144 @@ +# UploadsManager + + +- [Upload file version](#upload-file-version) +- [Preflight check before upload](#preflight-check-before-upload) +- [Upload file](#upload-file) +- [Upload a file with a preflight check](#upload-a-file-with-a-preflight-check) + +## Upload file version + +Update a file's content. For file sizes over 50MB we recommend +using the Chunk Upload APIs. + +The `attributes` part of the body must come **before** the +`file` part. Requests that do not follow this format when +uploading the file will receive a HTTP `400` error with a +`metadata_after_file_contents` error code. + +This operation is performed by calling function `uploadFileVersion`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-files-id-content/). + + +``` +client.getUploads().uploadFileVersion(uploadedFile.getId(), new UploadFileVersionRequestBody(new UploadFileVersionRequestBodyAttributesField(newFileVersionName), newFileContentStream)) +``` + +### Arguments + +- fileId `String` + - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" +- requestBody `UploadFileVersionRequestBody` + - Request body of uploadFileVersion method +- queryParams `UploadFileVersionQueryParams` + - Query parameters of uploadFileVersion method +- headers `UploadFileVersionHeaders` + - Headers of uploadFileVersion method + + +### Returns + +This function returns a value of type `Files`. + +Returns the new file object in a list. + + +## Preflight check before upload + +Performs a check to verify that a file will be accepted by Box +before you upload the entire file. + +This operation is performed by calling function `preflightFileUploadCheck`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/options-files-content/). + + +``` +client.getUploads().preflightFileUploadCheck(new PreflightFileUploadCheckRequestBody.Builder().name(newFileName).size(1024 * 1024).parent(new PreflightFileUploadCheckRequestBodyParentField.Builder().id("0").build()).build()) +``` + +### Arguments + +- requestBody `PreflightFileUploadCheckRequestBody` + - Request body of preflightFileUploadCheck method +- headers `PreflightFileUploadCheckHeaders` + - Headers of preflightFileUploadCheck method + + +### Returns + +This function returns a value of type `UploadUrl`. + +If the check passed, the response will include a session URL that +can be used to upload the file to. + + +## Upload file + +Uploads a small file to Box. For file sizes over 50MB we recommend +using the Chunk Upload APIs. + +The `attributes` part of the body must come **before** the +`file` part. Requests that do not follow this format when +uploading the file will receive a HTTP `400` error with a +`metadata_after_file_contents` error code. + +This operation is performed by calling function `uploadFile`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-files-content/). + + +``` +client.getUploads().uploadFile(new UploadFileRequestBody(new UploadFileRequestBodyAttributesField(newFileName, new UploadFileRequestBodyAttributesParentField("0")), fileContentStream)) +``` + +### Arguments + +- requestBody `UploadFileRequestBody` + - Request body of uploadFile method +- queryParams `UploadFileQueryParams` + - Query parameters of uploadFile method +- headers `UploadFileHeaders` + - Headers of uploadFile method + + +### Returns + +This function returns a value of type `Files`. + +Returns the new file object in a list. + + +## Upload a file with a preflight check + + Upload a file with a preflight check + +This operation is performed by calling function `uploadWithPreflightCheck`. + + + +``` +client.getUploads().uploadWithPreflightCheck(new UploadWithPreflightCheckRequestBody(new UploadWithPreflightCheckRequestBodyAttributesField(newFileName, new UploadWithPreflightCheckRequestBodyAttributesParentField("0"), -1), fileContentStream)) +``` + +### Arguments + +- requestBody `UploadWithPreflightCheckRequestBody` + +- queryParams `UploadWithPreflightCheckQueryParams` + - Query parameters of uploadFile method +- headers `UploadWithPreflightCheckHeaders` + - Headers of uploadFile method + + +### Returns + +This function returns a value of type `Files`. + + + + diff --git a/docs/sdkgen/usercollaborations.md b/docs/sdkgen/usercollaborations.md new file mode 100644 index 000000000..f95501c08 --- /dev/null +++ b/docs/sdkgen/usercollaborations.md @@ -0,0 +1,148 @@ +# UserCollaborationsManager + + +- [Get collaboration](#get-collaboration) +- [Update collaboration](#update-collaboration) +- [Remove collaboration](#remove-collaboration) +- [Create collaboration](#create-collaboration) + +## Get collaboration + +Retrieves a single collaboration. + +This operation is performed by calling function `getCollaborationById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-collaborations-id/). + + +``` +client.getUserCollaborations().getCollaborationById(collaborationId) +``` + +### Arguments + +- collaborationId `String` + - The ID of the collaboration. Example: "1234" +- queryParams `GetCollaborationByIdQueryParams` + - Query parameters of getCollaborationById method +- headers `GetCollaborationByIdHeaders` + - Headers of getCollaborationById method + + +### Returns + +This function returns a value of type `Collaboration`. + +Returns a collaboration object. + + +## Update collaboration + +Updates a collaboration. +Can be used to change the owner of an item, or to +accept collaboration invites. + +This operation is performed by calling function `updateCollaborationById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-collaborations-id/). + + +``` +client.getUserCollaborations().updateCollaborationById(collaborationId, new UpdateCollaborationByIdRequestBody(UpdateCollaborationByIdRequestBodyRoleField.VIEWER)) +``` + +### Arguments + +- collaborationId `String` + - The ID of the collaboration. Example: "1234" +- requestBody `UpdateCollaborationByIdRequestBody` + - Request body of updateCollaborationById method +- headers `UpdateCollaborationByIdHeaders` + - Headers of updateCollaborationById method + + +### Returns + +This function returns a value of type `Collaboration`. + +Returns an updated collaboration object unless the owner has changed.If the role is changed to `owner`, the collaboration is deleted +and a new collaboration is created. The previous `owner` of +the old collaboration will be a `co-owner` on the new collaboration. + + +## Remove collaboration + +Deletes a single collaboration. + +This operation is performed by calling function `deleteCollaborationById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-collaborations-id/). + + +``` +client.getUserCollaborations().deleteCollaborationById(collaborationId) +``` + +### Arguments + +- collaborationId `String` + - The ID of the collaboration. Example: "1234" +- headers `DeleteCollaborationByIdHeaders` + - Headers of deleteCollaborationById method + + +### Returns + +This function returns a value of type `void`. + +A blank response is returned if the collaboration was +successfully deleted. + + +## Create collaboration + +Adds a collaboration for a single user or a single group to a file +or folder. + +Collaborations can be created using email address, user IDs, or a +group IDs. + +If a collaboration is being created with a group, access to +this endpoint is dependent on the group's ability to be invited. + +If collaboration is in `pending` status, the following fields +are redacted: +- `login` and `name` are hidden if a collaboration was created +using `user_id`, +- `name` is hidden if a collaboration was created using `login`. + +This operation is performed by calling function `createCollaboration`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-collaborations/). + + +``` +client.getUserCollaborations().createCollaboration(new CreateCollaborationRequestBody(new CreateCollaborationRequestBodyItemField.Builder().type(CreateCollaborationRequestBodyItemTypeField.FOLDER).id(folder.getId()).build(), new CreateCollaborationRequestBodyAccessibleByField.Builder(CreateCollaborationRequestBodyAccessibleByTypeField.USER).id(user.getId()).build(), CreateCollaborationRequestBodyRoleField.EDITOR)) +``` + +### Arguments + +- requestBody `CreateCollaborationRequestBody` + - Request body of createCollaboration method +- queryParams `CreateCollaborationQueryParams` + - Query parameters of createCollaboration method +- headers `CreateCollaborationHeaders` + - Headers of createCollaboration method + + +### Returns + +This function returns a value of type `Collaboration`. + +Returns a new collaboration object. + + diff --git a/docs/sdkgen/users.md b/docs/sdkgen/users.md new file mode 100644 index 000000000..43d35d544 --- /dev/null +++ b/docs/sdkgen/users.md @@ -0,0 +1,230 @@ +# UsersManager + + +- [List enterprise users](#list-enterprise-users) +- [Create user](#create-user) +- [Get current user](#get-current-user) +- [Get user](#get-user) +- [Update user](#update-user) +- [Delete user](#delete-user) + +## List enterprise users + +Returns a list of all users for the Enterprise along with their `user_id`, +`public_name`, and `login`. + +The application and the authenticated user need to +have the permission to look up users in the entire +enterprise. + +This operation is performed by calling function `getUsers`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-users/). + + +``` +client.getUsers().getUsers() +``` + +### Arguments + +- queryParams `GetUsersQueryParams` + - Query parameters of getUsers method +- headers `GetUsersHeaders` + - Headers of getUsers method + + +### Returns + +This function returns a value of type `Users`. + +Returns all of the users in the enterprise. + + +## Create user + +Creates a new managed user in an enterprise. This endpoint +is only available to users and applications with the right +admin permissions. + +This operation is performed by calling function `createUser`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-users/). + + +``` +client.getUsers().createUser(new CreateUserRequestBody.Builder(userName).login(userLogin).isPlatformAccessOnly(true).build()) +``` + +### Arguments + +- requestBody `CreateUserRequestBody` + - Request body of createUser method +- queryParams `CreateUserQueryParams` + - Query parameters of createUser method +- headers `CreateUserHeaders` + - Headers of createUser method + + +### Returns + +This function returns a value of type `UserFull`. + +Returns a user object for the newly created user. + + +## Get current user + +Retrieves information about the user who is currently authenticated. + +In the case of a client-side authenticated OAuth 2.0 application +this will be the user who authorized the app. + +In the case of a JWT, server-side authenticated application +this will be the service account that belongs to the application +by default. + +Use the `As-User` header to change who this API call is made on behalf of. + +This operation is performed by calling function `getUserMe`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-users-me/). + + +``` +client.getUsers().getUserMe() +``` + +### Arguments + +- queryParams `GetUserMeQueryParams` + - Query parameters of getUserMe method +- headers `GetUserMeHeaders` + - Headers of getUserMe method + + +### Returns + +This function returns a value of type `UserFull`. + +Returns a single user object. + + +## Get user + +Retrieves information about a user in the enterprise. + +The application and the authenticated user need to +have the permission to look up users in the entire +enterprise. + +This endpoint also returns a limited set of information +for external users who are collaborated on content +owned by the enterprise for authenticated users with the +right scopes. In this case, disallowed fields will return +null instead. + +This operation is performed by calling function `getUserById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-users-id/). + + +``` +client.getUsers().getUserById(user.getId()) +``` + +### Arguments + +- userId `String` + - The ID of the user. Example: "12345" +- queryParams `GetUserByIdQueryParams` + - Query parameters of getUserById method +- headers `GetUserByIdHeaders` + - Headers of getUserById method + + +### Returns + +This function returns a value of type `UserFull`. + +Returns a single user object. + +Not all available fields are returned by default. Use the +[fields](#param-fields) query parameter to explicitly request +any specific fields using the [fields](#get-users-id--request--fields) +parameter. + + +## Update user + +Updates a managed or app user in an enterprise. This endpoint +is only available to users and applications with the right +admin permissions. + +This operation is performed by calling function `updateUserById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-users-id/). + + +``` +client.getUsers().updateUserById(user.getId(), new UpdateUserByIdRequestBody.Builder().name(updatedUserName).build()) +``` + +### Arguments + +- userId `String` + - The ID of the user. Example: "12345" +- requestBody `UpdateUserByIdRequestBody` + - Request body of updateUserById method +- queryParams `UpdateUserByIdQueryParams` + - Query parameters of updateUserById method +- headers `UpdateUserByIdHeaders` + - Headers of updateUserById method + + +### Returns + +This function returns a value of type `UserFull`. + +Returns the updated user object. + + +## Delete user + +Deletes a user. By default this will fail if the user +still owns any content. Move their owned content first +before proceeding, or use the `force` field to delete +the user and their files. + +This operation is performed by calling function `deleteUserById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-users-id/). + + +``` +client.getUsers().deleteUserById(user.getId()) +``` + +### Arguments + +- userId `String` + - The ID of the user. Example: "12345" +- queryParams `DeleteUserByIdQueryParams` + - Query parameters of deleteUserById method +- headers `DeleteUserByIdHeaders` + - Headers of deleteUserById method + + +### Returns + +This function returns a value of type `void`. + +Removes the user and returns an empty response. + + diff --git a/docs/sdkgen/webhooks.md b/docs/sdkgen/webhooks.md new file mode 100644 index 000000000..06989090a --- /dev/null +++ b/docs/sdkgen/webhooks.md @@ -0,0 +1,196 @@ +# WebhooksManager + + +- [List all webhooks](#list-all-webhooks) +- [Create webhook](#create-webhook) +- [Get webhook](#get-webhook) +- [Update webhook](#update-webhook) +- [Remove webhook](#remove-webhook) +- [Validate a webhook message](#validate-a-webhook-message) + +## List all webhooks + +Returns all defined webhooks for the requesting application. + +This API only returns webhooks that are applied to files or folders that are +owned by the authenticated user. This means that an admin can not see webhooks +created by a service account unless the admin has access to those folders, and +vice versa. + +This operation is performed by calling function `getWebhooks`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-webhooks/). + + +``` +client.getWebhooks().getWebhooks() +``` + +### Arguments + +- queryParams `GetWebhooksQueryParams` + - Query parameters of getWebhooks method +- headers `GetWebhooksHeaders` + - Headers of getWebhooks method + + +### Returns + +This function returns a value of type `Webhooks`. + +Returns a list of webhooks. + + +## Create webhook + +Creates a webhook. + +This operation is performed by calling function `createWebhook`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-webhooks/). + + +``` +client.getWebhooks().createWebhook(new CreateWebhookRequestBody(new CreateWebhookRequestBodyTargetField.Builder().id(folder.getId()).type(CreateWebhookRequestBodyTargetTypeField.FOLDER).build(), "https://example.com/new-webhook", Arrays.asList(CreateWebhookRequestBodyTriggersField.FILE_UPLOADED))) +``` + +### Arguments + +- requestBody `CreateWebhookRequestBody` + - Request body of createWebhook method +- headers `CreateWebhookHeaders` + - Headers of createWebhook method + + +### Returns + +This function returns a value of type `Webhook`. + +Returns the new webhook object. + + +## Get webhook + +Retrieves a specific webhook. + +This operation is performed by calling function `getWebhookById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-webhooks-id/). + + +``` +client.getWebhooks().getWebhookById(webhook.getId()) +``` + +### Arguments + +- webhookId `String` + - The ID of the webhook. Example: "3321123" +- headers `GetWebhookByIdHeaders` + - Headers of getWebhookById method + + +### Returns + +This function returns a value of type `Webhook`. + +Returns a webhook object. + + +## Update webhook + +Updates a webhook. + +This operation is performed by calling function `updateWebhookById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-webhooks-id/). + + +``` +client.getWebhooks().updateWebhookById(webhook.getId(), new UpdateWebhookByIdRequestBody.Builder().address("https://example.com/updated-webhook").build()) +``` + +### Arguments + +- webhookId `String` + - The ID of the webhook. Example: "3321123" +- requestBody `UpdateWebhookByIdRequestBody` + - Request body of updateWebhookById method +- headers `UpdateWebhookByIdHeaders` + - Headers of updateWebhookById method + + +### Returns + +This function returns a value of type `Webhook`. + +Returns the new webhook object. + + +## Remove webhook + +Deletes a webhook. + +This operation is performed by calling function `deleteWebhookById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-webhooks-id/). + + +``` +client.getWebhooks().deleteWebhookById(webhook.getId()) +``` + +### Arguments + +- webhookId `String` + - The ID of the webhook. Example: "3321123" +- headers `DeleteWebhookByIdHeaders` + - Headers of deleteWebhookById method + + +### Returns + +This function returns a value of type `void`. + +An empty response will be returned when the webhook +was successfully deleted. + + +## Validate a webhook message + +Validate a webhook message by verifying the signature and the delivery timestamp + +This operation is performed by calling function `validateMessage`. + + + +``` +WebhooksManager.validateMessage(body, headersWithCorrectDatetime, primaryKey, secondaryKey) +``` + +### Arguments + +- body `String` + - The request body of the webhook message +- headers `Map` + - The headers of the webhook message +- primaryKey `String` + - The primary signature to verify the message with +- secondaryKey `String` + - The secondary signature to verify the message with +- maxAge `Integer` + - The maximum age of the message in seconds, defaults to 10 minutes + + +### Returns + +This function returns a value of type `boolean`. + + + + diff --git a/docs/sdkgen/weblinks.md b/docs/sdkgen/weblinks.md new file mode 100644 index 000000000..14e0cefdb --- /dev/null +++ b/docs/sdkgen/weblinks.md @@ -0,0 +1,127 @@ +# WebLinksManager + + +- [Create web link](#create-web-link) +- [Get web link](#get-web-link) +- [Update web link](#update-web-link) +- [Remove web link](#remove-web-link) + +## Create web link + +Creates a web link object within a folder. + +This operation is performed by calling function `createWebLink`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-web-links/). + + +``` +client.getWebLinks().createWebLink(new CreateWebLinkRequestBody.Builder(url, new CreateWebLinkRequestBodyParentField(parent.getId())).name(name).description(description).build()) +``` + +### Arguments + +- requestBody `CreateWebLinkRequestBody` + - Request body of createWebLink method +- headers `CreateWebLinkHeaders` + - Headers of createWebLink method + + +### Returns + +This function returns a value of type `WebLink`. + +Returns the newly created web link object. + + +## Get web link + +Retrieve information about a web link. + +This operation is performed by calling function `getWebLinkById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-web-links-id/). + + +``` +client.getWebLinks().getWebLinkById(weblink.getId()) +``` + +### Arguments + +- webLinkId `String` + - The ID of the web link. Example: "12345" +- headers `GetWebLinkByIdHeaders` + - Headers of getWebLinkById method + + +### Returns + +This function returns a value of type `WebLink`. + +Returns the web link object. + + +## Update web link + +Updates a web link object. + +This operation is performed by calling function `updateWebLinkById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/put-web-links-id/). + + +``` +client.getWebLinks().updateWebLinkById(weblink.getId(), new UpdateWebLinkByIdRequestBody.Builder().name(updatedName).sharedLink(new UpdateWebLinkByIdRequestBodySharedLinkField.Builder().access(UpdateWebLinkByIdRequestBodySharedLinkAccessField.OPEN).password(password).build()).build()) +``` + +### Arguments + +- webLinkId `String` + - The ID of the web link. Example: "12345" +- requestBody `UpdateWebLinkByIdRequestBody` + - Request body of updateWebLinkById method +- headers `UpdateWebLinkByIdHeaders` + - Headers of updateWebLinkById method + + +### Returns + +This function returns a value of type `WebLink`. + +Returns the updated web link object. + + +## Remove web link + +Deletes a web link. + +This operation is performed by calling function `deleteWebLinkById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-web-links-id/). + + +``` +client.getWebLinks().deleteWebLinkById(weblink.getId()) +``` + +### Arguments + +- webLinkId `String` + - The ID of the web link. Example: "12345" +- headers `DeleteWebLinkByIdHeaders` + - Headers of deleteWebLinkById method + + +### Returns + +This function returns a value of type `void`. + +An empty response will be returned when the web link +was successfully deleted. + + diff --git a/docs/sdkgen/workflows.md b/docs/sdkgen/workflows.md new file mode 100644 index 000000000..f3ca3b98b --- /dev/null +++ b/docs/sdkgen/workflows.md @@ -0,0 +1,73 @@ +# WorkflowsManager + + +- [List workflows](#list-workflows) +- [Starts workflow based on request body](#starts-workflow-based-on-request-body) + +## List workflows + +Returns list of workflows that act on a given `folder ID`, and +have a flow with a trigger type of `WORKFLOW_MANUAL_START`. + +You application must be authorized to use the `Manage Box Relay` application +scope within the developer console in to use this endpoint. + +This operation is performed by calling function `getWorkflows`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-workflows/). + + +``` +adminClient.getWorkflows().getWorkflows(new GetWorkflowsQueryParams(workflowFolderId)) +``` + +### Arguments + +- queryParams `GetWorkflowsQueryParams` + - Query parameters of getWorkflows method +- headers `GetWorkflowsHeaders` + - Headers of getWorkflows method + + +### Returns + +This function returns a value of type `Workflows`. + +Returns the workflow. + + +## Starts workflow based on request body + +Initiates a flow with a trigger type of `WORKFLOW_MANUAL_START`. + +You application must be authorized to use the `Manage Box Relay` application +scope within the developer console. + +This operation is performed by calling function `startWorkflow`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-workflows-id-start/). + + +``` +adminClient.getWorkflows().startWorkflow(workflowToRun.getId(), new StartWorkflowRequestBody.Builder(new StartWorkflowRequestBodyFlowField.Builder().type("flow").id(workflowToRun.getFlows().get(0).getId()).build(), Arrays.asList(new StartWorkflowRequestBodyFilesField.Builder().type(StartWorkflowRequestBodyFilesTypeField.FILE).id(workflowFileId).build()), new StartWorkflowRequestBodyFolderField.Builder().type(StartWorkflowRequestBodyFolderTypeField.FOLDER).id(workflowFolderId).build()).type(StartWorkflowRequestBodyTypeField.WORKFLOW_PARAMETERS).build()) +``` + +### Arguments + +- workflowId `String` + - The ID of the workflow. Example: "12345" +- requestBody `StartWorkflowRequestBody` + - Request body of startWorkflow method +- headers `StartWorkflowHeaders` + - Headers of startWorkflow method + + +### Returns + +This function returns a value of type `void`. + +Starts the workflow. + + diff --git a/docs/sdkgen/zipdownloads.md b/docs/sdkgen/zipdownloads.md new file mode 100644 index 000000000..8d8fda3c5 --- /dev/null +++ b/docs/sdkgen/zipdownloads.md @@ -0,0 +1,163 @@ +# ZipDownloadsManager + + +- [Create zip download](#create-zip-download) +- [Download zip archive](#download-zip-archive) +- [Get zip download status](#get-zip-download-status) +- [Download ZIP](#download-zip) + +## Create zip download + +Creates a request to download multiple files and folders as a single `zip` +archive file. This API does not return the archive but instead performs all +the checks to ensure that the user has access to all the items, and then +returns a `download_url` and a `status_url` that can be used to download the +archive. + +The limit for an archive is either the Account's upload limit or +10,000 files, whichever is met first. + +**Note**: Downloading a large file can be +affected by various +factors such as distance, network latency, +bandwidth, and congestion, as well as packet loss +ratio and current server load. +For these reasons we recommend that a maximum ZIP archive +total size does not exceed 25GB. + +This operation is performed by calling function `createZipDownload`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-zip-downloads/). + + +``` +client.getZipDownloads().createZipDownload(new ZipDownloadRequest.Builder(Arrays.asList(new ZipDownloadRequestItemsField(ZipDownloadRequestItemsTypeField.FILE, file1.getId()), new ZipDownloadRequestItemsField(ZipDownloadRequestItemsTypeField.FILE, file2.getId()), new ZipDownloadRequestItemsField(ZipDownloadRequestItemsTypeField.FOLDER, folder1.getId()))).downloadFileName("zip").build()) +``` + +### Arguments + +- requestBody `ZipDownloadRequest` + - Request body of createZipDownload method +- headers `CreateZipDownloadHeaders` + - Headers of createZipDownload method + + +### Returns + +This function returns a value of type `ZipDownload`. + +If the `zip` archive is ready to be downloaded, the API will return a +response that will include a `download_url`, a `status_url`, as well as +any conflicts that might have occurred when creating the request. + + +## Download zip archive + +Returns the contents of a `zip` archive in binary format. This URL does not +require any form of authentication and could be used in a user's browser to +download the archive to a user's device. + +By default, this URL is only valid for a few seconds from the creation of +the request for this archive. Once a download has started it can not be +stopped and resumed, instead a new request for a zip archive would need to +be created. + +The URL of this endpoint should not be considered as fixed. Instead, use +the [Create zip download](e://post_zip_downloads) API to request to create a +`zip` archive, and then follow the `download_url` field in the response to +this endpoint. + +This operation is performed by calling function `getZipDownloadContent`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-zip-downloads-id-content/). + + +``` +client.getZipDownloads().getZipDownloadContent(zipDownload.getDownloadUrl()) +``` + +### Arguments + +- downloadUrl `String` + - The URL that can be used to download created `zip` archive. Example: `https://dl.boxcloud.com/2.0/zip_downloads/29l00nfxDyHOt7RphI9zT_w==nDnZEDjY2S8iEWWCHEEiptFxwoWojjlibZjJ6geuE5xnXENDTPxzgbks_yY=/content` +- headers `GetZipDownloadContentHeaders` + - Headers of getZipDownloadContent method + + +### Returns + +This function returns a value of type `InputStream`. + +Returns the content of the items requested for this download, formatted as +a stream of files and folders in a `zip` archive. + + +## Get zip download status + +Returns the download status of a `zip` archive, allowing an application to +inspect the progress of the download as well as the number of items that +might have been skipped. + +This endpoint can only be accessed once the download has started. +Subsequently this endpoint is valid for 12 hours from the start of the +download. + +The URL of this endpoint should not be considered as fixed. Instead, use +the [Create zip download](e://post_zip_downloads) API to request to create a +`zip` archive, and then follow the `status_url` field in the response to +this endpoint. + +This operation is performed by calling function `getZipDownloadStatus`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-zip-downloads-id-status/). + + +``` +client.getZipDownloads().getZipDownloadStatus(zipDownload.getStatusUrl()) +``` + +### Arguments + +- statusUrl `String` + - The URL that can be used to get the status of the `zip` archive being downloaded. Example: `https://dl.boxcloud.com/2.0/zip_downloads/29l00nfxDyHOt7RphI9zT_w==nDnZEDjY2S8iEWWCHEEiptFxwoWojjlibZjJ6geuE5xnXENDTPxzgbks_yY=/status` +- headers `GetZipDownloadStatusHeaders` + - Headers of getZipDownloadStatus method + + +### Returns + +This function returns a value of type `ZipDownloadStatus`. + +Returns the status of the `zip` archive that is being downloaded. + + +## Download ZIP + +Creates a zip and downloads its content + +This operation is performed by calling function `downloadZip`. + + + +``` +client.getZipDownloads().downloadZip(new ZipDownloadRequest.Builder(Arrays.asList(new ZipDownloadRequestItemsField(ZipDownloadRequestItemsTypeField.FILE, file1.getId()), new ZipDownloadRequestItemsField(ZipDownloadRequestItemsTypeField.FILE, file2.getId()), new ZipDownloadRequestItemsField(ZipDownloadRequestItemsTypeField.FOLDER, folder1.getId()))).downloadFileName("zip").build()) +``` + +### Arguments + +- requestBody `ZipDownloadRequest` + - Zip download request body +- headers `DownloadZipHeaders` + - Headers of zip download method + + +### Returns + +This function returns a value of type `InputStream`. + + + + diff --git a/src/example/java/com/box/sdk/example/AccessAsAppUser.java b/src/example/java/com/box/sdk/example/AccessAsAppUser.java index c9aee4890..bedeac19f 100644 --- a/src/example/java/com/box/sdk/example/AccessAsAppUser.java +++ b/src/example/java/com/box/sdk/example/AccessAsAppUser.java @@ -12,52 +12,53 @@ import java.io.IOException; import java.io.Reader; - public final class AccessAsAppUser { - private static final String USER_ID = ""; - private static final int MAX_DEPTH = 1; - private static final int MAX_CACHE_ENTRIES = 100; + private static final String USER_ID = ""; + private static final int MAX_DEPTH = 1; + private static final int MAX_CACHE_ENTRIES = 100; - private AccessAsAppUser() { - } + private AccessAsAppUser() {} - public static void main(String[] args) throws IOException { - // Limit logging messages to prevent polluting the output. - BoxLogger.defaultLogger().setLevelToWarning(); + public static void main(String[] args) throws IOException { + // Limit logging messages to prevent polluting the output. + BoxLogger.defaultLogger().setLevelToWarning(); - //It is a best practice to use an access token cache to prevent unneeded requests to Box for access tokens. - //For production applications it is recommended to use a distributed cache like Memcached or Redis, and to - //implement IAccessTokenCache to store and retrieve access tokens appropriately for your environment. - IAccessTokenCache accessTokenCache = new InMemoryLRUAccessTokenCache(MAX_CACHE_ENTRIES); + // It is a best practice to use an access token cache to prevent unneeded requests to Box for + // access tokens. + // For production applications it is recommended to use a distributed cache like Memcached or + // Redis, and to + // implement IAccessTokenCache to store and retrieve access tokens appropriately for your + // environment. + IAccessTokenCache accessTokenCache = new InMemoryLRUAccessTokenCache(MAX_CACHE_ENTRIES); - Reader reader = new FileReader("src/example/config/config.json"); - BoxConfig boxConfig = BoxConfig.readFrom(reader); + Reader reader = new FileReader("src/example/config/config.json"); + BoxConfig boxConfig = BoxConfig.readFrom(reader); - BoxDeveloperEditionAPIConnection api = BoxDeveloperEditionAPIConnection - .getUserConnection(USER_ID, boxConfig, accessTokenCache); + BoxDeveloperEditionAPIConnection api = + BoxDeveloperEditionAPIConnection.getUserConnection(USER_ID, boxConfig, accessTokenCache); - BoxUser.Info userInfo = BoxUser.getCurrentUser(api).getInfo(); - System.out.format("Welcome, %s!\n\n", userInfo.getName()); + BoxUser.Info userInfo = BoxUser.getCurrentUser(api).getInfo(); + System.out.format("Welcome, %s!\n\n", userInfo.getName()); - BoxFolder rootFolder = BoxFolder.getRootFolder(api); - listFolder(rootFolder, 0); - } + BoxFolder rootFolder = BoxFolder.getRootFolder(api); + listFolder(rootFolder, 0); + } + + private static void listFolder(BoxFolder folder, int depth) { + for (BoxItem.Info itemInfo : folder) { + StringBuilder indent = new StringBuilder(); + for (int i = 0; i < depth; i++) { + indent.append(" "); + } - private static void listFolder(BoxFolder folder, int depth) { - for (BoxItem.Info itemInfo : folder) { - StringBuilder indent = new StringBuilder(); - for (int i = 0; i < depth; i++) { - indent.append(" "); - } - - System.out.println(indent + itemInfo.getName()); - if (itemInfo instanceof BoxFolder.Info) { - BoxFolder childFolder = (BoxFolder) itemInfo.getResource(); - if (depth < MAX_DEPTH) { - listFolder(childFolder, depth + 1); - } - } + System.out.println(indent + itemInfo.getName()); + if (itemInfo instanceof BoxFolder.Info) { + BoxFolder childFolder = (BoxFolder) itemInfo.getResource(); + if (depth < MAX_DEPTH) { + listFolder(childFolder, depth + 1); } + } } + } } diff --git a/src/example/java/com/box/sdk/example/BoxDeveloperEditionAPIConnectionAsEnterpriseUser.java b/src/example/java/com/box/sdk/example/BoxDeveloperEditionAPIConnectionAsEnterpriseUser.java index c36a50206..213b1005d 100644 --- a/src/example/java/com/box/sdk/example/BoxDeveloperEditionAPIConnectionAsEnterpriseUser.java +++ b/src/example/java/com/box/sdk/example/BoxDeveloperEditionAPIConnectionAsEnterpriseUser.java @@ -13,31 +13,34 @@ public final class BoxDeveloperEditionAPIConnectionAsEnterpriseUser { - private static final String USER_ID = ""; - private static final int MAX_DEPTH = 1; - private static final int MAX_CACHE_ENTRIES = 100; + private static final String USER_ID = ""; + private static final int MAX_DEPTH = 1; + private static final int MAX_CACHE_ENTRIES = 100; - private static BoxDeveloperEditionAPIConnection api; + private static BoxDeveloperEditionAPIConnection api; - private BoxDeveloperEditionAPIConnectionAsEnterpriseUser() { - } + private BoxDeveloperEditionAPIConnectionAsEnterpriseUser() {} - public static void main(String[] args) throws IOException { - // Limit logging messages to prevent polluting the output. - BoxLogger.defaultLogger().setLevelToWarning(); + public static void main(String[] args) throws IOException { + // Limit logging messages to prevent polluting the output. + BoxLogger.defaultLogger().setLevelToWarning(); - //It is a best practice to use an access token cache to prevent unneeded requests to Box for access tokens. - //For production applications it is recommended to use a distributed cache like Memcached or Redis, and to - //implement IAccessTokenCache to store and retrieve access tokens appropriately for your environment. - IAccessTokenCache accessTokenCache = new InMemoryLRUAccessTokenCache(MAX_CACHE_ENTRIES); + // It is a best practice to use an access token cache to prevent unneeded requests to Box for + // access tokens. + // For production applications it is recommended to use a distributed cache like Memcached or + // Redis, and to + // implement IAccessTokenCache to store and retrieve access tokens appropriately for your + // environment. + IAccessTokenCache accessTokenCache = new InMemoryLRUAccessTokenCache(MAX_CACHE_ENTRIES); - Reader reader = new FileReader("src/example/config/config.json"); - BoxConfig boxConfig = BoxConfig.readFrom(reader); + Reader reader = new FileReader("src/example/config/config.json"); + BoxConfig boxConfig = BoxConfig.readFrom(reader); - api = new BoxDeveloperEditionAPIConnection(USER_ID, DeveloperEditionEntityType.USER, boxConfig, - accessTokenCache); + api = + new BoxDeveloperEditionAPIConnection( + USER_ID, DeveloperEditionEntityType.USER, boxConfig, accessTokenCache); - BoxUser.Info userInfo = BoxUser.getCurrentUser(api).getInfo(); - System.out.format("Welcome, %s!\n\n", userInfo.getName()); - } + BoxUser.Info userInfo = BoxUser.getCurrentUser(api).getInfo(); + System.out.format("Welcome, %s!\n\n", userInfo.getName()); + } } diff --git a/src/example/java/com/box/sdk/example/CreateAppUser.java b/src/example/java/com/box/sdk/example/CreateAppUser.java index 00ba03a63..2be55421c 100644 --- a/src/example/java/com/box/sdk/example/CreateAppUser.java +++ b/src/example/java/com/box/sdk/example/CreateAppUser.java @@ -11,39 +11,39 @@ import java.io.IOException; import java.io.Reader; - public final class CreateAppUser { - private static final String APP_USER_NAME = ""; - private static final String EXTERNAL_APP_USER_ID = ""; - private static final int MAX_CACHE_ENTRIES = 100; - - private CreateAppUser() { - } + private static final String APP_USER_NAME = ""; + private static final String EXTERNAL_APP_USER_ID = ""; + private static final int MAX_CACHE_ENTRIES = 100; - public static void main(String[] args) throws IOException { - // Limit logging messages to prevent polluting the output. - BoxLogger.defaultLogger().setLevelToWarning(); + private CreateAppUser() {} + public static void main(String[] args) throws IOException { + // Limit logging messages to prevent polluting the output. + BoxLogger.defaultLogger().setLevelToWarning(); - //It is a best practice to use an access token cache to prevent unneeded requests to Box for access tokens. - //For production applications it is recommended to use a distributed cache like Memcached or Redis, and to - //implement IAccessTokenCache to store and retrieve access tokens appropriately for your environment. - IAccessTokenCache accessTokenCache = new InMemoryLRUAccessTokenCache(MAX_CACHE_ENTRIES); + // It is a best practice to use an access token cache to prevent unneeded requests to Box for + // access tokens. + // For production applications it is recommended to use a distributed cache like Memcached or + // Redis, and to + // implement IAccessTokenCache to store and retrieve access tokens appropriately for your + // environment. + IAccessTokenCache accessTokenCache = new InMemoryLRUAccessTokenCache(MAX_CACHE_ENTRIES); - Reader reader = new FileReader("src/example/config/config.json"); - BoxConfig boxConfig = BoxConfig.readFrom(reader); + Reader reader = new FileReader("src/example/config/config.json"); + BoxConfig boxConfig = BoxConfig.readFrom(reader); - BoxDeveloperEditionAPIConnection api = BoxDeveloperEditionAPIConnection.getAppEnterpriseConnection( - boxConfig, accessTokenCache); + BoxDeveloperEditionAPIConnection api = + BoxDeveloperEditionAPIConnection.getAppEnterpriseConnection(boxConfig, accessTokenCache); - CreateUserParams params = new CreateUserParams(); - params.setSpaceAmount(1073741824); //1 GB - //This optional param can be used to store any id, like an email, of the user - //for which the associated app user is being created. - params.setExternalAppUserId(EXTERNAL_APP_USER_ID); - BoxUser.Info user = BoxUser.createAppUser(api, APP_USER_NAME, params); + CreateUserParams params = new CreateUserParams(); + params.setSpaceAmount(1073741824); // 1 GB + // This optional param can be used to store any id, like an email, of the user + // for which the associated app user is being created. + params.setExternalAppUserId(EXTERNAL_APP_USER_ID); + BoxUser.Info user = BoxUser.createAppUser(api, APP_USER_NAME, params); - System.out.format("User created with name %s and id %s\n\n", APP_USER_NAME, user.getID()); - } + System.out.format("User created with name %s and id %s\n\n", APP_USER_NAME, user.getID()); + } } diff --git a/src/example/java/com/box/sdk/example/Main.java b/src/example/java/com/box/sdk/example/Main.java index 5cbc33f72..24408ffe7 100644 --- a/src/example/java/com/box/sdk/example/Main.java +++ b/src/example/java/com/box/sdk/example/Main.java @@ -7,39 +7,38 @@ import com.box.sdk.BoxUser; public final class Main { - private static final String DEVELOPER_TOKEN = ""; - private static final int MAX_DEPTH = 1; + private static final String DEVELOPER_TOKEN = ""; + private static final int MAX_DEPTH = 1; - private Main() { - } + private Main() {} - public static void main(String[] args) { - // Limit logging messages to prevent polluting the output. - BoxLogger.defaultLogger().setLevelToWarning(); + public static void main(String[] args) { + // Limit logging messages to prevent polluting the output. + BoxLogger.defaultLogger().setLevelToWarning(); - BoxAPIConnection api = new BoxAPIConnection(DEVELOPER_TOKEN); + BoxAPIConnection api = new BoxAPIConnection(DEVELOPER_TOKEN); - BoxUser.Info userInfo = BoxUser.getCurrentUser(api).getInfo(); - System.out.format("Welcome, %s <%s>!\n\n", userInfo.getName(), userInfo.getLogin()); + BoxUser.Info userInfo = BoxUser.getCurrentUser(api).getInfo(); + System.out.format("Welcome, %s <%s>!\n\n", userInfo.getName(), userInfo.getLogin()); - BoxFolder rootFolder = BoxFolder.getRootFolder(api); - listFolder(rootFolder, 0); - } + BoxFolder rootFolder = BoxFolder.getRootFolder(api); + listFolder(rootFolder, 0); + } + + private static void listFolder(BoxFolder folder, int depth) { + for (BoxItem.Info itemInfo : folder) { + StringBuilder indent = new StringBuilder(); + for (int i = 0; i < depth; i++) { + indent.append(" "); + } - private static void listFolder(BoxFolder folder, int depth) { - for (BoxItem.Info itemInfo : folder) { - StringBuilder indent = new StringBuilder(); - for (int i = 0; i < depth; i++) { - indent.append(" "); - } - - System.out.println(indent + itemInfo.getName()); - if (itemInfo instanceof BoxFolder.Info) { - BoxFolder childFolder = (BoxFolder) itemInfo.getResource(); - if (depth < MAX_DEPTH) { - listFolder(childFolder, depth + 1); - } - } + System.out.println(indent + itemInfo.getName()); + if (itemInfo instanceof BoxFolder.Info) { + BoxFolder childFolder = (BoxFolder) itemInfo.getResource(); + if (depth < MAX_DEPTH) { + listFolder(childFolder, depth + 1); } + } } + } } diff --git a/src/example/java/com/box/sdk/example/SearchExamplesAsAppUser.java b/src/example/java/com/box/sdk/example/SearchExamplesAsAppUser.java index f69dc92ce..3ae7c28c6 100644 --- a/src/example/java/com/box/sdk/example/SearchExamplesAsAppUser.java +++ b/src/example/java/com/box/sdk/example/SearchExamplesAsAppUser.java @@ -25,331 +25,328 @@ public final class SearchExamplesAsAppUser { - private static final String USER_ID = ""; - private static final int MAX_CACHE_ENTRIES = 100; + private static final String USER_ID = ""; + private static final int MAX_CACHE_ENTRIES = 100; - private static BoxDeveloperEditionAPIConnection api; + private static BoxDeveloperEditionAPIConnection api; - private SearchExamplesAsAppUser() { - } - - public static void main(String[] args) throws IOException { - // Limit logging messages to prevent polluting the output. - Logger.getLogger("com.box.sdk").setLevel(Level.WARNING); + private SearchExamplesAsAppUser() {} - //It is a best practice to use an access token cache to prevent unneeded requests to Box for access tokens. - //For production applications it is recommended to use a distributed cache like Memcached or Redis, and to - //implement IAccessTokenCache to store and retrieve access tokens appropriately for your environment. - IAccessTokenCache accessTokenCache = new InMemoryLRUAccessTokenCache(MAX_CACHE_ENTRIES); + public static void main(String[] args) throws IOException { + // Limit logging messages to prevent polluting the output. + Logger.getLogger("com.box.sdk").setLevel(Level.WARNING); - Reader reader = new FileReader("src/example/config/config.json"); - BoxConfig boxConfig = BoxConfig.readFrom(reader); + // It is a best practice to use an access token cache to prevent unneeded requests to Box for + // access tokens. + // For production applications it is recommended to use a distributed cache like Memcached or + // Redis, and to + // implement IAccessTokenCache to store and retrieve access tokens appropriately for your + // environment. + IAccessTokenCache accessTokenCache = new InMemoryLRUAccessTokenCache(MAX_CACHE_ENTRIES); - api = BoxDeveloperEditionAPIConnection.getUserConnection(USER_ID, boxConfig, accessTokenCache); + Reader reader = new FileReader("src/example/config/config.json"); + BoxConfig boxConfig = BoxConfig.readFrom(reader); - BoxUser.Info userInfo = BoxUser.getCurrentUser(api).getInfo(); - System.out.format("Welcome, %s!\n\n", userInfo.getName()); + api = BoxDeveloperEditionAPIConnection.getUserConnection(USER_ID, boxConfig, accessTokenCache); - BoxSearch boxSearch = new BoxSearch(api); + BoxUser.Info userInfo = BoxUser.getCurrentUser(api).getInfo(); + System.out.format("Welcome, %s!\n\n", userInfo.getName()); - searchExample(boxSearch); - } + BoxSearch boxSearch = new BoxSearch(api); - private static void searchExample(BoxSearch bs) { - /** - * Use this class to specify all the different search parameters that you may want to use. - * Examples include: type, contentType, folderId's, metadata filters, created, updated. - * Also shows how to incrementally crawl result sets. - */ - BoxSearchParameters bsp = new BoxSearchParameters(); - - fileExtensionExample(bsp, bs); - ownerIdFilterExample(bsp, bs); - contentTypeFilterExample(bsp, bs); - createdDateFilterExample(bsp, bs); - updatedDateFilterExample(bsp, bs); - metaDataFilterDropdownExample(bsp, bs); - metaDataFilterGreaterThanNumberExample(bsp, bs); - metaDataFilterLessThanNumberExample(bsp, bs); - metaDataFilterGreaterThanDateExample(bsp, bs); - metaDataFilterLessThanDateExample(bsp, bs); - metaDataFilterGreaterLessThanDateExample(bsp, bs); + searchExample(boxSearch); + } + private static void searchExample(BoxSearch bs) { + /** + * Use this class to specify all the different search parameters that you may want to use. + * Examples include: type, contentType, folderId's, metadata filters, created, updated. Also + * shows how to incrementally crawl result sets. + */ + BoxSearchParameters bsp = new BoxSearchParameters(); + + fileExtensionExample(bsp, bs); + ownerIdFilterExample(bsp, bs); + contentTypeFilterExample(bsp, bs); + createdDateFilterExample(bsp, bs); + updatedDateFilterExample(bsp, bs); + metaDataFilterDropdownExample(bsp, bs); + metaDataFilterGreaterThanNumberExample(bsp, bs); + metaDataFilterLessThanNumberExample(bsp, bs); + metaDataFilterGreaterThanDateExample(bsp, bs); + metaDataFilterLessThanDateExample(bsp, bs); + metaDataFilterGreaterLessThanDateExample(bsp, bs); + } + + public static void crawlSearchResultExample(BoxSearchParameters bsp, BoxSearch bs) { + /** Example of how to crawl more than 1000+ results in a search query */ + + // Setup Result Partial Object + PartialCollection searchResults; + + // Starting point of the result set + long offset = 0; + // Number of results that would be pulled back + long limit = 1000; + + // Storing the full size of the results + long fullSizeOfResult = 0; + + while (offset <= fullSizeOfResult) { + searchResults = bs.searchRange(offset, limit, bsp); + fullSizeOfResult = searchResults.fullSize(); + + print("offset: " + offset + " of fullSizeOfResult: " + fullSizeOfResult); + printSearchResults(searchResults); + + offset += limit; } + } - public static void crawlSearchResultExample(BoxSearchParameters bsp, BoxSearch bs) { - /** - * Example of how to crawl more than 1000+ results in a search query - */ - - //Setup Result Partial Object - PartialCollection searchResults; - - //Starting point of the result set - long offset = 0; - //Number of results that would be pulled back - long limit = 1000; + public static void fileExtensionExample(BoxSearchParameters bsp, BoxSearch bs) { - //Storing the full size of the results - long fullSizeOfResult = 0; + print("******File Extension Search******"); + List fileExtensions = new ArrayList<>(); + fileExtensions.add("png"); + fileExtensions.add("docx"); - while (offset <= fullSizeOfResult) { - searchResults = bs.searchRange(offset, limit, bsp); - fullSizeOfResult = searchResults.fullSize(); + List ancestorFolderIds = new ArrayList<>(); + ancestorFolderIds.add("6725599265"); - print("offset: " + offset + " of fullSizeOfResult: " + fullSizeOfResult); - printSearchResults(searchResults); + bsp.setFileExtensions(fileExtensions); + bsp.setAncestorFolderIds(ancestorFolderIds); + bsp.setQuery("Testing"); - offset += limit; - } - } + crawlSearchResultExample(bsp, bs); + } - public static void fileExtensionExample(BoxSearchParameters bsp, BoxSearch bs) { + public static void ownerIdFilterExample(BoxSearchParameters bsp, BoxSearch bs) { - print("******File Extension Search******"); - List fileExtensions = new ArrayList<>(); - fileExtensions.add("png"); - fileExtensions.add("docx"); + print("******Owner Id's Filter Search******"); + List ownerUserIds = new ArrayList<>(); + ownerUserIds.add("268117237"); - List ancestorFolderIds = new ArrayList<>(); - ancestorFolderIds.add("6725599265"); + bsp.clearParameters(); + bsp.setQuery("Assemble"); + bsp.setOwnerUserIds(ownerUserIds); - bsp.setFileExtensions(fileExtensions); - bsp.setAncestorFolderIds(ancestorFolderIds); - bsp.setQuery("Testing"); + crawlSearchResultExample(bsp, bs); + } - crawlSearchResultExample(bsp, bs); - } + public static void contentTypeFilterExample(BoxSearchParameters bsp, BoxSearch bs) { + print("*****Description Search******"); + List contentTypes = new ArrayList<>(); + contentTypes.add("description"); - public static void ownerIdFilterExample(BoxSearchParameters bsp, BoxSearch bs) { + bsp.clearParameters(); + bsp.setContentTypes(contentTypes); + bsp.setQuery("test"); - print("******Owner Id's Filter Search******"); - List ownerUserIds = new ArrayList<>(); - ownerUserIds.add("268117237"); + crawlSearchResultExample(bsp, bs); + } - bsp.clearParameters(); - bsp.setQuery("Assemble"); - bsp.setOwnerUserIds(ownerUserIds); + public static void createdDateFilterExample(BoxSearchParameters bsp, BoxSearch bs) { + print("*****Created Date Range Search******"); + bsp.clearParameters(); + try { + SimpleDateFormat sdf = new SimpleDateFormat("M-dd-yyyy hh:mm:ss"); + String createdFromDateString = "01-31-2016 00:00:00"; + String createdToDateString = "04-01-2016 00:00:00"; - crawlSearchResultExample(bsp, bs); + Date createdFromDate = sdf.parse(createdFromDateString); + Date createdToDate = sdf.parse(createdToDateString); - } + DateRange createdRange = new DateRange(createdFromDate, createdToDate); - public static void contentTypeFilterExample(BoxSearchParameters bsp, BoxSearch bs) { - print("*****Description Search******"); - List contentTypes = new ArrayList<>(); - contentTypes.add("description"); + bsp.setCreatedRange(createdRange); + bsp.setQuery("File"); - bsp.clearParameters(); - bsp.setContentTypes(contentTypes); - bsp.setQuery("test"); + crawlSearchResultExample(bsp, bs); - crawlSearchResultExample(bsp, bs); + } catch (ParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); } + } - public static void createdDateFilterExample(BoxSearchParameters bsp, BoxSearch bs) { - print("*****Created Date Range Search******"); - bsp.clearParameters(); - try { - SimpleDateFormat sdf = new SimpleDateFormat("M-dd-yyyy hh:mm:ss"); - String createdFromDateString = "01-31-2016 00:00:00"; - String createdToDateString = "04-01-2016 00:00:00"; + public static void updatedDateFilterExample(BoxSearchParameters bsp, BoxSearch bs) { + print("*****Updated Date Range Search******"); + bsp.clearParameters(); + try { + SimpleDateFormat sdf = new SimpleDateFormat("M-dd-yyyy hh:mm:ss"); + String updatedFromDateString = "01-31-2016 00:00:00"; + String updatedToDateString = "05-01-2016 00:00:00"; - Date createdFromDate = sdf.parse(createdFromDateString); - Date createdToDate = sdf.parse(createdToDateString); + Date updatedFromDate = sdf.parse(updatedFromDateString); + Date updatedToDate = sdf.parse(updatedToDateString); - DateRange createdRange = new DateRange(createdFromDate, createdToDate); + DateRange updatedRange = new DateRange(updatedFromDate, updatedToDate); - bsp.setCreatedRange(createdRange); - bsp.setQuery("File"); + bsp.setUpdatedRange(updatedRange); + bsp.setQuery("File"); - crawlSearchResultExample(bsp, bs); + crawlSearchResultExample(bsp, bs); - } catch (ParseException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + } catch (ParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); } + } - public static void updatedDateFilterExample(BoxSearchParameters bsp, BoxSearch bs) { - print("*****Updated Date Range Search******"); - bsp.clearParameters(); - try { - SimpleDateFormat sdf = new SimpleDateFormat("M-dd-yyyy hh:mm:ss"); - String updatedFromDateString = "01-31-2016 00:00:00"; - String updatedToDateString = "05-01-2016 00:00:00"; + public static void metaDataFilterDropdownExample(BoxSearchParameters bsp, BoxSearch bs) { + print("******Metadata Filter Search Dropdown Value Check******"); + bsp.clearParameters(); - Date updatedFromDate = sdf.parse(updatedFromDateString); - Date updatedToDate = sdf.parse(updatedToDateString); + BoxMetadataFilter bmf = new BoxMetadataFilter(); + bmf.setScope("enterprise"); + bmf.setTemplateKey("test"); + SizeRange sizeRange = new SizeRange(12, 19); + bmf.addNumberRangeFilter("testnumber", sizeRange); - DateRange updatedRange = new DateRange(updatedFromDate, updatedToDate); + bmf.addFilter("test", "example"); - bsp.setUpdatedRange(updatedRange); - bsp.setQuery("File"); + bsp.setMetadataFilter(bmf); - crawlSearchResultExample(bsp, bs); + crawlSearchResultExample(bsp, bs); + } - } catch (ParseException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + public static void metaDataFilterGreaterThanNumberExample(BoxSearchParameters bsp, BoxSearch bs) { + print("******Metadata Filter Search Numbers Greater Than******"); + bsp.clearParameters(); - public static void metaDataFilterDropdownExample(BoxSearchParameters bsp, BoxSearch bs) { - print("******Metadata Filter Search Dropdown Value Check******"); - bsp.clearParameters(); + BoxMetadataFilter bmf = new BoxMetadataFilter(); + bmf.setScope("enterprise"); + bmf.setTemplateKey("test"); - BoxMetadataFilter bmf = new BoxMetadataFilter(); - bmf.setScope("enterprise"); - bmf.setTemplateKey("test"); + SizeRange sizeRange = new SizeRange(20, 0); + bmf.addNumberRangeFilter("testnumber", sizeRange); - SizeRange sizeRange = new SizeRange(12, 19); - bmf.addNumberRangeFilter("testnumber", sizeRange); + bsp.setMetadataFilter(bmf); - bmf.addFilter("test", "example"); + crawlSearchResultExample(bsp, bs); + } - bsp.setMetadataFilter(bmf); + public static void metaDataFilterLessThanNumberExample(BoxSearchParameters bsp, BoxSearch bs) { + print("******Metadata Filter Search Numbers Less Than******"); + bsp.clearParameters(); - crawlSearchResultExample(bsp, bs); - } + BoxMetadataFilter bmf = new BoxMetadataFilter(); + bmf.setScope("enterprise"); + bmf.setTemplateKey("test"); - public static void metaDataFilterGreaterThanNumberExample(BoxSearchParameters bsp, BoxSearch bs) { - print("******Metadata Filter Search Numbers Greater Than******"); - bsp.clearParameters(); + SizeRange sizeRange = new SizeRange(0, 20); + bmf.addNumberRangeFilter("testnumber", sizeRange); - BoxMetadataFilter bmf = new BoxMetadataFilter(); - bmf.setScope("enterprise"); - bmf.setTemplateKey("test"); + bsp.setMetadataFilter(bmf); - SizeRange sizeRange = new SizeRange(20, 0); - bmf.addNumberRangeFilter("testnumber", sizeRange); + crawlSearchResultExample(bsp, bs); + } - bsp.setMetadataFilter(bmf); + public static void metaDataFilterGreaterThanDateExample(BoxSearchParameters bsp, BoxSearch bs) { + print("******Metadata Filter Search Date Greater Than******"); + try { + bsp.clearParameters(); - crawlSearchResultExample(bsp, bs); - } + BoxMetadataFilter bmf = new BoxMetadataFilter(); + bmf.setScope("enterprise"); + bmf.setTemplateKey("test"); - public static void metaDataFilterLessThanNumberExample(BoxSearchParameters bsp, BoxSearch bs) { - print("******Metadata Filter Search Numbers Less Than******"); - bsp.clearParameters(); + SimpleDateFormat sdf = new SimpleDateFormat("M-dd-yyyy hh:mm:ss"); + String dateGreaterThanString = "03-01-2016 00:00:00"; - BoxMetadataFilter bmf = new BoxMetadataFilter(); - bmf.setScope("enterprise"); - bmf.setTemplateKey("test"); + Date dateGreaterThan = sdf.parse(dateGreaterThanString); - SizeRange sizeRange = new SizeRange(0, 20); - bmf.addNumberRangeFilter("testnumber", sizeRange); + DateRange dr = new DateRange(dateGreaterThan, null); - bsp.setMetadataFilter(bmf); + bmf.addDateRangeFilter("testDate", dr); - crawlSearchResultExample(bsp, bs); - } + bsp.setMetadataFilter(bmf); - public static void metaDataFilterGreaterThanDateExample(BoxSearchParameters bsp, BoxSearch bs) { - print("******Metadata Filter Search Date Greater Than******"); - try { - bsp.clearParameters(); - - BoxMetadataFilter bmf = new BoxMetadataFilter(); - bmf.setScope("enterprise"); - bmf.setTemplateKey("test"); - - SimpleDateFormat sdf = new SimpleDateFormat("M-dd-yyyy hh:mm:ss"); - String dateGreaterThanString = "03-01-2016 00:00:00"; - - Date dateGreaterThan = sdf.parse(dateGreaterThanString); - - DateRange dr = new DateRange(dateGreaterThan, null); - - bmf.addDateRangeFilter("testDate", dr); - - bsp.setMetadataFilter(bmf); - - crawlSearchResultExample(bsp, bs); - - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + crawlSearchResultExample(bsp, bs); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); } + } - public static void metaDataFilterLessThanDateExample(BoxSearchParameters bsp, BoxSearch bs) { - print("******Metadata Filter Search Date Less Than******"); - try { - bsp.clearParameters(); - - BoxMetadataFilter bmf = new BoxMetadataFilter(); - bmf.setScope("enterprise"); - bmf.setTemplateKey("test"); + public static void metaDataFilterLessThanDateExample(BoxSearchParameters bsp, BoxSearch bs) { + print("******Metadata Filter Search Date Less Than******"); + try { + bsp.clearParameters(); - SimpleDateFormat sdf = new SimpleDateFormat("M-dd-yyyy hh:mm:ss"); - String dateLessThanString = "05-03-2016 00:00:00"; + BoxMetadataFilter bmf = new BoxMetadataFilter(); + bmf.setScope("enterprise"); + bmf.setTemplateKey("test"); + SimpleDateFormat sdf = new SimpleDateFormat("M-dd-yyyy hh:mm:ss"); + String dateLessThanString = "05-03-2016 00:00:00"; - Date dateLessThan = sdf.parse(dateLessThanString); + Date dateLessThan = sdf.parse(dateLessThanString); - DateRange dr = new DateRange(null, dateLessThan); + DateRange dr = new DateRange(null, dateLessThan); - bmf.addDateRangeFilter("testDate", dr); + bmf.addDateRangeFilter("testDate", dr); - bsp.setMetadataFilter(bmf); + bsp.setMetadataFilter(bmf); - crawlSearchResultExample(bsp, bs); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + crawlSearchResultExample(bsp, bs); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); } + } - public static void metaDataFilterGreaterLessThanDateExample(BoxSearchParameters bsp, BoxSearch bs) { - print("******Metadata Filter Search Date Range Both GT and LT******"); - try { - bsp.clearParameters(); + public static void metaDataFilterGreaterLessThanDateExample( + BoxSearchParameters bsp, BoxSearch bs) { + print("******Metadata Filter Search Date Range Both GT and LT******"); + try { + bsp.clearParameters(); - BoxMetadataFilter bmf = new BoxMetadataFilter(); - bmf.setScope("enterprise"); - bmf.setTemplateKey("test"); + BoxMetadataFilter bmf = new BoxMetadataFilter(); + bmf.setScope("enterprise"); + bmf.setTemplateKey("test"); - SimpleDateFormat sdf = new SimpleDateFormat("M-dd-yyyy hh:mm:ss"); - String dateLessThanString = "05-15-2016 00:00:00"; - String dateGreaterThanString = "03-01-2016 00:00:00"; + SimpleDateFormat sdf = new SimpleDateFormat("M-dd-yyyy hh:mm:ss"); + String dateLessThanString = "05-15-2016 00:00:00"; + String dateGreaterThanString = "03-01-2016 00:00:00"; - Date dateGreaterThan = sdf.parse(dateGreaterThanString); - Date dateLessThan = sdf.parse(dateLessThanString); + Date dateGreaterThan = sdf.parse(dateGreaterThanString); + Date dateLessThan = sdf.parse(dateLessThanString); - DateRange dr = new DateRange(dateGreaterThan, dateLessThan); + DateRange dr = new DateRange(dateGreaterThan, dateLessThan); - bmf.addDateRangeFilter("testDate", dr); + bmf.addDateRangeFilter("testDate", dr); - bsp.setMetadataFilter(bmf); + bsp.setMetadataFilter(bmf); - crawlSearchResultExample(bsp, bs); + crawlSearchResultExample(bsp, bs); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); } + } - private static void printSearchResults(PartialCollection searchResults) { - //Crawl the folder - System.out.println("--==Results fullResultSize: " + searchResults.fullSize() + "==--"); - - for (BoxItem.Info itemInfo : searchResults) { - System.out.println("File Found: " + itemInfo.getName() + ", Owner: " + itemInfo.getOwnedBy().getID()); - } + private static void printSearchResults(PartialCollection searchResults) { + // Crawl the folder + System.out.println("--==Results fullResultSize: " + searchResults.fullSize() + "==--"); - System.out.println(); + for (BoxItem.Info itemInfo : searchResults) { + System.out.println( + "File Found: " + itemInfo.getName() + ", Owner: " + itemInfo.getOwnedBy().getID()); } - /** - * Used for a simple print function, leverages System.out.println. - * - * @param s string to be used as a print. - */ - private static void print(String s) { - System.out.println(s); - } + System.out.println(); + } + + /** + * Used for a simple print function, leverages System.out.println. + * + * @param s string to be used as a print. + */ + private static void print(String s) { + System.out.println(s); + } } diff --git a/src/intTest/java/com/box/sdk/BoxAIIT.java b/src/intTest/java/com/box/sdk/BoxAIIT.java index 6bc1efa9c..25465058e 100644 --- a/src/intTest/java/com/box/sdk/BoxAIIT.java +++ b/src/intTest/java/com/box/sdk/BoxAIIT.java @@ -23,315 +23,366 @@ import org.junit.BeforeClass; import org.junit.Test; - -/** - * {@link BoxGroup} related integration tests. - */ +/** {@link BoxGroup} related integration tests. */ public class BoxAIIT { - @BeforeClass - public static void setup() { - setupUniqeFolder(); - } - - @AfterClass - public static void afterClass() { - removeUniqueFolder(); - } - - - @Test - public void askAISingleItem() throws InterruptedException { - BoxAPIConnection api = jwtApiForServiceAccount(); - String fileName = "[askAISingleItem] Test File.txt"; - BoxFile uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); - - try { - BoxFile.Info uploadedFileInfo = uploadedFile.getInfo(); - // When a file has been just uploaded, AI service may not be ready to return text response - // and 412 is returned - retry(() -> { - BoxAIResponse response = BoxAI.sendAIRequest( + @BeforeClass + public static void setup() { + setupUniqeFolder(); + } + + @AfterClass + public static void afterClass() { + removeUniqueFolder(); + } + + @Test + public void askAISingleItem() throws InterruptedException { + BoxAPIConnection api = jwtApiForServiceAccount(); + String fileName = "[askAISingleItem] Test File.txt"; + BoxFile uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); + + try { + BoxFile.Info uploadedFileInfo = uploadedFile.getInfo(); + // When a file has been just uploaded, AI service may not be ready to return text response + // and 412 is returned + retry( + () -> { + BoxAIResponse response = + BoxAI.sendAIRequest( api, "What is the name of the file?", - Collections.singletonList(new BoxAIItem(uploadedFileInfo.getID(), BoxAIItem.Type.FILE)), - BoxAI.Mode.SINGLE_ITEM_QA - ); - assertThat(response.getAnswer(), containsString("Test file")); - assert response.getCreatedAt().before(new Date(System.currentTimeMillis())); - assertThat(response.getCompletionReason(), equalTo("done")); - }, 2, 2000); - - } finally { - deleteFile(uploadedFile); - } + Collections.singletonList( + new BoxAIItem(uploadedFileInfo.getID(), BoxAIItem.Type.FILE)), + BoxAI.Mode.SINGLE_ITEM_QA); + assertThat(response.getAnswer(), containsString("Test file")); + assert response.getCreatedAt().before(new Date(System.currentTimeMillis())); + assertThat(response.getCompletionReason(), equalTo("done")); + }, + 2, + 2000); + + } finally { + deleteFile(uploadedFile); } - - @Test - public void askAIMultipleItems() throws InterruptedException { - BoxAPIConnection api = jwtApiForServiceAccount(); - String fileName1 = "[askAIMultipleItems] Test File.txt"; - BoxFile uploadedFile1 = uploadFileToUniqueFolder(api, fileName1, "Test file"); - - try { - String fileName2 = "[askAIMultipleItems] Weather forecast.txt"; - BoxFile uploadedFile2 = uploadFileToUniqueFolder(api, fileName2, "Test file"); - - try { - BoxFile.Info uploadedFileInfo1 = uploadedFile1.getInfo(); - BoxFile.Info uploadedFileInfo2 = uploadedFile2.getInfo(); - - List items = new ArrayList<>(); - items.add(new BoxAIItem(uploadedFileInfo1.getID(), BoxAIItem.Type.FILE)); - items.add(new BoxAIItem(uploadedFileInfo2.getID(), BoxAIItem.Type.FILE)); - - // When a file has been just uploaded, AI service may not be ready to return text response - // and 412 is returned - retry(() -> { - BoxAIResponse response = BoxAI.sendAIRequest( - api, - "What is the content of these files?", - items, - BoxAI.Mode.MULTIPLE_ITEM_QA - ); - assertThat(response.getAnswer(), containsString("Test file")); - assert response.getCreatedAt().before(new Date(System.currentTimeMillis())); - assertThat(response.getCompletionReason(), equalTo("done")); - }, 2, 2000); - } finally { - deleteFile(uploadedFile2); - } - - } finally { - deleteFile(uploadedFile1); - } + } + + @Test + public void askAIMultipleItems() throws InterruptedException { + BoxAPIConnection api = jwtApiForServiceAccount(); + String fileName1 = "[askAIMultipleItems] Test File.txt"; + BoxFile uploadedFile1 = uploadFileToUniqueFolder(api, fileName1, "Test file"); + + try { + String fileName2 = "[askAIMultipleItems] Weather forecast.txt"; + BoxFile uploadedFile2 = uploadFileToUniqueFolder(api, fileName2, "Test file"); + + try { + BoxFile.Info uploadedFileInfo1 = uploadedFile1.getInfo(); + BoxFile.Info uploadedFileInfo2 = uploadedFile2.getInfo(); + + List items = new ArrayList<>(); + items.add(new BoxAIItem(uploadedFileInfo1.getID(), BoxAIItem.Type.FILE)); + items.add(new BoxAIItem(uploadedFileInfo2.getID(), BoxAIItem.Type.FILE)); + + // When a file has been just uploaded, AI service may not be ready to return text response + // and 412 is returned + retry( + () -> { + BoxAIResponse response = + BoxAI.sendAIRequest( + api, + "What is the content of these files?", + items, + BoxAI.Mode.MULTIPLE_ITEM_QA); + assertThat(response.getAnswer(), containsString("Test file")); + assert response.getCreatedAt().before(new Date(System.currentTimeMillis())); + assertThat(response.getCompletionReason(), equalTo("done")); + }, + 2, + 2000); + } finally { + deleteFile(uploadedFile2); + } + + } finally { + deleteFile(uploadedFile1); } - - @Test - public void askAITextGenItemWithDialogueHistory() throws ParseException, InterruptedException { - BoxAPIConnection api = jwtApiForServiceAccount(); - String fileName = "[askAITextGenItemWithDialogueHistory] Test File.txt"; - Date date1 = BoxDateFormat.parse("2021-01-01T00:00:00Z"); - Date date2 = BoxDateFormat.parse("2021-02-01T00:00:00Z"); - - BoxFile uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); - try { - // When a file has been just uploaded, AI service may not be ready to return text response - // and 412 is returned - retry(() -> { - BoxFile.Info uploadedFileInfo = uploadedFile.getInfo(); - assertThat(uploadedFileInfo.getName(), is(equalTo(fileName))); - - List dialogueHistory = new ArrayList<>(); - dialogueHistory.add( - new BoxAIDialogueEntry("What is the name of the file?", "Test file", date1) - ); - dialogueHistory.add( - new BoxAIDialogueEntry("What is the size of the file?", "10kb", date2) - ); - BoxAIResponse response = BoxAI.sendAITextGenRequest( + } + + @Test + public void askAITextGenItemWithDialogueHistory() throws ParseException, InterruptedException { + BoxAPIConnection api = jwtApiForServiceAccount(); + String fileName = "[askAITextGenItemWithDialogueHistory] Test File.txt"; + Date date1 = BoxDateFormat.parse("2021-01-01T00:00:00Z"); + Date date2 = BoxDateFormat.parse("2021-02-01T00:00:00Z"); + + BoxFile uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); + try { + // When a file has been just uploaded, AI service may not be ready to return text response + // and 412 is returned + retry( + () -> { + BoxFile.Info uploadedFileInfo = uploadedFile.getInfo(); + assertThat(uploadedFileInfo.getName(), is(equalTo(fileName))); + + List dialogueHistory = new ArrayList<>(); + dialogueHistory.add( + new BoxAIDialogueEntry("What is the name of the file?", "Test file", date1)); + dialogueHistory.add( + new BoxAIDialogueEntry("What is the size of the file?", "10kb", date2)); + BoxAIResponse response = + BoxAI.sendAITextGenRequest( api, "What is the name of the file?", - Collections.singletonList(new BoxAIItem(uploadedFileInfo.getID(), BoxAIItem.Type.FILE)), - dialogueHistory - ); - assertThat(response.getAnswer(), containsString("name")); - assert response.getCreatedAt().before(new Date(System.currentTimeMillis())); - assertThat(response.getCompletionReason(), equalTo("done")); - }, 2, 2000); - - } finally { - deleteFile(uploadedFile); - } - } - - @Test - public void getAIAgentDefaultConfiguration() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxAIAgent agent = BoxAI.getAiAgentDefaultConfig(api, BoxAIAgent.Mode.ASK); - BoxAIAgentAsk askAgent = (BoxAIAgentAsk) agent; - - assertThat(askAgent.getType(), is(equalTo(BoxAIAgentAsk.TYPE))); - assertThat(askAgent.getBasicText().getModel(), is(notNullValue())); - - BoxAIAgent agent2 = BoxAI.getAiAgentDefaultConfig(api, BoxAIAgent.Mode.TEXT_GEN); - BoxAIAgentTextGen textGenAgent = (BoxAIAgentTextGen) agent2; - - assertThat(textGenAgent.getType(), is(equalTo(BoxAIAgentTextGen.TYPE))); - assertThat(textGenAgent.getBasicGen().getModel(), is(notNullValue())); + Collections.singletonList( + new BoxAIItem(uploadedFileInfo.getID(), BoxAIItem.Type.FILE)), + dialogueHistory); + assertThat(response.getAnswer(), containsString("name")); + assert response.getCreatedAt().before(new Date(System.currentTimeMillis())); + assertThat(response.getCompletionReason(), equalTo("done")); + }, + 2, + 2000); + + } finally { + deleteFile(uploadedFile); } - - @Test - public void askAISingleItemWithAgent() throws InterruptedException { - BoxAPIConnection api = jwtApiForServiceAccount(); - String fileName = "[askAISingleItem] Test File.txt"; - BoxFile uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); - BoxAIAgent agent = BoxAI.getAiAgentDefaultConfig(api, BoxAIAgent.Mode.ASK); - BoxAIAgentAsk askAgent = (BoxAIAgentAsk) agent; - - try { - BoxFile.Info uploadedFileInfo = uploadedFile.getInfo(); - // When a file has been just uploaded, AI service may not be ready to return text response - // and 412 is returned - retry(() -> { - BoxAIResponse response = BoxAI.sendAIRequest( + } + + @Test + public void getAIAgentDefaultConfiguration() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxAIAgent agent = BoxAI.getAiAgentDefaultConfig(api, BoxAIAgent.Mode.ASK); + BoxAIAgentAsk askAgent = (BoxAIAgentAsk) agent; + + assertThat(askAgent.getType(), is(equalTo(BoxAIAgentAsk.TYPE))); + assertThat(askAgent.getBasicText().getModel(), is(notNullValue())); + + BoxAIAgent agent2 = BoxAI.getAiAgentDefaultConfig(api, BoxAIAgent.Mode.TEXT_GEN); + BoxAIAgentTextGen textGenAgent = (BoxAIAgentTextGen) agent2; + + assertThat(textGenAgent.getType(), is(equalTo(BoxAIAgentTextGen.TYPE))); + assertThat(textGenAgent.getBasicGen().getModel(), is(notNullValue())); + } + + @Test + public void askAISingleItemWithAgent() throws InterruptedException { + BoxAPIConnection api = jwtApiForServiceAccount(); + String fileName = "[askAISingleItem] Test File.txt"; + BoxFile uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); + BoxAIAgent agent = BoxAI.getAiAgentDefaultConfig(api, BoxAIAgent.Mode.ASK); + BoxAIAgentAsk askAgent = (BoxAIAgentAsk) agent; + + try { + BoxFile.Info uploadedFileInfo = uploadedFile.getInfo(); + // When a file has been just uploaded, AI service may not be ready to return text response + // and 412 is returned + retry( + () -> { + BoxAIResponse response = + BoxAI.sendAIRequest( api, "What is the name of the file?", - Collections.singletonList(new BoxAIItem(uploadedFileInfo.getID(), BoxAIItem.Type.FILE)), + Collections.singletonList( + new BoxAIItem(uploadedFileInfo.getID(), BoxAIItem.Type.FILE)), BoxAI.Mode.SINGLE_ITEM_QA, null, askAgent, - true - ); - assertThat(response.getAnswer(), containsString("Test file")); - assert response.getCreatedAt().before(new Date(System.currentTimeMillis())); - assertThat(response.getCompletionReason(), equalTo("done")); - }, 2, 2000); - - } finally { - deleteFile(uploadedFile); - } + true); + assertThat(response.getAnswer(), containsString("Test file")); + assert response.getCreatedAt().before(new Date(System.currentTimeMillis())); + assertThat(response.getCompletionReason(), equalTo("done")); + }, + 2, + 2000); + + } finally { + deleteFile(uploadedFile); } - - @Test - public void aiExtract() throws InterruptedException { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxAIAgent agent = BoxAI.getAiAgentDefaultConfig(api, BoxAIAgent.Mode.EXTRACT); - BoxAIAgentExtract agentExtract = (BoxAIAgentExtract) agent; - // AI team is going to move away from supporting overriding embeddings model - agentExtract.getLongText().setEmbeddings(null); - - BoxFile uploadedFile = uploadFileToUniqueFolder(api, "[aiExtract] Test File.txt", + } + + @Test + public void aiExtract() throws InterruptedException { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxAIAgent agent = BoxAI.getAiAgentDefaultConfig(api, BoxAIAgent.Mode.EXTRACT); + BoxAIAgentExtract agentExtract = (BoxAIAgentExtract) agent; + // AI team is going to move away from supporting overriding embeddings model + agentExtract.getLongText().setEmbeddings(null); + + BoxFile uploadedFile = + uploadFileToUniqueFolder( + api, + "[aiExtract] Test File.txt", "My name is John Doe. I live in San Francisco. I was born in 1990. I work at Box."); - try { - // When a file has been just uploaded, AI service may not be ready to return text response - // and 412 is returned - retry(() -> { - BoxAIResponse response = BoxAI.extractMetadataFreeform(api, + try { + // When a file has been just uploaded, AI service may not be ready to return text response + // and 412 is returned + retry( + () -> { + BoxAIResponse response = + BoxAI.extractMetadataFreeform( + api, "firstName, lastName, location, yearOfBirth, company", - Collections.singletonList(new BoxAIItem(uploadedFile.getID(), BoxAIItem.Type.FILE)), + Collections.singletonList( + new BoxAIItem(uploadedFile.getID(), BoxAIItem.Type.FILE)), agentExtract); - assertThat(response.getAnswer(), containsString("John")); - assertThat(response.getCompletionReason(), equalTo("done")); - }, 2, 2000); - } finally { - deleteFile(uploadedFile); - } + assertThat(response.getAnswer(), containsString("John")); + assertThat(response.getCompletionReason(), equalTo("done")); + }, + 2, + 2000); + } finally { + deleteFile(uploadedFile); } - - @Test - public void aiExtractStructuredWithFields() throws InterruptedException { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxAIAgent agent = BoxAI.getAiAgentDefaultConfig(api, BoxAIAgent.Mode.EXTRACT_STRUCTURED); - BoxAIAgentExtractStructured agentExtractStructured = (BoxAIAgentExtractStructured) agent; - // AI team is going to move away from supporting overriding embeddings model - agentExtractStructured.getLongText().setEmbeddings(null); - - BoxFile uploadedFile = uploadFileToUniqueFolder(api, "[aiExtractStructuredWithFields] Test File.txt", + } + + @Test + public void aiExtractStructuredWithFields() throws InterruptedException { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxAIAgent agent = BoxAI.getAiAgentDefaultConfig(api, BoxAIAgent.Mode.EXTRACT_STRUCTURED); + BoxAIAgentExtractStructured agentExtractStructured = (BoxAIAgentExtractStructured) agent; + // AI team is going to move away from supporting overriding embeddings model + agentExtractStructured.getLongText().setEmbeddings(null); + + BoxFile uploadedFile = + uploadFileToUniqueFolder( + api, + "[aiExtractStructuredWithFields] Test File.txt", "My name is John Doe. I was born in 4th July 1990. I am 34 years old. My hobby is guitar."); - try { - // When a file has been just uploaded, AI service may not be ready to return text response - // and 412 is returned - retry(() -> { - BoxAIExtractStructuredResponse response = BoxAI.extractMetadataStructured(api, - Collections.singletonList(new BoxAIItem(uploadedFile.getID(), BoxAIItem.Type.FILE)), - Arrays.asList( - new BoxAIExtractField("firstName"), - new BoxAIExtractField("lastName"), - new BoxAIExtractField("date", - "Person date of birth", - "Birth date", - "dateOfBirth", - null, - "What is the date of your birth?"), - new BoxAIExtractField("float", - "Person age", - "Age", - "age", - null, - "How old are you?"), - new BoxAIExtractField("multiSelect", - "Person hobby", - "Hobby", - "hobby", - Collections.singletonList(new BoxAIExtractFieldOption("guitar")), - "What is your hobby?") - ), + try { + // When a file has been just uploaded, AI service may not be ready to return text response + // and 412 is returned + retry( + () -> { + BoxAIExtractStructuredResponse response = + BoxAI.extractMetadataStructured( + api, + Collections.singletonList( + new BoxAIItem(uploadedFile.getID(), BoxAIItem.Type.FILE)), + Arrays.asList( + new BoxAIExtractField("firstName"), + new BoxAIExtractField("lastName"), + new BoxAIExtractField( + "date", + "Person date of birth", + "Birth date", + "dateOfBirth", + null, + "What is the date of your birth?"), + new BoxAIExtractField( + "float", "Person age", "Age", "age", null, "How old are you?"), + new BoxAIExtractField( + "multiSelect", + "Person hobby", + "Hobby", + "hobby", + Collections.singletonList(new BoxAIExtractFieldOption("guitar")), + "What is your hobby?")), agentExtractStructured); - assertThat(response.getSourceJson().get("answer"), is(equalTo(response.getAnswer()))); - - assertThat(response.getAnswer().get("firstName").asString(), is(equalTo("John"))); - assertThat(response.getAnswer().get("lastName").asString(), is(equalTo("Doe"))); - assertThat(response.getAnswer().get("dateOfBirth").asString(), is(equalTo("1990-07-04"))); - assertThat(response.getAnswer().get("age").asInt(), is(equalTo(34))); - assertThat(response.getAnswer().get("hobby").asArray().get(0).asString(), is(equalTo("guitar"))); - - assertThat(response.getCompletionReason(), equalTo("done")); - assertThat(response.getCreatedAt(), is(notNullValue())); - }, 2, 2000); - } finally { - deleteFile(uploadedFile); - } + assertThat(response.getSourceJson().get("answer"), is(equalTo(response.getAnswer()))); + + assertThat(response.getAnswer().get("firstName").asString(), is(equalTo("John"))); + assertThat(response.getAnswer().get("lastName").asString(), is(equalTo("Doe"))); + assertThat( + response.getAnswer().get("dateOfBirth").asString(), is(equalTo("1990-07-04"))); + assertThat(response.getAnswer().get("age").asInt(), is(equalTo(34))); + assertThat( + response.getAnswer().get("hobby").asArray().get(0).asString(), + is(equalTo("guitar"))); + + assertThat(response.getCompletionReason(), equalTo("done")); + assertThat(response.getCreatedAt(), is(notNullValue())); + }, + 2, + 2000); + } finally { + deleteFile(uploadedFile); } - - @Test - public void aiExtractStructuredWithMetadataTemplate() throws InterruptedException { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxAIAgent agent = BoxAI.getAiAgentDefaultConfig(api, BoxAIAgent.Mode.EXTRACT_STRUCTURED); - BoxAIAgentExtractStructured agentExtractStructured = (BoxAIAgentExtractStructured) agent; - // AI team is going to move away from supporting overriding embeddings model - agentExtractStructured.getLongText().setEmbeddings(null); - - BoxFile uploadedFile = uploadFileToUniqueFolder(api, "[aiExtractStructuredWithMetadataTemplate] Test File.txt", + } + + @Test + public void aiExtractStructuredWithMetadataTemplate() throws InterruptedException { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxAIAgent agent = BoxAI.getAiAgentDefaultConfig(api, BoxAIAgent.Mode.EXTRACT_STRUCTURED); + BoxAIAgentExtractStructured agentExtractStructured = (BoxAIAgentExtractStructured) agent; + // AI team is going to move away from supporting overriding embeddings model + agentExtractStructured.getLongText().setEmbeddings(null); + + BoxFile uploadedFile = + uploadFileToUniqueFolder( + api, + "[aiExtractStructuredWithMetadataTemplate] Test File.txt", "My name is John Doe. I was born in 4th July 1990. I am 34 years old. My hobby is guitar."); - String templateKey = "key" + java.util.UUID.randomUUID(); - MetadataTemplate template = MetadataTemplate.createMetadataTemplate(api, + String templateKey = "key" + java.util.UUID.randomUUID(); + MetadataTemplate template = + MetadataTemplate.createMetadataTemplate( + api, "enterprise", templateKey, templateKey, false, - Arrays.asList( - new MetadataTemplate.Field(Json.parse( - "{\"key\":\"firstName\",\"displayName\":\"First name\"," - + "\"description\":\"Person first name\",\"type\":\"string\"}").asObject()), - new MetadataTemplate.Field(Json.parse( - "{\"key\":\"lastName\",\"displayName\":\"Last name\"," - + "\"description\":\"Person last name\",\"type\":\"string\"}").asObject()), - new MetadataTemplate.Field(Json.parse( - "{\"key\":\"dateOfBirth\",\"displayName\":\"Birth date\"," - + "\"description\":\"Person date of birth\",\"type\":\"date\"}").asObject()), - new MetadataTemplate.Field(Json.parse( - "{\"key\":\"age\",\"displayName\":\"Age\"," - + "\"description\":\"Person age\",\"type\":\"float\"}").asObject()), - new MetadataTemplate.Field(Json.parse( - "{\"key\":\"hobby\",\"displayName\":\"Hobby\"," - + "\"description\":\"Person hobby\",\"type\":\"multiSelect\"," - + " \"options\":[{\"key\": \"guitar\"}, {\"key\": \"books\"}]}").asObject()) - )); - - try { - // When a file has been just uploaded, AI service may not be ready to return text response - // and 412 is returned - retry(() -> { - BoxAIExtractStructuredResponse response = BoxAI.extractMetadataStructured(api, - Collections.singletonList(new BoxAIItem(uploadedFile.getID(), BoxAIItem.Type.FILE)), + Arrays.asList( + new MetadataTemplate.Field( + Json.parse( + "{\"key\":\"firstName\",\"displayName\":\"First name\"," + + "\"description\":\"Person first name\",\"type\":\"string\"}") + .asObject()), + new MetadataTemplate.Field( + Json.parse( + "{\"key\":\"lastName\",\"displayName\":\"Last name\"," + + "\"description\":\"Person last name\",\"type\":\"string\"}") + .asObject()), + new MetadataTemplate.Field( + Json.parse( + "{\"key\":\"dateOfBirth\",\"displayName\":\"Birth date\"," + + "\"description\":\"Person date of birth\",\"type\":\"date\"}") + .asObject()), + new MetadataTemplate.Field( + Json.parse( + "{\"key\":\"age\",\"displayName\":\"Age\"," + + "\"description\":\"Person age\",\"type\":\"float\"}") + .asObject()), + new MetadataTemplate.Field( + Json.parse( + "{\"key\":\"hobby\",\"displayName\":\"Hobby\"," + + "\"description\":\"Person hobby\",\"type\":\"multiSelect\"," + + " \"options\":[{\"key\": \"guitar\"}, {\"key\": \"books\"}]}") + .asObject()))); + + try { + // When a file has been just uploaded, AI service may not be ready to return text response + // and 412 is returned + retry( + () -> { + BoxAIExtractStructuredResponse response = + BoxAI.extractMetadataStructured( + api, + Collections.singletonList( + new BoxAIItem(uploadedFile.getID(), BoxAIItem.Type.FILE)), new BoxAIExtractMetadataTemplate(templateKey, "enterprise"), agentExtractStructured); - assertThat(response.getSourceJson().get("answer"), is(equalTo(response.getAnswer()))); - - assertThat(response.getAnswer().get("firstName").asString(), is(equalTo("John"))); - assertThat(response.getAnswer().get("lastName").asString(), is(equalTo("Doe"))); - assertThat(response.getAnswer().get("dateOfBirth").asString(), is(equalTo("1990-07-04T00:00:00Z"))); - assertThat(response.getAnswer().get("age").asInt(), is(equalTo(34))); - assertThat(response.getAnswer().get("hobby").asArray().get(0).asString(), is(equalTo("guitar"))); - assertThat(response.getCompletionReason(), equalTo("done")); - assertThat(response.getCreatedAt(), is(notNullValue())); - }, 2, 2000); - } finally { - deleteFile(uploadedFile); - MetadataTemplate.deleteMetadataTemplate(api, template.getScope(), template.getTemplateKey()); - } + assertThat(response.getSourceJson().get("answer"), is(equalTo(response.getAnswer()))); + + assertThat(response.getAnswer().get("firstName").asString(), is(equalTo("John"))); + assertThat(response.getAnswer().get("lastName").asString(), is(equalTo("Doe"))); + assertThat( + response.getAnswer().get("dateOfBirth").asString(), + is(equalTo("1990-07-04T00:00:00Z"))); + assertThat(response.getAnswer().get("age").asInt(), is(equalTo(34))); + assertThat( + response.getAnswer().get("hobby").asArray().get(0).asString(), + is(equalTo("guitar"))); + assertThat(response.getCompletionReason(), equalTo("done")); + assertThat(response.getCreatedAt(), is(notNullValue())); + }, + 2, + 2000); + } finally { + deleteFile(uploadedFile); + MetadataTemplate.deleteMetadataTemplate(api, template.getScope(), template.getTemplateKey()); } + } } diff --git a/src/intTest/java/com/box/sdk/BoxAPIConnectionIT.java b/src/intTest/java/com/box/sdk/BoxAPIConnectionIT.java index f52631887..a3774320e 100644 --- a/src/intTest/java/com/box/sdk/BoxAPIConnectionIT.java +++ b/src/intTest/java/com/box/sdk/BoxAPIConnectionIT.java @@ -17,278 +17,279 @@ import org.junit.Ignore; import org.junit.Test; - public class BoxAPIConnectionIT { - @Test - public void requestIsSentNormallyWhenInterceptorReturnsNullResponse() throws MalformedURLException { - BoxAPIConnection api = new BoxAPIConnection(""); + @Test + public void requestIsSentNormallyWhenInterceptorReturnsNullResponse() + throws MalformedURLException { + BoxAPIConnection api = new BoxAPIConnection(""); - api.setRequestInterceptor(request -> null); + api.setRequestInterceptor(request -> null); - BoxAPIRequest request = new BoxAPIRequest(api, new URL("https://box.com"), "GET"); - try (BoxAPIResponse response = request.send()) { - assertThat(response.getResponseCode(), is(200)); - } + BoxAPIRequest request = new BoxAPIRequest(api, new URL("https://box.com"), "GET"); + try (BoxAPIResponse response = request.send()) { + assertThat(response.getResponseCode(), is(200)); } + } - @Test - public void refreshSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - String originalAccessToken = api.getAccessToken(); + @Test + public void refreshSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String originalAccessToken = api.getAccessToken(); - api.refresh(); + api.refresh(); - String actualAccessToken = api.getAccessToken(); + String actualAccessToken = api.getAccessToken(); - assertThat(originalAccessToken, not(equalTo(actualAccessToken))); - } + assertThat(originalAccessToken, not(equalTo(actualAccessToken))); + } - @Test - public void refreshesWhenGetAccessTokenIsCalledAndTokenHasExpired() { - BoxAPIConnection api = jwtApiForServiceAccount(); - String originalAccessToken = api.getAccessToken(); - api.setExpires(-1); + @Test + public void refreshesWhenGetAccessTokenIsCalledAndTokenHasExpired() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String originalAccessToken = api.getAccessToken(); + api.setExpires(-1); - String actualAccessToken = api.getAccessToken(); + String actualAccessToken = api.getAccessToken(); - assertThat(originalAccessToken, not(equalTo(actualAccessToken))); - } + assertThat(originalAccessToken, not(equalTo(actualAccessToken))); + } + + @Test + public void doesNotRefreshWhenGetAccessTokenIsCalledAndTokenHasNotExpired() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String originalAccessToken = api.getAccessToken(); + api.setExpires(Long.MAX_VALUE); + + String actualAccessToken = api.getAccessToken(); + + assertThat(originalAccessToken, equalTo(actualAccessToken)); + } + + @Test + public void successfullySavesAndRestoresConnection() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String state = api.save(); + BoxConfig boxConfig = jwtBoxConfig(); - @Test - public void doesNotRefreshWhenGetAccessTokenIsCalledAndTokenHasNotExpired() { - BoxAPIConnection api = jwtApiForServiceAccount(); - String originalAccessToken = api.getAccessToken(); - api.setExpires(Long.MAX_VALUE); + BoxAPIConnection restoredAPI = + BoxAPIConnection.restore(boxConfig.getClientId(), boxConfig.getClientSecret(), state); + assertThat(BoxFolder.getRootFolder(restoredAPI).getInfo().getID(), is("0")); + } - String actualAccessToken = api.getAccessToken(); + @Test + public void revokeToken() { + BoxAPIConnection api = jwtApiForServiceAccount(); - assertThat(originalAccessToken, equalTo(actualAccessToken)); + BoxFolder.getRootFolder(api); + + api.revokeToken(); + + try { + BoxFolder.getRootFolder(api); + } catch (BoxAPIException ex) { + assertEquals(401, ex.getResponseCode()); } + } + + @Test + public void appAndDeveloperEditionApiConnectionWorks() { + BoxDeveloperEditionAPIConnection appAuthConnection = jwtApiForServiceAccount(); + + final String name = "app user name two"; + BoxUser.Info createdUserInfo = BoxUser.createAppUser(appAuthConnection, name); + final String appUserId = createdUserInfo.getID(); + + InMemoryLRUAccessTokenCache accessTokenCache = new InMemoryLRUAccessTokenCache(1); + BoxDeveloperEditionAPIConnection api = + BoxDeveloperEditionAPIConnection.getUserConnection( + appUserId, jwtBoxConfig(), accessTokenCache); + BoxUser appUser = new BoxUser(api, appUserId); + + assertThat(api.getAccessToken(), not(equalTo(null))); + + BoxUser.Info info = appUser.getInfo(); - @Test - public void successfullySavesAndRestoresConnection() { - BoxAPIConnection api = jwtApiForServiceAccount(); - String state = api.save(); - BoxConfig boxConfig = jwtBoxConfig(); + assertThat(info.getID(), equalTo(appUserId)); + assertThat(info.getName(), equalTo(name)); - BoxAPIConnection restoredAPI = BoxAPIConnection.restore( - boxConfig.getClientId(), boxConfig.getClientSecret(), state - ); - assertThat(BoxFolder.getRootFolder(restoredAPI).getInfo().getID(), is("0")); + api.refresh(); + + BoxUser appUserFromAdmin = new BoxUser(appAuthConnection, appUserId); + appUserFromAdmin.delete(false, true); + } + + @Test + @Ignore("Takes too long to run") + public void appUsersAutomaticallyPaginatesCorrectly() { + BoxDeveloperEditionAPIConnection api = jwtApiForServiceAccount(); + + assertThat(api.getAccessToken(), not(equalTo(null))); + + long timestamp = Calendar.getInstance().getTimeInMillis(); + final String name = "appUsersAutomaticallyPaginate "; + final String externalAppUserId = "@example.com"; + + // Must be greater than the default response page size (100) to ensure a second page of results + final int totalCreatedTestAppUsers = 105; + + // Create Test App Users + System.out.println("Creating Test App Users"); + for (int i = 1; i <= totalCreatedTestAppUsers; i++) { + CreateUserParams params = new CreateUserParams(); + params.setExternalAppUserId(timestamp + "_" + i + externalAppUserId); + BoxUser.createAppUser(api, name + timestamp + " " + i, params); } - @Test - public void revokeToken() { - BoxAPIConnection api = jwtApiForServiceAccount(); + // Get App Users + Iterable users = + BoxUser.getAppUsersByExternalAppUserID(api, null, "external_app_user_id", "name"); + + // Iterate over the returned App Users + int totalReturnedTestAppUsers = 0; + System.out.println("Cleanup (delete) Test App Users"); + for (BoxUser.Info userInfo : users) { + System.out.println(userInfo.getName()); + BoxUser appUser = new BoxUser(api, userInfo.getID()); + + // Count the Test App Users just created. + if (userInfo.getName().startsWith(name + timestamp)) { + totalReturnedTestAppUsers++; + } + + // Delete the Test App Users just created. + // Deletes Test App Users created in previous test run, as well. + if (userInfo.getName().startsWith(name)) { + appUser.delete(false, true); + } + } - BoxFolder.getRootFolder(api); + assertEquals(totalCreatedTestAppUsers, totalReturnedTestAppUsers); + api.refresh(); + } - api.revokeToken(); + @Test + @Ignore("Takes too long to run") + public void appUsersManuallyPaginatesCorrectly() { + BoxDeveloperEditionAPIConnection api = jwtApiForServiceAccount(); - try { - BoxFolder.getRootFolder(api); - } catch (BoxAPIException ex) { - assertEquals(401, ex.getResponseCode()); - } + assertThat(api.getAccessToken(), not(equalTo(null))); + + final long timestamp = Calendar.getInstance().getTimeInMillis(); + final String name = "appUsersManuallyPaginate "; + final String externalAppUserId = "@example.com"; + + // Must be greater than defaultNetworkResponsePageSize to ensure a second page of results + final int totalCreatedTestAppUsers = 105; + + // Must be equal to default response limit (usually 100) + final int defaultNetworkResponsePageSize = 100; + + // Create Test App Users + System.out.println("Creating Test App Users"); + for (int i = 1; i <= totalCreatedTestAppUsers; i++) { + CreateUserParams params = new CreateUserParams(); + params.setExternalAppUserId(timestamp + "_" + i + externalAppUserId); + BoxUser.createAppUser(api, name + timestamp + " " + i, params); } - @Test - public void appAndDeveloperEditionApiConnectionWorks() { - BoxDeveloperEditionAPIConnection appAuthConnection = jwtApiForServiceAccount(); + // Get App Users + BoxResourceIterable users = + (BoxResourceIterable) + BoxUser.getAppUsersByExternalAppUserID( + api, null, true, null, "external_app_user_id", "name"); - final String name = "app user name two"; - BoxUser.Info createdUserInfo = BoxUser.createAppUser(appAuthConnection, name); - final String appUserId = createdUserInfo.getID(); + // Grab the marker to be able to resume iterating at some point in the future... + String marker = users.getNextMarker(); - InMemoryLRUAccessTokenCache accessTokenCache = new InMemoryLRUAccessTokenCache(1); - BoxDeveloperEditionAPIConnection api = - BoxDeveloperEditionAPIConnection.getUserConnection(appUserId, jwtBoxConfig(), accessTokenCache); - BoxUser appUser = new BoxUser(api, appUserId); + // As we iterate over the page of results, pageCursor is used to keep track + // of the current item in the page, so that iteration can be picked up where you left + // off later on. + int pageCursor = 0; - assertThat(api.getAccessToken(), not(equalTo(null))); + int totalReturnedTestAppUsers = 0; - BoxUser.Info info = appUser.getInfo(); + // Count App Users and stop iterating once we get to the last item on the first page of results + System.out.println("===FIRST PAGE==="); + for (BoxUser.Info userInfo : users) { + System.out.println(userInfo.getName()); - assertThat(info.getID(), equalTo(appUserId)); - assertThat(info.getName(), equalTo(name)); + // Count the Test App Users just created. + if (userInfo.getName().startsWith(name + timestamp)) { + totalReturnedTestAppUsers++; + } - api.refresh(); + // Stop iterating once we get to the last item on the page of results. + // If we were to keep iterating in this loop, then BoxResourceIterable would + // automatically make the request to get the next page of results. + if (pageCursor == defaultNetworkResponsePageSize - 1) { + break; + } - BoxUser appUserFromAdmin = new BoxUser(appAuthConnection, appUserId); - appUserFromAdmin.delete(false, true); + pageCursor++; } - @Test - @Ignore("Takes too long to run") - public void appUsersAutomaticallyPaginatesCorrectly() { - BoxDeveloperEditionAPIConnection api = jwtApiForServiceAccount(); - - assertThat(api.getAccessToken(), not(equalTo(null))); - - long timestamp = Calendar.getInstance().getTimeInMillis(); - final String name = "appUsersAutomaticallyPaginate "; - final String externalAppUserId = "@example.com"; - - // Must be greater than the default response page size (100) to ensure a second page of results - final int totalCreatedTestAppUsers = 105; - - // Create Test App Users - System.out.println("Creating Test App Users"); - for (int i = 1; i <= totalCreatedTestAppUsers; i++) { - CreateUserParams params = new CreateUserParams(); - params.setExternalAppUserId(timestamp + "_" + i + externalAppUserId); - BoxUser.createAppUser(api, name + timestamp + " " + i, params); - } - - // Get App Users - Iterable users = BoxUser.getAppUsersByExternalAppUserID(api, - null, "external_app_user_id", "name"); - - // Iterate over the returned App Users - int totalReturnedTestAppUsers = 0; - System.out.println("Cleanup (delete) Test App Users"); - for (BoxUser.Info userInfo : users) { - System.out.println(userInfo.getName()); - BoxUser appUser = new BoxUser(api, userInfo.getID()); - - // Count the Test App Users just created. - if (userInfo.getName().startsWith(name + timestamp)) { - totalReturnedTestAppUsers++; - } - - // Delete the Test App Users just created. - // Deletes Test App Users created in previous test run, as well. - if (userInfo.getName().startsWith(name)) { - appUser.delete(false, true); - } - } - - assertEquals(totalCreatedTestAppUsers, totalReturnedTestAppUsers); - api.refresh(); + // Manually get the second page of results, by passing the nextMarker from the last response. + // This simulates the scenario where we no longer have the users collection, so we need to + // make a new request, using the preserved marker value which points to the page containing + // the next item in the collection. + users = + (BoxResourceIterable) + BoxUser.getAppUsersByExternalAppUserID( + api, null, true, marker, "external_app_user_id", "name"); + + // We're now starting with the first item on the second page of results, + // so we reset pageCursor + pageCursor = 0; + + // Continue counting App Users + // If there are more pages of results, this loop uses the automatic pagination by continuously + // retrieving the next item and letting BoxResourceIterable determine and manage getting new + // pages. + System.out.println("===SECOND PAGE==="); + for (BoxUser.Info userInfo : users) { + System.out.println(userInfo.getName()); + + // Count the users just created. + if (userInfo.getName().startsWith(name + timestamp)) { + totalReturnedTestAppUsers++; + } + + pageCursor++; } - @Test - @Ignore("Takes too long to run") - public void appUsersManuallyPaginatesCorrectly() { - BoxDeveloperEditionAPIConnection api = jwtApiForServiceAccount(); - - assertThat(api.getAccessToken(), not(equalTo(null))); - - final long timestamp = Calendar.getInstance().getTimeInMillis(); - final String name = "appUsersManuallyPaginate "; - final String externalAppUserId = "@example.com"; - - // Must be greater than defaultNetworkResponsePageSize to ensure a second page of results - final int totalCreatedTestAppUsers = 105; - - // Must be equal to default response limit (usually 100) - final int defaultNetworkResponsePageSize = 100; - - // Create Test App Users - System.out.println("Creating Test App Users"); - for (int i = 1; i <= totalCreatedTestAppUsers; i++) { - CreateUserParams params = new CreateUserParams(); - params.setExternalAppUserId(timestamp + "_" + i + externalAppUserId); - BoxUser.createAppUser(api, name + timestamp + " " + i, params); - } - - // Get App Users - BoxResourceIterable users = - (BoxResourceIterable) BoxUser.getAppUsersByExternalAppUserID( - api, - null, - true, - null, - "external_app_user_id", "name"); - - // Grab the marker to be able to resume iterating at some point in the future... - String marker = users.getNextMarker(); - - // As we iterate over the page of results, pageCursor is used to keep track - // of the current item in the page, so that iteration can be picked up where you left - // off later on. - int pageCursor = 0; - - int totalReturnedTestAppUsers = 0; - - // Count App Users and stop iterating once we get to the last item on the first page of results - System.out.println("===FIRST PAGE==="); - for (BoxUser.Info userInfo : users) { - System.out.println(userInfo.getName()); - - // Count the Test App Users just created. - if (userInfo.getName().startsWith(name + timestamp)) { - totalReturnedTestAppUsers++; - } - - // Stop iterating once we get to the last item on the page of results. - // If we were to keep iterating in this loop, then BoxResourceIterable would - // automatically make the request to get the next page of results. - if (pageCursor == defaultNetworkResponsePageSize - 1) { - break; - } - - pageCursor++; - } - - // Manually get the second page of results, by passing the nextMarker from the last response. - // This simulates the scenario where we no longer have the users collection, so we need to - // make a new request, using the preserved marker value which points to the page containing - // the next item in the collection. - users = (BoxResourceIterable) BoxUser.getAppUsersByExternalAppUserID(api, - null, true, marker, "external_app_user_id", "name"); - - // We're now starting with the first item on the second page of results, - // so we reset pageCursor - pageCursor = 0; - - // Continue counting App Users - // If there are more pages of results, this loop uses the automatic pagination by continuously - // retrieving the next item and letting BoxResourceIterable determine and manage getting new - // pages. - System.out.println("===SECOND PAGE==="); - for (BoxUser.Info userInfo : users) { - System.out.println(userInfo.getName()); - - // Count the users just created. - if (userInfo.getName().startsWith(name + timestamp)) { - totalReturnedTestAppUsers++; - } - - pageCursor++; - } - - // Get App Users for post-test clean up - users = (BoxResourceIterable) BoxUser.getAppUsersByExternalAppUserID(api, - null, true, null, "external_app_user_id", "name"); - - // Clean up - System.out.println("Cleanup (delete) Test App Users"); - for (BoxUser.Info userInfo : users) { - BoxUser appUser = new BoxUser(api, userInfo.getID()); - - // Deletes users created in previous test run, as well. - if (userInfo.getName().startsWith(name)) { - appUser.delete(false, true); - } - } - - assertEquals(totalCreatedTestAppUsers, totalReturnedTestAppUsers); - api.refresh(); + // Get App Users for post-test clean up + users = + (BoxResourceIterable) + BoxUser.getAppUsersByExternalAppUserID( + api, null, true, null, "external_app_user_id", "name"); + + // Clean up + System.out.println("Cleanup (delete) Test App Users"); + for (BoxUser.Info userInfo : users) { + BoxUser appUser = new BoxUser(api, userInfo.getID()); + + // Deletes users created in previous test run, as well. + if (userInfo.getName().startsWith(name)) { + appUser.delete(false, true); + } } - @Test - public void getLowerScopedTokenWorks() { - BoxDeveloperEditionAPIConnection api = jwtApiForServiceAccount(); + assertEquals(totalCreatedTestAppUsers, totalReturnedTestAppUsers); + api.refresh(); + } - String originalToken = api.getAccessToken(); - List scopes = new ArrayList<>(); - scopes.add("item_preview"); - scopes.add("item_content_upload"); + @Test + public void getLowerScopedTokenWorks() { + BoxDeveloperEditionAPIConnection api = jwtApiForServiceAccount(); - ScopedToken newToken = api.getLowerScopedToken(scopes, null); - assertThat(newToken, notNullValue()); - assertThat(newToken.getAccessToken(), not(originalToken)); - } + String originalToken = api.getAccessToken(); + List scopes = new ArrayList<>(); + scopes.add("item_preview"); + scopes.add("item_content_upload"); + + ScopedToken newToken = api.getLowerScopedToken(scopes, null); + assertThat(newToken, notNullValue()); + assertThat(newToken.getAccessToken(), not(originalToken)); + } } diff --git a/src/intTest/java/com/box/sdk/BoxAPIRequestIT.java b/src/intTest/java/com/box/sdk/BoxAPIRequestIT.java index f1b5098e3..85e97893d 100644 --- a/src/intTest/java/com/box/sdk/BoxAPIRequestIT.java +++ b/src/intTest/java/com/box/sdk/BoxAPIRequestIT.java @@ -5,22 +5,20 @@ import org.junit.Test; -/** - * Integration test for BoxAPIRequest - */ +/** Integration test for BoxAPIRequest */ public class BoxAPIRequestIT { - @Test - public void loggingWorks() { - BoxLogger.defaultLogger().setLevelToAll(); - try { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxUser.getCurrentUser(api); - } catch (Exception e) { - e.printStackTrace(); - fail("Exception occured"); - } finally { - BoxLogger.defaultLogger().resetToDefaultLevel(); - } + @Test + public void loggingWorks() { + BoxLogger.defaultLogger().setLevelToAll(); + try { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxUser.getCurrentUser(api); + } catch (Exception e) { + e.printStackTrace(); + fail("Exception occured"); + } finally { + BoxLogger.defaultLogger().resetToDefaultLevel(); } + } } diff --git a/src/intTest/java/com/box/sdk/BoxApiProvider.java b/src/intTest/java/com/box/sdk/BoxApiProvider.java index 55495a910..893a4e2ee 100644 --- a/src/intTest/java/com/box/sdk/BoxApiProvider.java +++ b/src/intTest/java/com/box/sdk/BoxApiProvider.java @@ -8,27 +8,28 @@ final class BoxApiProvider { - private static final String JWT_CONFIG_ENV_NAME = "JAVA_JWT_CONFIG"; - - private BoxApiProvider() { - // hiding constructor - } - - static BoxDeveloperEditionAPIConnection jwtApiForServiceAccount() { - BoxConfig boxConfig = jwtBoxConfig(); - InMemoryLRUAccessTokenCache tokenCache = new InMemoryLRUAccessTokenCache(10); - return BoxDeveloperEditionAPIConnection.getAppEnterpriseConnection(boxConfig, tokenCache); - } - - static BoxConfig jwtBoxConfig() { - Map environmentProperties = System.getenv(); - String jwtConfigEncoded = getEnvProperty(environmentProperties, JWT_CONFIG_ENV_NAME); - byte[] decodedJwtConfig = Base64.getDecoder().decode(jwtConfigEncoded); - return BoxConfig.readFrom(new String(decodedJwtConfig)); - } - - private static String getEnvProperty(Map environmentProperties, String name) { - return Optional.ofNullable(environmentProperties.get(name)) - .orElseThrow(() -> new RuntimeException(format("Missing '%s' environmental variable", name))); - } + private static final String JWT_CONFIG_ENV_NAME = "JAVA_JWT_CONFIG"; + + private BoxApiProvider() { + // hiding constructor + } + + static BoxDeveloperEditionAPIConnection jwtApiForServiceAccount() { + BoxConfig boxConfig = jwtBoxConfig(); + InMemoryLRUAccessTokenCache tokenCache = new InMemoryLRUAccessTokenCache(10); + return BoxDeveloperEditionAPIConnection.getAppEnterpriseConnection(boxConfig, tokenCache); + } + + static BoxConfig jwtBoxConfig() { + Map environmentProperties = System.getenv(); + String jwtConfigEncoded = getEnvProperty(environmentProperties, JWT_CONFIG_ENV_NAME); + byte[] decodedJwtConfig = Base64.getDecoder().decode(jwtConfigEncoded); + return BoxConfig.readFrom(new String(decodedJwtConfig)); + } + + private static String getEnvProperty(Map environmentProperties, String name) { + return Optional.ofNullable(environmentProperties.get(name)) + .orElseThrow( + () -> new RuntimeException(format("Missing '%s' environmental variable", name))); + } } diff --git a/src/intTest/java/com/box/sdk/BoxClassificationTemplateIT.java b/src/intTest/java/com/box/sdk/BoxClassificationTemplateIT.java index 2f416db37..fdc879f8b 100644 --- a/src/intTest/java/com/box/sdk/BoxClassificationTemplateIT.java +++ b/src/intTest/java/com/box/sdk/BoxClassificationTemplateIT.java @@ -9,87 +9,115 @@ public class BoxClassificationTemplateIT { - public MetadataTemplate getOrCreateClassificationTemplate(BoxAPIConnection api) { - try { - return MetadataTemplate.getMetadataTemplate(api, Metadata.CLASSIFICATION_TEMPLATE_KEY); - } catch (BoxAPIException e) { - assertEquals(e.getResponseCode(), 404); - } + public MetadataTemplate getOrCreateClassificationTemplate(BoxAPIConnection api) { + try { + return MetadataTemplate.getMetadataTemplate(api, Metadata.CLASSIFICATION_TEMPLATE_KEY); + } catch (BoxAPIException e) { + assertEquals(e.getResponseCode(), 404); + } - MetadataTemplate.Field classification = new MetadataTemplate.Field(); - classification.setType("enum"); - classification.setKey("Box__Security__Classification__Key"); - classification.setDisplayName("Classification"); - classification.setIsHidden(false); + MetadataTemplate.Field classification = new MetadataTemplate.Field(); + classification.setType("enum"); + classification.setKey("Box__Security__Classification__Key"); + classification.setDisplayName("Classification"); + classification.setIsHidden(false); - List options = new ArrayList(); - options.add("sensitive"); - classification.setOptions(options); + List options = new ArrayList(); + options.add("sensitive"); + classification.setOptions(options); - List fields = new ArrayList(); - fields.add(classification); + List fields = new ArrayList(); + fields.add(classification); - return MetadataTemplate.createMetadataTemplate(api, Metadata.ENTERPRISE_METADATA_SCOPE, - Metadata.CLASSIFICATION_TEMPLATE_KEY, "Classification", false, fields); - } + return MetadataTemplate.createMetadataTemplate( + api, + Metadata.ENTERPRISE_METADATA_SCOPE, + Metadata.CLASSIFICATION_TEMPLATE_KEY, + "Classification", + false, + fields); + } - @Test - public void getUpdateClassificationTemplate() { - BoxAPIConnection api = jwtApiForServiceAccount(); - MetadataTemplate template = getOrCreateClassificationTemplate(api); - String fieldKey = template.getFields().get(0).getKey(); - String optionKey = template.getFields().get(0).getOptionsObjects().get(0).getKey(); + @Test + public void getUpdateClassificationTemplate() { + BoxAPIConnection api = jwtApiForServiceAccount(); + MetadataTemplate template = getOrCreateClassificationTemplate(api); + String fieldKey = template.getFields().get(0).getKey(); + String optionKey = template.getFields().get(0).getOptionsObjects().get(0).getKey(); - List updates = new ArrayList(); - String update = "{\n" - + " \"op\": \"editEnumOption\",\n" - + " \"fieldKey\": \"" + fieldKey + "\",\n" - + " \"enumOptionKey\": \"" + optionKey + "\",\n" - + " \"data\": {\n" - + " \"key\": \"" + optionKey + "\",\n" - + " \"staticConfig\": {\n" - + " \"classification\": {\n" - + " \"classificationDefinition\": \"Sensitive information.\",\n" - + " \"colorID\": 4\n" - + " }\n" - + " }\n" - + " }\n" - + "}"; - updates.add(new MetadataTemplate.FieldOperation(update)); + List updates = + new ArrayList(); + String update = + "{\n" + + " \"op\": \"editEnumOption\",\n" + + " \"fieldKey\": \"" + + fieldKey + + "\",\n" + + " \"enumOptionKey\": \"" + + optionKey + + "\",\n" + + " \"data\": {\n" + + " \"key\": \"" + + optionKey + + "\",\n" + + " \"staticConfig\": {\n" + + " \"classification\": {\n" + + " \"classificationDefinition\": \"Sensitive information.\",\n" + + " \"colorID\": 4\n" + + " }\n" + + " }\n" + + " }\n" + + "}"; + updates.add(new MetadataTemplate.FieldOperation(update)); - MetadataTemplate updatedTemplate = MetadataTemplate.updateMetadataTemplate(api, - Metadata.ENTERPRISE_METADATA_SCOPE, Metadata.CLASSIFICATION_TEMPLATE_KEY, updates); - MetadataTemplate.Option updatedOption = updatedTemplate.getFields().get(0).getOptionsObjects().get(0); - assertEquals(updatedOption.getKey(), "Sensitive"); - assertEquals( - updatedOption.getStaticConfig().getClassification().getString("classificationDefinition", - "null"), - "Sensitive information."); - assertEquals(updatedOption.getStaticConfig().getClassification().getInt("colorID", 0), - 4); - update = "{\n" - + " \"op\": \"editEnumOption\",\n" - + " \"fieldKey\": \"" + fieldKey + "\",\n" - + " \"enumOptionKey\": \"" + optionKey + "\",\n" - + " \"data\": {\n" - + " \"key\": \"" + optionKey + "\",\n" - + " \"staticConfig\": {\n" - + " \"classification\": {\n" - + " \"classificationDefinition\": \"Top Sensitive information.\",\n" - + " \"colorID\": 5\n" - + " }\n" - + " }\n" - + " }\n" - + "}"; - updates.clear(); - updates.add(new MetadataTemplate.FieldOperation(update)); + MetadataTemplate updatedTemplate = + MetadataTemplate.updateMetadataTemplate( + api, Metadata.ENTERPRISE_METADATA_SCOPE, Metadata.CLASSIFICATION_TEMPLATE_KEY, updates); + MetadataTemplate.Option updatedOption = + updatedTemplate.getFields().get(0).getOptionsObjects().get(0); + assertEquals(updatedOption.getKey(), "Sensitive"); + assertEquals( + updatedOption + .getStaticConfig() + .getClassification() + .getString("classificationDefinition", "null"), + "Sensitive information."); + assertEquals(updatedOption.getStaticConfig().getClassification().getInt("colorID", 0), 4); + update = + "{\n" + + " \"op\": \"editEnumOption\",\n" + + " \"fieldKey\": \"" + + fieldKey + + "\",\n" + + " \"enumOptionKey\": \"" + + optionKey + + "\",\n" + + " \"data\": {\n" + + " \"key\": \"" + + optionKey + + "\",\n" + + " \"staticConfig\": {\n" + + " \"classification\": {\n" + + " \"classificationDefinition\": \"Top Sensitive information.\",\n" + + " \"colorID\": 5\n" + + " }\n" + + " }\n" + + " }\n" + + "}"; + updates.clear(); + updates.add(new MetadataTemplate.FieldOperation(update)); - updatedTemplate = MetadataTemplate.updateMetadataTemplate(api, Metadata.ENTERPRISE_METADATA_SCOPE, - Metadata.CLASSIFICATION_TEMPLATE_KEY, updates); - updatedOption = updatedTemplate.getFields().get(0).getOptionsObjects().get(0); - assertEquals(updatedOption.getKey(), "Sensitive"); - assertEquals(updatedOption.getStaticConfig().getClassification().getString("classificationDefinition", - "null"), "Top Sensitive information."); - assertEquals(updatedOption.getStaticConfig().getClassification().getInt("colorID", 0), 5); - } + updatedTemplate = + MetadataTemplate.updateMetadataTemplate( + api, Metadata.ENTERPRISE_METADATA_SCOPE, Metadata.CLASSIFICATION_TEMPLATE_KEY, updates); + updatedOption = updatedTemplate.getFields().get(0).getOptionsObjects().get(0); + assertEquals(updatedOption.getKey(), "Sensitive"); + assertEquals( + updatedOption + .getStaticConfig() + .getClassification() + .getString("classificationDefinition", "null"), + "Top Sensitive information."); + assertEquals(updatedOption.getStaticConfig().getClassification().getInt("colorID", 0), 5); + } } diff --git a/src/intTest/java/com/box/sdk/BoxCollaborationAllowlistIT.java b/src/intTest/java/com/box/sdk/BoxCollaborationAllowlistIT.java index 9ee46585b..ca26822b7 100644 --- a/src/intTest/java/com/box/sdk/BoxCollaborationAllowlistIT.java +++ b/src/intTest/java/com/box/sdk/BoxCollaborationAllowlistIT.java @@ -16,70 +16,68 @@ import org.junit.Test; public class BoxCollaborationAllowlistIT { - private static final String DOMAIN_NAME = randomizeName("test") + ".com"; + private static final String DOMAIN_NAME = randomizeName("test") + ".com"; - @Before - public void beforeClass() { - removeAllowedDomains(DOMAIN_NAME); - } + @Before + public void beforeClass() { + removeAllowedDomains(DOMAIN_NAME); + } - @Test - public void createCollaborationAllowlistSucceeds() { - final String type = "collaboration_whitelist_entry"; + @Test + public void createCollaborationAllowlistSucceeds() { + final String type = "collaboration_whitelist_entry"; - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxCollaborationAllowlist.Info domainAllowlist = BoxCollaborationAllowlist.create( + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxCollaborationAllowlist.Info domainAllowlist = + BoxCollaborationAllowlist.create( api, "createCollaborationAllowlistSucceeds." + DOMAIN_NAME, - BoxCollaborationAllowlist.AllowlistDirection.BOTH - ); + BoxCollaborationAllowlist.AllowlistDirection.BOTH); - assertThat(domainAllowlist, is(notNullValue())); - assertEquals(domainAllowlist.getDirection(), BoxCollaborationAllowlist.AllowlistDirection.BOTH); - assertEquals(domainAllowlist.getType(), type); - } + assertThat(domainAllowlist, is(notNullValue())); + assertEquals(domainAllowlist.getDirection(), BoxCollaborationAllowlist.AllowlistDirection.BOTH); + assertEquals(domainAllowlist.getType(), type); + } - @Test - public void getAllCollaborationAllowlistsSucceeds() { - final String whitelistType = "collaboration_whitelist_entry"; + @Test + public void getAllCollaborationAllowlistsSucceeds() { + final String whitelistType = "collaboration_whitelist_entry"; - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxCollaborationAllowlist.create( - api, - "getAllCollaborationAllowlistsSucceeds." + DOMAIN_NAME, - BoxCollaborationAllowlist.AllowlistDirection.BOTH - ); + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxCollaborationAllowlist.create( + api, + "getAllCollaborationAllowlistsSucceeds." + DOMAIN_NAME, + BoxCollaborationAllowlist.AllowlistDirection.BOTH); - Iterable whitelists = BoxCollaborationAllowlist.getAll(api); - List whitelistList = newArrayList(whitelists); + Iterable whitelists = BoxCollaborationAllowlist.getAll(api); + List whitelistList = newArrayList(whitelists); - assertThat(whitelistList, is(not(Matchers.empty()))); - for (BoxCollaborationAllowlist.Info whitelistInfo : whitelistList) { - assertThat(whitelistInfo, is(notNullValue())); - assertEquals(whitelistInfo.getType(), whitelistType); - } + assertThat(whitelistList, is(not(Matchers.empty()))); + for (BoxCollaborationAllowlist.Info whitelistInfo : whitelistList) { + assertThat(whitelistInfo, is(notNullValue())); + assertEquals(whitelistInfo.getType(), whitelistType); } + } - @Test - public void getAllCollaborationAllowlistsAdditionalParamsSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); + @Test + public void getAllCollaborationAllowlistsAdditionalParamsSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); - BoxCollaborationAllowlist.create( - api, - "getAllCollaborationAllowlistsAdditionalParamsSucceeds." + DOMAIN_NAME, - BoxCollaborationAllowlist.AllowlistDirection.BOTH - ); + BoxCollaborationAllowlist.create( + api, + "getAllCollaborationAllowlistsAdditionalParamsSucceeds." + DOMAIN_NAME, + BoxCollaborationAllowlist.AllowlistDirection.BOTH); - Iterable whitelists = BoxCollaborationAllowlist.getAll(api, 10); - List whitelistList = newArrayList(whitelists); - assertThat(whitelistList, is(not(Matchers.empty()))); - } + Iterable whitelists = BoxCollaborationAllowlist.getAll(api, 10); + List whitelistList = newArrayList(whitelists); + assertThat(whitelistList, is(not(Matchers.empty()))); + } - private List newArrayList(Iterable iterable) { - List result = new ArrayList<>(); - for (T i : iterable) { - result.add(i); - } - return result; + private List newArrayList(Iterable iterable) { + List result = new ArrayList<>(); + for (T i : iterable) { + result.add(i); } + return result; + } } diff --git a/src/intTest/java/com/box/sdk/BoxCollaborationIT.java b/src/intTest/java/com/box/sdk/BoxCollaborationIT.java index a0eb957dc..02b4fb077 100644 --- a/src/intTest/java/com/box/sdk/BoxCollaborationIT.java +++ b/src/intTest/java/com/box/sdk/BoxCollaborationIT.java @@ -25,174 +25,176 @@ public class BoxCollaborationIT { - @BeforeClass - public static void setup() { - setupUniqeFolder(); + @BeforeClass + public static void setup() { + setupUniqeFolder(); + } + + @AfterClass + public static void tearDown() { + removeUniqueFolder(); + } + + @Test + public void updateInfoSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String folderName = "[addCollaborationToFolderSucceeds] Test Folder"; + String collaboratorLogin = TestConfig.getCollaborator(); + BoxCollaboration.Role originalRole = BoxCollaboration.Role.VIEWER; + BoxCollaboration.Role newRole = BoxCollaboration.Role.EDITOR; + BoxFolder rootFolder = getUniqueFolder(api); + BoxFolder folder = null; + try { + folder = rootFolder.createFolder(folderName).getResource(); + BoxCollaboration.Info collabInfo = folder.collaborate(collaboratorLogin, originalRole); + + assertThat(collabInfo.getRole(), is(equalTo(originalRole))); + assertNotNull(collabInfo.getIsAccessOnly()); + + BoxCollaboration collab = collabInfo.getResource(); + collabInfo.setRole(newRole); + collab.updateInfo(collabInfo); + + assertThat(collabInfo.getRole(), is(equalTo(newRole))); + Collection collabCollection = folder.getCollaborations(); + + assertEquals(collabCollection.size(), 1); + + Iterator collabs = collabCollection.iterator(); + BoxCollaboration.Info remoteCollab = collabs.next(); + assertThat(remoteCollab.getRole(), is(equalTo(newRole))); + } finally { + deleteFolder(folder); } - - @AfterClass - public static void tearDown() { - removeUniqueFolder(); + } + + @Test + public void deleteSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String folderName = "[deleteSucceeds] Test Folder"; + String collaboratorLogin = TestConfig.getCollaborator(); + BoxCollaboration.Role collaboratorRole = BoxCollaboration.Role.EDITOR; + BoxFolder rootFolder = UniqueTestFolder.getUniqueFolder(api); + BoxFolder folder = null; + try { + folder = rootFolder.createFolder(folderName).getResource(); + BoxCollaboration.Info collabInfo = folder.collaborate(collaboratorLogin, collaboratorRole); + BoxCollaboration collab = collabInfo.getResource(); + + collab.delete(); + + assertThat(folder.getCollaborations(), Matchers.hasSize(0)); + } finally { + deleteFolder(folder); } - - @Test - public void updateInfoSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - String folderName = "[addCollaborationToFolderSucceeds] Test Folder"; - String collaboratorLogin = TestConfig.getCollaborator(); - BoxCollaboration.Role originalRole = BoxCollaboration.Role.VIEWER; - BoxCollaboration.Role newRole = BoxCollaboration.Role.EDITOR; - BoxFolder rootFolder = getUniqueFolder(api); - BoxFolder folder = null; - try { - folder = rootFolder.createFolder(folderName).getResource(); - BoxCollaboration.Info collabInfo = folder.collaborate(collaboratorLogin, originalRole); - - assertThat(collabInfo.getRole(), is(equalTo(originalRole))); - assertNotNull(collabInfo.getIsAccessOnly()); - - BoxCollaboration collab = collabInfo.getResource(); - collabInfo.setRole(newRole); - collab.updateInfo(collabInfo); - - assertThat(collabInfo.getRole(), is(equalTo(newRole))); - Collection collabCollection = folder.getCollaborations(); - - assertEquals(collabCollection.size(), 1); - - Iterator collabs = collabCollection.iterator(); - BoxCollaboration.Info remoteCollab = collabs.next(); - assertThat(remoteCollab.getRole(), is(equalTo(newRole))); - } finally { - deleteFolder(folder); - } + } + + @Test + public void singleFileCollabSucceeds() { + HashMap collabsMap = new HashMap<>(); + BoxAPIConnection api = jwtApiForServiceAccount(); + String fileName = "[singleFileCollabSucceeds] Test File.txt"; + BoxFile uploadedFile = null; + BoxCollaborationAllowlist allowList = null; + + try { + uploadedFile = uploadFileToUniqueFolderWithSomeContent(api, fileName); + + String collaboratorLogin = TestConfig.getCollaborator(); + BoxCollaboration.Role originalRole = BoxCollaboration.Role.VIEWER; + BoxCollaboration.Role newRole = BoxCollaboration.Role.EDITOR; + + BoxCollaboration.Info collabInfo = + uploadedFile.collaborate(collaboratorLogin, originalRole, true, false); + + collabsMap.put(collabInfo.getID(), collabInfo); + + assertThat(collabInfo.getRole(), is(equalTo(originalRole))); + + BoxCollaboration collab = collabInfo.getResource(); + collabInfo.setRole(newRole); + collab.updateInfo(collabInfo); + + assertThat(collabInfo.getRole(), is(equalTo(newRole))); + + BoxCollaboration remoteCollab = new BoxCollaboration(api, collab.getID()); + BoxCollaboration.Info remoteInfo = remoteCollab.getInfo(); + assertThat(remoteInfo.getRole(), is(equalTo(newRole))); + assertThat(remoteInfo.getCreatedBy().getID(), is(collabInfo.getCreatedBy().getID())); + + allowList = BoxCollaborationAllowlist.create(api, "gmail.com", INBOUND).getResource(); + BoxCollaboration.Info collab2Info = + uploadedFile.collaborate("davidsmaynard@gmail.com", originalRole, false, false); + + collabsMap.put(collab2Info.getID(), collab2Info); + + BoxResourceIterable collabs = uploadedFile.getAllFileCollaborations(); + Iterator collabIterator = collabs.iterator(); + int numCollabs = 0; + + while (collabIterator.hasNext()) { + numCollabs++; + BoxCollaboration.Info fileCollabInfo = collabIterator.next(); + BoxCollaboration.Info localFileCollabInfor = collabsMap.get(fileCollabInfo.getID()); + + assertEquals(fileCollabInfo.getID(), localFileCollabInfor.getID()); + assertEquals( + fileCollabInfo.getCreatedBy().getID(), localFileCollabInfor.getCreatedBy().getID()); + assertEquals( + fileCollabInfo.getCreatedBy().getName(), localFileCollabInfor.getCreatedBy().getName()); + + assertEquals( + fileCollabInfo.getAccessibleBy().getID(), + localFileCollabInfor.getAccessibleBy().getID()); + assertEquals( + fileCollabInfo.getAccessibleBy().getName(), + localFileCollabInfor.getAccessibleBy().getName()); + + assertEquals(fileCollabInfo.getRole(), localFileCollabInfor.getRole()); + assertEquals(fileCollabInfo.getStatus(), localFileCollabInfor.getStatus()); + } + + assertEquals(2, numCollabs); + } finally { + CleanupTools.deleteFile(uploadedFile); + if (allowList != null) { + allowList.delete(); + } } - - @Test - public void deleteSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - String folderName = "[deleteSucceeds] Test Folder"; - String collaboratorLogin = TestConfig.getCollaborator(); - BoxCollaboration.Role collaboratorRole = BoxCollaboration.Role.EDITOR; - BoxFolder rootFolder = UniqueTestFolder.getUniqueFolder(api); - BoxFolder folder = null; - try { - folder = rootFolder.createFolder(folderName).getResource(); - BoxCollaboration.Info collabInfo = folder.collaborate(collaboratorLogin, collaboratorRole); - BoxCollaboration collab = collabInfo.getResource(); - - collab.delete(); - - assertThat(folder.getCollaborations(), Matchers.hasSize(0)); - } finally { - deleteFolder(folder); - } + } + + @Test + public void acceptPendingCollaboration() { + BoxAPIConnection api = jwtApiForServiceAccount(); + Collection pendingCollabs = + BoxCollaboration.getPendingCollaborations(api); + for (BoxCollaboration.Info collabInfo : pendingCollabs) { + // Accept the pending collaboration + collabInfo.setStatus(BoxCollaboration.Status.ACCEPTED); + collabInfo.getResource().updateInfo(collabInfo); } - - @Test - public void singleFileCollabSucceeds() { - HashMap collabsMap = new HashMap<>(); - BoxAPIConnection api = jwtApiForServiceAccount(); - String fileName = "[singleFileCollabSucceeds] Test File.txt"; - BoxFile uploadedFile = null; - BoxCollaborationAllowlist allowList = null; - - try { - uploadedFile = uploadFileToUniqueFolderWithSomeContent(api, fileName); - - String collaboratorLogin = TestConfig.getCollaborator(); - BoxCollaboration.Role originalRole = BoxCollaboration.Role.VIEWER; - BoxCollaboration.Role newRole = BoxCollaboration.Role.EDITOR; - - BoxCollaboration.Info collabInfo = - uploadedFile.collaborate(collaboratorLogin, originalRole, true, false); - - collabsMap.put(collabInfo.getID(), collabInfo); - - assertThat(collabInfo.getRole(), is(equalTo(originalRole))); - - BoxCollaboration collab = collabInfo.getResource(); - collabInfo.setRole(newRole); - collab.updateInfo(collabInfo); - - assertThat(collabInfo.getRole(), is(equalTo(newRole))); - - BoxCollaboration remoteCollab = new BoxCollaboration(api, collab.getID()); - BoxCollaboration.Info remoteInfo = remoteCollab.getInfo(); - assertThat(remoteInfo.getRole(), is(equalTo(newRole))); - assertThat(remoteInfo.getCreatedBy().getID(), is(collabInfo.getCreatedBy().getID())); - - - allowList = BoxCollaborationAllowlist.create(api, "gmail.com", INBOUND).getResource(); - BoxCollaboration.Info collab2Info = - uploadedFile.collaborate("davidsmaynard@gmail.com", originalRole, false, false); - - collabsMap.put(collab2Info.getID(), collab2Info); - - BoxResourceIterable collabs = uploadedFile.getAllFileCollaborations(); - Iterator collabIterator = collabs.iterator(); - int numCollabs = 0; - - while (collabIterator.hasNext()) { - numCollabs++; - BoxCollaboration.Info fileCollabInfo = collabIterator.next(); - BoxCollaboration.Info localFileCollabInfor = collabsMap.get(fileCollabInfo.getID()); - - assertEquals(fileCollabInfo.getID(), localFileCollabInfor.getID()); - assertEquals(fileCollabInfo.getCreatedBy().getID(), localFileCollabInfor.getCreatedBy().getID()); - assertEquals(fileCollabInfo.getCreatedBy().getName(), localFileCollabInfor.getCreatedBy().getName()); - - assertEquals(fileCollabInfo.getAccessibleBy().getID(), localFileCollabInfor.getAccessibleBy().getID()); - assertEquals(fileCollabInfo.getAccessibleBy().getName(), - localFileCollabInfor.getAccessibleBy().getName()); - - assertEquals(fileCollabInfo.getRole(), localFileCollabInfor.getRole()); - assertEquals(fileCollabInfo.getStatus(), localFileCollabInfor.getStatus()); - } - - assertEquals(2, numCollabs); - } finally { - CleanupTools.deleteFile(uploadedFile); - if (allowList != null) { - allowList.delete(); - } - } - } - - @Test - public void acceptPendingCollaboration() { - BoxAPIConnection api = jwtApiForServiceAccount(); - Collection pendingCollabs = BoxCollaboration.getPendingCollaborations(api); - for (BoxCollaboration.Info collabInfo : pendingCollabs) { - // Accept the pending collaboration - collabInfo.setStatus(BoxCollaboration.Status.ACCEPTED); - collabInfo.getResource().updateInfo(collabInfo); - } - } - - @Test - public void singleFileCollabWithAccessOnlySucceeds() { - HashMap collabsMap = new HashMap<>(); - BoxAPIConnection api = jwtApiForServiceAccount(); - String fileName = "[singleFileCollabSucceeds] Test File.txt"; - BoxFile uploadedFile = null; - try { - uploadedFile = uploadFileToUniqueFolderWithSomeContent(api, fileName); - JsonObject user = new JsonObject() - .add("login", TestConfig.getCollaborator()) - .add("type", "user"); - JsonObject file = new JsonObject() - .add("id", uploadedFile.getID()) - .add("type", "file"); - - BoxCollaboration.Role originalRole = BoxCollaboration.Role.VIEWER; - BoxCollaboration.Info collabInfo = BoxCollaboration.create(api, user, file, originalRole, - false, false, null, true); - - assertThat(collabInfo.getRole(), is(equalTo(originalRole))); - assertTrue(collabInfo.getIsAccessOnly()); - } finally { - CleanupTools.deleteFile(uploadedFile); - } + } + + @Test + public void singleFileCollabWithAccessOnlySucceeds() { + HashMap collabsMap = new HashMap<>(); + BoxAPIConnection api = jwtApiForServiceAccount(); + String fileName = "[singleFileCollabSucceeds] Test File.txt"; + BoxFile uploadedFile = null; + try { + uploadedFile = uploadFileToUniqueFolderWithSomeContent(api, fileName); + JsonObject user = + new JsonObject().add("login", TestConfig.getCollaborator()).add("type", "user"); + JsonObject file = new JsonObject().add("id", uploadedFile.getID()).add("type", "file"); + + BoxCollaboration.Role originalRole = BoxCollaboration.Role.VIEWER; + BoxCollaboration.Info collabInfo = + BoxCollaboration.create(api, user, file, originalRole, false, false, null, true); + + assertThat(collabInfo.getRole(), is(equalTo(originalRole))); + assertTrue(collabInfo.getIsAccessOnly()); + } finally { + CleanupTools.deleteFile(uploadedFile); } + } } diff --git a/src/intTest/java/com/box/sdk/BoxCollectionIT.java b/src/intTest/java/com/box/sdk/BoxCollectionIT.java index 174387b83..b26c7b183 100644 --- a/src/intTest/java/com/box/sdk/BoxCollectionIT.java +++ b/src/intTest/java/com/box/sdk/BoxCollectionIT.java @@ -10,18 +10,17 @@ public class BoxCollectionIT { - @Test - public void getAllCollectionsReturnsFavorites() { - BoxAPIConnection api = jwtApiForServiceAccount(); - ArrayList collectionList = new ArrayList<>(); - for (BoxCollection.Info info : BoxCollection.getAllCollections(api)) { - collectionList.add(info); - } - - assertThat(collectionList.size(), is(equalTo(1))); - BoxCollection.Info firstCollection = collectionList.get(0); - assertThat(firstCollection.getName(), is(equalTo("Favorites"))); - assertThat(firstCollection.getCollectionType(), is(equalTo("favorites"))); + @Test + public void getAllCollectionsReturnsFavorites() { + BoxAPIConnection api = jwtApiForServiceAccount(); + ArrayList collectionList = new ArrayList<>(); + for (BoxCollection.Info info : BoxCollection.getAllCollections(api)) { + collectionList.add(info); } + assertThat(collectionList.size(), is(equalTo(1))); + BoxCollection.Info firstCollection = collectionList.get(0); + assertThat(firstCollection.getName(), is(equalTo("Favorites"))); + assertThat(firstCollection.getCollectionType(), is(equalTo("favorites"))); + } } diff --git a/src/intTest/java/com/box/sdk/BoxCommentIT.java b/src/intTest/java/com/box/sdk/BoxCommentIT.java index c62fa54b8..26684c466 100644 --- a/src/intTest/java/com/box/sdk/BoxCommentIT.java +++ b/src/intTest/java/com/box/sdk/BoxCommentIT.java @@ -18,100 +18,101 @@ public class BoxCommentIT { - @BeforeClass - public static void setup() { - setupUniqeFolder(); + @BeforeClass + public static void setup() { + setupUniqeFolder(); + } + + @AfterClass + public static void tearDown() { + removeUniqueFolder(); + } + + @Test + public void replyToCommentSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + String fileName = randomizeName("[replyToCommentSucceeds] Test File.txt"); + byte[] fileBytes = "Non-empty string".getBytes(StandardCharsets.UTF_8); + String firstMessage = "First message"; + String replyMessage = "Reply message"; + + InputStream uploadStream = new ByteArrayInputStream(fileBytes); + BoxFile uploadedFile = rootFolder.uploadFile(uploadStream, fileName).getResource(); + try { + BoxComment.Info firstCommentInfo = uploadedFile.addComment(firstMessage); + BoxComment firstComment = firstCommentInfo.getResource(); + + BoxComment.Info replyCommentInfo = firstComment.reply(replyMessage); + + assertThat(replyCommentInfo.getMessage(), is(equalTo(replyMessage))); + assertThat(replyCommentInfo.getIsReplyComment(), is(true)); + assertThat(replyCommentInfo.getItem().getID(), is(equalTo(uploadedFile.getID()))); + } finally { + deleteFile(uploadedFile); } - - @AfterClass - public static void tearDown() { - removeUniqueFolder(); - } - @Test - public void replyToCommentSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - String fileName = randomizeName("[replyToCommentSucceeds] Test File.txt"); - byte[] fileBytes = "Non-empty string".getBytes(StandardCharsets.UTF_8); - String firstMessage = "First message"; - String replyMessage = "Reply message"; - - InputStream uploadStream = new ByteArrayInputStream(fileBytes); - BoxFile uploadedFile = rootFolder.uploadFile(uploadStream, fileName).getResource(); - try { - BoxComment.Info firstCommentInfo = uploadedFile.addComment(firstMessage); - BoxComment firstComment = firstCommentInfo.getResource(); - - BoxComment.Info replyCommentInfo = firstComment.reply(replyMessage); - - assertThat(replyCommentInfo.getMessage(), is(equalTo(replyMessage))); - assertThat(replyCommentInfo.getIsReplyComment(), is(true)); - assertThat(replyCommentInfo.getItem().getID(), is(equalTo(uploadedFile.getID()))); - } finally { - deleteFile(uploadedFile); - } - } - - @Test - public void getCommentInfoSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - String fileName = randomizeName("[getCommentInfoSucceeds] Test File.txt"); - byte[] fileBytes = "Non-empty string".getBytes(StandardCharsets.UTF_8); - String message = "Comment message"; - - InputStream uploadStream = new ByteArrayInputStream(fileBytes); - BoxFile uploadedFile = rootFolder.uploadFile(uploadStream, fileName).getResource(); - try { - BoxComment.Info commentInfo = uploadedFile.addComment(message); - BoxComment comment = commentInfo.getResource(); - commentInfo = comment.getInfo(); - - assertThat(commentInfo.getMessage(), is(equalTo(message))); - assertThat(commentInfo.getItem().getID(), is(equalTo(uploadedFile.getID()))); - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void getCommentInfoSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + String fileName = randomizeName("[getCommentInfoSucceeds] Test File.txt"); + byte[] fileBytes = "Non-empty string".getBytes(StandardCharsets.UTF_8); + String message = "Comment message"; + + InputStream uploadStream = new ByteArrayInputStream(fileBytes); + BoxFile uploadedFile = rootFolder.uploadFile(uploadStream, fileName).getResource(); + try { + BoxComment.Info commentInfo = uploadedFile.addComment(message); + BoxComment comment = commentInfo.getResource(); + commentInfo = comment.getInfo(); + + assertThat(commentInfo.getMessage(), is(equalTo(message))); + assertThat(commentInfo.getItem().getID(), is(equalTo(uploadedFile.getID()))); + } finally { + deleteFile(uploadedFile); } - - @Test - public void changeCommentMessageSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - String fileName = randomizeName("[changeCommentMessageSucceeds] Test File.txt"); - byte[] fileBytes = "Non-empty string".getBytes(StandardCharsets.UTF_8); - String originalMessage = "Original message"; - String changedMessage = "Changed message"; - - InputStream uploadStream = new ByteArrayInputStream(fileBytes); - BoxFile uploadedFile = rootFolder.uploadFile(uploadStream, fileName).getResource(); - try { - BoxComment.Info commentInfo = uploadedFile.addComment(originalMessage); - BoxComment comment = commentInfo.getResource(); - commentInfo = comment.changeMessage(changedMessage); - - assertThat(commentInfo.getMessage(), is(equalTo(changedMessage))); - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void changeCommentMessageSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + String fileName = randomizeName("[changeCommentMessageSucceeds] Test File.txt"); + byte[] fileBytes = "Non-empty string".getBytes(StandardCharsets.UTF_8); + String originalMessage = "Original message"; + String changedMessage = "Changed message"; + + InputStream uploadStream = new ByteArrayInputStream(fileBytes); + BoxFile uploadedFile = rootFolder.uploadFile(uploadStream, fileName).getResource(); + try { + BoxComment.Info commentInfo = uploadedFile.addComment(originalMessage); + BoxComment comment = commentInfo.getResource(); + commentInfo = comment.changeMessage(changedMessage); + + assertThat(commentInfo.getMessage(), is(equalTo(changedMessage))); + } finally { + deleteFile(uploadedFile); } - - @Test - public void deleteCommentSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - String fileName = randomizeName("[deleteCommentSucceeds] Test File.txt"); - byte[] fileBytes = "Non-empty string".getBytes(StandardCharsets.UTF_8); - String message = "Comment message"; - - InputStream uploadStream = new ByteArrayInputStream(fileBytes); - BoxFile uploadedFile = rootFolder.uploadFile(uploadStream, fileName).getResource(); - try { - BoxComment.Info commentInfo = uploadedFile.addComment(message); - BoxComment comment = commentInfo.getResource(); - comment.delete(); - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void deleteCommentSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + String fileName = randomizeName("[deleteCommentSucceeds] Test File.txt"); + byte[] fileBytes = "Non-empty string".getBytes(StandardCharsets.UTF_8); + String message = "Comment message"; + + InputStream uploadStream = new ByteArrayInputStream(fileBytes); + BoxFile uploadedFile = rootFolder.uploadFile(uploadStream, fileName).getResource(); + try { + BoxComment.Info commentInfo = uploadedFile.addComment(message); + BoxComment comment = commentInfo.getResource(); + comment.delete(); + } finally { + deleteFile(uploadedFile); } + } } diff --git a/src/intTest/java/com/box/sdk/BoxFileIT.java b/src/intTest/java/com/box/sdk/BoxFileIT.java index 15ee91809..c2bc26934 100644 --- a/src/intTest/java/com/box/sdk/BoxFileIT.java +++ b/src/intTest/java/com/box/sdk/BoxFileIT.java @@ -74,1224 +74,1249 @@ import org.junit.BeforeClass; import org.junit.Test; -/** - * {@link BoxFile} related integration tests. - */ +/** {@link BoxFile} related integration tests. */ public class BoxFileIT { - @BeforeClass - public static void setup() { - setupUniqeFolder(); + @BeforeClass + public static void setup() { + setupUniqeFolder(); + } + + @AfterClass + public static void tearDown() { + removeUniqueFolder(); + } + + protected static byte[] readAllBytes(String fileName) { + try (RandomAccessFile f = new RandomAccessFile(fileName, "r")) { + byte[] b = new byte[(int) f.length()]; + f.read(b); + return b; + } catch (IOException e) { + throw new RuntimeException(e); } - - @AfterClass - public static void tearDown() { - removeUniqueFolder(); + } + + @Test + public void getInfoWithRepresentationsIntegrationTestWithSimpleHint() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFile uploadedFile = null; + try { + uploadedFile = uploadSampleFileToUniqueFolder(api, "red_100x100.png"); + List representations = + uploadedFile.getInfoWithRepresentations("[png]").getRepresentations(); + assertTrue("There should be at least one representation", representations.size() > 0); + } finally { + deleteFile(uploadedFile); } - - protected static byte[] readAllBytes(String fileName) { - try (RandomAccessFile f = new RandomAccessFile(fileName, "r")) { - byte[] b = new byte[(int) f.length()]; - f.read(b); - return b; - } catch (IOException e) { - throw new RuntimeException(e); - } + } + + @Test + public void getInfoWithRepresentationsIntegrationTestWithComplexHint() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFile uploadedFile = null; + try { + uploadedFile = uploadSampleFileToUniqueFolder(api, "red_100x100.png"); + List representations = + uploadedFile + .getInfoWithRepresentations("[jpg,png?dimensions=1024x1024][pdf]") + .getRepresentations(); + assertTrue("There should be at least one representation", representations.size() > 0); + } finally { + deleteFile(uploadedFile); } - - @Test - public void getInfoWithRepresentationsIntegrationTestWithSimpleHint() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFile uploadedFile = null; - try { - uploadedFile = uploadSampleFileToUniqueFolder(api, "red_100x100.png"); - List representations = - uploadedFile.getInfoWithRepresentations("[png]").getRepresentations(); - assertTrue("There should be at least one representation", representations.size() > 0); - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void getRepresentationContentSucceeds() throws InterruptedException { + BoxAPIConnection api = jwtApiForServiceAccount(); + String fileName = "smalltest.pdf"; + BoxFile file = null; + try { + file = uploadSampleFileToUniqueFolder(api, fileName); + final String fileId = file.getID(); + String representationHint = "[jpg?dimensions=32x32]"; + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + Retry.retry( + () -> { + new BoxFile(api, fileId).getRepresentationContent(representationHint, outputStream); + byte[] downloadedRepresentationContent = outputStream.toByteArray(); + + assertNotNull(downloadedRepresentationContent); + }, + 5, + 100); + } finally { + deleteFile(file); } - - @Test - public void getInfoWithRepresentationsIntegrationTestWithComplexHint() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFile uploadedFile = null; - try { - uploadedFile = uploadSampleFileToUniqueFolder(api, "red_100x100.png"); - List representations = uploadedFile.getInfoWithRepresentations( - "[jpg,png?dimensions=1024x1024][pdf]").getRepresentations(); - assertTrue("There should be at least one representation", representations.size() > 0); - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void getRepresentationContentWithExtractedTextSucceeds() throws InterruptedException { + BoxAPIConnection api = jwtApiForServiceAccount(); + String fileName = "text.pdf"; + BoxFile file = null; + try { + file = uploadSampleFileToUniqueFolder(api, fileName); + final String fileId = file.getID(); + String representationHint = "[extracted_text]"; + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + Retry.retry( + () -> { + new BoxFile(api, fileId).getRepresentationContent(representationHint, outputStream); + byte[] downloadedRepresentationContent = outputStream.toByteArray(); + String text = new String(downloadedRepresentationContent, StandardCharsets.UTF_8); + assertTrue(text.contains("Lorem ipsum")); + }, + 5, + 100); + } finally { + deleteFile(file); } - - @Test - public void getRepresentationContentSucceeds() throws InterruptedException { - BoxAPIConnection api = jwtApiForServiceAccount(); - String fileName = "smalltest.pdf"; - BoxFile file = null; - try { - file = uploadSampleFileToUniqueFolder(api, fileName); - final String fileId = file.getID(); - String representationHint = "[jpg?dimensions=32x32]"; - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - Retry.retry(() -> { - new BoxFile(api, fileId).getRepresentationContent(representationHint, outputStream); - byte[] downloadedRepresentationContent = outputStream.toByteArray(); - - assertNotNull(downloadedRepresentationContent); - }, 5, 100); - } finally { - deleteFile(file); - } + } + + @Test + public void uploadFileStreamSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder folder = getUniqueFolder(api); + + byte[] fileContent = new byte[10000]; + new Random().nextBytes(fileContent); + + BoxFile uploadedFile = null; + try { + InputStream uploadStream = new ByteArrayInputStream(fileContent); + BoxFile.Info uploadedFileInfo = folder.uploadFile(uploadStream, BoxFileIT.generateString()); + uploadedFile = uploadedFileInfo.getResource(); + + ByteArrayOutputStream downloadStream = new ByteArrayOutputStream(); + uploadedFile.download(downloadStream); + byte[] downloadedFileContent = downloadStream.toByteArray(); + + assertThat(downloadedFileContent, is(equalTo(fileContent))); + assertThat( + folder, hasItem(Matchers.hasProperty("ID", equalTo(uploadedFile.getID())))); + } finally { + deleteFile(uploadedFile); } - - @Test - public void getRepresentationContentWithExtractedTextSucceeds() throws InterruptedException { - BoxAPIConnection api = jwtApiForServiceAccount(); - String fileName = "text.pdf"; - BoxFile file = null; - try { - file = uploadSampleFileToUniqueFolder(api, fileName); - final String fileId = file.getID(); - String representationHint = "[extracted_text]"; - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - Retry.retry(() -> { - new BoxFile(api, fileId).getRepresentationContent(representationHint, outputStream); - byte[] downloadedRepresentationContent = outputStream.toByteArray(); - String text = new String(downloadedRepresentationContent, StandardCharsets.UTF_8); - assertTrue(text.contains("Lorem ipsum")); - }, 5, 100); - } finally { - deleteFile(file); - } + } + + @Test + public void uploadAndDownloadFileSucceeds() throws IOException { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder folder = getUniqueFolder(api); + String fileName = "red_100x100.png"; + URL fileURL = this.getClass().getResource("/sample-files/" + fileName); + String filePath = URLDecoder.decode(fileURL.getFile(), "utf-8"); + long fileSize = new File(filePath).length(); + byte[] fileContent = readAllBytes(filePath); + BoxFile uploadedFile = null; + try { + InputStream uploadStream = Files.newInputStream(Paths.get(filePath)); + ProgressListener mockUploadListener = mock(ProgressListener.class); + BoxFile.Info uploadedFileInfo = + folder.uploadFile(uploadStream, BoxFileIT.generateString(), fileSize, mockUploadListener); + uploadedFile = uploadedFileInfo.getResource(); + + ByteArrayOutputStream downloadStream = new ByteArrayOutputStream(); + ProgressListener mockDownloadListener = mock(ProgressListener.class); + uploadedFile.download(downloadStream, mockDownloadListener); + byte[] downloadedFileContent = downloadStream.toByteArray(); + + assertThat(downloadedFileContent, is(equalTo(fileContent))); + assertThat( + folder, hasItem(Matchers.hasProperty("ID", equalTo(uploadedFile.getID())))); + verify(mockUploadListener, atLeastOnce()) + .onProgressChanged(anyLong(), longThat(is(equalTo(fileSize)))); + verify(mockDownloadListener, atLeastOnce()) + .onProgressChanged(anyLong(), longThat(is(equalTo(fileSize)))); + } finally { + deleteFile(uploadedFile); } - - @Test - public void uploadFileStreamSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder folder = getUniqueFolder(api); - - byte[] fileContent = new byte[10000]; - new Random().nextBytes(fileContent); - - BoxFile uploadedFile = null; - try { - InputStream uploadStream = new ByteArrayInputStream(fileContent); - BoxFile.Info uploadedFileInfo = folder.uploadFile(uploadStream, BoxFileIT.generateString()); - uploadedFile = uploadedFileInfo.getResource(); - - ByteArrayOutputStream downloadStream = new ByteArrayOutputStream(); - uploadedFile.download(downloadStream); - byte[] downloadedFileContent = downloadStream.toByteArray(); - - assertThat(downloadedFileContent, is(equalTo(fileContent))); - assertThat(folder, hasItem(Matchers.hasProperty("ID", equalTo(uploadedFile.getID())))); - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void downloadFileUseZstdSucceeds() throws IOException { + BoxAPIConnection api = jwtApiForServiceAccount(); + api.setUseZstdCompression(true); + + String fileName = "smalltest.pdf"; + URL fileURL = this.getClass().getResource("/sample-files/" + fileName); + String filePath = URLDecoder.decode(fileURL.getFile(), "utf-8"); + byte[] fileContent = readAllBytes(filePath); + BoxFile file = null; + try { + file = uploadSampleFileToUniqueFolder(api, fileName); + + ByteArrayOutputStream downloadStream = new ByteArrayOutputStream(); + ProgressListener mockDownloadListener = mock(ProgressListener.class); + + URL url = CONTENT_URL_TEMPLATE.build(api.getBaseURL(), file.getID()); + BoxAPIRequest request = new BoxAPIRequest(api, url, "GET"); + BoxAPIResponse response = request.send(); + writeStream(response, downloadStream, mockDownloadListener); + + byte[] downloadedFileContent = downloadStream.toByteArray(); + assertThat(response.getHeaders().get("X-Content-Encoding").get(0), is(equalTo("zstd"))); + assertThat(downloadedFileContent, is(equalTo(fileContent))); + } finally { + deleteFile(file); } - - @Test - public void uploadAndDownloadFileSucceeds() throws IOException { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder folder = getUniqueFolder(api); - String fileName = "red_100x100.png"; - URL fileURL = this.getClass().getResource("/sample-files/" + fileName); - String filePath = URLDecoder.decode(fileURL.getFile(), "utf-8"); - long fileSize = new File(filePath).length(); - byte[] fileContent = readAllBytes(filePath); - BoxFile uploadedFile = null; - try { - InputStream uploadStream = Files.newInputStream(Paths.get(filePath)); - ProgressListener mockUploadListener = mock(ProgressListener.class); - BoxFile.Info uploadedFileInfo = folder.uploadFile( - uploadStream, BoxFileIT.generateString(), fileSize, mockUploadListener - ); - uploadedFile = uploadedFileInfo.getResource(); - - ByteArrayOutputStream downloadStream = new ByteArrayOutputStream(); - ProgressListener mockDownloadListener = mock(ProgressListener.class); - uploadedFile.download(downloadStream, mockDownloadListener); - byte[] downloadedFileContent = downloadStream.toByteArray(); - - assertThat(downloadedFileContent, is(equalTo(fileContent))); - assertThat(folder, hasItem(Matchers.hasProperty("ID", equalTo(uploadedFile.getID())))); - verify(mockUploadListener, atLeastOnce()).onProgressChanged(anyLong(), longThat(is(equalTo(fileSize)))); - verify(mockDownloadListener, atLeastOnce()).onProgressChanged(anyLong(), longThat(is(equalTo(fileSize)))); - } finally { - deleteFile(uploadedFile); - } - + } + + @Test + public void uploadAndDownloadFileDisabledZstdSucceeds() throws IOException { + BoxAPIConnection api = jwtApiForServiceAccount(); + api.setUseZstdCompression(false); + + String fileName = "smalltest.pdf"; + URL fileURL = this.getClass().getResource("/sample-files/" + fileName); + String filePath = URLDecoder.decode(fileURL.getFile(), "utf-8"); + byte[] fileContent = readAllBytes(filePath); + BoxFile file = null; + try { + file = uploadSampleFileToUniqueFolder(api, fileName); + + ByteArrayOutputStream downloadStream = new ByteArrayOutputStream(); + ProgressListener mockDownloadListener = mock(ProgressListener.class); + + URL url = CONTENT_URL_TEMPLATE.build(api.getBaseURL(), file.getID()); + BoxAPIRequest request = new BoxAPIRequest(api, url, "GET"); + BoxAPIResponse response = request.send(); + writeStream(response, downloadStream, mockDownloadListener); + + byte[] downloadedFileContent = downloadStream.toByteArray(); + assertThat(response.getHeaders().get("X-Content-Encoding"), is(nullValue())); + assertThat(downloadedFileContent, is(equalTo(fileContent))); + } finally { + deleteFile(file); } - - @Test - public void downloadFileUseZstdSucceeds() throws IOException { - BoxAPIConnection api = jwtApiForServiceAccount(); - api.setUseZstdCompression(true); - - String fileName = "smalltest.pdf"; - URL fileURL = this.getClass().getResource("/sample-files/" + fileName); - String filePath = URLDecoder.decode(fileURL.getFile(), "utf-8"); - byte[] fileContent = readAllBytes(filePath); - BoxFile file = null; - try { - file = uploadSampleFileToUniqueFolder(api, fileName); - - ByteArrayOutputStream downloadStream = new ByteArrayOutputStream(); - ProgressListener mockDownloadListener = mock(ProgressListener.class); - - URL url = CONTENT_URL_TEMPLATE.build(api.getBaseURL(), file.getID()); - BoxAPIRequest request = new BoxAPIRequest(api, url, "GET"); - BoxAPIResponse response = request.send(); - writeStream(response, downloadStream, mockDownloadListener); - - byte[] downloadedFileContent = downloadStream.toByteArray(); - assertThat(response.getHeaders().get("X-Content-Encoding").get(0), is(equalTo("zstd"))); - assertThat(downloadedFileContent, is(equalTo(fileContent))); - } finally { - deleteFile(file); - } + } + + @Test + public void downloadFileRangeSucceeds() throws IOException { + BoxAPIConnection api = jwtApiForServiceAccount(); + String fileName = "red_100x100.png"; + BoxFile uploadedFile = null; + try { + uploadedFile = uploadSampleFileToUniqueFolder(api, fileName); + BoxFile.Info uplodedFileInfo = uploadedFile.getInfo(); + long firstHalf = uplodedFileInfo.getSize() / 2; + + ByteArrayOutputStream downloadStream = new ByteArrayOutputStream(); + uploadedFile.downloadRange(downloadStream, 0, firstHalf); + uploadedFile.downloadRange(downloadStream, firstHalf + 1); + byte[] downloadedFileContent = downloadStream.toByteArray(); + + assertThat(downloadedFileContent, is(equalTo(this.readFileContent(fileName)))); + } finally { + deleteFile(uploadedFile); } - - @Test - public void uploadAndDownloadFileDisabledZstdSucceeds() throws IOException { - BoxAPIConnection api = jwtApiForServiceAccount(); - api.setUseZstdCompression(false); - - String fileName = "smalltest.pdf"; - URL fileURL = this.getClass().getResource("/sample-files/" + fileName); - String filePath = URLDecoder.decode(fileURL.getFile(), "utf-8"); - byte[] fileContent = readAllBytes(filePath); - BoxFile file = null; - try { - file = uploadSampleFileToUniqueFolder(api, fileName); - - ByteArrayOutputStream downloadStream = new ByteArrayOutputStream(); - ProgressListener mockDownloadListener = mock(ProgressListener.class); - - URL url = CONTENT_URL_TEMPLATE.build(api.getBaseURL(), file.getID()); - BoxAPIRequest request = new BoxAPIRequest(api, url, "GET"); - BoxAPIResponse response = request.send(); - writeStream(response, downloadStream, mockDownloadListener); - - byte[] downloadedFileContent = downloadStream.toByteArray(); - assertThat(response.getHeaders().get("X-Content-Encoding"), is(nullValue())); - assertThat(downloadedFileContent, is(equalTo(fileContent))); - } finally { - deleteFile(file); - } - } - - @Test - public void downloadFileRangeSucceeds() throws IOException { - BoxAPIConnection api = jwtApiForServiceAccount(); - String fileName = "red_100x100.png"; - BoxFile uploadedFile = null; - try { - uploadedFile = uploadSampleFileToUniqueFolder(api, fileName); - BoxFile.Info uplodedFileInfo = uploadedFile.getInfo(); - long firstHalf = uplodedFileInfo.getSize() / 2; - - ByteArrayOutputStream downloadStream = new ByteArrayOutputStream(); - uploadedFile.downloadRange(downloadStream, 0, firstHalf); - uploadedFile.downloadRange(downloadStream, firstHalf + 1); - byte[] downloadedFileContent = downloadStream.toByteArray(); - - assertThat(downloadedFileContent, is(equalTo(this.readFileContent(fileName)))); - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void getInfoWithOnlyTheNameField() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String fileName = "[getInfoWithOnlyTheNameField] Test File.txt"; + BoxFile uploadedFile = null; + + try { + uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); + BoxFile.Info uploadedFileInfo = uploadedFile.getInfo("name"); + + assertThat(uploadedFileInfo.getName(), is(equalTo(fileName))); + assertThat(uploadedFileInfo.getDescription(), is(nullValue())); + assertThat(uploadedFileInfo.getSize(), is(equalTo(0L))); + } finally { + deleteFile(uploadedFile); } + } - @Test - public void getInfoWithOnlyTheNameField() { - BoxAPIConnection api = jwtApiForServiceAccount(); - String fileName = "[getInfoWithOnlyTheNameField] Test File.txt"; - BoxFile uploadedFile = null; - - try { - uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); - BoxFile.Info uploadedFileInfo = uploadedFile.getInfo("name"); - - assertThat(uploadedFileInfo.getName(), is(equalTo(fileName))); - assertThat(uploadedFileInfo.getDescription(), is(nullValue())); - assertThat(uploadedFileInfo.getSize(), is(equalTo(0L))); - } finally { - deleteFile(uploadedFile); - } - - } - - @Test - public void fileLockAndUnlockSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - String fileName = "[getInfoWithOnlyTheLockField] Test File" + Calendar.getInstance().getTimeInMillis() + ".txt"; - BoxFile uploadedFile = null; - - try { - uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); + @Test + public void fileLockAndUnlockSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String fileName = + "[getInfoWithOnlyTheLockField] Test File" + + Calendar.getInstance().getTimeInMillis() + + ".txt"; + BoxFile uploadedFile = null; - Calendar calendar = Calendar.getInstance(); - calendar.add(Calendar.DAY_OF_YEAR, 1); - Date expiresAt = calendar.getTime(); - uploadedFile.lock(expiresAt, false); + try { + uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); - BoxFile.Info uploadedFileInfo = uploadedFile.getInfo("lock", "created_by"); - BoxLock fileLock = uploadedFileInfo.getLock(); + Calendar calendar = Calendar.getInstance(); + calendar.add(Calendar.DAY_OF_YEAR, 1); + Date expiresAt = calendar.getTime(); + uploadedFile.lock(expiresAt, false); - assertThat(fileLock, is(instanceOf(BoxLock.class))); - assertThat(fileLock.getExpiresAt().toString(), is(equalTo(expiresAt.toString()))); - assertThat(fileLock.getIsDownloadPrevented(), is(equalTo(false))); - assertThat(fileLock.getCreatedBy().getID(), is(equalTo(uploadedFileInfo.getCreatedBy().getID()))); + BoxFile.Info uploadedFileInfo = uploadedFile.getInfo("lock", "created_by"); + BoxLock fileLock = uploadedFileInfo.getLock(); - uploadedFile.unlock(); + assertThat(fileLock, is(instanceOf(BoxLock.class))); + assertThat(fileLock.getExpiresAt().toString(), is(equalTo(expiresAt.toString()))); + assertThat(fileLock.getIsDownloadPrevented(), is(equalTo(false))); + assertThat( + fileLock.getCreatedBy().getID(), is(equalTo(uploadedFileInfo.getCreatedBy().getID()))); - BoxFile.Info updatedFileInfo = uploadedFile.getInfo("lock"); - assertThat(updatedFileInfo.getLock(), is(nullValue())); + uploadedFile.unlock(); - uploadedFile.lock(true); + BoxFile.Info updatedFileInfo = uploadedFile.getInfo("lock"); + assertThat(updatedFileInfo.getLock(), is(nullValue())); - uploadedFileInfo = uploadedFile.getInfo("lock", "created_by"); - fileLock = uploadedFileInfo.getLock(); + uploadedFile.lock(true); - assertThat(fileLock, is(instanceOf(BoxLock.class))); - assertNull(fileLock.getExpiresAt()); - assertThat(fileLock.getIsDownloadPrevented(), is(equalTo(true))); - assertThat(fileLock.getCreatedBy().getID(), is(equalTo(uploadedFileInfo.getCreatedBy().getID()))); + uploadedFileInfo = uploadedFile.getInfo("lock", "created_by"); + fileLock = uploadedFileInfo.getLock(); - uploadedFile.unlock(); + assertThat(fileLock, is(instanceOf(BoxLock.class))); + assertNull(fileLock.getExpiresAt()); + assertThat(fileLock.getIsDownloadPrevented(), is(equalTo(true))); + assertThat( + fileLock.getCreatedBy().getID(), is(equalTo(uploadedFileInfo.getCreatedBy().getID()))); - uploadedFile.lock(); + uploadedFile.unlock(); - uploadedFileInfo = uploadedFile.getInfo("lock", "created_by"); - fileLock = uploadedFileInfo.getLock(); + uploadedFile.lock(); - assertThat(fileLock, is(instanceOf(BoxLock.class))); - assertNull(fileLock.getExpiresAt()); - assertThat(fileLock.getIsDownloadPrevented(), is(equalTo(false))); - assertThat(fileLock.getCreatedBy().getID(), is(equalTo(uploadedFileInfo.getCreatedBy().getID()))); + uploadedFileInfo = uploadedFile.getInfo("lock", "created_by"); + fileLock = uploadedFileInfo.getLock(); - uploadedFile.unlock(); - } finally { - deleteFile(uploadedFile); - } + assertThat(fileLock, is(instanceOf(BoxLock.class))); + assertNull(fileLock.getExpiresAt()); + assertThat(fileLock.getIsDownloadPrevented(), is(equalTo(false))); + assertThat( + fileLock.getCreatedBy().getID(), is(equalTo(uploadedFileInfo.getCreatedBy().getID()))); + uploadedFile.unlock(); + } finally { + deleteFile(uploadedFile); } - - @Test - public void getInfoWithAllFields() { - BoxAPIConnection api = jwtApiForServiceAccount(); - String fileName = "[getInfoWithAllFields] Test File.txt"; - BoxFile uploadedFile = null; - try { - uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); - BoxFile.Info uploadedFileInfo = uploadedFile.getInfo(BoxFile.ALL_FIELDS); - - assertThat(uploadedFileInfo.getName(), is(equalTo(fileName))); - assertThat(uploadedFileInfo.getVersionNumber(), is(equalTo("1"))); - assertThat(uploadedFileInfo.getCommentCount(), is(equalTo(0L))); - assertThat(uploadedFileInfo.getExtension(), is(equalTo("txt"))); - assertThat(uploadedFileInfo.getIsPackage(), is(false)); - assertThat(uploadedFileInfo.getItemStatus(), is(equalTo("active"))); - assertThat(uploadedFileInfo.getVersion(), not(nullValue())); - assertThat(uploadedFileInfo.getVersion().getVersionID(), not(nullValue())); - assertThat(uploadedFileInfo.getPermissions(), hasItem(BoxFile.Permission.CAN_INVITE_COLLABORATOR)); - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void getInfoWithAllFields() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String fileName = "[getInfoWithAllFields] Test File.txt"; + BoxFile uploadedFile = null; + try { + uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); + BoxFile.Info uploadedFileInfo = uploadedFile.getInfo(BoxFile.ALL_FIELDS); + + assertThat(uploadedFileInfo.getName(), is(equalTo(fileName))); + assertThat(uploadedFileInfo.getVersionNumber(), is(equalTo("1"))); + assertThat(uploadedFileInfo.getCommentCount(), is(equalTo(0L))); + assertThat(uploadedFileInfo.getExtension(), is(equalTo("txt"))); + assertThat(uploadedFileInfo.getIsPackage(), is(false)); + assertThat(uploadedFileInfo.getItemStatus(), is(equalTo("active"))); + assertThat(uploadedFileInfo.getVersion(), not(nullValue())); + assertThat(uploadedFileInfo.getVersion().getVersionID(), not(nullValue())); + assertThat( + uploadedFileInfo.getPermissions(), hasItem(BoxFile.Permission.CAN_INVITE_COLLABORATOR)); + } finally { + deleteFile(uploadedFile); } - - @Test - public void updateFileWithSpecialCharsInNameSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - String originalFileName = "[updateFileWithSpecialCharsInNameSucceeds] abc\";def.txt"; - - BoxFile uploadedFile = null; - try { - uploadedFile = uploadFileToUniqueFolder(api, originalFileName, "Test file"); - assertThat(uploadedFile.getInfo().getName(), is(equalTo(originalFileName))); - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void updateFileWithSpecialCharsInNameSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String originalFileName = "[updateFileWithSpecialCharsInNameSucceeds] abc\";def.txt"; + + BoxFile uploadedFile = null; + try { + uploadedFile = uploadFileToUniqueFolder(api, originalFileName, "Test file"); + assertThat(uploadedFile.getInfo().getName(), is(equalTo(originalFileName))); + } finally { + deleteFile(uploadedFile); } - - @Test - public void updateFileInfoSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - String originalFileName = "[updateFileInfoSucceeds] Original Name.txt"; - String newFileName = "[updateFileInfoSucceeds] New Name.txt"; - BoxFile uploadedFile = null; - try { - uploadedFile = uploadFileToUniqueFolder(api, originalFileName, "Test file"); - - BoxFile.Info newInfo = uploadedFile.new Info(); - newInfo.setName(newFileName); - uploadedFile.updateInfo(newInfo); - - assertThat(uploadedFile.getInfo().getName(), is(equalTo(newFileName))); - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void updateFileInfoSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String originalFileName = "[updateFileInfoSucceeds] Original Name.txt"; + String newFileName = "[updateFileInfoSucceeds] New Name.txt"; + BoxFile uploadedFile = null; + try { + uploadedFile = uploadFileToUniqueFolder(api, originalFileName, "Test file"); + + BoxFile.Info newInfo = uploadedFile.new Info(); + newInfo.setName(newFileName); + uploadedFile.updateInfo(newInfo); + + assertThat(uploadedFile.getInfo().getName(), is(equalTo(newFileName))); + } finally { + deleteFile(uploadedFile); } - - @Test - public void renameFileSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - String originalFileName = "[renameFileSucceeds] Original Name.txt"; - String newFileName = "[renameFileSucceeds] New Name.txt"; - BoxFile uploadedFile = null; - try { - uploadedFile = uploadFileToUniqueFolder(api, originalFileName, "Test file"); - - uploadedFile.rename(newFileName); - BoxFile.Info newInfo = uploadedFile.getInfo(); - - assertThat(newInfo.getName(), is(equalTo(newFileName))); - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void renameFileSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String originalFileName = "[renameFileSucceeds] Original Name.txt"; + String newFileName = "[renameFileSucceeds] New Name.txt"; + BoxFile uploadedFile = null; + try { + uploadedFile = uploadFileToUniqueFolder(api, originalFileName, "Test file"); + + uploadedFile.rename(newFileName); + BoxFile.Info newInfo = uploadedFile.getInfo(); + + assertThat(newInfo.getName(), is(equalTo(newFileName))); + } finally { + deleteFile(uploadedFile); } - - @Test - public void uploadAndDownloadMultipleVersionsSucceeds() throws UnsupportedEncodingException { - BoxFile uploadedFile = null; - String fileName = "[uploadAndDownloadMultipleVersionsSucceeds] Multi-version File.txt"; - String version1Content = "Version 1"; - String version1Sha = "db3cbc01da600701b9fe4a497fe328e71fa7022f"; - String version2Content = "Version 2"; - ProgressListener mockUploadListener = mock(ProgressListener.class); - try { - uploadedFile = uploadTwoFileVersionsToUniqueFolder(fileName, version1Content, - version2Content, mockUploadListener); - Collection versions = uploadedFile.getVersions(); - BoxFileVersion previousVersion = versions.iterator().next(); - - ByteArrayOutputStream downloadStream = new ByteArrayOutputStream(); - ProgressListener mockDownloadListener = mock(ProgressListener.class); - previousVersion.download(downloadStream, mockDownloadListener); - String downloadedContent = downloadStream.toString(StandardCharsets.UTF_8.name()); - - assertThat(versions, hasSize(1)); - assertThat(previousVersion.getSha1(), is(equalTo(version1Sha))); - assertThat(downloadedContent, equalTo(version1Content)); - verify(mockDownloadListener, atLeastOnce()).onProgressChanged(anyLong(), anyLong()); - long version1Size = version1Content.getBytes(StandardCharsets.UTF_8).length; - verify(mockUploadListener, atLeastOnce()).onProgressChanged(anyLong(), - longThat(is(equalTo(version1Size)))); - - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void uploadAndDownloadMultipleVersionsSucceeds() throws UnsupportedEncodingException { + BoxFile uploadedFile = null; + String fileName = "[uploadAndDownloadMultipleVersionsSucceeds] Multi-version File.txt"; + String version1Content = "Version 1"; + String version1Sha = "db3cbc01da600701b9fe4a497fe328e71fa7022f"; + String version2Content = "Version 2"; + ProgressListener mockUploadListener = mock(ProgressListener.class); + try { + uploadedFile = + uploadTwoFileVersionsToUniqueFolder( + fileName, version1Content, version2Content, mockUploadListener); + Collection versions = uploadedFile.getVersions(); + BoxFileVersion previousVersion = versions.iterator().next(); + + ByteArrayOutputStream downloadStream = new ByteArrayOutputStream(); + ProgressListener mockDownloadListener = mock(ProgressListener.class); + previousVersion.download(downloadStream, mockDownloadListener); + String downloadedContent = downloadStream.toString(StandardCharsets.UTF_8.name()); + + assertThat(versions, hasSize(1)); + assertThat(previousVersion.getSha1(), is(equalTo(version1Sha))); + assertThat(downloadedContent, equalTo(version1Content)); + verify(mockDownloadListener, atLeastOnce()).onProgressChanged(anyLong(), anyLong()); + long version1Size = version1Content.getBytes(StandardCharsets.UTF_8).length; + verify(mockUploadListener, atLeastOnce()) + .onProgressChanged(anyLong(), longThat(is(equalTo(version1Size)))); + + } finally { + deleteFile(uploadedFile); } - - @Test - public void uploadNewVersionSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - String fileName = "Multi-version File.txt"; - String updatedFileName = "[uploadNewVersionSucceeds] Multi-version File.txt"; - Date contentModifiedAt = new Date(10000); - BoxFile uploadedFile = null; - try { - uploadedFile = uploadFileToUniqueFolder(api, fileName, "Version 1"); - InputStream uploadStream = this.getFileContent("Version 1"); - BoxFile.Info newVersion = uploadedFile.uploadNewVersion( - uploadStream, - null, - contentModifiedAt, - updatedFileName, - 0, - null - ); - - assertEquals(updatedFileName, newVersion.getName()); - assertEquals(contentModifiedAt, newVersion.getContentModifiedAt()); - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void uploadNewVersionSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String fileName = "Multi-version File.txt"; + String updatedFileName = "[uploadNewVersionSucceeds] Multi-version File.txt"; + Date contentModifiedAt = new Date(10000); + BoxFile uploadedFile = null; + try { + uploadedFile = uploadFileToUniqueFolder(api, fileName, "Version 1"); + InputStream uploadStream = this.getFileContent("Version 1"); + BoxFile.Info newVersion = + uploadedFile.uploadNewVersion( + uploadStream, null, contentModifiedAt, updatedFileName, 0, null); + + assertEquals(updatedFileName, newVersion.getName()); + assertEquals(contentModifiedAt, newVersion.getContentModifiedAt()); + } finally { + deleteFile(uploadedFile); } - - @Test - public void getVersionSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - String fileName = "[getVersionByIdSucceeds] Multi-version File.txt"; - BoxFile uploadedFile = null; - try { - uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); - uploadedFile.uploadNewVersion(this.getFileContent("Version 2")); - - Collection versions = uploadedFile.getVersions(); - BoxFileVersion versionFromGetVersions = versions.iterator().next(); - - BoxFileVersion versionFromGetById = uploadedFile.getVersionByID(versionFromGetVersions.getID()); - - assertThat(versionFromGetVersions.getVersionID(), equalTo(versionFromGetById.getVersionID())); - assertThat(versionFromGetVersions.getFileID(), equalTo(versionFromGetById.getFileID())); - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void getVersionSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String fileName = "[getVersionByIdSucceeds] Multi-version File.txt"; + BoxFile uploadedFile = null; + try { + uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); + uploadedFile.uploadNewVersion(this.getFileContent("Version 2")); + + Collection versions = uploadedFile.getVersions(); + BoxFileVersion versionFromGetVersions = versions.iterator().next(); + + BoxFileVersion versionFromGetById = + uploadedFile.getVersionByID(versionFromGetVersions.getID()); + + assertThat(versionFromGetVersions.getVersionID(), equalTo(versionFromGetById.getVersionID())); + assertThat(versionFromGetVersions.getFileID(), equalTo(versionFromGetById.getFileID())); + } finally { + deleteFile(uploadedFile); } - - @Test - public void deleteVersionSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - String fileName = "[deleteVersionSucceeds] Multi-version File.txt"; - BoxFile uploadedFile = null; - try { - uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); - uploadedFile.uploadNewVersion(this.getFileContent("Version 2")); - - Collection versions = uploadedFile.getVersions(); - BoxFileVersion previousVersion = versions.iterator().next(); - previousVersion.delete(); - - Collection versionsAfterRemove = uploadedFile.getVersions(); - assertThat(versionsAfterRemove, Matchers.hasSize(1)); - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void deleteVersionSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String fileName = "[deleteVersionSucceeds] Multi-version File.txt"; + BoxFile uploadedFile = null; + try { + uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); + uploadedFile.uploadNewVersion(this.getFileContent("Version 2")); + + Collection versions = uploadedFile.getVersions(); + BoxFileVersion previousVersion = versions.iterator().next(); + previousVersion.delete(); + + Collection versionsAfterRemove = uploadedFile.getVersions(); + assertThat(versionsAfterRemove, Matchers.hasSize(1)); + } finally { + deleteFile(uploadedFile); } - - @Test - public void shouldReturnTrashedAtForADeleteVersion() { - BoxAPIConnection api = jwtApiForServiceAccount(); - String fileName = "[deleteVersionSucceeds] Multi-version File.txt"; - BoxFile uploadedFile = null; - try { - uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); - uploadedFile.uploadNewVersion(this.getFileContent("Version 2")); - Collection versions = uploadedFile.getVersions(); - assertThat(versions, Matchers.hasSize(1)); - - BoxFileVersion version = versions.iterator().next(); - assertThat(version.getTrashedAt(), is(nullValue())); - - version.delete(); - - BoxFileVersion trashedVersion = uploadedFile.getVersions().iterator().next(); - assertThat(trashedVersion.getTrashedAt(), is(notNullValue())); - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void shouldReturnTrashedAtForADeleteVersion() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String fileName = "[deleteVersionSucceeds] Multi-version File.txt"; + BoxFile uploadedFile = null; + try { + uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); + uploadedFile.uploadNewVersion(this.getFileContent("Version 2")); + Collection versions = uploadedFile.getVersions(); + assertThat(versions, Matchers.hasSize(1)); + + BoxFileVersion version = versions.iterator().next(); + assertThat(version.getTrashedAt(), is(nullValue())); + + version.delete(); + + BoxFileVersion trashedVersion = uploadedFile.getVersions().iterator().next(); + assertThat(trashedVersion.getTrashedAt(), is(notNullValue())); + } finally { + deleteFile(uploadedFile); } - - @Test - public void promoteVersionsSucceeds() throws UnsupportedEncodingException { - BoxAPIConnection api = jwtApiForServiceAccount(); - String fileName = "[promoteVersionsSucceeds] Multi-version File.txt"; - BoxFile uploadedFile = null; - try { - uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); - uploadedFile.uploadNewVersion(this.getFileContent("Version 1")); - uploadedFile.uploadNewVersion(this.getFileContent("Version 2")); - - Iterator iterator = uploadedFile.getVersions().iterator(); - BoxFileVersion version1 = iterator.next(); - version1.promote(); - - ByteArrayOutputStream downloadStream = new ByteArrayOutputStream(); - uploadedFile.download(downloadStream); - String downloadedContent = downloadStream.toString(StandardCharsets.UTF_8.name()); - assertThat(downloadedContent, equalTo("Version 1")); - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void promoteVersionsSucceeds() throws UnsupportedEncodingException { + BoxAPIConnection api = jwtApiForServiceAccount(); + String fileName = "[promoteVersionsSucceeds] Multi-version File.txt"; + BoxFile uploadedFile = null; + try { + uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); + uploadedFile.uploadNewVersion(this.getFileContent("Version 1")); + uploadedFile.uploadNewVersion(this.getFileContent("Version 2")); + + Iterator iterator = uploadedFile.getVersions().iterator(); + BoxFileVersion version1 = iterator.next(); + version1.promote(); + + ByteArrayOutputStream downloadStream = new ByteArrayOutputStream(); + uploadedFile.download(downloadStream); + String downloadedContent = downloadStream.toString(StandardCharsets.UTF_8.name()); + assertThat(downloadedContent, equalTo("Version 1")); + } finally { + deleteFile(uploadedFile); } - - @Test - public void canListVersions() { - BoxFile uploadedFile = null; - String fileName = "[canListVersions] Multi-version File.txt"; - try { - - uploadedFile = uploadTwoFileVersionsToUniqueFolder( - fileName, "Version 1", "Version 2", mock(ProgressListener.class) - ); - - Collection versions = uploadedFile.getVersions(); - assertThat(versions.size(), is(1)); - BoxFileVersion version = versions.iterator().next(); - assertThat(version.getName(), is(notNullValue())); - assertThat(version.getFileID(), is(notNullValue())); - assertThat(version.getCreatedAt(), is(notNullValue())); - assertThat(version.getVersionNumber(), is(nullValue())); - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void canListVersions() { + BoxFile uploadedFile = null; + String fileName = "[canListVersions] Multi-version File.txt"; + try { + + uploadedFile = + uploadTwoFileVersionsToUniqueFolder( + fileName, "Version 1", "Version 2", mock(ProgressListener.class)); + + Collection versions = uploadedFile.getVersions(); + assertThat(versions.size(), is(1)); + BoxFileVersion version = versions.iterator().next(); + assertThat(version.getName(), is(notNullValue())); + assertThat(version.getFileID(), is(notNullValue())); + assertThat(version.getCreatedAt(), is(notNullValue())); + assertThat(version.getVersionNumber(), is(nullValue())); + } finally { + deleteFile(uploadedFile); } - - @Test - public void canPaginateOverListOfVersions() { - BoxFile uploadedFile = null; - String fileName = "[canPaginateOverListOfVersions] Multi-version File.txt"; - try { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder uniqueFolder = getUniqueFolder(api); - uploadedFile = uploadFileWithContentToSpecifiedFolder(fileName, "Version 1", uniqueFolder); - - byte[] fileBytes = "Version 2".getBytes(StandardCharsets.UTF_8); - uploadedFile.uploadNewVersion( - new ByteArrayInputStream(fileBytes), null, fileBytes.length, mock(ProgressListener.class)); - - fileBytes = "Version 3".getBytes(StandardCharsets.UTF_8); - uploadedFile.uploadNewVersion( - new ByteArrayInputStream(fileBytes), null, fileBytes.length, mock(ProgressListener.class)); - - Collection versionsPart1 = uploadedFile.getVersionsRange(0, 1); - assertThat(versionsPart1.size(), is(1)); - BoxFileVersion boxFileVersion1 = versionsPart1.iterator().next(); - - Collection versionsPart2 = uploadedFile.getVersionsRange(1, 2); - assertThat(versionsPart2.size(), is(1)); - BoxFileVersion boxFileVersion2 = versionsPart2.iterator().next(); - - Collection allVersions = uploadedFile.getVersionsRange(0, 10); - assertThat(allVersions.size(), is(2)); - Iterator iterator = allVersions.iterator(); - assertThat(iterator.next(), is(boxFileVersion1)); - assertThat(iterator.next(), is(boxFileVersion2)); - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void canPaginateOverListOfVersions() { + BoxFile uploadedFile = null; + String fileName = "[canPaginateOverListOfVersions] Multi-version File.txt"; + try { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder uniqueFolder = getUniqueFolder(api); + uploadedFile = uploadFileWithContentToSpecifiedFolder(fileName, "Version 1", uniqueFolder); + + byte[] fileBytes = "Version 2".getBytes(StandardCharsets.UTF_8); + uploadedFile.uploadNewVersion( + new ByteArrayInputStream(fileBytes), + null, + fileBytes.length, + mock(ProgressListener.class)); + + fileBytes = "Version 3".getBytes(StandardCharsets.UTF_8); + uploadedFile.uploadNewVersion( + new ByteArrayInputStream(fileBytes), + null, + fileBytes.length, + mock(ProgressListener.class)); + + Collection versionsPart1 = uploadedFile.getVersionsRange(0, 1); + assertThat(versionsPart1.size(), is(1)); + BoxFileVersion boxFileVersion1 = versionsPart1.iterator().next(); + + Collection versionsPart2 = uploadedFile.getVersionsRange(1, 2); + assertThat(versionsPart2.size(), is(1)); + BoxFileVersion boxFileVersion2 = versionsPart2.iterator().next(); + + Collection allVersions = uploadedFile.getVersionsRange(0, 10); + assertThat(allVersions.size(), is(2)); + Iterator iterator = allVersions.iterator(); + assertThat(iterator.next(), is(boxFileVersion1)); + assertThat(iterator.next(), is(boxFileVersion2)); + } finally { + deleteFile(uploadedFile); } - - @Test - public void canListVersionsWithSpecificFields() { - BoxFile uploadedFile = null; - String fileName = "[canListVersionsWithSpecificFields] Multi-version File.txt"; - try { - - uploadedFile = uploadTwoFileVersionsToUniqueFolder( - fileName, "Version 1", "Version 2", mock(ProgressListener.class) - ); - - Collection versions = uploadedFile.getVersions("name", "version_number"); - assertThat(versions.size(), is(1)); - BoxFileVersion version = versions.iterator().next(); - assertThat(version.getName(), is(notNullValue())); - assertThat(version.getFileID(), is(notNullValue())); - assertThat(version.getCreatedAt(), is(nullValue())); - assertThat(version.getVersionNumber(), is(1L)); - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void canListVersionsWithSpecificFields() { + BoxFile uploadedFile = null; + String fileName = "[canListVersionsWithSpecificFields] Multi-version File.txt"; + try { + + uploadedFile = + uploadTwoFileVersionsToUniqueFolder( + fileName, "Version 1", "Version 2", mock(ProgressListener.class)); + + Collection versions = uploadedFile.getVersions("name", "version_number"); + assertThat(versions.size(), is(1)); + BoxFileVersion version = versions.iterator().next(); + assertThat(version.getName(), is(notNullValue())); + assertThat(version.getFileID(), is(notNullValue())); + assertThat(version.getCreatedAt(), is(nullValue())); + assertThat(version.getVersionNumber(), is(1L)); + } finally { + deleteFile(uploadedFile); } - - @Test - public void canListVersionsWithAllFields() { - BoxFile uploadedFile = null; - String fileName = "[canListVersionsWithAllFields] Multi-version File.txt"; - try { - // given - uploadedFile = uploadTwoFileVersionsToUniqueFolder( - fileName, "Version 1", "Version 2", mock(ProgressListener.class) - ); - BoxFileVersion version1 = uploadedFile.getVersions().iterator().next(); - version1.promote(); - version1.delete(); - - // when - Collection versions = uploadedFile.getVersions(ALL_VERSION_FIELDS); - - //then - assertThat(versions.size(), is(2)); - Iterator iterator = versions.iterator(); - iterator.next(); - BoxFileVersion version = iterator.next(); - assertThat(version.getID(), is(notNullValue())); - assertThat(version.getSha1(), is(notNullValue())); - assertThat(version.getName(), is(notNullValue())); - assertThat(version.getSize(), is(notNullValue())); - assertThat(version.getUploaderDisplayName(), is(notNullValue())); - assertThat(version.getCreatedAt(), is(notNullValue())); - assertThat(version.getModifiedAt(), is(notNullValue())); - assertThat(version.getModifiedBy(), is(notNullValue())); - assertThat(version.getTrashedAt(), is(notNullValue())); - assertThat(version.getTrashedBy(), is(notNullValue())); - assertThat(version.getPurgedAt(), is(notNullValue())); - assertThat(version.getFileID(), is(uploadedFile.getID())); - assertThat(version.getVersionNumber(), is(notNullValue())); - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void canListVersionsWithAllFields() { + BoxFile uploadedFile = null; + String fileName = "[canListVersionsWithAllFields] Multi-version File.txt"; + try { + // given + uploadedFile = + uploadTwoFileVersionsToUniqueFolder( + fileName, "Version 1", "Version 2", mock(ProgressListener.class)); + BoxFileVersion version1 = uploadedFile.getVersions().iterator().next(); + version1.promote(); + version1.delete(); + + // when + Collection versions = uploadedFile.getVersions(ALL_VERSION_FIELDS); + + // then + assertThat(versions.size(), is(2)); + Iterator iterator = versions.iterator(); + iterator.next(); + BoxFileVersion version = iterator.next(); + assertThat(version.getID(), is(notNullValue())); + assertThat(version.getSha1(), is(notNullValue())); + assertThat(version.getName(), is(notNullValue())); + assertThat(version.getSize(), is(notNullValue())); + assertThat(version.getUploaderDisplayName(), is(notNullValue())); + assertThat(version.getCreatedAt(), is(notNullValue())); + assertThat(version.getModifiedAt(), is(notNullValue())); + assertThat(version.getModifiedBy(), is(notNullValue())); + assertThat(version.getTrashedAt(), is(notNullValue())); + assertThat(version.getTrashedBy(), is(notNullValue())); + assertThat(version.getPurgedAt(), is(notNullValue())); + assertThat(version.getFileID(), is(uploadedFile.getID())); + assertThat(version.getVersionNumber(), is(notNullValue())); + } finally { + deleteFile(uploadedFile); } - - @Test - public void copyFileSucceeds() throws UnsupportedEncodingException { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder uploadFolder = getUniqueFolder(api); - String originalFileName = "[copyFileSucceeds] Original File.txt"; - String newFileName = "[copyFileSucceeds] New File.txt"; - String fileContent = "Test file"; - BoxFile uploadedFile = null; - BoxFile copiedFile = null; - try { - uploadedFile = uploadFileToUniqueFolder(api, originalFileName, fileContent); - copiedFile = uploadedFile.copy(uploadFolder, newFileName).getResource(); - - ByteArrayOutputStream downloadStream = new ByteArrayOutputStream(); - copiedFile.download(downloadStream); - String downloadedContent = downloadStream.toString(StandardCharsets.UTF_8.name()); - assertThat(downloadedContent, equalTo(fileContent)); - } finally { - deleteFile(uploadedFile); - deleteFile(copiedFile); - } + } + + @Test + public void copyFileSucceeds() throws UnsupportedEncodingException { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder uploadFolder = getUniqueFolder(api); + String originalFileName = "[copyFileSucceeds] Original File.txt"; + String newFileName = "[copyFileSucceeds] New File.txt"; + String fileContent = "Test file"; + BoxFile uploadedFile = null; + BoxFile copiedFile = null; + try { + uploadedFile = uploadFileToUniqueFolder(api, originalFileName, fileContent); + copiedFile = uploadedFile.copy(uploadFolder, newFileName).getResource(); + + ByteArrayOutputStream downloadStream = new ByteArrayOutputStream(); + copiedFile.download(downloadStream); + String downloadedContent = downloadStream.toString(StandardCharsets.UTF_8.name()); + assertThat(downloadedContent, equalTo(fileContent)); + } finally { + deleteFile(uploadedFile); + deleteFile(copiedFile); } - - @Test - public void moveFileSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - String fileName = "[moveFileSucceeds] Test File.txt"; - String folderName = "[moveFileSucceeds] Destination Folder"; - BoxFile uploadedFile = null; - BoxFolder destinationFolder = null; - try { - uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); - - destinationFolder = getUniqueFolder(api).createFolder(folderName).getResource(); - uploadedFile.move(destinationFolder); - - assertThat(destinationFolder, - hasItem(Matchers.hasProperty("ID", equalTo(uploadedFile.getID())))); - } finally { - deleteFile(uploadedFile); - deleteFolder(destinationFolder); - } + } + + @Test + public void moveFileSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String fileName = "[moveFileSucceeds] Test File.txt"; + String folderName = "[moveFileSucceeds] Destination Folder"; + BoxFile uploadedFile = null; + BoxFolder destinationFolder = null; + try { + uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); + + destinationFolder = getUniqueFolder(api).createFolder(folderName).getResource(); + uploadedFile.move(destinationFolder); + + assertThat( + destinationFolder, + hasItem(Matchers.hasProperty("ID", equalTo(uploadedFile.getID())))); + } finally { + deleteFile(uploadedFile); + deleteFolder(destinationFolder); } - - @Test - public void createAndUpdateSharedLinkSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - String fileName = "[createAndUpdateSharedLinkSucceeds] Test File.txt"; - BoxFile uploadedFile = null; - try { - uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); - assertThat( - uploadedFile.getInfo("is_accessible_via_shared_link").getIsAccessibleViaSharedLink(), - is(false) - ); - BoxSharedLink sharedLink = uploadedFile.createSharedLink( - new BoxSharedLinkRequest() - .access(OPEN) - .permissions(true, true, true) - ); - - assertThat(sharedLink.getURL(), not(is(emptyOrNullString()))); - - sharedLink.getPermissions().setCanDownload(false); - BoxFile.Info info = uploadedFile.new Info(); - info.setSharedLink(sharedLink); - uploadedFile.updateInfo(info); - - BoxFile.Info updatedInfo = uploadedFile.getInfo("shared_link", "is_accessible_via_shared_link"); - assertThat(updatedInfo.getSharedLink().getPermissions().getCanDownload(), is(false)); - assertThat(updatedInfo.getIsAccessibleViaSharedLink(), is(true)); - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void createAndUpdateSharedLinkSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String fileName = "[createAndUpdateSharedLinkSucceeds] Test File.txt"; + BoxFile uploadedFile = null; + try { + uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); + assertThat( + uploadedFile.getInfo("is_accessible_via_shared_link").getIsAccessibleViaSharedLink(), + is(false)); + BoxSharedLink sharedLink = + uploadedFile.createSharedLink( + new BoxSharedLinkRequest().access(OPEN).permissions(true, true, true)); + + assertThat(sharedLink.getURL(), not(is(emptyOrNullString()))); + + sharedLink.getPermissions().setCanDownload(false); + BoxFile.Info info = uploadedFile.new Info(); + info.setSharedLink(sharedLink); + uploadedFile.updateInfo(info); + + BoxFile.Info updatedInfo = + uploadedFile.getInfo("shared_link", "is_accessible_via_shared_link"); + assertThat(updatedInfo.getSharedLink().getPermissions().getCanDownload(), is(false)); + assertThat(updatedInfo.getIsAccessibleViaSharedLink(), is(true)); + } finally { + deleteFile(uploadedFile); } - - @Test - public void downloadpdateSharedLinkSucceeds() throws IOException { - BoxAPIConnection api = jwtApiForServiceAccount(); - String fileName = "[downloadpdateSharedLinkSucceeds] Test File.txt"; - String fileContent = "Test file"; - String password = "Secret123@"; - BoxFile uploadedFile = null; - try { - uploadedFile = uploadFileToUniqueFolder(api, fileName, fileContent); - assertThat( - uploadedFile.getInfo("is_accessible_via_shared_link").getIsAccessibleViaSharedLink(), - is(false) - ); - BoxSharedLink sharedLink = uploadedFile.createSharedLink( - new BoxSharedLinkRequest() - .access(OPEN) - .password(password) - .permissions(true, true, true) - ); - - ByteArrayOutputStream downloadStream = new ByteArrayOutputStream(); - BoxFile.downloadFromSharedLink(api, downloadStream, sharedLink.getURL(), password); - downloadStream.close(); - byte[] downloadedFileContent = downloadStream.toByteArray(); - assertThat(downloadedFileContent, is(equalTo(fileContent.getBytes()))); - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void downloadpdateSharedLinkSucceeds() throws IOException { + BoxAPIConnection api = jwtApiForServiceAccount(); + String fileName = "[downloadpdateSharedLinkSucceeds] Test File.txt"; + String fileContent = "Test file"; + String password = "Secret123@"; + BoxFile uploadedFile = null; + try { + uploadedFile = uploadFileToUniqueFolder(api, fileName, fileContent); + assertThat( + uploadedFile.getInfo("is_accessible_via_shared_link").getIsAccessibleViaSharedLink(), + is(false)); + BoxSharedLink sharedLink = + uploadedFile.createSharedLink( + new BoxSharedLinkRequest() + .access(OPEN) + .password(password) + .permissions(true, true, true)); + + ByteArrayOutputStream downloadStream = new ByteArrayOutputStream(); + BoxFile.downloadFromSharedLink(api, downloadStream, sharedLink.getURL(), password); + downloadStream.close(); + byte[] downloadedFileContent = downloadStream.toByteArray(); + assertThat(downloadedFileContent, is(equalTo(fileContent.getBytes()))); + } finally { + deleteFile(uploadedFile); } - - @Test - public void createEditableSharedLinkSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - String fileName = "[createEditableSharedLinkSucceeds] Test File.txt"; - BoxFile uploadedFile = null; - try { - uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); - uploadedFile.createSharedLink( - new BoxSharedLinkRequest() - .permissions(true, true, true) - ); - - BoxSharedLink.Permissions createdPermissions = uploadedFile.getInfo().getSharedLink().getPermissions(); - assertThat(createdPermissions.getCanPreview(), is(true)); - assertThat(createdPermissions.getCanDownload(), is(true)); - assertThat(createdPermissions.getCanEdit(), is(true)); - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void createEditableSharedLinkSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String fileName = "[createEditableSharedLinkSucceeds] Test File.txt"; + BoxFile uploadedFile = null; + try { + uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); + uploadedFile.createSharedLink(new BoxSharedLinkRequest().permissions(true, true, true)); + + BoxSharedLink.Permissions createdPermissions = + uploadedFile.getInfo().getSharedLink().getPermissions(); + assertThat(createdPermissions.getCanPreview(), is(true)); + assertThat(createdPermissions.getCanDownload(), is(true)); + assertThat(createdPermissions.getCanEdit(), is(true)); + } finally { + deleteFile(uploadedFile); } - - @Test - public void addCommentSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - String fileName = "[addCommentSucceeds] Test File.txt"; - String commentMessage = "Non-empty message"; - BoxFile uploadedFile = null; - - try { - uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); - BoxComment.Info addedCommentInfo = uploadedFile.addComment(commentMessage); - - assertThat(addedCommentInfo.getMessage(), is(equalTo(commentMessage))); - assertThat(uploadedFile.getComments(), - hasItem(Matchers.hasProperty("ID", equalTo(addedCommentInfo.getID())))); - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void addCommentSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String fileName = "[addCommentSucceeds] Test File.txt"; + String commentMessage = "Non-empty message"; + BoxFile uploadedFile = null; + + try { + uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); + BoxComment.Info addedCommentInfo = uploadedFile.addComment(commentMessage); + + assertThat(addedCommentInfo.getMessage(), is(equalTo(commentMessage))); + assertThat( + uploadedFile.getComments(), + hasItem(Matchers.hasProperty("ID", equalTo(addedCommentInfo.getID())))); + } finally { + deleteFile(uploadedFile); } - - @Test - public void addCommentWithMentionSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - String fileName = "[addCommentWithMentionSucceeds] Test File.txt"; - String commentMessage = String.format( + } + + @Test + public void addCommentWithMentionSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String fileName = "[addCommentWithMentionSucceeds] Test File.txt"; + String commentMessage = + String.format( "Message mentioning @[%s:%s]", - TestConfig.getCollaboratorID(), - TestConfig.getCollaborator() - ); - BoxFile uploadedFile = null; - - try { - uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); - BoxComment.Info addedCommentInfo = uploadedFile.addComment(commentMessage); - - String expectedCommentMessage = "Message mentioning " + TestConfig.getCollaborator(); - assertThat(addedCommentInfo.getMessage(), is(equalTo(expectedCommentMessage))); - assertThat(uploadedFile.getComments(), - hasItem(Matchers.hasProperty("ID", equalTo(addedCommentInfo.getID())))); - } finally { - deleteFile(uploadedFile); - } + TestConfig.getCollaboratorID(), TestConfig.getCollaborator()); + BoxFile uploadedFile = null; + + try { + uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); + BoxComment.Info addedCommentInfo = uploadedFile.addComment(commentMessage); + + String expectedCommentMessage = "Message mentioning " + TestConfig.getCollaborator(); + assertThat(addedCommentInfo.getMessage(), is(equalTo(expectedCommentMessage))); + assertThat( + uploadedFile.getComments(), + hasItem(Matchers.hasProperty("ID", equalTo(addedCommentInfo.getID())))); + } finally { + deleteFile(uploadedFile); } - - @Test - public void createMetadataAndGetMetadataOnInfoSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - String fileName = "[createMetadataSucceeds] Test File.txt"; - - BoxFile uploadedFile = null; - try { - uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); - uploadedFile.createMetadata(new Metadata().add("/foo", "bar")); - - Metadata metadata = uploadedFile.getMetadata(); - assertNotNull(metadata); - assertEquals("bar", metadata.getString("/foo")); - - Metadata actualMD = uploadedFile.getInfo("metadata.global.properties") - .getMetadata("properties", "global"); - assertNotNull("Metadata should not be null for this file", actualMD); - } catch (BoxAPIException e) { - fail("Metadata should have been present on this folder"); - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void createMetadataAndGetMetadataOnInfoSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String fileName = "[createMetadataSucceeds] Test File.txt"; + + BoxFile uploadedFile = null; + try { + uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); + uploadedFile.createMetadata(new Metadata().add("/foo", "bar")); + + Metadata metadata = uploadedFile.getMetadata(); + assertNotNull(metadata); + assertEquals("bar", metadata.getString("/foo")); + + Metadata actualMD = + uploadedFile.getInfo("metadata.global.properties").getMetadata("properties", "global"); + assertNotNull("Metadata should not be null for this file", actualMD); + } catch (BoxAPIException e) { + fail("Metadata should have been present on this folder"); + } finally { + deleteFile(uploadedFile); } - - @Test - public void updateMetadataSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - String fileName = "[updateMetadataSucceeds] Test File.txt"; - BoxFile uploadedFile = null; - try { - uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); - uploadedFile.createMetadata(new Metadata().add("/foo", "bar")); - - Metadata metadata = uploadedFile.getMetadata(); - assertNotNull(metadata); - assertEquals("bar", metadata.getString("/foo")); - - uploadedFile.updateMetadata(metadata.replace("/foo", "baz")); - - Metadata updatedMetadata = uploadedFile.getMetadata(); - assertNotNull(updatedMetadata); - assertEquals("baz", updatedMetadata.getString("/foo")); - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void updateMetadataSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String fileName = "[updateMetadataSucceeds] Test File.txt"; + BoxFile uploadedFile = null; + try { + uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); + uploadedFile.createMetadata(new Metadata().add("/foo", "bar")); + + Metadata metadata = uploadedFile.getMetadata(); + assertNotNull(metadata); + assertEquals("bar", metadata.getString("/foo")); + + uploadedFile.updateMetadata(metadata.replace("/foo", "baz")); + + Metadata updatedMetadata = uploadedFile.getMetadata(); + assertNotNull(updatedMetadata); + assertEquals("baz", updatedMetadata.getString("/foo")); + } finally { + deleteFile(uploadedFile); } - - @Test - public void addTaskSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - String fileName = "[addTaskSucceeds] Test File " + Calendar.getInstance().getTimeInMillis() + ".txt"; - String taskMessage = "Non-empty message"; - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); - Date dueAt = new Date(new Date().getTime() + (1000 * 24 * 60 * 60)); - BoxFile uploadedFile = null; - try { - uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); - BoxTask.Info addedTaskInfo = uploadedFile.addTask(BoxTask.Action.REVIEW, taskMessage, dueAt); - - assertThat(addedTaskInfo.getMessage(), is(equalTo(taskMessage))); - assertThat(dateFormat.format(addedTaskInfo.getDueAt()), is(equalTo(dateFormat.format(dueAt)))); - assertThat(uploadedFile.getTasks(), hasItem(Matchers.hasProperty("ID", - equalTo(addedTaskInfo.getID())))); - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void addTaskSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String fileName = + "[addTaskSucceeds] Test File " + Calendar.getInstance().getTimeInMillis() + ".txt"; + String taskMessage = "Non-empty message"; + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); + Date dueAt = new Date(new Date().getTime() + (1000 * 24 * 60 * 60)); + BoxFile uploadedFile = null; + try { + uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); + BoxTask.Info addedTaskInfo = uploadedFile.addTask(BoxTask.Action.REVIEW, taskMessage, dueAt); + + assertThat(addedTaskInfo.getMessage(), is(equalTo(taskMessage))); + assertThat( + dateFormat.format(addedTaskInfo.getDueAt()), is(equalTo(dateFormat.format(dueAt)))); + assertThat( + uploadedFile.getTasks(), + hasItem(Matchers.hasProperty("ID", equalTo(addedTaskInfo.getID())))); + } finally { + deleteFile(uploadedFile); } - - @Test - public void getPreviewLink() { - BoxAPIConnection api = jwtApiForServiceAccount(); - String fileName = "[getPreviewLink] Test File.txt"; - BoxFile uploadedFile = null; - - try { - uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); - URL uploadedFilePreviewLink = uploadedFile.getPreviewLink(); - - assertThat(uploadedFilePreviewLink, is(notNullValue())); - assertThat(uploadedFilePreviewLink.toString(), not(is(emptyOrNullString()))); - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void getPreviewLink() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String fileName = "[getPreviewLink] Test File.txt"; + BoxFile uploadedFile = null; + + try { + uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); + URL uploadedFilePreviewLink = uploadedFile.getPreviewLink(); + + assertThat(uploadedFilePreviewLink, is(notNullValue())); + assertThat(uploadedFilePreviewLink.toString(), not(is(emptyOrNullString()))); + } finally { + deleteFile(uploadedFile); } - - @Test - public void getDownloadURL() { - BoxAPIConnection api = jwtApiForServiceAccount(); - String fileName = "[getPreviewLink] Test File.txt"; - BoxFile uploadedFile = null; - - try { - uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); - URL uploadedFileDownloadURL = uploadedFile.getDownloadURL(); - - assertThat(uploadedFileDownloadURL, is(notNullValue())); - assertThat(uploadedFileDownloadURL.toString(), not(is(emptyOrNullString()))); - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void getDownloadURL() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String fileName = "[getPreviewLink] Test File.txt"; + BoxFile uploadedFile = null; + + try { + uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); + URL uploadedFileDownloadURL = uploadedFile.getDownloadURL(); + + assertThat(uploadedFileDownloadURL, is(notNullValue())); + assertThat(uploadedFileDownloadURL.toString(), not(is(emptyOrNullString()))); + } finally { + deleteFile(uploadedFile); } - - @Test - public void setCollectionsSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - String fileName = "[setCollectionsSucceeds] Test File " + Calendar.getInstance().getTimeInMillis() + ".txt"; - BoxFile uploadedFile = null; - try { - uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); - Iterable collections = BoxCollection.getAllCollections(api); - BoxCollection.Info favoritesInfo = collections.iterator().next(); - BoxFile.Info updatedInfo = uploadedFile.setCollections(favoritesInfo.getResource()); - - assertThat(updatedInfo.getCollections(), hasItem(Matchers.hasProperty("ID", - equalTo(favoritesInfo.getID())))); - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void setCollectionsSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String fileName = + "[setCollectionsSucceeds] Test File " + Calendar.getInstance().getTimeInMillis() + ".txt"; + BoxFile uploadedFile = null; + try { + uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); + Iterable collections = BoxCollection.getAllCollections(api); + BoxCollection.Info favoritesInfo = collections.iterator().next(); + BoxFile.Info updatedInfo = uploadedFile.setCollections(favoritesInfo.getResource()); + + assertThat( + updatedInfo.getCollections(), + hasItem(Matchers.hasProperty("ID", equalTo(favoritesInfo.getID())))); + } finally { + deleteFile(uploadedFile); } - - @Test - public void setCollectionsWithInfoSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - String fileName = "[setCollectionsWithInfoSucceeds] Test File.txt"; - BoxFile uploadedFile = null; - try { - uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); - Iterable collections = BoxCollection.getAllCollections(api); - BoxCollection.Info favoritesInfo = collections.iterator().next(); - ArrayList newCollections = new ArrayList<>(); - newCollections.add(favoritesInfo.getResource()); - BoxFile.Info fileInfo = uploadedFile.new Info(); - fileInfo.setCollections(newCollections); - uploadedFile.updateInfo(fileInfo); - BoxFile.Info updatedInfo = uploadedFile.getInfo("collections"); - - assertThat(fileInfo.getCollections(), hasItem(Matchers.hasProperty("ID", - equalTo(favoritesInfo.getID())))); - assertThat(updatedInfo.getCollections(), hasItem(Matchers.hasProperty("ID", - equalTo(favoritesInfo.getID())))); - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void setCollectionsWithInfoSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String fileName = "[setCollectionsWithInfoSucceeds] Test File.txt"; + BoxFile uploadedFile = null; + try { + uploadedFile = uploadFileToUniqueFolder(api, fileName, "Test file"); + Iterable collections = BoxCollection.getAllCollections(api); + BoxCollection.Info favoritesInfo = collections.iterator().next(); + ArrayList newCollections = new ArrayList<>(); + newCollections.add(favoritesInfo.getResource()); + BoxFile.Info fileInfo = uploadedFile.new Info(); + fileInfo.setCollections(newCollections); + uploadedFile.updateInfo(fileInfo); + BoxFile.Info updatedInfo = uploadedFile.getInfo("collections"); + + assertThat( + fileInfo.getCollections(), + hasItem(Matchers.hasProperty("ID", equalTo(favoritesInfo.getID())))); + assertThat( + updatedInfo.getCollections(), + hasItem(Matchers.hasProperty("ID", equalTo(favoritesInfo.getID())))); + } finally { + deleteFile(uploadedFile); } + } - @Test - public void uploadSessionCommitFlowSuccess() throws Exception { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder folder = getUniqueFolder(api); + @Test + public void uploadSessionCommitFlowSuccess() throws Exception { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder folder = getUniqueFolder(api); - BoxFile uploadedFile = null; - File file; - try { - file = FileUtils.generate(randomizeName("LargeFile.txt"), 21_000_000); - long fileSize = file.length(); + BoxFile uploadedFile = null; + File file; + try { + file = FileUtils.generate(randomizeName("LargeFile.txt"), 21_000_000); + long fileSize = file.length(); - //Create the session - BoxFileUploadSession.Info session = - this.createFileUploadSession(folder, BoxFileIT.generateString(), fileSize); + // Create the session + BoxFileUploadSession.Info session = + this.createFileUploadSession(folder, BoxFileIT.generateString(), fileSize); - //Create the parts - MessageDigest fileDigest = this.uploadParts(session, fileSize, file); + // Create the parts + MessageDigest fileDigest = this.uploadParts(session, fileSize, file); - //List the session parts - List parts = this.listUploadSessionParts(session.getResource()); + // List the session parts + List parts = this.listUploadSessionParts(session.getResource()); - byte[] digestBytes = fileDigest.digest(); - String digest = Base64.encode(digestBytes); + byte[] digestBytes = fileDigest.digest(); + String digest = Base64.encode(digestBytes); - //Verify the delete session - uploadedFile = this.commitSession(session.getResource(), digest, parts); - } finally { - deleteFile(uploadedFile); - } + // Verify the delete session + uploadedFile = this.commitSession(session.getResource(), digest, parts); + } finally { + deleteFile(uploadedFile); } - - @Test - public void uploadSessionAbortFlowSuccess() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder folder = getUniqueFolder(api); - BoxFileUploadSession.Info sessionInfo = - this.createFileUploadSession(folder, BoxFileIT.generateString(), 25_000_000); - assertNotNull(sessionInfo.getUploadSessionId()); - assertNotNull(sessionInfo.getSessionExpiresAt()); - - BoxFileUploadSession.Endpoints endpoints = sessionInfo.getSessionEndpoints(); - assertNotNull(endpoints); - assertNotNull(endpoints.getUploadPartEndpoint()); - assertNotNull(endpoints.getStatusEndpoint()); - assertNotNull(endpoints.getListPartsEndpoint()); - assertNotNull(endpoints.getCommitEndpoint()); - assertNotNull(endpoints.getAbortEndpoint()); - - //Verify the status of the session - BoxFileUploadSession session = sessionInfo.getResource(); - this.verifySessionExists(session); - - //Verify the delete session - session.abort(); - this.verifySessionWasAborted(session); + } + + @Test + public void uploadSessionAbortFlowSuccess() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder folder = getUniqueFolder(api); + BoxFileUploadSession.Info sessionInfo = + this.createFileUploadSession(folder, BoxFileIT.generateString(), 25_000_000); + assertNotNull(sessionInfo.getUploadSessionId()); + assertNotNull(sessionInfo.getSessionExpiresAt()); + + BoxFileUploadSession.Endpoints endpoints = sessionInfo.getSessionEndpoints(); + assertNotNull(endpoints); + assertNotNull(endpoints.getUploadPartEndpoint()); + assertNotNull(endpoints.getStatusEndpoint()); + assertNotNull(endpoints.getListPartsEndpoint()); + assertNotNull(endpoints.getCommitEndpoint()); + assertNotNull(endpoints.getAbortEndpoint()); + + // Verify the status of the session + BoxFileUploadSession session = sessionInfo.getResource(); + this.verifySessionExists(session); + + // Verify the delete session + session.abort(); + this.verifySessionWasAborted(session); + } + + @Test + public void uploadLargeFileVersionWithAttributes() throws Exception { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFile uploadedFile = null; + try { + uploadedFile = + uploadFileWithSomeContent(randomizeName("LargeFile.txt"), getUniqueFolder(api)); + + Map fileAttributes = new HashMap<>(); + fileAttributes.put("content_modified_at", "2017-04-08T00:58:08Z"); + + File file = FileUtils.generate(randomizeName("LargeFile.txt"), 21_000_000); + FileInputStream stream = new FileInputStream(file); + BoxFile.Info fileVersion = + uploadedFile.uploadLargeFile(stream, file.length(), fileAttributes); + assertNotNull(fileVersion); + + assertEquals(1491613088000L, fileVersion.getContentModifiedAt().getTime()); + } finally { + deleteFile(uploadedFile); } - - @Test - public void uploadLargeFileVersionWithAttributes() throws Exception { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFile uploadedFile = null; - try { - uploadedFile = uploadFileWithSomeContent(randomizeName("LargeFile.txt"), getUniqueFolder(api)); - - Map fileAttributes = new HashMap<>(); - fileAttributes.put("content_modified_at", "2017-04-08T00:58:08Z"); - - File file = FileUtils.generate(randomizeName("LargeFile.txt"), 21_000_000); - FileInputStream stream = new FileInputStream(file); - BoxFile.Info fileVersion = uploadedFile.uploadLargeFile(stream, file.length(), fileAttributes); - assertNotNull(fileVersion); - - assertEquals(1491613088000L, fileVersion.getContentModifiedAt().getTime()); - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void setsVanityNameOnASharedLink() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFile uploadedFile = null; + try { + uploadedFile = uploadFileToUniqueFolderWithSomeContent(api, "file_to_share.txt"); + + String vanityName = "myCustomName-" + System.currentTimeMillis(); + BoxSharedLinkRequest request = + new BoxSharedLinkRequest() + .permissions(true, true) + .access(OPEN) + .vanityName(vanityName) + .password("my-random-password"); + BoxSharedLink linkWithVanityName = uploadedFile.createSharedLink(request); + + assertThat(linkWithVanityName.getVanityName(), is(vanityName)); + BoxSharedLink sharedLink = uploadedFile.getInfo().getSharedLink(); + assertThat(sharedLink.getVanityName(), is(vanityName)); + assertThat(sharedLink.getPermissions().getCanPreview(), is(true)); + assertThat(sharedLink.getPermissions().getCanDownload(), is(true)); + assertThat(sharedLink.getAccess(), is(OPEN)); + assertThat(sharedLink.getIsPasswordEnabled(), is(true)); + } finally { + deleteFile(uploadedFile); } - - @Test - public void setsVanityNameOnASharedLink() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFile uploadedFile = null; - try { - uploadedFile = uploadFileToUniqueFolderWithSomeContent(api, "file_to_share.txt"); - - String vanityName = "myCustomName-" + System.currentTimeMillis(); - BoxSharedLinkRequest request = new BoxSharedLinkRequest() - .permissions(true, true) - .access(OPEN) - .vanityName(vanityName) - .password("my-random-password"); - BoxSharedLink linkWithVanityName = uploadedFile.createSharedLink(request); - - assertThat(linkWithVanityName.getVanityName(), is(vanityName)); - BoxSharedLink sharedLink = uploadedFile.getInfo().getSharedLink(); - assertThat(sharedLink.getVanityName(), is(vanityName)); - assertThat(sharedLink.getPermissions().getCanPreview(), is(true)); - assertThat(sharedLink.getPermissions().getCanDownload(), is(true)); - assertThat(sharedLink.getAccess(), is(OPEN)); - assertThat(sharedLink.getIsPasswordEnabled(), is(true)); - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void createDefaultSharedLink() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFile uploadedFile = null; + try { + uploadedFile = uploadFileToUniqueFolderWithSomeContent(api, "file_to_share.txt"); + BoxSharedLinkRequest request = new BoxSharedLinkRequest(); + uploadedFile.createSharedLink(request); + BoxSharedLink sharedLink = uploadedFile.getInfo().getSharedLink(); + assertThat(sharedLink, is(notNullValue())); + } finally { + deleteFile(uploadedFile); } - - @Test - public void createDefaultSharedLink() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFile uploadedFile = null; - try { - uploadedFile = uploadFileToUniqueFolderWithSomeContent(api, "file_to_share.txt"); - BoxSharedLinkRequest request = new BoxSharedLinkRequest(); - uploadedFile.createSharedLink(request); - BoxSharedLink sharedLink = uploadedFile.getInfo().getSharedLink(); - assertThat(sharedLink, is(notNullValue())); - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void setsAndRetrievesDispositionAt() throws ParseException { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder testFolder = null; + try { + String policyId = RetentionPolicyUtils.getOneDayRetentionPolicy(api).getID(); + BoxFolder rootFolder = getUniqueFolder(api); + testFolder = + rootFolder.createFolder(randomizeName("[setsAndRetrievesDispositionAt]")).getResource(); + createAssignmentToFolder(api, policyId, testFolder.getID()); + BoxFile uploadedFile = uploadFileWithSomeContent("file_with_disposition.txt", testFolder); + BoxFile.Info info = uploadedFile.getInfo(); + + String dispositionAt = BoxDateFormat.format(LocalDateTime.now().plusDays(7).toInstant(UTC)); + info.setDispositionAt(BoxDateFormat.parse(dispositionAt)); + uploadedFile.updateInfo(info); + + BoxFile.Info updatedInfo = uploadedFile.getInfo("disposition_at"); + assertThat(BoxDateFormat.format(updatedInfo.getDispositionAt()), is(dispositionAt)); + } finally { + deleteFolder(testFolder); } - - @Test - public void setsAndRetrievesDispositionAt() throws ParseException { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder testFolder = null; - try { - String policyId = RetentionPolicyUtils.getOneDayRetentionPolicy(api).getID(); - BoxFolder rootFolder = getUniqueFolder(api); - testFolder = rootFolder.createFolder(randomizeName("[setsAndRetrievesDispositionAt]")).getResource(); - createAssignmentToFolder(api, policyId, testFolder.getID()); - BoxFile uploadedFile = uploadFileWithSomeContent("file_with_disposition.txt", testFolder); - BoxFile.Info info = uploadedFile.getInfo(); - - String dispositionAt = BoxDateFormat.format(LocalDateTime.now().plusDays(7).toInstant(UTC)); - info.setDispositionAt(BoxDateFormat.parse(dispositionAt)); - uploadedFile.updateInfo(info); - - BoxFile.Info updatedInfo = uploadedFile.getInfo("disposition_at"); - assertThat(BoxDateFormat.format(updatedInfo.getDispositionAt()), is(dispositionAt)); - } finally { - deleteFolder(testFolder); - } + } + + @Test + public void uploadAndDownloadEmptyFileSucceeds() throws IOException { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder folder = getUniqueFolder(api); + String fileName = "empty_file"; + URL fileURL = this.getClass().getResource("/sample-files/" + fileName); + String filePath = URLDecoder.decode(fileURL.getFile(), "utf-8"); + long fileSize = new File(filePath).length(); + byte[] fileContent = readAllBytes(filePath); + BoxFile uploadedFile = null; + try { + InputStream uploadStream = Files.newInputStream(Paths.get(filePath)); + ProgressListener mockUploadListener = mock(ProgressListener.class); + BoxFile.Info uploadedFileInfo = + folder.uploadFile(uploadStream, BoxFileIT.generateString(), fileSize, mockUploadListener); + uploadedFile = uploadedFileInfo.getResource(); + + ByteArrayOutputStream downloadStream = new ByteArrayOutputStream(); + uploadedFile.download(downloadStream); + byte[] downloadedFileContent = downloadStream.toByteArray(); + + assertThat(downloadedFileContent, is(equalTo(fileContent))); + assertThat( + folder, hasItem(Matchers.hasProperty("ID", equalTo(uploadedFile.getID())))); + } finally { + deleteFile(uploadedFile); } - - @Test - public void uploadAndDownloadEmptyFileSucceeds() throws IOException { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder folder = getUniqueFolder(api); - String fileName = "empty_file"; - URL fileURL = this.getClass().getResource("/sample-files/" + fileName); - String filePath = URLDecoder.decode(fileURL.getFile(), "utf-8"); - long fileSize = new File(filePath).length(); - byte[] fileContent = readAllBytes(filePath); - BoxFile uploadedFile = null; - try { - InputStream uploadStream = Files.newInputStream(Paths.get(filePath)); - ProgressListener mockUploadListener = mock(ProgressListener.class); - BoxFile.Info uploadedFileInfo = folder.uploadFile( - uploadStream, BoxFileIT.generateString(), fileSize, mockUploadListener - ); - uploadedFile = uploadedFileInfo.getResource(); - - ByteArrayOutputStream downloadStream = new ByteArrayOutputStream(); - uploadedFile.download(downloadStream); - byte[] downloadedFileContent = downloadStream.toByteArray(); - - assertThat(downloadedFileContent, is(equalTo(fileContent))); - assertThat(folder, hasItem(Matchers.hasProperty("ID", equalTo(uploadedFile.getID())))); - } finally { - deleteFile(uploadedFile); - } - - } - - private byte[] readFileContent(String fileName) throws IOException { - URL fileURL = this.getClass().getResource("/sample-files/" + fileName); - String filePath = URLDecoder.decode(fileURL.getFile(), "utf-8"); - return readAllBytes(filePath); + } + + private byte[] readFileContent(String fileName) throws IOException { + URL fileURL = this.getClass().getResource("/sample-files/" + fileName); + String filePath = URLDecoder.decode(fileURL.getFile(), "utf-8"); + return readAllBytes(filePath); + } + + private ByteArrayInputStream getFileContent(String fileContent) { + return new ByteArrayInputStream(fileContent.getBytes(UTF_8)); + } + + private BoxFileUploadSession.Info createFileUploadSession( + BoxFolder folder, String fileName, long fileSize) { + BoxFileUploadSession.Info session = folder.createUploadSession(fileName, fileSize); + assertNotNull(session.getUploadSessionId()); + assertNotNull(session.getSessionExpiresAt()); + + BoxFileUploadSession.Endpoints endpoints = session.getSessionEndpoints(); + assertNotNull(endpoints); + assertNotNull(endpoints.getUploadPartEndpoint()); + assertNotNull(endpoints.getStatusEndpoint()); + assertNotNull(endpoints.getListPartsEndpoint()); + assertNotNull(endpoints.getCommitEndpoint()); + assertNotNull(endpoints.getAbortEndpoint()); + + return session; + } + + private MessageDigest uploadParts(BoxFileUploadSession.Info session, long fileSize, File file) + throws Exception { + + FileInputStream stream = new FileInputStream(file); + MessageDigest fileDigest = MessageDigest.getInstance("SHA1"); + DigestInputStream dis = new DigestInputStream(stream, fileDigest); + + long offset = 0; + long processed = 0; + boolean canBreak = false; + do { + long min = session.getPartSize(); + long diff = fileSize - processed; + if (diff < min) { + min = diff; + canBreak = true; + } + + BoxFileUploadSessionPart part = + session.getResource().uploadPart(dis, offset, (int) min, fileSize); + assertNotNull(part.getSha1()); + assertNotNull(part.getPartId()); + assertEquals(part.getOffset(), offset); + assertTrue(part.getSize() <= session.getPartSize()); + offset = offset + session.getPartSize(); + processed += min; + } while (!canBreak); + + return fileDigest; + } + + private List listUploadSessionParts(BoxFileUploadSession session) { + BoxFileUploadSessionPartList list = session.listParts(0, 100); + return list.getEntries(); + } + + private BoxFile commitSession( + BoxFileUploadSession session, String digest, List parts) { + BoxFile.Info file = session.commit(digest, parts, null, null, null); + assertNotNull(file); + return file.getResource(); + } + + private void verifySessionExists(BoxFileUploadSession session) { + assertNotNull(session); + BoxFileUploadSession.Info sessionInfo = session.getStatus(); + assertNotNull(sessionInfo.getUploadSessionId()); + assertNotNull(sessionInfo.getSessionExpiresAt()); + } + + private void verifySessionWasAborted(BoxFileUploadSession session) { + try { + session.getStatus(); + // If the session is aborted, this line should not be executed. + fail("Upload session is not deleted"); + } catch (BoxAPIException apiEx) { + assertEquals(apiEx.getResponseCode(), 404); } + } - private ByteArrayInputStream getFileContent(String fileContent) { - return new ByteArrayInputStream(fileContent.getBytes(UTF_8)); - } - - - private BoxFileUploadSession.Info createFileUploadSession(BoxFolder folder, String fileName, long fileSize) { - BoxFileUploadSession.Info session = folder.createUploadSession(fileName, fileSize); - assertNotNull(session.getUploadSessionId()); - assertNotNull(session.getSessionExpiresAt()); - - BoxFileUploadSession.Endpoints endpoints = session.getSessionEndpoints(); - assertNotNull(endpoints); - assertNotNull(endpoints.getUploadPartEndpoint()); - assertNotNull(endpoints.getStatusEndpoint()); - assertNotNull(endpoints.getListPartsEndpoint()); - assertNotNull(endpoints.getCommitEndpoint()); - assertNotNull(endpoints.getAbortEndpoint()); - - return session; - } - - private MessageDigest uploadParts(BoxFileUploadSession.Info session, long fileSize, File file) - throws Exception { - - FileInputStream stream = new FileInputStream(file); - MessageDigest fileDigest = MessageDigest.getInstance("SHA1"); - DigestInputStream dis = new DigestInputStream(stream, fileDigest); - - long offset = 0; - long processed = 0; - boolean canBreak = false; - do { - long min = session.getPartSize(); - long diff = fileSize - processed; - if (diff < min) { - min = diff; - canBreak = true; - } - - BoxFileUploadSessionPart part = session.getResource().uploadPart(dis, offset, (int) min, fileSize); - assertNotNull(part.getSha1()); - assertNotNull(part.getPartId()); - assertEquals(part.getOffset(), offset); - assertTrue(part.getSize() <= session.getPartSize()); - offset = offset + session.getPartSize(); - processed += min; - } while (!canBreak); - - return fileDigest; - } - - private List listUploadSessionParts(BoxFileUploadSession session) { - BoxFileUploadSessionPartList list = session.listParts(0, 100); - return list.getEntries(); - } - - private BoxFile commitSession(BoxFileUploadSession session, String digest, List parts) { - BoxFile.Info file = session.commit(digest, parts, null, null, null); - assertNotNull(file); - return file.getResource(); - } - - private void verifySessionExists(BoxFileUploadSession session) { - assertNotNull(session); - BoxFileUploadSession.Info sessionInfo = session.getStatus(); - assertNotNull(sessionInfo.getUploadSessionId()); - assertNotNull(sessionInfo.getSessionExpiresAt()); - } - - private void verifySessionWasAborted(BoxFileUploadSession session) { - try { - session.getStatus(); - //If the session is aborted, this line should not be executed. - fail("Upload session is not deleted"); - } catch (BoxAPIException apiEx) { - assertEquals(apiEx.getResponseCode(), 404); - } - } - - private static String generateString() { - return randomUUID().toString(); - } + private static String generateString() { + return randomUUID().toString(); + } } diff --git a/src/intTest/java/com/box/sdk/BoxFolderIT.java b/src/intTest/java/com/box/sdk/BoxFolderIT.java index 130a870b7..328252e85 100644 --- a/src/intTest/java/com/box/sdk/BoxFolderIT.java +++ b/src/intTest/java/com/box/sdk/BoxFolderIT.java @@ -64,911 +64,981 @@ import org.junit.BeforeClass; import org.junit.Test; -/** - * {@link BoxFolder} related integration tests. - */ +/** {@link BoxFolder} related integration tests. */ public class BoxFolderIT { - private static final String GMAIL_COM_DOMAIN = "gmail.com"; - private static final String YAHOO_COM_DOMAIN = "yahoo.com"; - - @BeforeClass - public static void setup() { - setupUniqeFolder(); - } - - @AfterClass - public static void tearDown() { - removeUniqueFolder(); - } - - @Before - public void clearAllowedDomains() { - removeAllowedDomains(GMAIL_COM_DOMAIN, YAHOO_COM_DOMAIN); - } - - @Test - public void creatingAndDeletingFolderSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - BoxFolder childFolder = - rootFolder.createFolder("[creatingAndDeletingFolderSucceeds] Ĥȅľľő Ƒŕőďő").getResource(); - - assertThat(rootFolder, - hasItem(Matchers.hasProperty("ID", equalTo(childFolder.getID())))); - - childFolder.delete(false); - assertThat(rootFolder, - not(hasItem(Matchers.hasProperty("ID", equalTo(childFolder.getID()))))); + private static final String GMAIL_COM_DOMAIN = "gmail.com"; + private static final String YAHOO_COM_DOMAIN = "yahoo.com"; + + @BeforeClass + public static void setup() { + setupUniqeFolder(); + } + + @AfterClass + public static void tearDown() { + removeUniqueFolder(); + } + + @Before + public void clearAllowedDomains() { + removeAllowedDomains(GMAIL_COM_DOMAIN, YAHOO_COM_DOMAIN); + } + + @Test + public void creatingAndDeletingFolderSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + BoxFolder childFolder = + rootFolder.createFolder("[creatingAndDeletingFolderSucceeds] Ĥȅľľő Ƒŕőďő").getResource(); + + assertThat( + rootFolder, + hasItem(Matchers.hasProperty("ID", equalTo(childFolder.getID())))); + + childFolder.delete(false); + assertThat( + rootFolder, + not(hasItem(Matchers.hasProperty("ID", equalTo(childFolder.getID()))))); + } + + @Test + public void getFolderInfoReturnsCorrectInfo() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxUser currentUser = BoxUser.getCurrentUser(api); + final String expectedName = "[getFolderInfoReturnsCorrectInfo] Child Folder"; + final String expectedCreatedByID = currentUser.getID(); + BoxFolder childFolder = null; + + BoxFolder rootFolder = getUniqueFolder(api); + final String expectedParentFolderID = rootFolder.getID(); + final String expectedParentFolderName = rootFolder.getInfo().getName(); + + try { + childFolder = rootFolder.createFolder(expectedName).getResource(); + BoxFolder.Info info = childFolder.getInfo(BoxItem.ALL_FIELDS); + + String actualName = info.getName(); + String actualCreatedByID = info.getCreatedBy().getID(); + String actualParentFolderID = info.getParent().getID(); + String actualParentFolderName = info.getParent().getName(); + List actualPathCollection = info.getPathCollection(); + + assertThat(expectedName, equalTo(actualName)); + assertThat(expectedCreatedByID, equalTo(actualCreatedByID)); + assertThat(expectedParentFolderID, equalTo(actualParentFolderID)); + assertThat(expectedParentFolderName, equalTo(actualParentFolderName)); + assertThat( + actualPathCollection, hasItem(Matchers.hasProperty("ID", equalTo("0")))); + assertThat(info.getPermissions(), is(equalTo(EnumSet.allOf(BoxFolder.Permission.class)))); + assertThat(info.getItemStatus(), is(equalTo("active"))); + } finally { + this.deleteFolder(childFolder); } - - @Test - public void getFolderInfoReturnsCorrectInfo() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxUser currentUser = BoxUser.getCurrentUser(api); - final String expectedName = "[getFolderInfoReturnsCorrectInfo] Child Folder"; - final String expectedCreatedByID = currentUser.getID(); - BoxFolder childFolder = null; - - BoxFolder rootFolder = getUniqueFolder(api); - final String expectedParentFolderID = rootFolder.getID(); - final String expectedParentFolderName = rootFolder.getInfo().getName(); - - try { - childFolder = rootFolder.createFolder(expectedName).getResource(); - BoxFolder.Info info = childFolder.getInfo(BoxItem.ALL_FIELDS); - - String actualName = info.getName(); - String actualCreatedByID = info.getCreatedBy().getID(); - String actualParentFolderID = info.getParent().getID(); - String actualParentFolderName = info.getParent().getName(); - List actualPathCollection = info.getPathCollection(); - - assertThat(expectedName, equalTo(actualName)); - assertThat(expectedCreatedByID, equalTo(actualCreatedByID)); - assertThat(expectedParentFolderID, equalTo(actualParentFolderID)); - assertThat(expectedParentFolderName, equalTo(actualParentFolderName)); - assertThat(actualPathCollection, hasItem(Matchers.hasProperty("ID", equalTo("0")))); - assertThat(info.getPermissions(), is(equalTo(EnumSet.allOf(BoxFolder.Permission.class)))); - assertThat(info.getItemStatus(), is(equalTo("active"))); - } finally { - this.deleteFolder(childFolder); + } + + @Test + public void getInfoWithOnlyTheNameField() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + final String expectedName = UniqueTestFolder.getUniqueFolderName(); + + BoxFolder.Info rootFolderInfo = rootFolder.getInfo("name"); + + assertThat(expectedName, equalTo(rootFolderInfo.getName())); + assertThat(rootFolderInfo.getDescription(), is(nullValue())); + assertThat(rootFolderInfo.getSize(), is(0L)); + } + + @Test + public void iterateWithOnlyTheNameField() { + final String expectedName = "[iterateWithOnlyTheNameField] Child Folder"; + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + BoxFolder childFolder = null; + + try { + childFolder = rootFolder.createFolder(expectedName).getResource(); + + Iterable children = rootFolder.getChildren("name"); + boolean found = false; + for (BoxItem.Info childInfo : children) { + if (childInfo.getID().equals(childFolder.getID())) { + found = true; + assertThat(childInfo.getName(), is(equalTo(expectedName))); + assertThat(childInfo.getSize(), is(equalTo(0L))); + assertThat(childInfo.getDescription(), is(nullValue())); } + } + assertThat(found, is(true)); + } finally { + this.deleteFolder(childFolder); } - - @Test - public void getInfoWithOnlyTheNameField() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - final String expectedName = UniqueTestFolder.getUniqueFolderName(); - - BoxFolder.Info rootFolderInfo = rootFolder.getInfo("name"); - - assertThat(expectedName, equalTo(rootFolderInfo.getName())); - assertThat(rootFolderInfo.getDescription(), is(nullValue())); - assertThat(rootFolderInfo.getSize(), is(0L)); + } + + @Test + public void uploadFileSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + BoxFile uploadedFile = null; + + try { + uploadedFile = uploadFileToUniqueFolderWithSomeContent(api, randomizeName("Test File")); + + assertThat( + rootFolder, + hasItem(Matchers.hasProperty("ID", equalTo(uploadedFile.getID())))); + } finally { + this.deleteFile(uploadedFile); + assertThat( + rootFolder, + not(hasItem(Matchers.hasProperty("ID", equalTo(uploadedFile.getID()))))); } - - @Test - public void iterateWithOnlyTheNameField() { - final String expectedName = "[iterateWithOnlyTheNameField] Child Folder"; - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - BoxFolder childFolder = null; - - try { - childFolder = rootFolder.createFolder(expectedName).getResource(); - - Iterable children = rootFolder.getChildren("name"); - boolean found = false; - for (BoxItem.Info childInfo : children) { - if (childInfo.getID().equals(childFolder.getID())) { - found = true; - assertThat(childInfo.getName(), is(equalTo(expectedName))); - assertThat(childInfo.getSize(), is(equalTo(0L))); - assertThat(childInfo.getDescription(), is(nullValue())); - } - } - assertThat(found, is(true)); - } finally { - this.deleteFolder(childFolder); - } + } + + @Test + public void uploadFileUploadFileCallbackSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + BoxFile uploadedFile = null; + final AtomicReference callbackWasCalled = new AtomicReference<>(false); + + try { + + final String fileContent = randomizeName("Test file"); + uploadedFile = + rootFolder + .uploadFile( + outputStream -> { + outputStream.write(fileContent.getBytes()); + callbackWasCalled.set(true); + }, + "Test File.txt") + .getResource(); + + assertThat( + rootFolder, + hasItem(Matchers.hasProperty("ID", equalTo(uploadedFile.getID())))); + assertTrue("Callback was not called", callbackWasCalled.get()); + } finally { + this.deleteFile(uploadedFile); } - - @Test - public void uploadFileSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - BoxFile uploadedFile = null; - - try { - uploadedFile = uploadFileToUniqueFolderWithSomeContent(api, randomizeName("Test File")); - - assertThat(rootFolder, hasItem(Matchers.hasProperty("ID", equalTo(uploadedFile.getID())))); - } finally { - this.deleteFile(uploadedFile); - assertThat(rootFolder, - not(hasItem(Matchers.hasProperty("ID", equalTo(uploadedFile.getID()))))); - } + } + + @Test + public void uploadFileWithCreatedAndModifiedDatesSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); + dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + BoxFile uploadedFile = null; + try { + Date created = new Date(1415318114); + Date modified = new Date(1315318114); + final String fileContent = "Test file"; + InputStream stream = new ByteArrayInputStream(fileContent.getBytes(StandardCharsets.UTF_8)); + FileUploadParams params = + new FileUploadParams() + .setName("[uploadFileWithCreatedAndModifiedDatesSucceeds] Test File.txt") + .setContent(stream) + .setModified(modified) + .setCreated(created); + BoxFile.Info info = rootFolder.uploadFile(params); + uploadedFile = info.getResource(); + + assertThat( + dateFormat.format(info.getContentCreatedAt()), is(equalTo(dateFormat.format(created)))); + assertThat( + dateFormat.format(info.getContentModifiedAt()), is(equalTo(dateFormat.format(modified)))); + assertThat( + rootFolder, + hasItem(Matchers.hasProperty("ID", equalTo(uploadedFile.getID())))); + } finally { + this.deleteFile(uploadedFile); } - - @Test - public void uploadFileUploadFileCallbackSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - BoxFile uploadedFile = null; - final AtomicReference callbackWasCalled = new AtomicReference<>(false); - - try { - - final String fileContent = randomizeName("Test file"); - uploadedFile = rootFolder.uploadFile(outputStream -> { - outputStream.write(fileContent.getBytes()); - callbackWasCalled.set(true); - }, "Test File.txt").getResource(); - - assertThat(rootFolder, hasItem(Matchers.hasProperty("ID", equalTo(uploadedFile.getID())))); - assertTrue("Callback was not called", callbackWasCalled.get()); - } finally { - this.deleteFile(uploadedFile); - } + } + + @Test + public void updateFolderInfoSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + final String originalName = "[updateFolderInfoSucceeds] Child Folder"; + final String updatedName = "[updateFolderInfoSucceeds] Updated Child Folder"; + BoxFolder childFolder = null; + + try { + BoxFolder.Info info = rootFolder.createFolder(originalName); + childFolder = info.getResource(); + info.setName(updatedName); + childFolder.updateInfo(info); + assertThat(info.getName(), equalTo(updatedName)); + } finally { + this.deleteFolder(childFolder); + assertThat( + rootFolder, + not(hasItem(Matchers.hasProperty("ID", equalTo(childFolder.getID()))))); } - - - @Test - public void uploadFileWithCreatedAndModifiedDatesSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); - dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - BoxFile uploadedFile = null; - try { - Date created = new Date(1415318114); - Date modified = new Date(1315318114); - final String fileContent = "Test file"; - InputStream stream = new ByteArrayInputStream(fileContent.getBytes(StandardCharsets.UTF_8)); - FileUploadParams params = new FileUploadParams() - .setName("[uploadFileWithCreatedAndModifiedDatesSucceeds] Test File.txt").setContent(stream) - .setModified(modified).setCreated(created); - BoxFile.Info info = rootFolder.uploadFile(params); - uploadedFile = info.getResource(); - - assertThat(dateFormat.format(info.getContentCreatedAt()), is(equalTo(dateFormat.format(created)))); - assertThat(dateFormat.format(info.getContentModifiedAt()), is(equalTo(dateFormat.format(modified)))); - assertThat(rootFolder, hasItem(Matchers.hasProperty("ID", equalTo(uploadedFile.getID())))); - } finally { - this.deleteFile(uploadedFile); - } + } + + @Test + public void updateCanNonOwnersViewCollaboratorsSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + final String name = "[updateCanNonOwnersViewCollaboratorsSucceeds] Child Folder"; + BoxFolder childFolder = null; + + try { + BoxFolder.Info info = rootFolder.createFolder(name); + childFolder = info.getResource(); + boolean getCanNonOwnersViewCollaborators = + childFolder + .getInfo("can_non_owners_view_collaborators") + .getCanNonOwnersViewCollaborators(); + // need to set both + info.setCanNonOwnersViewCollaborators(!getCanNonOwnersViewCollaborators); + info.setCanNonOwnersInvite(!getCanNonOwnersViewCollaborators); + childFolder.updateInfo(info); + + assertThat( + info.getCanNonOwnersViewCollaborators(), equalTo(!getCanNonOwnersViewCollaborators)); + assertThat(info.getCanNonOwnersInvite(), equalTo(!getCanNonOwnersViewCollaborators)); + } finally { + this.deleteFolder(childFolder); + assertThat( + rootFolder, + not(hasItem(Matchers.hasProperty("ID", equalTo(childFolder.getID()))))); } - - @Test - public void updateFolderInfoSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - final String originalName = "[updateFolderInfoSucceeds] Child Folder"; - final String updatedName = "[updateFolderInfoSucceeds] Updated Child Folder"; - BoxFolder childFolder = null; - - try { - BoxFolder.Info info = rootFolder.createFolder(originalName); - childFolder = info.getResource(); - info.setName(updatedName); - childFolder.updateInfo(info); - assertThat(info.getName(), equalTo(updatedName)); - } finally { - this.deleteFolder(childFolder); - assertThat(rootFolder, - not(hasItem(Matchers.hasProperty("ID", equalTo(childFolder.getID()))))); - } + } + + @Test + public void copyFolderToSameDestinationWithNewNameSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + final String originalName = "[copyFolderToSameDestinationWithNewNameSucceeds] Child Folder"; + final String newName = "[copyFolderToSameDestinationWithNewNameSucceeds] New Child Folder"; + BoxFolder originalFolder = null; + BoxFolder copiedFolder = null; + try { + originalFolder = rootFolder.createFolder(originalName).getResource(); + BoxFolder.Info copiedFolderInfo = originalFolder.copy(rootFolder, newName); + copiedFolder = copiedFolderInfo.getResource(); + + assertThat(copiedFolderInfo.getName(), is(equalTo(newName))); + assertThat( + rootFolder, + hasItem(Matchers.hasProperty("ID", equalTo(originalFolder.getID())))); + assertThat( + rootFolder, + hasItem(Matchers.hasProperty("ID", equalTo(copiedFolder.getID())))); + } finally { + this.deleteFolder(originalFolder); + this.deleteFolder(copiedFolder); + assertThat( + rootFolder, + not(hasItem(Matchers.hasProperty("ID", equalTo(originalFolder.getID()))))); + assertThat( + rootFolder, + not(hasItem(Matchers.hasProperty("ID", equalTo(copiedFolder.getID()))))); } - - @Test - public void updateCanNonOwnersViewCollaboratorsSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - final String name = "[updateCanNonOwnersViewCollaboratorsSucceeds] Child Folder"; - BoxFolder childFolder = null; - - try { - BoxFolder.Info info = rootFolder.createFolder(name); - childFolder = info.getResource(); - boolean getCanNonOwnersViewCollaborators = childFolder.getInfo("can_non_owners_view_collaborators") - .getCanNonOwnersViewCollaborators(); - // need to set both - info.setCanNonOwnersViewCollaborators(!getCanNonOwnersViewCollaborators); - info.setCanNonOwnersInvite(!getCanNonOwnersViewCollaborators); - childFolder.updateInfo(info); - - assertThat(info.getCanNonOwnersViewCollaborators(), equalTo(!getCanNonOwnersViewCollaborators)); - assertThat(info.getCanNonOwnersInvite(), equalTo(!getCanNonOwnersViewCollaborators)); - } finally { - this.deleteFolder(childFolder); - assertThat(rootFolder, - not(hasItem(Matchers.hasProperty("ID", equalTo(childFolder.getID()))))); - } - } - - @Test - public void copyFolderToSameDestinationWithNewNameSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - final String originalName = "[copyFolderToSameDestinationWithNewNameSucceeds] Child Folder"; - final String newName = "[copyFolderToSameDestinationWithNewNameSucceeds] New Child Folder"; - BoxFolder originalFolder = null; - BoxFolder copiedFolder = null; - try { - originalFolder = rootFolder.createFolder(originalName).getResource(); - BoxFolder.Info copiedFolderInfo = originalFolder.copy(rootFolder, newName); - copiedFolder = copiedFolderInfo.getResource(); - - assertThat(copiedFolderInfo.getName(), is(equalTo(newName))); - assertThat(rootFolder, hasItem(Matchers.hasProperty("ID", equalTo(originalFolder.getID())))); - assertThat(rootFolder, hasItem(Matchers.hasProperty("ID", equalTo(copiedFolder.getID())))); - } finally { - this.deleteFolder(originalFolder); - this.deleteFolder(copiedFolder); - assertThat(rootFolder, - not(hasItem(Matchers.hasProperty("ID", equalTo(originalFolder.getID()))))); - assertThat(rootFolder, - not(hasItem(Matchers.hasProperty("ID", equalTo(copiedFolder.getID()))))); - } - } - - @Test - public void moveFolderSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - final String child1Name = "[moveFolderSucceeds] Child Folder"; - final String child2Name = "[moveFolderSucceeds] Child Folder 2"; - BoxFolder childFolder1 = null; - - try { - childFolder1 = rootFolder.createFolder(child1Name).getResource(); - BoxFolder childFolder2 = rootFolder.createFolder(child2Name).getResource(); - - assertThat(rootFolder, hasItem(Matchers.hasProperty("ID", equalTo(childFolder1.getID())))); - assertThat(rootFolder, hasItem(Matchers.hasProperty("ID", equalTo(childFolder2.getID())))); - - childFolder2.move(childFolder1); - - assertThat(childFolder1, - hasItem(Matchers.hasProperty("ID", equalTo(childFolder2.getID())))); - assertThat(rootFolder, - not(hasItem(Matchers.hasProperty("ID", equalTo(childFolder2.getID()))))); - } finally { - this.deleteFolder(childFolder1); - assertThat(rootFolder, - not(hasItem(Matchers.hasProperty("ID", equalTo(childFolder1.getID()))))); - } + } + + @Test + public void moveFolderSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + final String child1Name = "[moveFolderSucceeds] Child Folder"; + final String child2Name = "[moveFolderSucceeds] Child Folder 2"; + BoxFolder childFolder1 = null; + + try { + childFolder1 = rootFolder.createFolder(child1Name).getResource(); + BoxFolder childFolder2 = rootFolder.createFolder(child2Name).getResource(); + + assertThat( + rootFolder, + hasItem(Matchers.hasProperty("ID", equalTo(childFolder1.getID())))); + assertThat( + rootFolder, + hasItem(Matchers.hasProperty("ID", equalTo(childFolder2.getID())))); + + childFolder2.move(childFolder1); + + assertThat( + childFolder1, + hasItem(Matchers.hasProperty("ID", equalTo(childFolder2.getID())))); + assertThat( + rootFolder, + not(hasItem(Matchers.hasProperty("ID", equalTo(childFolder2.getID()))))); + } finally { + this.deleteFolder(childFolder1); + assertThat( + rootFolder, + not(hasItem(Matchers.hasProperty("ID", equalTo(childFolder1.getID()))))); } + } - @Test - public void renameFolderSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - final String originalName = "[renameFolderSucceeds] Original Name"; - final String newName = "[renameFolderSucceeds] New Name"; - BoxFolder childFolder = null; + @Test + public void renameFolderSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + final String originalName = "[renameFolderSucceeds] Original Name"; + final String newName = "[renameFolderSucceeds] New Name"; + BoxFolder childFolder = null; - try { - childFolder = rootFolder.createFolder(originalName).getResource(); + try { + childFolder = rootFolder.createFolder(originalName).getResource(); - childFolder.rename(newName); + childFolder.rename(newName); - BoxFolder.Info childFolderInfo = childFolder.getInfo(); - assertThat(childFolderInfo.getName(), is(equalTo(newName))); - } finally { - this.deleteFolder(childFolder); - } + BoxFolder.Info childFolderInfo = childFolder.getInfo(); + assertThat(childFolderInfo.getName(), is(equalTo(newName))); + } finally { + this.deleteFolder(childFolder); } - - @Test - public void addCollaboratorSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - String folderName = "[addCollaborationToFolderSucceeds] Test Folder"; - String collaboratorLogin = TestConfig.getCollaborator(); - Role collaboratorRole = Role.CO_OWNER; - BoxFolder folder = null; - - try { - folder = rootFolder.createFolder(folderName).getResource(); - - BoxCollaboration.Info collabInfo = folder.collaborate(collaboratorLogin, collaboratorRole); - BoxUser.Info accessibleBy = (BoxUser.Info) collabInfo.getAccessibleBy(); - - assertThat(accessibleBy.getLogin(), is(equalTo(collaboratorLogin))); - assertThat(collabInfo.getRole(), is(equalTo(collaboratorRole))); - } finally { - this.deleteFolder(folder); - } + } + + @Test + public void addCollaboratorSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + String folderName = "[addCollaborationToFolderSucceeds] Test Folder"; + String collaboratorLogin = TestConfig.getCollaborator(); + Role collaboratorRole = Role.CO_OWNER; + BoxFolder folder = null; + + try { + folder = rootFolder.createFolder(folderName).getResource(); + + BoxCollaboration.Info collabInfo = folder.collaborate(collaboratorLogin, collaboratorRole); + BoxUser.Info accessibleBy = (BoxUser.Info) collabInfo.getAccessibleBy(); + + assertThat(accessibleBy.getLogin(), is(equalTo(collaboratorLogin))); + assertThat(collabInfo.getRole(), is(equalTo(collaboratorRole))); + } finally { + this.deleteFolder(folder); } - - @Test - public void addCollaborationsWithAttributesSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - String folderName = "[getCollaborationsSucceeds] Test Folder"; - BoxFolder folder = null; - BoxCollaborationAllowlist allowGmail = null; - BoxCollaborationAllowlist allowYahoo = null; - - try { - folder = rootFolder.createFolder(folderName).getResource(); - allowGmail = BoxCollaborationAllowlist.create(api, GMAIL_COM_DOMAIN, INBOUND).getResource(); - allowYahoo = BoxCollaborationAllowlist.create(api, YAHOO_COM_DOMAIN, INBOUND).getResource(); - //fails because of canViewPath = true - https://jira.inside-box.net/browse/CONTENT-1431 - BoxCollaboration.Info collabInfo = - folder.collaborate("karthik2001123@yahoo.com", Role.CO_OWNER, false, false); - String collabID = collabInfo.getID(); - - //fails because of canViewPath = true - https://jira.inside-box.net/browse/CONTENT-1431 - BoxCollaboration.Info collabInfo2 = - folder.collaborate("davidsmaynard@gmail.com", Role.VIEWER, false, false); - - Collection collaborations = folder.getCollaborations(); - - assertThat(collaborations, hasSize(2)); - assertThat(collaborations, - hasItem(Matchers.hasProperty("ID", equalTo(collabID)))); - assertThat(collaborations, - hasItem(Matchers.hasProperty("ID", equalTo(collabInfo2.getID())))); - } finally { - this.deleteFolder(folder); - this.deleteCollaborationAllowList(allowGmail); - this.deleteCollaborationAllowList(allowYahoo); - } + } + + @Test + public void addCollaborationsWithAttributesSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + String folderName = "[getCollaborationsSucceeds] Test Folder"; + BoxFolder folder = null; + BoxCollaborationAllowlist allowGmail = null; + BoxCollaborationAllowlist allowYahoo = null; + + try { + folder = rootFolder.createFolder(folderName).getResource(); + allowGmail = BoxCollaborationAllowlist.create(api, GMAIL_COM_DOMAIN, INBOUND).getResource(); + allowYahoo = BoxCollaborationAllowlist.create(api, YAHOO_COM_DOMAIN, INBOUND).getResource(); + // fails because of canViewPath = true - https://jira.inside-box.net/browse/CONTENT-1431 + BoxCollaboration.Info collabInfo = + folder.collaborate("karthik2001123@yahoo.com", Role.CO_OWNER, false, false); + String collabID = collabInfo.getID(); + + // fails because of canViewPath = true - https://jira.inside-box.net/browse/CONTENT-1431 + BoxCollaboration.Info collabInfo2 = + folder.collaborate("davidsmaynard@gmail.com", Role.VIEWER, false, false); + + Collection collaborations = folder.getCollaborations(); + + assertThat(collaborations, hasSize(2)); + assertThat( + collaborations, + hasItem(Matchers.hasProperty("ID", equalTo(collabID)))); + assertThat( + collaborations, + hasItem(Matchers.hasProperty("ID", equalTo(collabInfo2.getID())))); + } finally { + this.deleteFolder(folder); + this.deleteCollaborationAllowList(allowGmail); + this.deleteCollaborationAllowList(allowYahoo); } - - @Test - public void getCollaborationsHasCorrectCollaborations() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - String folderName = "[getCollaborationsHasCorrectCollaborations] Test Folder"; - BoxFolder folder = null; - BoxCollaborationAllowlist allowGmail = null; - - try { - folder = rootFolder.createFolder(folderName).getResource(); - allowGmail = BoxCollaborationAllowlist.create(api, GMAIL_COM_DOMAIN, INBOUND).getResource(); - BoxCollaboration.Info collabInfo = folder.collaborate(TestConfig.getCollaborator(), Role.CO_OWNER); - String collabID = collabInfo.getID(); - - Collection collaborations = folder.getCollaborations(); - - assertThat(collaborations, hasSize(1)); - assertThat(collaborations, - hasItem(Matchers.hasProperty("ID", equalTo(collabID)))); - } finally { - this.deleteFolder(folder); - this.deleteCollaborationAllowList(allowGmail); - } + } + + @Test + public void getCollaborationsHasCorrectCollaborations() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + String folderName = "[getCollaborationsHasCorrectCollaborations] Test Folder"; + BoxFolder folder = null; + BoxCollaborationAllowlist allowGmail = null; + + try { + folder = rootFolder.createFolder(folderName).getResource(); + allowGmail = BoxCollaborationAllowlist.create(api, GMAIL_COM_DOMAIN, INBOUND).getResource(); + BoxCollaboration.Info collabInfo = + folder.collaborate(TestConfig.getCollaborator(), Role.CO_OWNER); + String collabID = collabInfo.getID(); + + Collection collaborations = folder.getCollaborations(); + + assertThat(collaborations, hasSize(1)); + assertThat( + collaborations, + hasItem(Matchers.hasProperty("ID", equalTo(collabID)))); + } finally { + this.deleteFolder(folder); + this.deleteCollaborationAllowList(allowGmail); } - - @Test - public void setFolderUploadEmailSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - String folderName = "[setFolderUploadEmailSucceeds] Test Folder"; - BoxFolder folder = null; - - try { - BoxUploadEmail uploadEmail = new BoxUploadEmail(); - uploadEmail.setAccess(BoxUploadEmail.Access.OPEN); - - folder = rootFolder.createFolder(folderName).getResource(); - BoxFolder.Info info = folder.new Info(); - info.setUploadEmail(uploadEmail); - folder.updateInfo(info); - - BoxUploadEmail updatedEmailInfo = info.getUploadEmail(); - assertThat(updatedEmailInfo.getEmail(), not(is(emptyOrNullString()))); - assertThat(updatedEmailInfo.getAccess(), is(equalTo(BoxUploadEmail.Access.OPEN))); - - info.setUploadEmail(null); - uploadEmail = info.getUploadEmail(); - assertThat(uploadEmail, is(nullValue())); - } finally { - this.deleteFolder(folder); - } + } + + @Test + public void setFolderUploadEmailSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + String folderName = "[setFolderUploadEmailSucceeds] Test Folder"; + BoxFolder folder = null; + + try { + BoxUploadEmail uploadEmail = new BoxUploadEmail(); + uploadEmail.setAccess(BoxUploadEmail.Access.OPEN); + + folder = rootFolder.createFolder(folderName).getResource(); + BoxFolder.Info info = folder.new Info(); + info.setUploadEmail(uploadEmail); + folder.updateInfo(info); + + BoxUploadEmail updatedEmailInfo = info.getUploadEmail(); + assertThat(updatedEmailInfo.getEmail(), not(is(emptyOrNullString()))); + assertThat(updatedEmailInfo.getAccess(), is(equalTo(BoxUploadEmail.Access.OPEN))); + + info.setUploadEmail(null); + uploadEmail = info.getUploadEmail(); + assertThat(uploadEmail, is(nullValue())); + } finally { + this.deleteFolder(folder); } - - @Test - public void getSharedItemAndItsChildrenSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - String folderName = "[getSharedItemAndItsChildrenSucceeds] Test Folder"; - String childFolderName = "[getSharedItemAndItsChildrenSucceeds] Child Folder"; - BoxFolder folder = null; - - try { - folder = rootFolder.createFolder(folderName).getResource(); - BoxFolder childFolder = folder.createFolder(childFolderName).getResource(); - assertThat( - folder.getInfo("is_accessible_via_shared_link").getIsAccessibleViaSharedLink(), - is(false) - ); - BoxSharedLink sharedLink = folder.createSharedLink(new BoxSharedLinkRequest().access(OPEN)); - - BoxFolder.Info sharedItem = (BoxFolder.Info) BoxItem.getSharedItem(api, sharedLink.getURL()); - - assertThat(sharedItem.getID(), is(equalTo(folder.getID()))); - assertThat(sharedItem.getResource(), - hasItem(Matchers.hasProperty("ID", equalTo(childFolder.getID())))); - assertThat( - folder.getInfo("is_accessible_via_shared_link").getIsAccessibleViaSharedLink(), - is(true) - ); - } finally { - this.deleteFolder(folder); - } + } + + @Test + public void getSharedItemAndItsChildrenSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + String folderName = "[getSharedItemAndItsChildrenSucceeds] Test Folder"; + String childFolderName = "[getSharedItemAndItsChildrenSucceeds] Child Folder"; + BoxFolder folder = null; + + try { + folder = rootFolder.createFolder(folderName).getResource(); + BoxFolder childFolder = folder.createFolder(childFolderName).getResource(); + assertThat( + folder.getInfo("is_accessible_via_shared_link").getIsAccessibleViaSharedLink(), + is(false)); + BoxSharedLink sharedLink = folder.createSharedLink(new BoxSharedLinkRequest().access(OPEN)); + + BoxFolder.Info sharedItem = (BoxFolder.Info) BoxItem.getSharedItem(api, sharedLink.getURL()); + + assertThat(sharedItem.getID(), is(equalTo(folder.getID()))); + assertThat( + sharedItem.getResource(), + hasItem(Matchers.hasProperty("ID", equalTo(childFolder.getID())))); + assertThat( + folder.getInfo("is_accessible_via_shared_link").getIsAccessibleViaSharedLink(), is(true)); + } finally { + this.deleteFolder(folder); } + } + + @Test + public void createWebLinkSucceeds() throws MalformedURLException { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + + BoxWebLink createdWebLink = + rootFolder + .createWebLink( + "[createWebLinkSucceeds] Test Web Link", + new URL("https://api.box.com"), + "[createWebLinkSucceeds] Test Web Link") + .getResource(); - @Test - public void createWebLinkSucceeds() throws MalformedURLException { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - - BoxWebLink createdWebLink = rootFolder.createWebLink("[createWebLinkSucceeds] Test Web Link", - new URL("https://api.box.com"), "[createWebLinkSucceeds] Test Web Link").getResource(); + assertThat( + rootFolder, + hasItem(Matchers.hasProperty("ID", equalTo(createdWebLink.getID())))); - assertThat(rootFolder, hasItem(Matchers.hasProperty("ID", equalTo(createdWebLink.getID())))); + createdWebLink.delete(); + assertThat( + rootFolder, + not(hasItem(Matchers.hasProperty("ID", equalTo(createdWebLink.getID()))))); + } - createdWebLink.delete(); - assertThat(rootFolder, not(hasItem(Matchers.hasProperty("ID", equalTo(createdWebLink.getID()))))); - } + @Test + public void createWebLinkWithNoNameSucceeds() throws MalformedURLException { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); - @Test - public void createWebLinkWithNoNameSucceeds() throws MalformedURLException { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - - BoxWebLink createdWebLink = rootFolder + BoxWebLink createdWebLink = + rootFolder .createWebLink(new URL("https://api.box.com"), "[createWebLinkSucceeds] Test Web Link") .getResource(); - assertThat(rootFolder, hasItem(Matchers.hasProperty("ID", equalTo(createdWebLink.getID())))); + assertThat( + rootFolder, + hasItem(Matchers.hasProperty("ID", equalTo(createdWebLink.getID())))); - createdWebLink.delete(); - assertThat(rootFolder, not(hasItem(Matchers.hasProperty("ID", equalTo(createdWebLink.getID()))))); - } + createdWebLink.delete(); + assertThat( + rootFolder, + not(hasItem(Matchers.hasProperty("ID", equalTo(createdWebLink.getID()))))); + } - @Test - public void createWebLinkWithNoDescriptionSucceeds() throws MalformedURLException { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); + @Test + public void createWebLinkWithNoDescriptionSucceeds() throws MalformedURLException { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); - BoxWebLink createdWebLink = rootFolder + BoxWebLink createdWebLink = + rootFolder .createWebLink("[createWebLinkSucceeds] Test Web Link", new URL("https://api.box.com")) .getResource(); - assertThat(rootFolder, hasItem(Matchers.hasProperty("ID", equalTo(createdWebLink.getID())))); - - createdWebLink.delete(); - assertThat(rootFolder, not(hasItem(Matchers.hasProperty("ID", equalTo(createdWebLink.getID()))))); - } - - @Test - public void createWebLinkWithNoNameOrDescriptionSucceeds() throws MalformedURLException { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - - BoxWebLink createdWebLink = rootFolder.createWebLink(new URL("https://api.box.com")).getResource(); - - assertThat(rootFolder, hasItem(Matchers.hasProperty("ID", equalTo(createdWebLink.getID())))); - - createdWebLink.delete(); - assertThat(rootFolder, not(hasItem(Matchers.hasProperty("ID", equalTo(createdWebLink.getID()))))); - } - - - @Test - public void createPropertiesMetadataSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - final String key = "/testKey"; - final String value = "testValue"; - final String folderName = "[createPropertiesMetadataSucceeds] Metadata Folder " + assertThat( + rootFolder, + hasItem(Matchers.hasProperty("ID", equalTo(createdWebLink.getID())))); + + createdWebLink.delete(); + assertThat( + rootFolder, + not(hasItem(Matchers.hasProperty("ID", equalTo(createdWebLink.getID()))))); + } + + @Test + public void createWebLinkWithNoNameOrDescriptionSucceeds() throws MalformedURLException { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + + BoxWebLink createdWebLink = + rootFolder.createWebLink(new URL("https://api.box.com")).getResource(); + + assertThat( + rootFolder, + hasItem(Matchers.hasProperty("ID", equalTo(createdWebLink.getID())))); + + createdWebLink.delete(); + assertThat( + rootFolder, + not(hasItem(Matchers.hasProperty("ID", equalTo(createdWebLink.getID()))))); + } + + @Test + public void createPropertiesMetadataSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + final String key = "/testKey"; + final String value = "testValue"; + final String folderName = + "[createPropertiesMetadataSucceeds] Metadata Folder " + Calendar.getInstance().getTimeInMillis(); - BoxFolder folder = null; + BoxFolder folder = null; - try { - Metadata md = new Metadata(); - md.add(key, value); - folder = rootFolder.createFolder(folderName).getResource(); - Metadata createdMD = folder.createMetadata(md); + try { + Metadata md = new Metadata(); + md.add(key, value); + folder = rootFolder.createFolder(folderName).getResource(); + Metadata createdMD = folder.createMetadata(md); - assertThat(createdMD.getString(key), is(equalTo(value))); - } finally { - this.deleteFolder(folder); - } + assertThat(createdMD.getString(key), is(equalTo(value))); + } finally { + this.deleteFolder(folder); } - - @Test - public void getMetadataOnInfoSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - final String key = "/testKey"; - final String value = "testValue"; - final String folderName = "[createPropertiesMetadataSucceeds] Metadata Folder " + } + + @Test + public void getMetadataOnInfoSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + final String key = "/testKey"; + final String value = "testValue"; + final String folderName = + "[createPropertiesMetadataSucceeds] Metadata Folder " + Calendar.getInstance().getTimeInMillis(); - BoxFolder folder = null; - - try { - Metadata md = new Metadata(); - md.add(key, value); - folder = rootFolder.createFolder(folderName).getResource(); - folder.createMetadata(md); - Metadata actualMD = folder.getInfo("metadata.global.properties") - .getMetadata("properties", "global"); - assertNotNull("Metadata should not be null for this folder", actualMD); - } catch (BoxAPIException e) { - fail("Metadata should have been present on this folder"); - } finally { - this.deleteFolder(folder); - } + BoxFolder folder = null; + + try { + Metadata md = new Metadata(); + md.add(key, value); + folder = rootFolder.createFolder(folderName).getResource(); + folder.createMetadata(md); + Metadata actualMD = + folder.getInfo("metadata.global.properties").getMetadata("properties", "global"); + assertNotNull("Metadata should not be null for this folder", actualMD); + } catch (BoxAPIException e) { + fail("Metadata should have been present on this folder"); + } finally { + this.deleteFolder(folder); } - - @Test - public void deletePropertiesMetadataSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - final String key = "/testKey"; - final String value = "testValue"; - final String folderName = "[createPropertiesMetadataSucceeds] Metadata Folder " + } + + @Test + public void deletePropertiesMetadataSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + final String key = "/testKey"; + final String value = "testValue"; + final String folderName = + "[createPropertiesMetadataSucceeds] Metadata Folder " + Calendar.getInstance().getTimeInMillis(); - Metadata md = new Metadata(); - md.add(key, value); - BoxFolder folder = rootFolder.createFolder(folderName).getResource(); - folder.createMetadata(md); - folder.deleteMetadata(); - - try { - folder.getMetadata(); - fail("Metadata was not removed"); - } catch (BoxAPIException e) { - assertThat(e.getResponseCode(), is(equalTo(404))); - } finally { - folder.delete(false); - } + Metadata md = new Metadata(); + md.add(key, value); + BoxFolder folder = rootFolder.createFolder(folderName).getResource(); + folder.createMetadata(md); + folder.deleteMetadata(); + + try { + folder.getMetadata(); + fail("Metadata was not removed"); + } catch (BoxAPIException e) { + assertThat(e.getResponseCode(), is(equalTo(404))); + } finally { + folder.delete(false); } - - /** - * Verifies the fix for issue #325. - */ - @Test - public void sharedLinkInfoHasEffectiveAccess() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - BoxFolder folder = null; - try { - folder = rootFolder.createFolder("[sharedLinkInfoHasEffectiveAccess] Test Folder").getResource(); - BoxSharedLink sharedLink = folder.createSharedLink(new BoxSharedLinkRequest().access(OPEN)); - - assertThat(sharedLink, Matchers.hasProperty("effectiveAccess")); - assertThat(sharedLink.getEffectiveAccess(), equalTo(BoxSharedLink.Access.OPEN)); - } finally { - this.deleteFolder(folder); - } - + } + + /** Verifies the fix for issue #325. */ + @Test + public void sharedLinkInfoHasEffectiveAccess() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + BoxFolder folder = null; + try { + folder = + rootFolder.createFolder("[sharedLinkInfoHasEffectiveAccess] Test Folder").getResource(); + BoxSharedLink sharedLink = folder.createSharedLink(new BoxSharedLinkRequest().access(OPEN)); + + assertThat(sharedLink, Matchers.hasProperty("effectiveAccess")); + assertThat(sharedLink.getEffectiveAccess(), equalTo(BoxSharedLink.Access.OPEN)); + } finally { + this.deleteFolder(folder); } - - @Test - public void uploadSessionAbortFlowSuccess() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - - String fileName = randomizeName("LargeFile.txt"); - - BoxFileUploadSession.Info session = rootFolder.createUploadSession(fileName, 25_000_000); - assertNotNull(session.getUploadSessionId()); - assertNotNull(session.getSessionExpiresAt()); - - BoxFileUploadSession.Endpoints endpoints = session.getSessionEndpoints(); - assertNotNull(endpoints); - assertNotNull(endpoints.getUploadPartEndpoint()); - assertNotNull(endpoints.getStatusEndpoint()); - assertNotNull(endpoints.getListPartsEndpoint()); - assertNotNull(endpoints.getCommitEndpoint()); - assertNotNull(endpoints.getAbortEndpoint()); - - //Verify the status of the session - this.getUploadSessionStatus(session.getResource()); - - //Verify the delete session - this.abortUploadSession(session.getResource()); + } + + @Test + public void uploadSessionAbortFlowSuccess() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + + String fileName = randomizeName("LargeFile.txt"); + + BoxFileUploadSession.Info session = rootFolder.createUploadSession(fileName, 25_000_000); + assertNotNull(session.getUploadSessionId()); + assertNotNull(session.getSessionExpiresAt()); + + BoxFileUploadSession.Endpoints endpoints = session.getSessionEndpoints(); + assertNotNull(endpoints); + assertNotNull(endpoints.getUploadPartEndpoint()); + assertNotNull(endpoints.getStatusEndpoint()); + assertNotNull(endpoints.getListPartsEndpoint()); + assertNotNull(endpoints.getCommitEndpoint()); + assertNotNull(endpoints.getAbortEndpoint()); + + // Verify the status of the session + this.getUploadSessionStatus(session.getResource()); + + // Verify the delete session + this.abortUploadSession(session.getResource()); + } + + @Test + public void uploadLargeFileWithAttributes() throws Exception { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + File file = FileUtils.generate(randomizeName("LargeFile.txt"), 21_000_000); + FileInputStream stream = new FileInputStream(file); + BoxFile fileUploaded = null; + + try { + Map fileAttributes = new HashMap<>(); + fileAttributes.put("content_modified_at", "2017-04-08T00:58:08Z"); + + BoxFile.Info info = + rootFolder.uploadLargeFile(stream, "large", file.length(), fileAttributes); + fileUploaded = info.getResource(); + assertNotNull(fileUploaded); + + assertEquals(1491613088000L, info.getContentModifiedAt().getTime()); + } finally { + this.deleteFile(fileUploaded); } - - @Test - public void uploadLargeFileWithAttributes() throws Exception { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - File file = FileUtils.generate(randomizeName("LargeFile.txt"), 21_000_000); - FileInputStream stream = new FileInputStream(file); - BoxFile fileUploaded = null; - - try { - Map fileAttributes = new HashMap<>(); - fileAttributes.put("content_modified_at", "2017-04-08T00:58:08Z"); - - BoxFile.Info info = rootFolder.uploadLargeFile(stream, "large", file.length(), fileAttributes); - fileUploaded = info.getResource(); - assertNotNull(fileUploaded); - - assertEquals(1491613088000L, info.getContentModifiedAt().getTime()); - } finally { - this.deleteFile(fileUploaded); - } + } + + @Test + public void setsVanityNameOnASharedLink() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + BoxFolder sharedFolder = null; + try { + sharedFolder = rootFolder.createFolder(UUID.randomUUID().toString()).getResource(); + + String vanityName = "myCustomName-" + System.currentTimeMillis(); + BoxSharedLinkRequest request = + new BoxSharedLinkRequest() + .permissions(true, true) + .access(OPEN) + .vanityName(vanityName) + .password("my-very-secret-password"); + BoxSharedLink linkWithVanityName = sharedFolder.createSharedLink(request); + + assertThat(linkWithVanityName.getVanityName(), is(vanityName)); + assertThat(sharedFolder.getInfo().getSharedLink().getVanityName(), is(vanityName)); + assertThat(linkWithVanityName.getPermissions().getCanDownload(), is(true)); + assertThat(linkWithVanityName.getPermissions().getCanPreview(), is(true)); + assertThat(linkWithVanityName.getAccess(), is(OPEN)); + assertThat(linkWithVanityName.getIsPasswordEnabled(), is(true)); + } finally { + this.deleteFolder(sharedFolder); } - - @Test - public void setsVanityNameOnASharedLink() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - BoxFolder sharedFolder = null; - try { - sharedFolder = rootFolder.createFolder(UUID.randomUUID().toString()).getResource(); - - String vanityName = "myCustomName-" + System.currentTimeMillis(); - BoxSharedLinkRequest request = new BoxSharedLinkRequest() - .permissions(true, true) - .access(OPEN) - .vanityName(vanityName) - .password("my-very-secret-password"); - BoxSharedLink linkWithVanityName = sharedFolder.createSharedLink(request); - - assertThat(linkWithVanityName.getVanityName(), is(vanityName)); - assertThat(sharedFolder.getInfo().getSharedLink().getVanityName(), is(vanityName)); - assertThat(linkWithVanityName.getPermissions().getCanDownload(), is(true)); - assertThat(linkWithVanityName.getPermissions().getCanPreview(), is(true)); - assertThat(linkWithVanityName.getAccess(), is(OPEN)); - assertThat(linkWithVanityName.getIsPasswordEnabled(), is(true)); - } finally { - this.deleteFolder(sharedFolder); - } + } + + @Test + public void iterateWithOffset() { + final String expectedName = "[iterateWithOnlyTheNameField] Child Folder"; + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + BoxFolder childFolder = null; + + try { + childFolder = rootFolder.createFolder(expectedName).getResource(); + for (int i = 1; i <= 3; i++) { + uploadFileWithSomeContent("sample_file_" + i, childFolder); + } + + Iterable page = childFolder.getChildren("name", ASC, 1, 1); + assertThat(getNames(page), contains("sample_file_2", "sample_file_3")); + + } finally { + this.deleteFolder(childFolder); } - - @Test - public void iterateWithOffset() { - final String expectedName = "[iterateWithOnlyTheNameField] Child Folder"; - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - BoxFolder childFolder = null; - - try { - childFolder = rootFolder.createFolder(expectedName).getResource(); - for (int i = 1; i <= 3; i++) { - uploadFileWithSomeContent("sample_file_" + i, childFolder); - } - - Iterable page = childFolder.getChildren("name", ASC, 1, 1); - assertThat(getNames(page), contains("sample_file_2", "sample_file_3")); - - } finally { - this.deleteFolder(childFolder); - } + } + + @Test + public void iterateWithOffsetUsingNewIterator() { + final String expectedName = "[iterateWithOnlyTheNameField] Child Folder"; + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + BoxFolder childFolder = null; + + try { + childFolder = rootFolder.createFolder(expectedName).getResource(); + for (int i = 1; i <= 3; i++) { + uploadFileWithSomeContent("sample_file_" + i, childFolder); + } + + Iterable page = childFolder.getChildren(ascending("name"), offset(1, 1)); + assertThat(getNames(page), contains("sample_file_2", "sample_file_3")); + + } finally { + this.deleteFolder(childFolder); } - - @Test - public void iterateWithOffsetUsingNewIterator() { - final String expectedName = "[iterateWithOnlyTheNameField] Child Folder"; - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - BoxFolder childFolder = null; - - try { - childFolder = rootFolder.createFolder(expectedName).getResource(); - for (int i = 1; i <= 3; i++) { - uploadFileWithSomeContent("sample_file_" + i, childFolder); - } - - Iterable page = childFolder.getChildren(ascending("name"), offset(1, 1)); - assertThat(getNames(page), contains("sample_file_2", "sample_file_3")); - - } finally { - this.deleteFolder(childFolder); - } + } + + @Test + public void iterateWithMarker() { + final String expectedName = "[iterateWithOnlyTheNameField] Child Folder"; + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + BoxFolder childFolder = null; + + try { + childFolder = rootFolder.createFolder(expectedName).getResource(); + for (int i = 1; i <= 2; i++) { + uploadFileWithSomeContent("sample_file_" + i, childFolder); + } + + Iterable page = childFolder.getChildren(none(), marker(1)); + assertThat(getNames(page), contains("sample_file_1", "sample_file_2")); + + } finally { + this.deleteFolder(childFolder); } + } - @Test - public void iterateWithMarker() { - final String expectedName = "[iterateWithOnlyTheNameField] Child Folder"; - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - BoxFolder childFolder = null; + @Test + public void uploadFileVersionInSeparateThreadsSucceeds() + throws IOException, InterruptedException { + BoxAPIConnection api = jwtApiForServiceAccount(); + Semaphore semaphore = new Semaphore(0); - try { - childFolder = rootFolder.createFolder(expectedName).getResource(); - for (int i = 1; i <= 2; i++) { - uploadFileWithSomeContent("sample_file_" + i, childFolder); - } + PipedOutputStream outputStream = new PipedOutputStream(); + PipedInputStream inputStream = new PipedInputStream(); + outputStream.connect(inputStream); - Iterable page = childFolder.getChildren(none(), marker(1)); - assertThat(getNames(page), contains("sample_file_1", "sample_file_2")); + String fileContent = "This is only a test"; + final BoxFile uploadedFile = + uploadFileToUniqueFolder(api, randomizeName("Test File"), fileContent); - } finally { - this.deleteFolder(childFolder); - } - } - - @Test - public void uploadFileVersionInSeparateThreadsSucceeds() throws IOException, InterruptedException { - BoxAPIConnection api = jwtApiForServiceAccount(); - Semaphore semaphore = new Semaphore(0); - - PipedOutputStream outputStream = new PipedOutputStream(); - PipedInputStream inputStream = new PipedInputStream(); - outputStream.connect(inputStream); - - String fileContent = "This is only a test"; - final BoxFile uploadedFile = uploadFileToUniqueFolder(api, randomizeName("Test File"), fileContent); - - new Thread( + new Thread( () -> { + try { + new BoxFile(api, uploadedFile.getID()).download(outputStream); + } finally { try { - new BoxFile(api, uploadedFile.getID()).download(outputStream); - } finally { - try { - outputStream.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - }).start(); - - new Thread( - () -> { - new BoxFile(api, uploadedFile.getID()).uploadNewVersion(inputStream); - try { - inputStream.close(); - semaphore.release(); + outputStream.close(); } catch (IOException e) { - throw new RuntimeException(e); + throw new RuntimeException(e); } - }).start(); - - - semaphore.acquire(); - ByteArrayOutputStream output = new ByteArrayOutputStream(); - new BoxFile(api, uploadedFile.getID()).download(output); - assertThat(output.toString(), is(fileContent)); - } - - @Test - public void uploadFileVersionWithProgressInSeparateThreadsSucceeds() throws IOException, InterruptedException { - BoxAPIConnection api = jwtApiForServiceAccount(); - Semaphore semaphore = new Semaphore(0); - - PipedOutputStream outputStream = new PipedOutputStream(); - PipedInputStream inputStream = new PipedInputStream(); - outputStream.connect(inputStream); - AtomicLong bytesUploaded = new AtomicLong(0); - ProgressListener progressListener = (numBytes, totalBytes) -> bytesUploaded.set(numBytes); - - String fileContent = "This is only a test"; - long fileSize = fileContent.getBytes(UTF_8).length; - - final BoxFile uploadedFile = uploadFileToUniqueFolder(api, randomizeName("Test File"), fileContent); + } + }) + .start(); - new Thread( + new Thread( () -> { - try { - new BoxFile(api, uploadedFile.getID()).download(outputStream); - } finally { - semaphore.release(); - } - }).start(); - - new Thread( + new BoxFile(api, uploadedFile.getID()).uploadNewVersion(inputStream); + try { + inputStream.close(); + semaphore.release(); + } catch (IOException e) { + throw new RuntimeException(e); + } + }) + .start(); + + semaphore.acquire(); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + new BoxFile(api, uploadedFile.getID()).download(output); + assertThat(output.toString(), is(fileContent)); + } + + @Test + public void uploadFileVersionWithProgressInSeparateThreadsSucceeds() + throws IOException, InterruptedException { + BoxAPIConnection api = jwtApiForServiceAccount(); + Semaphore semaphore = new Semaphore(0); + + PipedOutputStream outputStream = new PipedOutputStream(); + PipedInputStream inputStream = new PipedInputStream(); + outputStream.connect(inputStream); + AtomicLong bytesUploaded = new AtomicLong(0); + ProgressListener progressListener = (numBytes, totalBytes) -> bytesUploaded.set(numBytes); + + String fileContent = "This is only a test"; + long fileSize = fileContent.getBytes(UTF_8).length; + + final BoxFile uploadedFile = + uploadFileToUniqueFolder(api, randomizeName("Test File"), fileContent); + + new Thread( () -> { - new BoxFile(api, uploadedFile.getID()) - .uploadNewVersion(inputStream, new Date(), fileSize, progressListener); + try { + new BoxFile(api, uploadedFile.getID()).download(outputStream); + } finally { semaphore.release(); - }).start(); - - - semaphore.acquire(2); - ByteArrayOutputStream output = new ByteArrayOutputStream(); - new BoxFile(api, uploadedFile.getID()).download(output); - assertThat(output.toString(), is(fileContent)); - assertThat(bytesUploaded.get(), is(fileSize)); - } - - @Test - public void uploadFileInSeparateThreadSucceeds() throws IOException, InterruptedException { - BoxAPIConnection api = jwtApiForServiceAccount(); - Semaphore semaphore = new Semaphore(0); - - PipedOutputStream outputStream = new PipedOutputStream(); - PipedInputStream inputStream = new PipedInputStream(); - outputStream.connect(inputStream); + } + }) + .start(); - String fileContent = "Test"; - byte[] bytes = fileContent.getBytes(UTF_8); - - AtomicReference uploadedFileId = new AtomicReference<>(); - - new Thread( + new Thread( () -> { - IntStream.range(0, bytes.length) - .forEach(i -> { + new BoxFile(api, uploadedFile.getID()) + .uploadNewVersion(inputStream, new Date(), fileSize, progressListener); + semaphore.release(); + }) + .start(); + + semaphore.acquire(2); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + new BoxFile(api, uploadedFile.getID()).download(output); + assertThat(output.toString(), is(fileContent)); + assertThat(bytesUploaded.get(), is(fileSize)); + } + + @Test + public void uploadFileInSeparateThreadSucceeds() throws IOException, InterruptedException { + BoxAPIConnection api = jwtApiForServiceAccount(); + Semaphore semaphore = new Semaphore(0); + + PipedOutputStream outputStream = new PipedOutputStream(); + PipedInputStream inputStream = new PipedInputStream(); + outputStream.connect(inputStream); + + String fileContent = "Test"; + byte[] bytes = fileContent.getBytes(UTF_8); + + AtomicReference uploadedFileId = new AtomicReference<>(); + + new Thread( + () -> { + IntStream.range(0, bytes.length) + .forEach( + i -> { try { - outputStream.write(bytes[i]); - Thread.sleep(100); + outputStream.write(bytes[i]); + Thread.sleep(100); } catch (InterruptedException | IOException e) { - throw new RuntimeException(e); + throw new RuntimeException(e); } - }); - try { - outputStream.close(); - semaphore.release(); - } catch (IOException e) { - throw new RuntimeException(e); - } - }).start(); + }); + try { + outputStream.close(); + semaphore.release(); + } catch (IOException e) { + throw new RuntimeException(e); + } + }) + .start(); - new Thread( + new Thread( () -> { - BoxFile.Info uploadedFile = getUniqueFolder(api) - .uploadFile(inputStream, randomizeName("dynamic_upload")); - uploadedFileId.set(uploadedFile.getID()); - try { - inputStream.close(); - semaphore.release(); - } catch (IOException e) { - throw new RuntimeException(e); - } - }).start(); - - - semaphore.acquire(2); - ByteArrayOutputStream output = new ByteArrayOutputStream(); - new BoxFile(api, uploadedFileId.get()).download(output); - assertThat(output.toString(), is(fileContent)); - } - - private Collection getNames(Iterable page) { - Collection result = new ArrayList<>(); - for (BoxItem.Info info : page) { - result.add(info.getName()); - } - return result; - } - - private void getUploadSessionStatus(BoxFileUploadSession session) { - assertNotNull(session); - BoxFileUploadSession.Info sessionInfo = session.getStatus(); - assertNotNull(sessionInfo.getSessionExpiresAt()); + BoxFile.Info uploadedFile = + getUniqueFolder(api).uploadFile(inputStream, randomizeName("dynamic_upload")); + uploadedFileId.set(uploadedFile.getID()); + try { + inputStream.close(); + semaphore.release(); + } catch (IOException e) { + throw new RuntimeException(e); + } + }) + .start(); + + semaphore.acquire(2); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + new BoxFile(api, uploadedFileId.get()).download(output); + assertThat(output.toString(), is(fileContent)); + } + + private Collection getNames(Iterable page) { + Collection result = new ArrayList<>(); + for (BoxItem.Info info : page) { + result.add(info.getName()); } - - private void abortUploadSession(BoxFileUploadSession session) { - session.abort(); - - try { - session.getStatus(); - fail("Upload session is not deleted"); - } catch (BoxAPIException apiEx) { - assertEquals(apiEx.getResponseCode(), 404); - } + return result; + } + + private void getUploadSessionStatus(BoxFileUploadSession session) { + assertNotNull(session); + BoxFileUploadSession.Info sessionInfo = session.getStatus(); + assertNotNull(sessionInfo.getSessionExpiresAt()); + } + + private void abortUploadSession(BoxFileUploadSession session) { + session.abort(); + + try { + session.getStatus(); + fail("Upload session is not deleted"); + } catch (BoxAPIException apiEx) { + assertEquals(apiEx.getResponseCode(), 404); } + } - private void deleteFolder(BoxFolder folder) { - if (folder != null) { - folder.delete(true); - } + private void deleteFolder(BoxFolder folder) { + if (folder != null) { + folder.delete(true); } + } - - private void deleteFile(BoxFile file) { - if (file != null) { - file.delete(); - } + private void deleteFile(BoxFile file) { + if (file != null) { + file.delete(); } + } - private void deleteCollaborationAllowList(BoxCollaborationAllowlist collaborationAllowList) { - if (collaborationAllowList != null) { - collaborationAllowList.delete(); - } + private void deleteCollaborationAllowList(BoxCollaborationAllowlist collaborationAllowList) { + if (collaborationAllowList != null) { + collaborationAllowList.delete(); } + } } diff --git a/src/intTest/java/com/box/sdk/BoxGroupIT.java b/src/intTest/java/com/box/sdk/BoxGroupIT.java index 0cb4252a7..4db7961ea 100644 --- a/src/intTest/java/com/box/sdk/BoxGroupIT.java +++ b/src/intTest/java/com/box/sdk/BoxGroupIT.java @@ -23,154 +23,158 @@ import org.junit.BeforeClass; import org.junit.Test; -/** - * {@link BoxGroup} related integration tests. - */ +/** {@link BoxGroup} related integration tests. */ public class BoxGroupIT { - @BeforeClass - public static void setup() { - setupUniqeFolder(); + @BeforeClass + public static void setup() { + setupUniqeFolder(); + } + + @AfterClass + public static void afterClass() { + removeUniqueFolder(); + } + + @Before + public void cleanup() { + removeAllGroups(); + } + + @Test + public void createAndDeleteGroupSucceeds() { + final String groupName = "[createAndDeleteGroupSucceeds] Test Group"; + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxGroup.Info createdGroupInfo = BoxGroup.createGroup(api, groupName); + + assertThat(createdGroupInfo.getName(), equalTo(groupName)); + + createdGroupInfo.getResource().delete(); + Iterable groups = BoxGroup.getAllGroupsByName(api, groupName); + assertThat(createListFrom(groups), Matchers.hasSize(0)); + } + + @Test + public void addMembershipSucceedsAndGetMembershipsHasCorrectMemberships() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String groupName = "[addMembershipSucceedsAndGetMembershipsHasCorrectMemberships] Test Group"; + BoxUser user = BoxUser.getCurrentUser(api); + BoxGroupMembership.GroupRole groupRole = BoxGroupMembership.GroupRole.ADMIN; + + BoxGroup group = BoxGroup.createGroup(api, groupName).getResource(); + BoxGroupMembership.Info membershipInfo = group.addMembership(user, groupRole); + String membershipID = membershipInfo.getID(); + + assertThat(membershipInfo.getUser().getID(), is(equalTo(user.getID()))); + assertThat(membershipInfo.getGroup().getID(), is(equalTo(group.getID()))); + assertThat(membershipInfo.getGroupRole(), is(equalTo(groupRole))); + + Collection memberships = group.getMemberships(); + + assertThat(memberships, hasSize(1)); + assertThat( + memberships, + hasItem(Matchers.hasProperty("ID", equalTo(membershipID)))); + + group.delete(); + } + + @Test + public void getInfoSucceeds() { + final String groupName = "[getInfoSucceeds] Test Group"; + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxGroup createdGroup = null; + try { + createdGroup = BoxGroup.createGroup(api, groupName).getResource(); + BoxGroup.Info createdGroupInfo = createdGroup.getInfo(); + + assertThat(createdGroupInfo.getName(), equalTo(groupName)); + } finally { + deleteGroup(createdGroup); } + } - @AfterClass - public static void afterClass() { - removeUniqueFolder(); - } - - @Before - public void cleanup() { - removeAllGroups(); - } + @Test + public void getCollaborationsSucceedsAndHandlesResponseCorrectly() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String groupName = "[getCollaborationsSucceedsAndHandlesResponseCorrectly] Test Group"; - @Test - public void createAndDeleteGroupSucceeds() { - final String groupName = "[createAndDeleteGroupSucceeds] Test Group"; - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxGroup.Info createdGroupInfo = BoxGroup.createGroup(api, groupName); + BoxGroup group = null; + BoxFolder folder = null; - assertThat(createdGroupInfo.getName(), equalTo(groupName)); - - createdGroupInfo.getResource().delete(); - Iterable groups = BoxGroup.getAllGroupsByName(api, groupName); - assertThat(createListFrom(groups), Matchers.hasSize(0)); - } + String folderName = "[getCollaborationsSucceedsAndHandlesResponseCorrectly] Test Folder"; - @Test - public void addMembershipSucceedsAndGetMembershipsHasCorrectMemberships() { - BoxAPIConnection api = jwtApiForServiceAccount(); - String groupName = "[addMembershipSucceedsAndGetMembershipsHasCorrectMemberships] Test Group"; - BoxUser user = BoxUser.getCurrentUser(api); - BoxGroupMembership.GroupRole groupRole = BoxGroupMembership.GroupRole.ADMIN; + try { + group = BoxGroup.createGroup(api, groupName).getResource(); + BoxCollaborator collabGroup = new BoxGroup(api, group.getID()); + folder = getUniqueFolder(api).createFolder(folderName).getResource(); - BoxGroup group = BoxGroup.createGroup(api, groupName).getResource(); - BoxGroupMembership.Info membershipInfo = group.addMembership(user, groupRole); - String membershipID = membershipInfo.getID(); + BoxCollaboration.Info collabInfo = + folder.collaborate(collabGroup, BoxCollaboration.Role.EDITOR); - assertThat(membershipInfo.getUser().getID(), is(equalTo(user.getID()))); - assertThat(membershipInfo.getGroup().getID(), is(equalTo(group.getID()))); - assertThat(membershipInfo.getGroupRole(), is(equalTo(groupRole))); + Collection collaborations = group.getCollaborations(); - Collection memberships = group.getMemberships(); - - assertThat(memberships, hasSize(1)); - assertThat(memberships, hasItem(Matchers.hasProperty("ID", equalTo(membershipID)))); - - group.delete(); + assertThat(collaborations, hasSize(1)); + assertThat( + collaborations, + hasItem(Matchers.hasProperty("ID", equalTo(collabInfo.getID())))); + } finally { + deleteGroup(group); + deleteFolder(folder); } - - @Test - public void getInfoSucceeds() { - final String groupName = "[getInfoSucceeds] Test Group"; - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxGroup createdGroup = null; - try { - createdGroup = BoxGroup.createGroup(api, groupName).getResource(); - BoxGroup.Info createdGroupInfo = createdGroup.getInfo(); - - assertThat(createdGroupInfo.getName(), equalTo(groupName)); - } finally { - deleteGroup(createdGroup); - } + } + + @Test + public void getAllGroupsByNameSearchesCorrectly() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String groupName = "getAllGroupsByNameSearchesCorrectly"; + BoxGroup group = BoxGroup.createGroup(api, groupName).getResource(); + try { + // Searching groups requires few seconds delay. + Thread.sleep(5000); + } catch (InterruptedException ie) { + // Do nothing } - - @Test - public void getCollaborationsSucceedsAndHandlesResponseCorrectly() { - BoxAPIConnection api = jwtApiForServiceAccount(); - String groupName = "[getCollaborationsSucceedsAndHandlesResponseCorrectly] Test Group"; - - BoxGroup group = null; - BoxFolder folder = null; - - String folderName = "[getCollaborationsSucceedsAndHandlesResponseCorrectly] Test Folder"; - - try { - group = BoxGroup.createGroup(api, groupName).getResource(); - BoxCollaborator collabGroup = new BoxGroup(api, group.getID()); - folder = getUniqueFolder(api).createFolder(folderName).getResource(); - - BoxCollaboration.Info collabInfo = folder.collaborate(collabGroup, BoxCollaboration.Role.EDITOR); - - Collection collaborations = group.getCollaborations(); - - assertThat(collaborations, hasSize(1)); - assertThat(collaborations, hasItem( - Matchers.hasProperty("ID", equalTo(collabInfo.getID()))) - ); - } finally { - deleteGroup(group); - deleteFolder(folder); - } + try { + Iterator iterator = BoxGroup.getAllGroupsByName(api, groupName).iterator(); + boolean matchingGroup; + do { + BoxGroup.Info groupInfo = iterator.next(); + matchingGroup = groupName.equals(groupInfo.getName()); + } while (!matchingGroup && iterator.hasNext()); + assertTrue("Group was not found", matchingGroup); + } finally { + deleteGroup(group); } - - @Test - public void getAllGroupsByNameSearchesCorrectly() { - BoxAPIConnection api = jwtApiForServiceAccount(); - String groupName = "getAllGroupsByNameSearchesCorrectly"; - BoxGroup group = BoxGroup.createGroup(api, groupName).getResource(); - try { - //Searching groups requires few seconds delay. - Thread.sleep(5000); - } catch (InterruptedException ie) { - //Do nothing - } - - try { - Iterator iterator = BoxGroup.getAllGroupsByName(api, groupName).iterator(); - boolean matchingGroup; - do { - BoxGroup.Info groupInfo = iterator.next(); - matchingGroup = groupName.equals(groupInfo.getName()); - } while (!matchingGroup && iterator.hasNext()); - assertTrue("Group was not found", matchingGroup); - } finally { - deleteGroup(group); - } + } + + @Test + public void getAllGroupsByNameWithFieldsOptionSearchesCorrectly() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String groupName = "getAllGroupsByNameWithFieldsOptionSearchesCorrectly"; + String groupDescription = "This is Test Group"; + BoxGroup group = + BoxGroup.createGroup(api, groupName, null, null, groupDescription, null, null) + .getResource(); + try { + // Searching groups requires few seconds delay. + Thread.sleep(5000); + } catch (InterruptedException ie) { + // Do nothing } - - @Test - public void getAllGroupsByNameWithFieldsOptionSearchesCorrectly() { - BoxAPIConnection api = jwtApiForServiceAccount(); - String groupName = "getAllGroupsByNameWithFieldsOptionSearchesCorrectly"; - String groupDescription = "This is Test Group"; - BoxGroup group = BoxGroup.createGroup(api, groupName, null, null, groupDescription, null, null).getResource(); - try { - //Searching groups requires few seconds delay. - Thread.sleep(5000); - } catch (InterruptedException ie) { - //Do nothing - } - try { - Iterator iterator = BoxGroup.getAllGroupsByName(api, groupName, "description").iterator(); - boolean matchingGroup; - do { - BoxGroup.Info groupInfo = iterator.next(); - matchingGroup = groupInfo.getName() == null && groupDescription.equals(groupInfo.getDescription()); - } while (!matchingGroup && iterator.hasNext()); - assertTrue("Group was not found", matchingGroup); - } finally { - deleteGroup(group); - } + try { + Iterator iterator = + BoxGroup.getAllGroupsByName(api, groupName, "description").iterator(); + boolean matchingGroup; + do { + BoxGroup.Info groupInfo = iterator.next(); + matchingGroup = + groupInfo.getName() == null && groupDescription.equals(groupInfo.getDescription()); + } while (!matchingGroup && iterator.hasNext()); + assertTrue("Group was not found", matchingGroup); + } finally { + deleteGroup(group); } + } } diff --git a/src/intTest/java/com/box/sdk/BoxGroupMembershipIT.java b/src/intTest/java/com/box/sdk/BoxGroupMembershipIT.java index c6930fc69..364e110f7 100644 --- a/src/intTest/java/com/box/sdk/BoxGroupMembershipIT.java +++ b/src/intTest/java/com/box/sdk/BoxGroupMembershipIT.java @@ -12,100 +12,103 @@ import java.util.Map; import org.junit.Test; -/** - * {@link BoxGroupMembership} related integration tests. - */ +/** {@link BoxGroupMembership} related integration tests. */ public class BoxGroupMembershipIT { - @Test - public void getInfoSucceeds() { - final String groupName = "[getGroupMembershipInfoSucceeds] Test Group " - + Calendar.getInstance().getTimeInMillis(); - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxUser user = BoxUser.getCurrentUser(api); - BoxGroupMembership.GroupRole role = BoxGroupMembership.GroupRole.MEMBER; - - BoxGroup.Info groupInfo = BoxGroup.createGroup(api, groupName); - BoxUser.Info userInfo = user.getInfo(); - BoxGroup group = groupInfo.getResource(); - - BoxGroupMembership membership = group.addMembership(user, role).getResource(); - BoxGroupMembership.Info membershipInfo = membership.getInfo(); - - assertThat(membershipInfo.getUser().getID(), is(equalTo(user.getID()))); - assertThat(membershipInfo.getUser().getName(), is(equalTo(userInfo.getName()))); - assertThat(membershipInfo.getUser().getLogin(), is(equalTo(userInfo.getLogin()))); - assertThat(membershipInfo.getGroup().getID(), is(equalTo(group.getID()))); - assertThat(membershipInfo.getGroup().getName(), is(equalTo(groupInfo.getName()))); - assertThat(membershipInfo.getGroupRole(), is(equalTo(role))); - - deleteGroup(group); - } - - @Test - public void updateInfoSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - String groupName = "[updateGroupMembershipInfoSucceeds] Test Group"; - BoxUser user = BoxUser.getCurrentUser(api); - BoxGroupMembership.GroupRole originalRole = BoxGroupMembership.GroupRole.MEMBER; - BoxGroupMembership.GroupRole newRole = BoxGroupMembership.GroupRole.ADMIN; - - Map configurablePermissions = new HashMap<>(); - configurablePermissions.put(Permission.CAN_CREATE_ACCOUNTS, false); - - BoxGroup group = BoxGroup.createGroup(api, groupName).getResource(); - - BoxGroupMembership.Info membershipInfo = group.addMembership(user, originalRole); - - assertThat(membershipInfo.getGroupRole(), is(equalTo(originalRole))); - - BoxGroupMembership membership = membershipInfo.getResource(); - membershipInfo.setGroupRole(newRole); - membershipInfo.setConfigurablePermissions(configurablePermissions); - membership.updateInfo(membershipInfo); - - assertThat(membershipInfo.getGroupRole(), is(equalTo(newRole))); - assertThat(membershipInfo.getConfigurablePermissions().get(Permission.CAN_CREATE_ACCOUNTS), - is(equalTo(false))); - - deleteGroup(group); - } - - @Test - public void addWithConfigurablePermissionsSucceds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - String groupName = "[addWithConfigurablePermissionsSucceeds] Test Group"; - BoxUser user = BoxUser.getCurrentUser(api); - BoxGroupMembership.GroupRole role = BoxGroupMembership.GroupRole.ADMIN; - - Map configurablePermissions = new HashMap<>(); - configurablePermissions.put(Permission.CAN_CREATE_ACCOUNTS, false); - - BoxGroup group = BoxGroup.createGroup(api, groupName).getResource(); - - BoxGroupMembership.Info membershipInfo = group.addMembership(user, role, configurablePermissions); - - assertThat(membershipInfo.getConfigurablePermissions().get(Permission.CAN_CREATE_ACCOUNTS), - is(equalTo(false))); - assertThat(membershipInfo.getConfigurablePermissions().get(Permission.CAN_EDIT_ACCOUNTS), - is(equalTo(true))); - - deleteGroup(group); - } - - @Test - public void deleteSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - String groupName = "[deleteGroupMembershipSucceeds] Test Group " + Calendar.getInstance().getTimeInMillis(); - BoxUser user = BoxUser.getCurrentUser(api); - BoxGroupMembership.GroupRole originalRole = BoxGroupMembership.GroupRole.MEMBER; - - BoxGroup group = BoxGroup.createGroup(api, groupName).getResource(); - - BoxGroupMembership.Info membershipInfo = group.addMembership(user, originalRole); - BoxGroupMembership membership = membershipInfo.getResource(); - membership.delete(); - - deleteGroup(group); - } + @Test + public void getInfoSucceeds() { + final String groupName = + "[getGroupMembershipInfoSucceeds] Test Group " + Calendar.getInstance().getTimeInMillis(); + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxUser user = BoxUser.getCurrentUser(api); + BoxGroupMembership.GroupRole role = BoxGroupMembership.GroupRole.MEMBER; + + BoxGroup.Info groupInfo = BoxGroup.createGroup(api, groupName); + BoxUser.Info userInfo = user.getInfo(); + BoxGroup group = groupInfo.getResource(); + + BoxGroupMembership membership = group.addMembership(user, role).getResource(); + BoxGroupMembership.Info membershipInfo = membership.getInfo(); + + assertThat(membershipInfo.getUser().getID(), is(equalTo(user.getID()))); + assertThat(membershipInfo.getUser().getName(), is(equalTo(userInfo.getName()))); + assertThat(membershipInfo.getUser().getLogin(), is(equalTo(userInfo.getLogin()))); + assertThat(membershipInfo.getGroup().getID(), is(equalTo(group.getID()))); + assertThat(membershipInfo.getGroup().getName(), is(equalTo(groupInfo.getName()))); + assertThat(membershipInfo.getGroupRole(), is(equalTo(role))); + + deleteGroup(group); + } + + @Test + public void updateInfoSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String groupName = "[updateGroupMembershipInfoSucceeds] Test Group"; + BoxUser user = BoxUser.getCurrentUser(api); + BoxGroupMembership.GroupRole originalRole = BoxGroupMembership.GroupRole.MEMBER; + BoxGroupMembership.GroupRole newRole = BoxGroupMembership.GroupRole.ADMIN; + + Map configurablePermissions = new HashMap<>(); + configurablePermissions.put(Permission.CAN_CREATE_ACCOUNTS, false); + + BoxGroup group = BoxGroup.createGroup(api, groupName).getResource(); + + BoxGroupMembership.Info membershipInfo = group.addMembership(user, originalRole); + + assertThat(membershipInfo.getGroupRole(), is(equalTo(originalRole))); + + BoxGroupMembership membership = membershipInfo.getResource(); + membershipInfo.setGroupRole(newRole); + membershipInfo.setConfigurablePermissions(configurablePermissions); + membership.updateInfo(membershipInfo); + + assertThat(membershipInfo.getGroupRole(), is(equalTo(newRole))); + assertThat( + membershipInfo.getConfigurablePermissions().get(Permission.CAN_CREATE_ACCOUNTS), + is(equalTo(false))); + + deleteGroup(group); + } + + @Test + public void addWithConfigurablePermissionsSucceds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String groupName = "[addWithConfigurablePermissionsSucceeds] Test Group"; + BoxUser user = BoxUser.getCurrentUser(api); + BoxGroupMembership.GroupRole role = BoxGroupMembership.GroupRole.ADMIN; + + Map configurablePermissions = new HashMap<>(); + configurablePermissions.put(Permission.CAN_CREATE_ACCOUNTS, false); + + BoxGroup group = BoxGroup.createGroup(api, groupName).getResource(); + + BoxGroupMembership.Info membershipInfo = + group.addMembership(user, role, configurablePermissions); + + assertThat( + membershipInfo.getConfigurablePermissions().get(Permission.CAN_CREATE_ACCOUNTS), + is(equalTo(false))); + assertThat( + membershipInfo.getConfigurablePermissions().get(Permission.CAN_EDIT_ACCOUNTS), + is(equalTo(true))); + + deleteGroup(group); + } + + @Test + public void deleteSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String groupName = + "[deleteGroupMembershipSucceeds] Test Group " + Calendar.getInstance().getTimeInMillis(); + BoxUser user = BoxUser.getCurrentUser(api); + BoxGroupMembership.GroupRole originalRole = BoxGroupMembership.GroupRole.MEMBER; + + BoxGroup group = BoxGroup.createGroup(api, groupName).getResource(); + + BoxGroupMembership.Info membershipInfo = group.addMembership(user, originalRole); + BoxGroupMembership membership = membershipInfo.getResource(); + membership.delete(); + + deleteGroup(group); + } } diff --git a/src/intTest/java/com/box/sdk/BoxRecentsIT.java b/src/intTest/java/com/box/sdk/BoxRecentsIT.java index 67dc61e46..2880a4d36 100644 --- a/src/intTest/java/com/box/sdk/BoxRecentsIT.java +++ b/src/intTest/java/com/box/sdk/BoxRecentsIT.java @@ -12,75 +12,75 @@ import org.junit.BeforeClass; import org.junit.Test; -/** - * {@link BoxRecents} related integration tests. - */ +/** {@link BoxRecents} related integration tests. */ public class BoxRecentsIT { - @BeforeClass - public static void setup() { - setupUniqeFolder(); - } + @BeforeClass + public static void setup() { + setupUniqeFolder(); + } - @AfterClass - public static void tearDown() { - removeUniqueFolder(); - } + @AfterClass + public static void tearDown() { + removeUniqueFolder(); + } - @Test - public void getRecentsWorkWithoutFields() { - BoxFile uploadedFile = null; - try { - BoxAPIConnection api = jwtApiForServiceAccount(); - api.asUser(TestConfig.getCollaboratorID()); + @Test + public void getRecentsWorkWithoutFields() { + BoxFile uploadedFile = null; + try { + BoxAPIConnection api = jwtApiForServiceAccount(); + api.asUser(TestConfig.getCollaboratorID()); - //Create a file to check if it comes up in recents - String fileName = "[recentItemTest] Multi-version File.txt"; - String version1Content = "Version 1"; - String version2Content = "Version 2"; - uploadedFile = uploadTwoFileVersionsToUniqueFolder(fileName, version1Content, version2Content, null); + // Create a file to check if it comes up in recents + String fileName = "[recentItemTest] Multi-version File.txt"; + String version1Content = "Version 1"; + String version2Content = "Version 2"; + uploadedFile = + uploadTwoFileVersionsToUniqueFolder(fileName, version1Content, version2Content, null); - BoxResourceIterable recentItems = BoxRecents.getRecentItems(api, 100); - assertNotNull("Should receive a response", recentItems); - Iterator recentItemIterator = recentItems.iterator(); - if (recentItemIterator.hasNext()) { - BoxRecentItem recentItem = recentItemIterator.next(); - assertNotNull("type should be not be null", recentItem.getType()); - assertNotNull("interactedAt date should not be null", recentItem.getInteractedAt()); - assertNotNull("interactionType should not be null", recentItem.getInteractionType()); - assertNotNull("item should not be null", recentItem.getItem()); - } - } finally { - deleteFile(uploadedFile); - } + BoxResourceIterable recentItems = BoxRecents.getRecentItems(api, 100); + assertNotNull("Should receive a response", recentItems); + Iterator recentItemIterator = recentItems.iterator(); + if (recentItemIterator.hasNext()) { + BoxRecentItem recentItem = recentItemIterator.next(); + assertNotNull("type should be not be null", recentItem.getType()); + assertNotNull("interactedAt date should not be null", recentItem.getInteractedAt()); + assertNotNull("interactionType should not be null", recentItem.getInteractionType()); + assertNotNull("item should not be null", recentItem.getItem()); + } + } finally { + deleteFile(uploadedFile); } + } - @Test - public void getRecentsWorkWithFields() { - BoxFile uploadedFile = null; - try { - BoxAPIConnection api = jwtApiForServiceAccount(); - api.asUser(TestConfig.getCollaboratorID()); + @Test + public void getRecentsWorkWithFields() { + BoxFile uploadedFile = null; + try { + BoxAPIConnection api = jwtApiForServiceAccount(); + api.asUser(TestConfig.getCollaboratorID()); - //Create a file to check if it comes up in recents - String fileName = "[recentItemTest] Multi-version File.txt"; - String version1Content = "Version 1"; - String version2Content = "Version 2"; - uploadedFile = uploadTwoFileVersionsToUniqueFolder(fileName, version1Content, version2Content, null); + // Create a file to check if it comes up in recents + String fileName = "[recentItemTest] Multi-version File.txt"; + String version1Content = "Version 1"; + String version2Content = "Version 2"; + uploadedFile = + uploadTwoFileVersionsToUniqueFolder(fileName, version1Content, version2Content, null); - BoxResourceIterable recentItems = BoxRecents.getRecentItems(api, 100, "created_at"); - assertNotNull("Should receive a response", recentItems); - Iterator recentItemIterator = recentItems.iterator(); - if (recentItemIterator.hasNext()) { - BoxRecentItem recentItem = recentItemIterator.next(); - assertNotNull("type should be not be null", recentItem.getType()); - assertNotNull("interactedAt date should not be null", recentItem.getInteractedAt()); - assertNotNull("interactionType should not be null", recentItem.getInteractionType()); - assertNotNull("item should not be null", recentItem.getItem()); - assertNotNull("item's created_at should not be null", recentItem.getItem().getCreatedAt()); - } - } finally { - deleteFile(uploadedFile); - } + BoxResourceIterable recentItems = + BoxRecents.getRecentItems(api, 100, "created_at"); + assertNotNull("Should receive a response", recentItems); + Iterator recentItemIterator = recentItems.iterator(); + if (recentItemIterator.hasNext()) { + BoxRecentItem recentItem = recentItemIterator.next(); + assertNotNull("type should be not be null", recentItem.getType()); + assertNotNull("interactedAt date should not be null", recentItem.getInteractedAt()); + assertNotNull("interactionType should not be null", recentItem.getInteractionType()); + assertNotNull("item should not be null", recentItem.getItem()); + assertNotNull("item's created_at should not be null", recentItem.getItem().getCreatedAt()); + } + } finally { + deleteFile(uploadedFile); } - + } } diff --git a/src/intTest/java/com/box/sdk/BoxRetentionPolicyAssignmentIT.java b/src/intTest/java/com/box/sdk/BoxRetentionPolicyAssignmentIT.java index e2360e1cd..518247f41 100644 --- a/src/intTest/java/com/box/sdk/BoxRetentionPolicyAssignmentIT.java +++ b/src/intTest/java/com/box/sdk/BoxRetentionPolicyAssignmentIT.java @@ -21,112 +21,119 @@ import org.junit.BeforeClass; import org.junit.Test; -/** - * {@link BoxRetentionPolicyAssignment} related integration tests. - */ +/** {@link BoxRetentionPolicyAssignment} related integration tests. */ public class BoxRetentionPolicyAssignmentIT { - private static BoxRetentionPolicy policy; + private static BoxRetentionPolicy policy; - @BeforeClass - public static void beforeClass() { - BoxAPIConnection api = jwtApiForServiceAccount(); - policy = RetentionPolicyUtils.getOneDayRetentionPolicy(api); - setupUniqeFolder(); - } + @BeforeClass + public static void beforeClass() { + BoxAPIConnection api = jwtApiForServiceAccount(); + policy = RetentionPolicyUtils.getOneDayRetentionPolicy(api); + setupUniqeFolder(); + } - @AfterClass - public static void tearDown() { - removeUniqueFolder(); - } + @AfterClass + public static void tearDown() { + removeUniqueFolder(); + } - @Test - public void attachPolicyToFileAndGetFilesUnderRetentionAndDeleteAttachment() throws InterruptedException { - //given - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder.Info folder = getUniqueFolder(api) + @Test + public void attachPolicyToFileAndGetFilesUnderRetentionAndDeleteAttachment() + throws InterruptedException { + // given + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder.Info folder = + getUniqueFolder(api) .createFolder(randomizeName("attachPolicyToFileAndGetFilesUnderRetention")); - try { - BoxRetentionPolicyAssignment.Info assignmentInfo = createAssignmentToFolder( - api, policy.getID(), folder.getID() - ); - BoxFile boxFile = uploadFileWithSomeContent("file_with_retention.txt", folder.getResource()); + try { + BoxRetentionPolicyAssignment.Info assignmentInfo = + createAssignmentToFolder(api, policy.getID(), folder.getID()); + 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 - List matchingFileWithRetention1 = - StreamSupport.stream(filesUnderRetention.spliterator(), false) - .filter(f -> f.getID().equals(boxFile.getID())) - .collect(Collectors.toList()); - assertThat(matchingFileWithRetention1, hasSize(1)); + // 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(50); + // when + assignment.delete(); + Retry.retry( + () -> { + Iterable filesUnderRetention2 = + new BoxRetentionPolicyAssignment(api, assignmentInfo.getID()) + .getFilesUnderRetention(50); - //then - List matchingFileWithRetention2 = - StreamSupport.stream(filesUnderRetention2.spliterator(), false) - .filter(f -> f.getID().equals(boxFile.getID())) - .collect(Collectors.toList()); - assertTrue(matchingFileWithRetention2.isEmpty()); - }, 10, 3000); - } finally { - //cleanup - deleteFolder(folder.getResource()); - } + // then + List matchingFileWithRetention2 = + StreamSupport.stream(filesUnderRetention2.spliterator(), false) + .filter(f -> f.getID().equals(boxFile.getID())) + .collect(Collectors.toList()); + assertTrue(matchingFileWithRetention2.isEmpty()); + }, + 10, + 3000); + } finally { + // cleanup + deleteFolder(folder.getResource()); } + } - @Test - public void attachPolicyToFileAndGetFileVersionsUnderRetentionAndDeleteAttachment() throws InterruptedException { - //given - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder folder = getUniqueFolder(api) + @Test + public void attachPolicyToFileAndGetFileVersionsUnderRetentionAndDeleteAttachment() + throws InterruptedException { + // given + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder folder = + getUniqueFolder(api) .createFolder(randomizeName("attachPolicyToFileAndGetFileVersionsUnderRetention")) .getResource(); - try { - BoxRetentionPolicyAssignment.Info assignmentInfo = createAssignmentToFolder( - api, policy.getID(), folder.getID() - ); - BoxFile boxFile = uploadTwoFileVersionsToSpecifiedFolder( - "file_with_retention.txt", - "v1", - "v2", - folder, - mock(ProgressListener.class) - ); + 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 filesVersionsUnderRetention1 = assignment.getFileVersionsUnderRetention(5); + // 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)); + // 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(50); + // when + assignment.delete(); + Retry.retry( + () -> { + Iterable filesVersionsUnderRetention2 = + assignment.getFileVersionsUnderRetention(50); - //then - List matchingFileWithRetention2 = - StreamSupport.stream(filesVersionsUnderRetention2.spliterator(), false) - .filter(f -> f.getID().equals(boxFile.getID())) - .collect(Collectors.toList()); - assertTrue(matchingFileWithRetention2.isEmpty()); - }, 10, 3000); - } finally { - //cleanup - deleteFolder(folder); - } + // then + List matchingFileWithRetention2 = + StreamSupport.stream(filesVersionsUnderRetention2.spliterator(), false) + .filter(f -> f.getID().equals(boxFile.getID())) + .collect(Collectors.toList()); + assertTrue(matchingFileWithRetention2.isEmpty()); + }, + 10, + 3000); + } finally { + // cleanup + deleteFolder(folder); } + } } diff --git a/src/intTest/java/com/box/sdk/BoxSignRequestIT.java b/src/intTest/java/com/box/sdk/BoxSignRequestIT.java index 8bfa2e108..4532030cc 100644 --- a/src/intTest/java/com/box/sdk/BoxSignRequestIT.java +++ b/src/intTest/java/com/box/sdk/BoxSignRequestIT.java @@ -27,223 +27,228 @@ import org.junit.BeforeClass; import org.junit.Test; -/** - * {@link BoxSignRequest} related integration tests. - */ +/** {@link BoxSignRequest} related integration tests. */ public class BoxSignRequestIT { - @BeforeClass - public static void setup() { - setupUniqeFolder(); - } - - @AfterClass - public static void tearDown() { - removeUniqueFolder(); - } - - @Test - public void createListAndCancelSignRequest() throws InterruptedException { - // Test Setup - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder uniqueFolder = getUniqueFolder(api); - String fileName = "file_to_sign.pdf"; - String file2Name = "file_to_sign2.pdf"; - BoxFile file = null; - BoxFile file2 = null; - BoxFolder signedFileFolder = null; - AtomicReference signRequestInfoCancel = new AtomicReference<>(); - - try { - - file = uploadSampleFileToUniqueFolder(api, fileName); - file2 = uploadSampleFileToUniqueFolder(api, file2Name); - List files = new ArrayList<>(); - files.add(new BoxSignRequestFile(file.getID())); - files.add(new BoxSignRequestFile(file2.getID())); - - String signerEmail = "user@example.com"; - Boolean signerLoginRequired = false; - String signerPassword = "password"; - Boolean signerSuppressNotifications = false; - String signerVerficationPhoneNumber = "+16314578901"; - - List signers = new ArrayList<>(); - BoxSignRequestSigner newSigner = new BoxSignRequestSigner(signerEmail).setInPerson(false) - .setLoginRequired(signerLoginRequired).setPassword(signerPassword) - .setSuppressNotifications(signerSuppressNotifications) - .setVerificationPhoneNumber(signerVerficationPhoneNumber); - signers.add(newSigner); - - signedFileFolder = uniqueFolder.createFolder("Folder - signRequestIntegrationTest").getResource(); - - // Do Create - List prefillTags = new ArrayList<>(); - Instant dateInstant = LocalDateTime.of(2021, 11, 20, 11, 0, 0) - .toInstant(UTC); - prefillTags.add(new BoxSignRequestPrefillTag(file.getID(), Date.from(dateInstant))); - BoxSignRequestCreateParams createParams = new BoxSignRequestCreateParams() - .setIsDocumentPreparationNeeded(true) - .setPrefillTags(prefillTags); - BoxSignRequest.Info signRequestInfoCreate = BoxSignRequest - .createSignRequest(api, files, signers, signedFileFolder.getID(), createParams); - - String signRequestIdCreate = signRequestInfoCreate.getID(); - BoxFile.Info fileInfoCreate = signRequestInfoCreate.getSourceFiles().get(0); - BoxFile.Info file2InfoCreate = signRequestInfoCreate.getSourceFiles().get(1); - - // todo: get signer by role type. Using index=1 is fragile, as order may not be guaranteed. - //signer at index 0 has role=final_copy_reader - //signer at index 1 has role=signer - BoxSignRequestSigner signerCreate = signRequestInfoCreate.getSigners().get(1); - - // Test Create - assertNotNull(signRequestInfoCreate.getPrepareUrl()); - // The order of the files in the response is not guaranteed - if (file.getID().equals(fileInfoCreate.getID())) { - assertEquals(file2.getID(), file2InfoCreate.getID()); - } else { - assertEquals(file.getID(), file2InfoCreate.getID()); - assertEquals(file2.getID(), fileInfoCreate.getID()); - } - assertEquals(signerEmail, signerCreate.getEmail()); - assertNotNull(signRequestInfoCreate.getID()); - - // Do Get by ID - BoxSignRequest signRequestGetByID = new BoxSignRequest(api, signRequestIdCreate); - BoxSignRequest.Info signRequestInfoGetByID = signRequestGetByID.getInfo(); - BoxFile.Info fileInfo = signRequestInfoGetByID.getSourceFiles().get(0); - BoxFile.Info file2Info = signRequestInfoGetByID.getSourceFiles().get(1); - BoxSignRequestPrefillTag prefillTag = signRequestInfoGetByID.getPrefillTags().get(0); - assertEquals(prefillTag.getDocumentTagId(), file.getID()); - assertEquals(BoxDateFormat.formatAsDateOnly(prefillTag.getDateValue()), "2021-11-20"); - - // Todo: get signer by role type. Using index=1 is fragile, as order may not be guaranteed. - //signer at index 0 has role=final_copy_reader - //signer at index 1 has role=signer - BoxSignRequestSigner signer = signRequestInfoGetByID.getSigners().get(1); - - // Test Get by ID - // The order of the files in the response is not guaranteed - if (file.getID().equals(fileInfo.getID())) { - assertEquals(file2.getID(), file2Info.getID()); - } else { - assertEquals(file.getID(), file2Info.getID()); - assertEquals(file2.getID(), fileInfo.getID()); - } - assertEquals(signerEmail, signer.getEmail()); - assertEquals(signRequestIdCreate, signRequestInfoGetByID.getID()); - assertEquals(signerLoginRequired, signer.getLoginRequired()); - assertEquals(signerSuppressNotifications, signer.getSuppressNotifications()); - assertEquals(signerVerficationPhoneNumber, signer.getVerificationPhoneNumber()); - - // Resend sign request - retry(signRequestGetByID::resend, 5, 500); - - // Do Get All - Iterable signRequestsGetAll = BoxSignRequest.getAll(api); - - // Test Get All - assertTrue(signRequestsGetAll.iterator().hasNext()); - - - // Do Cancel - // Cancel will fail if it's too soon after creation - retry(() -> signRequestInfoCancel.set(signRequestGetByID.cancel()), 5, 1000); - BoxSignRequest signRequestGetByIDAfterCancel = new BoxSignRequest(api, signRequestIdCreate); - BoxSignRequest.Info signRequestInfoAfterCancel = signRequestGetByIDAfterCancel.getInfo(); - BoxSignRequest.BoxSignRequestStatus signRequestStatusAfterCancel = signRequestInfoAfterCancel.getStatus(); - - // Test Cancel - assertNotNull("Expected Cancel Sign Request but got null", signRequestInfoCancel.get()); - assertEquals(BoxSignRequest.BoxSignRequestStatus.Cancelled, signRequestInfoCancel.get().getStatus()); - assertEquals(BoxSignRequest.BoxSignRequestStatus.Cancelled, signRequestStatusAfterCancel); - } finally { - if (signRequestInfoCancel.get() != null) { - // Clean up - List signRequestFiles = signRequestInfoCancel.get().getSignFiles().getFiles(); - for (BoxFile.Info signRequestFile : signRequestFiles) { - BoxFile fileToDelete = new BoxFile(api, signRequestFile.getID()); - fileToDelete.delete(); - } - } - deleteFile(file); - deleteFile(file2); - deleteFolder(signedFileFolder); + @BeforeClass + public static void setup() { + setupUniqeFolder(); + } + + @AfterClass + public static void tearDown() { + removeUniqueFolder(); + } + + @Test + public void createListAndCancelSignRequest() throws InterruptedException { + // Test Setup + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder uniqueFolder = getUniqueFolder(api); + String fileName = "file_to_sign.pdf"; + String file2Name = "file_to_sign2.pdf"; + BoxFile file = null; + BoxFile file2 = null; + BoxFolder signedFileFolder = null; + AtomicReference signRequestInfoCancel = new AtomicReference<>(); + + try { + + file = uploadSampleFileToUniqueFolder(api, fileName); + file2 = uploadSampleFileToUniqueFolder(api, file2Name); + List files = new ArrayList<>(); + files.add(new BoxSignRequestFile(file.getID())); + files.add(new BoxSignRequestFile(file2.getID())); + + String signerEmail = "user@example.com"; + Boolean signerLoginRequired = false; + String signerPassword = "password"; + Boolean signerSuppressNotifications = false; + String signerVerficationPhoneNumber = "+16314578901"; + + List signers = new ArrayList<>(); + BoxSignRequestSigner newSigner = + new BoxSignRequestSigner(signerEmail) + .setInPerson(false) + .setLoginRequired(signerLoginRequired) + .setPassword(signerPassword) + .setSuppressNotifications(signerSuppressNotifications) + .setVerificationPhoneNumber(signerVerficationPhoneNumber); + signers.add(newSigner); + + signedFileFolder = + uniqueFolder.createFolder("Folder - signRequestIntegrationTest").getResource(); + + // Do Create + List prefillTags = new ArrayList<>(); + Instant dateInstant = LocalDateTime.of(2021, 11, 20, 11, 0, 0).toInstant(UTC); + prefillTags.add(new BoxSignRequestPrefillTag(file.getID(), Date.from(dateInstant))); + BoxSignRequestCreateParams createParams = + new BoxSignRequestCreateParams() + .setIsDocumentPreparationNeeded(true) + .setPrefillTags(prefillTags); + BoxSignRequest.Info signRequestInfoCreate = + BoxSignRequest.createSignRequest( + api, files, signers, signedFileFolder.getID(), createParams); + + String signRequestIdCreate = signRequestInfoCreate.getID(); + BoxFile.Info fileInfoCreate = signRequestInfoCreate.getSourceFiles().get(0); + BoxFile.Info file2InfoCreate = signRequestInfoCreate.getSourceFiles().get(1); + + // todo: get signer by role type. Using index=1 is fragile, as order may not be guaranteed. + // signer at index 0 has role=final_copy_reader + // signer at index 1 has role=signer + BoxSignRequestSigner signerCreate = signRequestInfoCreate.getSigners().get(1); + + // Test Create + assertNotNull(signRequestInfoCreate.getPrepareUrl()); + // The order of the files in the response is not guaranteed + if (file.getID().equals(fileInfoCreate.getID())) { + assertEquals(file2.getID(), file2InfoCreate.getID()); + } else { + assertEquals(file.getID(), file2InfoCreate.getID()); + assertEquals(file2.getID(), fileInfoCreate.getID()); + } + assertEquals(signerEmail, signerCreate.getEmail()); + assertNotNull(signRequestInfoCreate.getID()); + + // Do Get by ID + BoxSignRequest signRequestGetByID = new BoxSignRequest(api, signRequestIdCreate); + BoxSignRequest.Info signRequestInfoGetByID = signRequestGetByID.getInfo(); + BoxFile.Info fileInfo = signRequestInfoGetByID.getSourceFiles().get(0); + BoxFile.Info file2Info = signRequestInfoGetByID.getSourceFiles().get(1); + BoxSignRequestPrefillTag prefillTag = signRequestInfoGetByID.getPrefillTags().get(0); + assertEquals(prefillTag.getDocumentTagId(), file.getID()); + assertEquals(BoxDateFormat.formatAsDateOnly(prefillTag.getDateValue()), "2021-11-20"); + + // Todo: get signer by role type. Using index=1 is fragile, as order may not be guaranteed. + // signer at index 0 has role=final_copy_reader + // signer at index 1 has role=signer + BoxSignRequestSigner signer = signRequestInfoGetByID.getSigners().get(1); + + // Test Get by ID + // The order of the files in the response is not guaranteed + if (file.getID().equals(fileInfo.getID())) { + assertEquals(file2.getID(), file2Info.getID()); + } else { + assertEquals(file.getID(), file2Info.getID()); + assertEquals(file2.getID(), fileInfo.getID()); + } + assertEquals(signerEmail, signer.getEmail()); + assertEquals(signRequestIdCreate, signRequestInfoGetByID.getID()); + assertEquals(signerLoginRequired, signer.getLoginRequired()); + assertEquals(signerSuppressNotifications, signer.getSuppressNotifications()); + assertEquals(signerVerficationPhoneNumber, signer.getVerificationPhoneNumber()); + + // Resend sign request + retry(signRequestGetByID::resend, 5, 500); + + // Do Get All + Iterable signRequestsGetAll = BoxSignRequest.getAll(api); + + // Test Get All + assertTrue(signRequestsGetAll.iterator().hasNext()); + + // Do Cancel + // Cancel will fail if it's too soon after creation + retry(() -> signRequestInfoCancel.set(signRequestGetByID.cancel()), 5, 1000); + BoxSignRequest signRequestGetByIDAfterCancel = new BoxSignRequest(api, signRequestIdCreate); + BoxSignRequest.Info signRequestInfoAfterCancel = signRequestGetByIDAfterCancel.getInfo(); + BoxSignRequest.BoxSignRequestStatus signRequestStatusAfterCancel = + signRequestInfoAfterCancel.getStatus(); + + // Test Cancel + assertNotNull("Expected Cancel Sign Request but got null", signRequestInfoCancel.get()); + assertEquals( + BoxSignRequest.BoxSignRequestStatus.Cancelled, signRequestInfoCancel.get().getStatus()); + assertEquals(BoxSignRequest.BoxSignRequestStatus.Cancelled, signRequestStatusAfterCancel); + } finally { + if (signRequestInfoCancel.get() != null) { + // Clean up + List signRequestFiles = signRequestInfoCancel.get().getSignFiles().getFiles(); + for (BoxFile.Info signRequestFile : signRequestFiles) { + BoxFile fileToDelete = new BoxFile(api, signRequestFile.getID()); + fileToDelete.delete(); } + } + deleteFile(file); + deleteFile(file2); + deleteFolder(signedFileFolder); } - - @Test - public void createSignRequestForGroup() throws InterruptedException { - // Test Setup - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder uniqueFolder = getUniqueFolder(api); - BoxFile file = null; - BoxFolder signedFileFolder = null; - BoxUser groupMemberUser1 = null; - BoxUser groupMemberUser2 = null; - String userName1 = randomizeName("login1") + "@boz.com"; - String userName2 = randomizeName("login2") + "@boz.com"; - AtomicReference signRequestInfoCancel = new AtomicReference<>(); - String signerGroupName = randomizeName("GroupName"); - - try { - groupMemberUser1 = BoxUser.createEnterpriseUser(api, userName1, "userName1").getResource(); - groupMemberUser2 = BoxUser.createEnterpriseUser(api, userName2, "userName2").getResource(); - - file = uploadSampleFileToUniqueFolder(api, "file_to_sign.pdf"); - List files = Collections.singletonList(new BoxSignRequestFile(file.getID())); - - List signers = new ArrayList<>(); - signers.add(new BoxSignRequestSigner(userName1).setSignerGroupId(signerGroupName)); - signers.add(new BoxSignRequestSigner(userName2).setSignerGroupId(signerGroupName)); - - signedFileFolder = uniqueFolder.createFolder("Folder - signRequestGroupIntegrationTest").getResource(); - - // Do Create - BoxSignRequest.Info signRequestInfoCreate = BoxSignRequest - .createSignRequest(api, files, signers, signedFileFolder.getID()); - - String signRequestIdCreate = signRequestInfoCreate.getID(); - List createdSigners = signRequestInfoCreate.getSigners(); - BoxSignRequestSigner createdSigner1 = createdSigners.get(1); - BoxSignRequestSigner createdSigner2 = createdSigners.get(2); - - // Test Create - assertNotNull(signRequestInfoCreate.getID()); - assertEquals(createdSigners.size(), 3); - assertEquals(createdSigner1.getSignerGroupId(), createdSigner2.getSignerGroupId()); - assertNotEquals(createdSigner1.getSignerGroupId(), signerGroupName); - - // Do Get by ID - BoxSignRequest signRequestGetByID = new BoxSignRequest(api, signRequestIdCreate); - - List signersGet = signRequestGetByID.getInfo().getSigners(); - BoxSignRequestSigner signer1Get = signersGet.get(1); - BoxSignRequestSigner signer2Get = createdSigners.get(2); - - // Test Get - assertNotNull(signRequestInfoCreate.getID()); - assertEquals(signersGet.size(), 3); - assertEquals(signer1Get.getSignerGroupId(), signer2Get.getSignerGroupId()); - assertEquals(signer1Get.getSignerGroupId(), createdSigner1.getSignerGroupId()); - - retry(() -> signRequestInfoCancel.set(signRequestGetByID.cancel()), 5, 1000); - - } finally { - deleteUser(groupMemberUser1); - deleteUser(groupMemberUser2); - - if (signRequestInfoCancel.get() != null) { - // Clean up - List signRequestFiles = signRequestInfoCancel.get().getSignFiles().getFiles(); - for (BoxFile.Info signRequestFile : signRequestFiles) { - BoxFile fileToDelete = new BoxFile(api, signRequestFile.getID()); - fileToDelete.delete(); - } - } - deleteFile(file); - deleteFolder(signedFileFolder); + } + + @Test + public void createSignRequestForGroup() throws InterruptedException { + // Test Setup + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder uniqueFolder = getUniqueFolder(api); + BoxFile file = null; + BoxFolder signedFileFolder = null; + BoxUser groupMemberUser1 = null; + BoxUser groupMemberUser2 = null; + String userName1 = randomizeName("login1") + "@boz.com"; + String userName2 = randomizeName("login2") + "@boz.com"; + AtomicReference signRequestInfoCancel = new AtomicReference<>(); + String signerGroupName = randomizeName("GroupName"); + + try { + groupMemberUser1 = BoxUser.createEnterpriseUser(api, userName1, "userName1").getResource(); + groupMemberUser2 = BoxUser.createEnterpriseUser(api, userName2, "userName2").getResource(); + + file = uploadSampleFileToUniqueFolder(api, "file_to_sign.pdf"); + List files = + Collections.singletonList(new BoxSignRequestFile(file.getID())); + + List signers = new ArrayList<>(); + signers.add(new BoxSignRequestSigner(userName1).setSignerGroupId(signerGroupName)); + signers.add(new BoxSignRequestSigner(userName2).setSignerGroupId(signerGroupName)); + + signedFileFolder = + uniqueFolder.createFolder("Folder - signRequestGroupIntegrationTest").getResource(); + + // Do Create + BoxSignRequest.Info signRequestInfoCreate = + BoxSignRequest.createSignRequest(api, files, signers, signedFileFolder.getID()); + + String signRequestIdCreate = signRequestInfoCreate.getID(); + List createdSigners = signRequestInfoCreate.getSigners(); + BoxSignRequestSigner createdSigner1 = createdSigners.get(1); + BoxSignRequestSigner createdSigner2 = createdSigners.get(2); + + // Test Create + assertNotNull(signRequestInfoCreate.getID()); + assertEquals(createdSigners.size(), 3); + assertEquals(createdSigner1.getSignerGroupId(), createdSigner2.getSignerGroupId()); + assertNotEquals(createdSigner1.getSignerGroupId(), signerGroupName); + + // Do Get by ID + BoxSignRequest signRequestGetByID = new BoxSignRequest(api, signRequestIdCreate); + + List signersGet = signRequestGetByID.getInfo().getSigners(); + BoxSignRequestSigner signer1Get = signersGet.get(1); + BoxSignRequestSigner signer2Get = createdSigners.get(2); + + // Test Get + assertNotNull(signRequestInfoCreate.getID()); + assertEquals(signersGet.size(), 3); + assertEquals(signer1Get.getSignerGroupId(), signer2Get.getSignerGroupId()); + assertEquals(signer1Get.getSignerGroupId(), createdSigner1.getSignerGroupId()); + + retry(() -> signRequestInfoCancel.set(signRequestGetByID.cancel()), 5, 1000); + + } finally { + deleteUser(groupMemberUser1); + deleteUser(groupMemberUser2); + + if (signRequestInfoCancel.get() != null) { + // Clean up + List signRequestFiles = signRequestInfoCancel.get().getSignFiles().getFiles(); + for (BoxFile.Info signRequestFile : signRequestFiles) { + BoxFile fileToDelete = new BoxFile(api, signRequestFile.getID()); + fileToDelete.delete(); } + } + deleteFile(file); + deleteFolder(signedFileFolder); } + } } - diff --git a/src/intTest/java/com/box/sdk/BoxTaskIT.java b/src/intTest/java/com/box/sdk/BoxTaskIT.java index 586ecc3ef..0bcb80014 100644 --- a/src/intTest/java/com/box/sdk/BoxTaskIT.java +++ b/src/intTest/java/com/box/sdk/BoxTaskIT.java @@ -16,48 +16,46 @@ import org.junit.BeforeClass; import org.junit.Test; -/** - * {@link BoxTask} related integration tests. - */ +/** {@link BoxTask} related integration tests. */ public class BoxTaskIT { - @BeforeClass - public static void beforeClass() { - setupUniqeFolder(); - } - - @After - public void tearDown() { - removeUniqueFolder(); - } - - @Test - public void updateInfoSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - String fileName = "[updateInfoSucceeds] Test File.txt"; - String originalMessage = "Original message"; - String changedMessage = "Changed message"; - BoxFile uploadedFile = null; - - try { - uploadedFile = uploadFileToUniqueFolderWithSomeContent(api, fileName); - Calendar calendar = new GregorianCalendar(); - calendar.set(Calendar.SECOND, 0); - calendar.set(Calendar.MILLISECOND, 0); - calendar.add(Calendar.DATE, 1); - Date dueAt = calendar.getTime(); - - BoxTask.Info taskInfo = uploadedFile.addTask(BoxTask.Action.REVIEW, originalMessage, dueAt); - - BoxTask task = taskInfo.getResource(); - taskInfo.setMessage(changedMessage); - taskInfo.setDueAt(dueAt); - task.updateInfo(taskInfo); - - assertThat(taskInfo.getMessage(), is(equalTo(changedMessage))); - assertThat(taskInfo.getDueAt(), is(equalTo(dueAt))); - } finally { - deleteFile(uploadedFile); - } + @BeforeClass + public static void beforeClass() { + setupUniqeFolder(); + } + + @After + public void tearDown() { + removeUniqueFolder(); + } + + @Test + public void updateInfoSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String fileName = "[updateInfoSucceeds] Test File.txt"; + String originalMessage = "Original message"; + String changedMessage = "Changed message"; + BoxFile uploadedFile = null; + + try { + uploadedFile = uploadFileToUniqueFolderWithSomeContent(api, fileName); + Calendar calendar = new GregorianCalendar(); + calendar.set(Calendar.SECOND, 0); + calendar.set(Calendar.MILLISECOND, 0); + calendar.add(Calendar.DATE, 1); + Date dueAt = calendar.getTime(); + + BoxTask.Info taskInfo = uploadedFile.addTask(BoxTask.Action.REVIEW, originalMessage, dueAt); + + BoxTask task = taskInfo.getResource(); + taskInfo.setMessage(changedMessage); + taskInfo.setDueAt(dueAt); + task.updateInfo(taskInfo); + + assertThat(taskInfo.getMessage(), is(equalTo(changedMessage))); + assertThat(taskInfo.getDueAt(), is(equalTo(dueAt))); + } finally { + deleteFile(uploadedFile); } + } } diff --git a/src/intTest/java/com/box/sdk/BoxTermsOfServiceIT.java b/src/intTest/java/com/box/sdk/BoxTermsOfServiceIT.java index 2cee70f68..05ca45b4c 100644 --- a/src/intTest/java/com/box/sdk/BoxTermsOfServiceIT.java +++ b/src/intTest/java/com/box/sdk/BoxTermsOfServiceIT.java @@ -10,36 +10,37 @@ @Ignore("Terms of servcie are disabled on test account") public class BoxTermsOfServiceIT { - @Test - public void getAllTermsOfServicesWithNoParamSucceeds() { - final String tosType = "terms_of_service"; + @Test + public void getAllTermsOfServicesWithNoParamSucceeds() { + final String tosType = "terms_of_service"; - BoxAPIConnection api = new BoxAPIConnection(TestConfig.getAccessToken()); + BoxAPIConnection api = new BoxAPIConnection(TestConfig.getAccessToken()); - List termsOfServicesInfo = BoxTermsOfService.getAllTermsOfServices(api); + List termsOfServicesInfo = BoxTermsOfService.getAllTermsOfServices(api); - for (BoxTermsOfService.Info info : termsOfServicesInfo) { - assertNotNull(info); - assertNotNull(info.getEnterprise()); - assertEquals(tosType, info.getType()); - } + for (BoxTermsOfService.Info info : termsOfServicesInfo) { + assertNotNull(info); + assertNotNull(info.getEnterprise()); + assertEquals(tosType, info.getType()); } + } - @Test - public void getAllTermsOfServicesWithParamSucceeds() { - final String type = "terms_of_service"; - final BoxTermsOfService.TermsOfServiceType tosType = BoxTermsOfService.TermsOfServiceType.MANAGED; + @Test + public void getAllTermsOfServicesWithParamSucceeds() { + final String type = "terms_of_service"; + final BoxTermsOfService.TermsOfServiceType tosType = + BoxTermsOfService.TermsOfServiceType.MANAGED; - BoxAPIConnection api = new BoxAPIConnection(TestConfig.getAccessToken()); + BoxAPIConnection api = new BoxAPIConnection(TestConfig.getAccessToken()); - List termsOfServicesInfo = BoxTermsOfService.getAllTermsOfServices(api, - BoxTermsOfService.TermsOfServiceType.MANAGED); + List termsOfServicesInfo = + BoxTermsOfService.getAllTermsOfServices(api, BoxTermsOfService.TermsOfServiceType.MANAGED); - for (BoxTermsOfService.Info info : termsOfServicesInfo) { - assertNotNull(info); - assertNotNull(info.getEnterprise()); - assertEquals(tosType, info.getTosType()); - assertEquals(type, info.getType()); - } + for (BoxTermsOfService.Info info : termsOfServicesInfo) { + assertNotNull(info); + assertNotNull(info.getEnterprise()); + assertEquals(tosType, info.getTosType()); + assertEquals(type, info.getType()); } + } } diff --git a/src/intTest/java/com/box/sdk/BoxTransactionalAPIConnectionIT.java b/src/intTest/java/com/box/sdk/BoxTransactionalAPIConnectionIT.java index 3a52010c3..dc93dc5df 100644 --- a/src/intTest/java/com/box/sdk/BoxTransactionalAPIConnectionIT.java +++ b/src/intTest/java/com/box/sdk/BoxTransactionalAPIConnectionIT.java @@ -14,96 +14,97 @@ @Ignore("Setup JWT connection") public class BoxTransactionalAPIConnectionIT { - @Test - public void successfullyCreatesTransactionalConnection() { - final String transactionalAccessToken = TestConfig.getTransactionalAccessToken(); - - BoxAPIConnection transactionConnection = BoxTransactionalAPIConnection - .getTransactionConnection(transactionalAccessToken, "item_preview"); - assertThat(transactionConnection.getAccessToken(), is(notNullValue())); - } - - @Test - public void successfullyCreatesEmbedLinkWithTransactionalConnection() { - final String transactionalAccessToken = TestConfig.getTransactionalAccessToken(); - - BoxAPIConnection api = new BoxAPIConnection(transactionalAccessToken); - BoxFolder rootFolder = BoxFolder.getRootFolder(api); - String fileName = "[successfullyCreatesEmbedLinkWithTransactionalConnection] Test File.txt"; - String fileContent = "Test file"; - byte[] fileBytes = fileContent.getBytes(StandardCharsets.UTF_8); - - InputStream uploadStream = new ByteArrayInputStream(fileBytes); - BoxFile uploadedFileOne = rootFolder.uploadFile(uploadStream, fileName).getResource(); - BoxFile uploadedFileTwo = rootFolder.uploadFile(uploadStream, fileName).getResource(); - - BoxAPIConnection transactionConnection = BoxTransactionalAPIConnection - .getTransactionConnection(transactionalAccessToken, "item_preview"); - - // Transactional connection should be able to generate preview - // link for any file since it is not resource scoped - BoxFile transactionalFileOne = new BoxFile(transactionConnection, uploadedFileOne.getID()); - URL transactionalFileOnePreviewLink = transactionalFileOne.getPreviewLink(); - - assertThat(transactionalFileOnePreviewLink, is(notNullValue())); - assertThat(transactionalFileOnePreviewLink.toString(), not(is(emptyOrNullString()))); - - BoxFile transactionalFileTwo = new BoxFile(transactionConnection, uploadedFileTwo.getID()); - URL transactionalFileTwoPreviewLink = transactionalFileTwo.getPreviewLink(); - - assertThat(transactionalFileTwoPreviewLink, is(notNullValue())); - assertThat(transactionalFileTwoPreviewLink.toString(), not(is(emptyOrNullString()))); - } - - @Test - public void successfullyCreatesEmbedLinkWithResourceScopedTransactionalConnection() { - final String transactionalAccessToken = TestConfig.getTransactionalAccessToken(); - - BoxAPIConnection api = new BoxAPIConnection(transactionalAccessToken); - BoxFolder rootFolder = BoxFolder.getRootFolder(api); - String fileName = "[successfullyCreatesEmbedLinkWithTransactionalConnection] Test File.txt"; - String fileContent = "Test file"; - byte[] fileBytes = fileContent.getBytes(StandardCharsets.UTF_8); - - InputStream uploadStream = new ByteArrayInputStream(fileBytes); - BoxFile uploadedFile = rootFolder.uploadFile(uploadStream, fileName).getResource(); - - BoxAPIConnection transactionConnection = BoxTransactionalAPIConnection - .getTransactionConnection( - transactionalAccessToken, - "item_preview", - "https://api.box.com/2.0/files/" + uploadedFile.getID() - ); - - BoxFile transactionalFile = new BoxFile(transactionConnection, uploadedFile.getID()); - URL transactionalFilePreviewLink = transactionalFile.getPreviewLink(); - - assertThat(transactionalFilePreviewLink, is(notNullValue())); - assertThat(transactionalFilePreviewLink.toString(), not(is(emptyOrNullString()))); - } - - @Test(expected = BoxAPIException.class) - public void throwsWhenAttemptingToCreatesEmbedLinkWithAnotherFilesResourceScopedTransactionalConnection() { - final String transactionalAccessToken = TestConfig.getTransactionalAccessToken(); - - BoxAPIConnection api = new BoxAPIConnection(transactionalAccessToken); - BoxFolder rootFolder = BoxFolder.getRootFolder(api); - String fileName = "[successfullyCreatesEmbedLinkWithTransactionalConnection] Test File.txt"; - String fileContent = "Test file"; - byte[] fileBytes = fileContent.getBytes(StandardCharsets.UTF_8); - - InputStream uploadStream = new ByteArrayInputStream(fileBytes); - BoxFile uploadedFileOne = rootFolder.uploadFile(uploadStream, fileName).getResource(); - BoxFile uploadedFileTwo = rootFolder.uploadFile(uploadStream, fileName).getResource(); - - BoxAPIConnection transactionConnection = BoxTransactionalAPIConnection - .getTransactionConnection( - transactionalAccessToken, - "item_preview", - "https://api.box.com/2.0/files/" + uploadedFileOne.getID() - ); - - BoxFile transactionalFileTwo = new BoxFile(transactionConnection, uploadedFileTwo.getID()); - transactionalFileTwo.getPreviewLink(); - } + @Test + public void successfullyCreatesTransactionalConnection() { + final String transactionalAccessToken = TestConfig.getTransactionalAccessToken(); + + BoxAPIConnection transactionConnection = + BoxTransactionalAPIConnection.getTransactionConnection( + transactionalAccessToken, "item_preview"); + assertThat(transactionConnection.getAccessToken(), is(notNullValue())); + } + + @Test + public void successfullyCreatesEmbedLinkWithTransactionalConnection() { + final String transactionalAccessToken = TestConfig.getTransactionalAccessToken(); + + BoxAPIConnection api = new BoxAPIConnection(transactionalAccessToken); + BoxFolder rootFolder = BoxFolder.getRootFolder(api); + String fileName = "[successfullyCreatesEmbedLinkWithTransactionalConnection] Test File.txt"; + String fileContent = "Test file"; + byte[] fileBytes = fileContent.getBytes(StandardCharsets.UTF_8); + + InputStream uploadStream = new ByteArrayInputStream(fileBytes); + BoxFile uploadedFileOne = rootFolder.uploadFile(uploadStream, fileName).getResource(); + BoxFile uploadedFileTwo = rootFolder.uploadFile(uploadStream, fileName).getResource(); + + BoxAPIConnection transactionConnection = + BoxTransactionalAPIConnection.getTransactionConnection( + transactionalAccessToken, "item_preview"); + + // Transactional connection should be able to generate preview + // link for any file since it is not resource scoped + BoxFile transactionalFileOne = new BoxFile(transactionConnection, uploadedFileOne.getID()); + URL transactionalFileOnePreviewLink = transactionalFileOne.getPreviewLink(); + + assertThat(transactionalFileOnePreviewLink, is(notNullValue())); + assertThat(transactionalFileOnePreviewLink.toString(), not(is(emptyOrNullString()))); + + BoxFile transactionalFileTwo = new BoxFile(transactionConnection, uploadedFileTwo.getID()); + URL transactionalFileTwoPreviewLink = transactionalFileTwo.getPreviewLink(); + + assertThat(transactionalFileTwoPreviewLink, is(notNullValue())); + assertThat(transactionalFileTwoPreviewLink.toString(), not(is(emptyOrNullString()))); + } + + @Test + public void successfullyCreatesEmbedLinkWithResourceScopedTransactionalConnection() { + final String transactionalAccessToken = TestConfig.getTransactionalAccessToken(); + + BoxAPIConnection api = new BoxAPIConnection(transactionalAccessToken); + BoxFolder rootFolder = BoxFolder.getRootFolder(api); + String fileName = "[successfullyCreatesEmbedLinkWithTransactionalConnection] Test File.txt"; + String fileContent = "Test file"; + byte[] fileBytes = fileContent.getBytes(StandardCharsets.UTF_8); + + InputStream uploadStream = new ByteArrayInputStream(fileBytes); + BoxFile uploadedFile = rootFolder.uploadFile(uploadStream, fileName).getResource(); + + BoxAPIConnection transactionConnection = + BoxTransactionalAPIConnection.getTransactionConnection( + transactionalAccessToken, + "item_preview", + "https://api.box.com/2.0/files/" + uploadedFile.getID()); + + BoxFile transactionalFile = new BoxFile(transactionConnection, uploadedFile.getID()); + URL transactionalFilePreviewLink = transactionalFile.getPreviewLink(); + + assertThat(transactionalFilePreviewLink, is(notNullValue())); + assertThat(transactionalFilePreviewLink.toString(), not(is(emptyOrNullString()))); + } + + @Test(expected = BoxAPIException.class) + public void + throwsWhenAttemptingToCreatesEmbedLinkWithAnotherFilesResourceScopedTransactionalConnection() { + final String transactionalAccessToken = TestConfig.getTransactionalAccessToken(); + + BoxAPIConnection api = new BoxAPIConnection(transactionalAccessToken); + BoxFolder rootFolder = BoxFolder.getRootFolder(api); + String fileName = "[successfullyCreatesEmbedLinkWithTransactionalConnection] Test File.txt"; + String fileContent = "Test file"; + byte[] fileBytes = fileContent.getBytes(StandardCharsets.UTF_8); + + InputStream uploadStream = new ByteArrayInputStream(fileBytes); + BoxFile uploadedFileOne = rootFolder.uploadFile(uploadStream, fileName).getResource(); + BoxFile uploadedFileTwo = rootFolder.uploadFile(uploadStream, fileName).getResource(); + + BoxAPIConnection transactionConnection = + BoxTransactionalAPIConnection.getTransactionConnection( + transactionalAccessToken, + "item_preview", + "https://api.box.com/2.0/files/" + uploadedFileOne.getID()); + + BoxFile transactionalFileTwo = new BoxFile(transactionConnection, uploadedFileTwo.getID()); + transactionalFileTwo.getPreviewLink(); + } } diff --git a/src/intTest/java/com/box/sdk/BoxTrashIT.java b/src/intTest/java/com/box/sdk/BoxTrashIT.java index b2623e73a..7c2c25464 100644 --- a/src/intTest/java/com/box/sdk/BoxTrashIT.java +++ b/src/intTest/java/com/box/sdk/BoxTrashIT.java @@ -21,201 +21,209 @@ import org.junit.Test; public class BoxTrashIT { - @BeforeClass - public static void setup() { - setupUniqeFolder(); + @BeforeClass + public static void setup() { + setupUniqeFolder(); + } + + @AfterClass + public static void tearDown() { + removeUniqueFolder(); + } + + @Test + public void getAllTrashedItems() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxTrash trash = new BoxTrash(api); + BoxFolder rootFolder = getUniqueFolder(api); + BoxFolder trashedFolder = + rootFolder.createFolder("[getAllTrashedItems] Trashed Folder").getResource(); + trashedFolder.delete(false); + + BoxItem.Info someItemFromTrash = trash.iterator().next(); + + assertThat(someItemFromTrash, not(nullValue())); + } + + @Test + public void getAllTrashedItemsWithLimit() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxTrash trash = new BoxTrash(api); + BoxFolder rootFolder = getUniqueFolder(api); + BoxFolder trashedFolder = + rootFolder.createFolder("[getAllTrashedItemsWithLimit] Trashed Folder").getResource(); + trashedFolder.delete(false); + + BoxItem.Info someItemFromTrash = + trash.items(SortParameters.none(), PagingParameters.offset(0, 1)).iterator().next(); + + assertThat(someItemFromTrash, not(nullValue())); + } + + @Test + public void getTrashedFolderInfo() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxTrash trash = new BoxTrash(api); + BoxFolder rootFolder = getUniqueFolder(api); + String trashedFolderName = "[getTrashedFolderInfo] Trashed Folder"; + BoxFolder trashedFolder = rootFolder.createFolder(trashedFolderName).getResource(); + trashedFolder.delete(false); + + BoxFolder.Info info = trash.getFolderInfo(trashedFolder.getID()); + + assertThat(info.getName(), is(equalTo(trashedFolderName))); + assertThat(info.getItemStatus(), is(equalTo("trashed"))); + } + + @Test + public void permanentlyDeleteTrashedFolder() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxTrash trash = new BoxTrash(api); + BoxFolder rootFolder = getUniqueFolder(api); + String folderName = "[permanentlyDeleteTrashedFolder] Trashed Folder"; + + BoxFolder folder = rootFolder.createFolder(folderName).getResource(); + folder.delete(false); + trash.deleteFolder(folder.getID()); + + assertFolderIsNotTrashed(trash, folder); + } + + @Test + public void restoreTrashedFolderSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxTrash trash = new BoxTrash(api); + BoxFolder rootFolder = getUniqueFolder(api); + String folderName = "[restoreTrashedFolderWithNewNameSucceeds] Trashed Folder"; + + BoxFolder folder = rootFolder.createFolder(folderName).getResource(); + folder.delete(false); + trash.restoreFolder(folder.getID()); + + assertFolderIsNotTrashed(trash, folder); + assertThat( + rootFolder, hasItem(Matchers.hasProperty("ID", equalTo(folder.getID())))); + folder.delete(false); + } + + @Test + public void restoreTrashedFolderWithNewNameSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxTrash trash = new BoxTrash(api); + BoxFolder rootFolder = getUniqueFolder(api); + String folderName = "[restoreTrashedFolderWithNewNameSucceeds] Trashed Folder"; + String restoredFolderName = "[restoreTrashedFolderWithNewNameSucceeds] Trashed Folder"; + BoxFolder folder = null; + + try { + folder = rootFolder.createFolder(folderName).getResource(); + folder.delete(false); + BoxFolder.Info restoredFolderInfo = + trash.restoreFolder(folder.getID(), restoredFolderName, null); + + assertThat(restoredFolderInfo.getName(), is(equalTo(restoredFolderName))); + assertFolderIsNotTrashed(trash, folder); + assertThat( + rootFolder, hasItem(Matchers.hasProperty("ID", equalTo(folder.getID())))); + } finally { + CleanupTools.deleteFolder(folder); } - - @AfterClass - public static void tearDown() { - removeUniqueFolder(); - } - - @Test - public void getAllTrashedItems() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxTrash trash = new BoxTrash(api); - BoxFolder rootFolder = getUniqueFolder(api); - BoxFolder trashedFolder = rootFolder.createFolder("[getAllTrashedItems] Trashed Folder").getResource(); - trashedFolder.delete(false); - - BoxItem.Info someItemFromTrash = trash.iterator().next(); - - assertThat(someItemFromTrash, not(nullValue())); - } - - @Test - public void getAllTrashedItemsWithLimit() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxTrash trash = new BoxTrash(api); - BoxFolder rootFolder = getUniqueFolder(api); - BoxFolder trashedFolder = rootFolder.createFolder("[getAllTrashedItemsWithLimit] Trashed Folder") - .getResource(); - trashedFolder.delete(false); - - BoxItem.Info someItemFromTrash = trash.items(SortParameters.none(), PagingParameters.offset(0, 1)) - .iterator().next(); - - assertThat(someItemFromTrash, not(nullValue())); - } - - @Test - public void getTrashedFolderInfo() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxTrash trash = new BoxTrash(api); - BoxFolder rootFolder = getUniqueFolder(api); - String trashedFolderName = "[getTrashedFolderInfo] Trashed Folder"; - BoxFolder trashedFolder = rootFolder.createFolder(trashedFolderName).getResource(); - trashedFolder.delete(false); - - BoxFolder.Info info = trash.getFolderInfo(trashedFolder.getID()); - - assertThat(info.getName(), is(equalTo(trashedFolderName))); - assertThat(info.getItemStatus(), is(equalTo("trashed"))); - } - - @Test - public void permanentlyDeleteTrashedFolder() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxTrash trash = new BoxTrash(api); - BoxFolder rootFolder = getUniqueFolder(api); - String folderName = "[permanentlyDeleteTrashedFolder] Trashed Folder"; - - BoxFolder folder = rootFolder.createFolder(folderName).getResource(); - folder.delete(false); - trash.deleteFolder(folder.getID()); - - assertFolderIsNotTrashed(trash, folder); + } + + @Test + public void getTrashedFileInfo() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxTrash trash = new BoxTrash(api); + BoxFolder rootFolder = getUniqueFolder(api); + String fileName = "[getTrashedFileInfo] Trashed File.txt"; + String fileContent = "Trashed file"; + byte[] fileBytes = fileContent.getBytes(StandardCharsets.UTF_8); + + InputStream uploadStream = new ByteArrayInputStream(fileBytes); + BoxFile uploadedFile = rootFolder.uploadFile(uploadStream, fileName).getResource(); + uploadedFile.delete(); + + BoxFile.Info trashedFileInfo = trash.getFileInfo(uploadedFile.getID()); + + assertThat(trashedFileInfo.getName(), is(equalTo(fileName))); + assertThat(trashedFileInfo.getItemStatus(), is(equalTo("trashed"))); + } + + @Test + public void permanentlyDeleteTrashedFile() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxTrash trash = new BoxTrash(api); + BoxFolder rootFolder = getUniqueFolder(api); + String fileName = "[permanentlyDeleteTrashedFile] Trashed File.txt"; + String fileContent = "Trashed file"; + byte[] fileBytes = fileContent.getBytes(StandardCharsets.UTF_8); + + InputStream uploadStream = new ByteArrayInputStream(fileBytes); + BoxFile uploadedFile = rootFolder.uploadFile(uploadStream, fileName).getResource(); + uploadedFile.delete(); + trash.deleteFile(uploadedFile.getID()); + + assertFileIsNotTrashed(trash, uploadedFile); + } + + @Test + public void restoreTrashedFileSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxTrash trash = new BoxTrash(api); + BoxFolder rootFolder = getUniqueFolder(api); + String fileName = "[restoreTrashedFileSucceeds] Trashed File.txt"; + BoxFile uploadedFile = null; + try { + uploadedFile = uploadFileToUniqueFolderWithSomeContent(api, fileName); + uploadedFile.delete(); + trash.restoreFile(uploadedFile.getID()); + + assertFileIsNotTrashed(trash, uploadedFile); + assertThat( + rootFolder, + hasItem(Matchers.hasProperty("ID", equalTo(uploadedFile.getID())))); + } finally { + deleteFile(uploadedFile); } - - @Test - public void restoreTrashedFolderSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxTrash trash = new BoxTrash(api); - BoxFolder rootFolder = getUniqueFolder(api); - String folderName = "[restoreTrashedFolderWithNewNameSucceeds] Trashed Folder"; - - BoxFolder folder = rootFolder.createFolder(folderName).getResource(); - folder.delete(false); - trash.restoreFolder(folder.getID()); - - assertFolderIsNotTrashed(trash, folder); - assertThat(rootFolder, hasItem(Matchers.hasProperty("ID", equalTo(folder.getID())))); - folder.delete(false); - } - - @Test - public void restoreTrashedFolderWithNewNameSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxTrash trash = new BoxTrash(api); - BoxFolder rootFolder = getUniqueFolder(api); - String folderName = "[restoreTrashedFolderWithNewNameSucceeds] Trashed Folder"; - String restoredFolderName = "[restoreTrashedFolderWithNewNameSucceeds] Trashed Folder"; - BoxFolder folder = null; - - try { - folder = rootFolder.createFolder(folderName).getResource(); - folder.delete(false); - BoxFolder.Info restoredFolderInfo = trash.restoreFolder(folder.getID(), restoredFolderName, null); - - assertThat(restoredFolderInfo.getName(), is(equalTo(restoredFolderName))); - assertFolderIsNotTrashed(trash, folder); - assertThat(rootFolder, hasItem(Matchers.hasProperty("ID", equalTo(folder.getID())))); - } finally { - CleanupTools.deleteFolder(folder); - } - } - - @Test - public void getTrashedFileInfo() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxTrash trash = new BoxTrash(api); - BoxFolder rootFolder = getUniqueFolder(api); - String fileName = "[getTrashedFileInfo] Trashed File.txt"; - String fileContent = "Trashed file"; - byte[] fileBytes = fileContent.getBytes(StandardCharsets.UTF_8); - - InputStream uploadStream = new ByteArrayInputStream(fileBytes); - BoxFile uploadedFile = rootFolder.uploadFile(uploadStream, fileName).getResource(); - uploadedFile.delete(); - - BoxFile.Info trashedFileInfo = trash.getFileInfo(uploadedFile.getID()); - - assertThat(trashedFileInfo.getName(), is(equalTo(fileName))); - assertThat(trashedFileInfo.getItemStatus(), is(equalTo("trashed"))); - } - - @Test - public void permanentlyDeleteTrashedFile() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxTrash trash = new BoxTrash(api); - BoxFolder rootFolder = getUniqueFolder(api); - String fileName = "[permanentlyDeleteTrashedFile] Trashed File.txt"; - String fileContent = "Trashed file"; - byte[] fileBytes = fileContent.getBytes(StandardCharsets.UTF_8); - - InputStream uploadStream = new ByteArrayInputStream(fileBytes); - BoxFile uploadedFile = rootFolder.uploadFile(uploadStream, fileName).getResource(); - uploadedFile.delete(); - trash.deleteFile(uploadedFile.getID()); - - assertFileIsNotTrashed(trash, uploadedFile); - } - - @Test - public void restoreTrashedFileSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxTrash trash = new BoxTrash(api); - BoxFolder rootFolder = getUniqueFolder(api); - String fileName = "[restoreTrashedFileSucceeds] Trashed File.txt"; - BoxFile uploadedFile = null; - try { - uploadedFile = uploadFileToUniqueFolderWithSomeContent(api, fileName); - uploadedFile.delete(); - trash.restoreFile(uploadedFile.getID()); - - assertFileIsNotTrashed(trash, uploadedFile); - assertThat(rootFolder, hasItem(Matchers.hasProperty("ID", equalTo(uploadedFile.getID())))); - } finally { - deleteFile(uploadedFile); - } - - } - - @Test - public void restoreTrashedFileWithNewNameSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxTrash trash = new BoxTrash(api); - BoxFolder rootFolder = getUniqueFolder(api); - String fileName = "[restoreTrashedFileWithNewNameSucceeds] Trashed File.txt"; - String restoredFileName = "[restoreTrashedFileWithNewNameSucceeds] Restored File.txt"; - BoxFile uploadedFile = null; - try { - uploadedFile = uploadFileToUniqueFolderWithSomeContent(api, fileName); - uploadedFile.delete(); - BoxFile.Info restoredFileInfo = trash.restoreFile(uploadedFile.getID(), restoredFileName, null); - - assertThat(restoredFileInfo.getName(), is(equalTo(restoredFileName))); - assertFileIsNotTrashed(trash, uploadedFile); - assertThat(rootFolder, hasItem(Matchers.hasProperty("ID", equalTo(uploadedFile.getID())))); - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void restoreTrashedFileWithNewNameSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxTrash trash = new BoxTrash(api); + BoxFolder rootFolder = getUniqueFolder(api); + String fileName = "[restoreTrashedFileWithNewNameSucceeds] Trashed File.txt"; + String restoredFileName = "[restoreTrashedFileWithNewNameSucceeds] Restored File.txt"; + BoxFile uploadedFile = null; + try { + uploadedFile = uploadFileToUniqueFolderWithSomeContent(api, fileName); + uploadedFile.delete(); + BoxFile.Info restoredFileInfo = + trash.restoreFile(uploadedFile.getID(), restoredFileName, null); + + assertThat(restoredFileInfo.getName(), is(equalTo(restoredFileName))); + assertFileIsNotTrashed(trash, uploadedFile); + assertThat( + rootFolder, + hasItem(Matchers.hasProperty("ID", equalTo(uploadedFile.getID())))); + } finally { + deleteFile(uploadedFile); } + } - private void assertFileIsNotTrashed(BoxTrash trash, BoxFile file) { - try { - trash.getFileInfo(file.getID(), "id"); - } catch (BoxAPIResponseException e) { - assertThat(e.getResponseCode(), is(404)); - } + private void assertFileIsNotTrashed(BoxTrash trash, BoxFile file) { + try { + trash.getFileInfo(file.getID(), "id"); + } catch (BoxAPIResponseException e) { + assertThat(e.getResponseCode(), is(404)); } + } - private void assertFolderIsNotTrashed(BoxTrash trash, BoxFolder folder) { - try { - trash.getFolderInfo(folder.getID(), "id"); - } catch (BoxAPIResponseException e) { - assertThat(e.getResponseCode(), is(404)); - } + private void assertFolderIsNotTrashed(BoxTrash trash, BoxFolder folder) { + try { + trash.getFolderInfo(folder.getID(), "id"); + } catch (BoxAPIResponseException e) { + assertThat(e.getResponseCode(), is(404)); } + } } diff --git a/src/intTest/java/com/box/sdk/BoxUserIT.java b/src/intTest/java/com/box/sdk/BoxUserIT.java index 28b05649d..31235f091 100644 --- a/src/intTest/java/com/box/sdk/BoxUserIT.java +++ b/src/intTest/java/com/box/sdk/BoxUserIT.java @@ -31,145 +31,148 @@ import org.junit.BeforeClass; import org.junit.Test; -/** - * {@link BoxUser} related tests. - */ +/** {@link BoxUser} related tests. */ public class BoxUserIT { - private static final String NEW_USER_LOGIN = UUID.randomUUID() + "@boz.com"; - private static final String NEW_USER_NAME = UUID.randomUUID().toString(); + private static final String NEW_USER_LOGIN = UUID.randomUUID() + "@boz.com"; + private static final String NEW_USER_NAME = UUID.randomUUID().toString(); - @BeforeClass - public static void cleanup() { - BoxAPIConnection api = jwtApiForServiceAccount(); - for (BoxUser.Info user : BoxUser.getAllEnterpriseUsers(api, NEW_USER_LOGIN)) { - user.getResource().delete(false, true); - } - Logger.getLogger(OkHttpClient.class.getName()).setLevel(Level.FINE); + @BeforeClass + public static void cleanup() { + BoxAPIConnection api = jwtApiForServiceAccount(); + for (BoxUser.Info user : BoxUser.getAllEnterpriseUsers(api, NEW_USER_LOGIN)) { + user.getResource().delete(false, true); } + Logger.getLogger(OkHttpClient.class.getName()).setLevel(Level.FINE); + } - @Test(timeout = 10000) - public void getCurrentUserInfoIsCorrect() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxUser user = BoxUser.getCurrentUser(api); - BoxUser.Info info = user.getInfo(BoxUser.ALL_FIELDS); - - assertNotNull(info.getEnterprise().getID()); - assertNotNull(info.getEnterprise().getName()); - } - - @Test(timeout = 10000) - public void createAndForcefullyDeleteEnterpriseUser() { - BoxAPIConnection api = jwtApiForServiceAccount(); - // Since deleting users happens in a separate process in the backend - // it is really an asynchronous call. So we have to use a new user in - // this test in case the previous user's deletion hasn't completed. - - BoxUser.Info createdUserInfo = BoxUser.createEnterpriseUser(api, NEW_USER_LOGIN, NEW_USER_NAME); - - assertNotNull(createdUserInfo.getID()); - assertEquals(NEW_USER_NAME, createdUserInfo.getName()); - assertEquals(NEW_USER_LOGIN, createdUserInfo.getLogin()); - - createdUserInfo.getResource().delete(false, true); - - Iterable users = BoxUser.getAllEnterpriseUsers(api, NEW_USER_LOGIN); - assertThat(createListFrom(users), Matchers.hasSize(0)); - } - - @Test(timeout = 10000) - public void createAndDeleteEnterpriseUser() { - BoxAPIConnection api = jwtApiForServiceAccount(); - // Since deleting users happens in a separate process in the backend - // it is really an asynchronous call. So we have to use a new user in - // this test in case the previous user's deletion hasn't completed. - - BoxUser.Info createdUserInfo = BoxUser.createEnterpriseUser(api, NEW_USER_LOGIN, NEW_USER_NAME); - - assertNotNull(createdUserInfo.getID()); - assertEquals(NEW_USER_NAME, createdUserInfo.getName()); - assertEquals(NEW_USER_LOGIN, createdUserInfo.getLogin()); - - createdUserInfo.getResource().delete(); - - Iterable users = BoxUser.getAllEnterpriseUsers(api, NEW_USER_LOGIN); - assertThat(createListFrom(users), Matchers.hasSize(0)); - } - - @Test(timeout = 10000) - public void getMembershipsHasCorrectMemberships() { - BoxAPIConnection api = jwtApiForServiceAccount(); - String groupName = "[getMembershipsHasCorrectMemberships] Test Group"; - BoxUser user = BoxUser.getCurrentUser(api); - BoxGroupMembership.GroupRole groupRole = BoxGroupMembership.GroupRole.ADMIN; - - BoxGroup group = BoxGroup.createGroup(api, groupName).getResource(); - BoxGroupMembership.Info membershipInfo = group.addMembership(user, groupRole); - String membershipID = membershipInfo.getID(); - - Collection memberships = user.getMemberships(); - - assertThat(memberships, hasSize(greaterThanOrEqualTo(1))); - assertThat(memberships, hasItem(Matchers.hasProperty("ID", equalTo(membershipID)))); - - group.delete(); - } - - @Test(timeout = 10000) - public void updateUserInfo() { - BoxAPIConnection api = jwtApiForServiceAccount(); - final String login = "login3+" + Calendar.getInstance().getTimeInMillis() + "@boz.com"; - final String originalName = "original name"; - final String updatedName = "updated name"; - - BoxUser.Info userInfo = BoxUser.createEnterpriseUser(api, login, originalName); - userInfo.setName(updatedName); - - BoxUser user = userInfo.getResource(); - user.updateInfo(userInfo, "name"); - - assertEquals(updatedName, userInfo.getName()); - - user.delete(false, false); + @Test(timeout = 10000) + public void getCurrentUserInfoIsCorrect() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxUser user = BoxUser.getCurrentUser(api); + BoxUser.Info info = user.getInfo(BoxUser.ALL_FIELDS); + + assertNotNull(info.getEnterprise().getID()); + assertNotNull(info.getEnterprise().getName()); + } + + @Test(timeout = 10000) + public void createAndForcefullyDeleteEnterpriseUser() { + BoxAPIConnection api = jwtApiForServiceAccount(); + // Since deleting users happens in a separate process in the backend + // it is really an asynchronous call. So we have to use a new user in + // this test in case the previous user's deletion hasn't completed. + + BoxUser.Info createdUserInfo = BoxUser.createEnterpriseUser(api, NEW_USER_LOGIN, NEW_USER_NAME); + + assertNotNull(createdUserInfo.getID()); + assertEquals(NEW_USER_NAME, createdUserInfo.getName()); + assertEquals(NEW_USER_LOGIN, createdUserInfo.getLogin()); + + createdUserInfo.getResource().delete(false, true); + + Iterable users = BoxUser.getAllEnterpriseUsers(api, NEW_USER_LOGIN); + assertThat(createListFrom(users), Matchers.hasSize(0)); + } + + @Test(timeout = 10000) + public void createAndDeleteEnterpriseUser() { + BoxAPIConnection api = jwtApiForServiceAccount(); + // Since deleting users happens in a separate process in the backend + // it is really an asynchronous call. So we have to use a new user in + // this test in case the previous user's deletion hasn't completed. + + BoxUser.Info createdUserInfo = BoxUser.createEnterpriseUser(api, NEW_USER_LOGIN, NEW_USER_NAME); + + assertNotNull(createdUserInfo.getID()); + assertEquals(NEW_USER_NAME, createdUserInfo.getName()); + assertEquals(NEW_USER_LOGIN, createdUserInfo.getLogin()); + + createdUserInfo.getResource().delete(); + + Iterable users = BoxUser.getAllEnterpriseUsers(api, NEW_USER_LOGIN); + assertThat(createListFrom(users), Matchers.hasSize(0)); + } + + @Test(timeout = 10000) + public void getMembershipsHasCorrectMemberships() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String groupName = "[getMembershipsHasCorrectMemberships] Test Group"; + BoxUser user = BoxUser.getCurrentUser(api); + BoxGroupMembership.GroupRole groupRole = BoxGroupMembership.GroupRole.ADMIN; + + BoxGroup group = BoxGroup.createGroup(api, groupName).getResource(); + BoxGroupMembership.Info membershipInfo = group.addMembership(user, groupRole); + String membershipID = membershipInfo.getID(); + + Collection memberships = user.getMemberships(); + + assertThat(memberships, hasSize(greaterThanOrEqualTo(1))); + assertThat( + memberships, + hasItem(Matchers.hasProperty("ID", equalTo(membershipID)))); + + group.delete(); + } + + @Test(timeout = 10000) + public void updateUserInfo() { + BoxAPIConnection api = jwtApiForServiceAccount(); + final String login = "login3+" + Calendar.getInstance().getTimeInMillis() + "@boz.com"; + final String originalName = "original name"; + final String updatedName = "updated name"; + + BoxUser.Info userInfo = BoxUser.createEnterpriseUser(api, login, originalName); + userInfo.setName(updatedName); + + BoxUser user = userInfo.getResource(); + user.updateInfo(userInfo, "name"); + + assertEquals(updatedName, userInfo.getName()); + + user.delete(false, false); + } + + @Test(timeout = 60000) + public void uploadGetAndDeleteAvatar() throws IOException, InterruptedException { + // given + BoxAPIConnection api = jwtApiForServiceAccount(); + String filePath = getSampleFilePath("red_100x100.png"); + BoxUser user = new BoxUser(api, TestConfig.getUserId()); + + // when + AvatarUploadResponse response = user.uploadAvatar(new File(filePath)); + + // then + assertThat(response.getSmall(), not(emptyOrNullString())); + assertThat(response.getLarge(), not(emptyOrNullString())); + assertThat(response.getPreview(), not(emptyOrNullString())); + + retry( + () -> { + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { + user.downloadAvatar(outputStream); + assertTrue("Could not read avatar binary data", outputStream.size() > 0); + } catch (IOException e) { + throw new RuntimeException(e); + } + }, + 5, + 1000); + + // when + user.deleteAvatar(); + + // then + try { + user.downloadAvatar(new ByteArrayOutputStream()); + } catch (BoxAPIException e) { + assertThat(e.getResponseCode(), is(404)); } + } - @Test(timeout = 60000) - public void uploadGetAndDeleteAvatar() throws IOException, InterruptedException { - // given - BoxAPIConnection api = jwtApiForServiceAccount(); - String filePath = getSampleFilePath("red_100x100.png"); - BoxUser user = new BoxUser(api, TestConfig.getUserId()); - - // when - AvatarUploadResponse response = user.uploadAvatar(new File(filePath)); - - // then - assertThat(response.getSmall(), not(emptyOrNullString())); - assertThat(response.getLarge(), not(emptyOrNullString())); - assertThat(response.getPreview(), not(emptyOrNullString())); - - retry(() -> { - try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { - user.downloadAvatar(outputStream); - assertTrue("Could not read avatar binary data", outputStream.size() > 0); - } catch (IOException e) { - throw new RuntimeException(e); - } - }, 5, 1000); - - // when - user.deleteAvatar(); - - // then - try { - user.downloadAvatar(new ByteArrayOutputStream()); - } catch (BoxAPIException e) { - assertThat(e.getResponseCode(), is(404)); - } - } - - private String getSampleFilePath(String fileName) throws UnsupportedEncodingException { - URL fileURL = this.getClass().getResource("/sample-files/" + fileName); - return URLDecoder.decode(fileURL.getFile(), "utf-8"); - } + private String getSampleFilePath(String fileName) throws UnsupportedEncodingException { + URL fileURL = this.getClass().getResource("/sample-files/" + fileName); + return URLDecoder.decode(fileURL.getFile(), "utf-8"); + } } diff --git a/src/intTest/java/com/box/sdk/BoxWebHookIT.java b/src/intTest/java/com/box/sdk/BoxWebHookIT.java index 6206027db..45205f998 100644 --- a/src/intTest/java/com/box/sdk/BoxWebHookIT.java +++ b/src/intTest/java/com/box/sdk/BoxWebHookIT.java @@ -33,181 +33,218 @@ import org.junit.BeforeClass; import org.junit.Test; -/** - * {@link BoxWebHook} related integration tests. - */ +/** {@link BoxWebHook} related integration tests. */ public class BoxWebHookIT { - @BeforeClass - public static void setup() { - setupUniqeFolder(); + @BeforeClass + public static void setup() { + setupUniqeFolder(); + } + + @AfterClass + public static void afterClass() { + removeUniqueFolder(); + } + + @Test + public void createWebHookFileSucceeds() throws IOException { + BoxAPIConnection api = jwtApiForServiceAccount(); + String fileName = "[createWebhook] Test File.txt"; + + BoxFile uploadedFile = null; + + try { + uploadedFile = uploadFileToUniqueFolderWithSomeContent(api, fileName); + URL address = new URL("https://www.google.com"); + BoxWebHook.Info info = + BoxWebHook.create( + uploadedFile, + address, + BoxWebHook.Trigger.FILE_PREVIEWED, + BoxWebHook.Trigger.FILE_LOCKED); + + assertThat(info.getID(), is(notNullValue())); + assertThat(info.getAddress(), is(equalTo(address))); + assertThat( + info.getTarget().getType(), is(equalTo(BoxResource.getResourceType(BoxFile.class)))); + assertThat(info.getTarget().getId(), is(equalTo(uploadedFile.getID()))); + assertThat( + info.getTriggers(), + is( + equalTo( + this.toSet( + new BoxWebHook.Trigger[] { + BoxWebHook.Trigger.FILE_PREVIEWED, BoxWebHook.Trigger.FILE_LOCKED + })))); + + info.getResource().delete(); + } finally { + deleteFile(uploadedFile); } - - @AfterClass - public static void afterClass() { - removeUniqueFolder(); + } + + @Test + public void createWebHookFolderSucceeds() throws IOException { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + String folderName = "[createWebhook] Folder"; + BoxFolder folder = null; + + try { + folder = rootFolder.createFolder(folderName).getResource(); + URL address = new URL("https://www.google.com"); + BoxWebHook.Info info = BoxWebHook.create(folder, address, FOLDER_DOWNLOADED, FOLDER_COPIED); + + assertThat(info.getID(), is(notNullValue())); + assertThat(info.getAddress(), is(equalTo(address))); + assertThat( + info.getTarget().getType(), is(equalTo(BoxResource.getResourceType(BoxFolder.class)))); + assertThat(info.getTarget().getId(), is(equalTo(folder.getID()))); + assertThat( + info.getTriggers(), + is(equalTo(this.toSet(new BoxWebHook.Trigger[] {FOLDER_COPIED, FOLDER_DOWNLOADED})))); + + info.getResource().delete(); + } finally { + deleteFolder(folder); } - - @Test - public void createWebHookFileSucceeds() throws IOException { - BoxAPIConnection api = jwtApiForServiceAccount(); - String fileName = "[createWebhook] Test File.txt"; - - BoxFile uploadedFile = null; - - try { - uploadedFile = uploadFileToUniqueFolderWithSomeContent(api, fileName); - URL address = new URL("https://www.google.com"); - BoxWebHook.Info info = BoxWebHook.create(uploadedFile, address, - BoxWebHook.Trigger.FILE_PREVIEWED, BoxWebHook.Trigger.FILE_LOCKED); - - assertThat(info.getID(), is(notNullValue())); - assertThat(info.getAddress(), is(equalTo(address))); - assertThat(info.getTarget().getType(), is(equalTo(BoxResource.getResourceType(BoxFile.class)))); - assertThat(info.getTarget().getId(), is(equalTo(uploadedFile.getID()))); - assertThat(info.getTriggers(), is(equalTo(this.toSet( - new BoxWebHook.Trigger[]{BoxWebHook.Trigger.FILE_PREVIEWED, BoxWebHook.Trigger.FILE_LOCKED})))); - - info.getResource().delete(); - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void listWebHooksSucceeds() throws IOException { + BoxAPIConnection api = jwtApiForServiceAccount(); + String fileName = "[listWebhooks] Test File.txt"; + BoxFile uploadedFile = null; + + try { + uploadedFile = uploadFileToUniqueFolderWithSomeContent(api, fileName); + URL address = new URL("https://www.google.com"); + BoxWebHook.Info info = + BoxWebHook.create(uploadedFile, address, BoxWebHook.Trigger.FILE_PREVIEWED); + Iterable webhooks = BoxWebHook.all(api); + + assertThat( + webhooks, hasItem(Matchers.hasProperty("ID", equalTo(info.getID())))); + + info.getResource().delete(); + + webhooks = BoxWebHook.all(api); + assertThat( + webhooks, + not(hasItem(Matchers.hasProperty("ID", equalTo(info.getID()))))); + } finally { + deleteFile(uploadedFile); } - - @Test - public void createWebHookFolderSucceeds() throws IOException { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - String folderName = "[createWebhook] Folder"; - BoxFolder folder = null; - - try { - folder = rootFolder.createFolder(folderName).getResource(); - URL address = new URL("https://www.google.com"); - BoxWebHook.Info info = BoxWebHook.create(folder, address, FOLDER_DOWNLOADED, FOLDER_COPIED); - - assertThat(info.getID(), is(notNullValue())); - assertThat(info.getAddress(), is(equalTo(address))); - assertThat(info.getTarget().getType(), is(equalTo(BoxResource.getResourceType(BoxFolder.class)))); - assertThat(info.getTarget().getId(), is(equalTo(folder.getID()))); - assertThat(info.getTriggers(), - is(equalTo(this.toSet(new BoxWebHook.Trigger[]{FOLDER_COPIED, FOLDER_DOWNLOADED})))); - - info.getResource().delete(); - } finally { - deleteFolder(folder); - } + } + + @Test + public void updateWebHookInfoSucceeds() throws IOException { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = BoxFolder.getRootFolder(api); + String fileName = "[updateWebHookInfoSucceeds] Test File.txt"; + byte[] fileBytes = "Non-empty string".getBytes(StandardCharsets.UTF_8); + + InputStream uploadStream = new ByteArrayInputStream(fileBytes); + BoxFile uploadedFile = rootFolder.uploadFile(uploadStream, fileName).getResource(); + + try { + URL address = new URL("https://www.google.com"); + BoxWebHook webHook = + BoxWebHook.create( + uploadedFile, + address, + BoxWebHook.Trigger.FILE_PREVIEWED, + BoxWebHook.Trigger.FILE_LOCKED) + .getResource(); + + URL newAddress = new URL("https://www.yahoo.com"); + + BoxWebHook.Info newInfo = webHook.new Info(); + newInfo.setTriggers(BoxWebHook.Trigger.FILE_UNLOCKED); + newInfo.setAddress(newAddress); + + webHook.updateInfo(newInfo); + + assertThat(newInfo.getAddress(), is(equalTo(newAddress))); + assertThat( + newInfo.getTriggers(), + is(equalTo(this.toSet(new BoxWebHook.Trigger[] {BoxWebHook.Trigger.FILE_UNLOCKED})))); + + webHook.delete(); + } finally { + deleteFile(uploadedFile); } - - @Test - public void listWebHooksSucceeds() throws IOException { - BoxAPIConnection api = jwtApiForServiceAccount(); - String fileName = "[listWebhooks] Test File.txt"; - BoxFile uploadedFile = null; - - try { - uploadedFile = uploadFileToUniqueFolderWithSomeContent(api, fileName); - URL address = new URL("https://www.google.com"); - BoxWebHook.Info info = BoxWebHook.create(uploadedFile, address, BoxWebHook.Trigger.FILE_PREVIEWED); - Iterable webhooks = BoxWebHook.all(api); - - assertThat(webhooks, hasItem(Matchers.hasProperty("ID", equalTo(info.getID())))); - - info.getResource().delete(); - - webhooks = BoxWebHook.all(api); - assertThat(webhooks, not(hasItem(Matchers.hasProperty("ID", equalTo(info.getID()))))); - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void createWebHookSignRequestOnFileSucceeds() throws IOException { + BoxAPIConnection api = jwtApiForServiceAccount(); + String fileName = "file_to_sign.pdf"; + + BoxFile file = null; + try { + file = uploadSampleFileToUniqueFolder(api, fileName); + URL address = new URL("https://www.google.com"); + + BoxWebHook.Info webHookInfo = + BoxWebHook.create( + file, address, SIGN_REQUEST_DECLINED, SIGN_REQUEST_EXPIRED, SIGN_REQUEST_COMPLETED); + + assertThat(webHookInfo.getID(), is(notNullValue())); + assertThat(webHookInfo.getAddress(), is(equalTo(address))); + assertThat( + webHookInfo.getTarget().getType(), + is(equalTo(BoxResource.getResourceType(BoxFile.class)))); + assertThat(webHookInfo.getTarget().getId(), is(equalTo(file.getID()))); + assertThat( + webHookInfo.getTriggers(), + is( + equalTo( + this.toSet( + new BoxWebHook.Trigger[] { + SIGN_REQUEST_DECLINED, SIGN_REQUEST_EXPIRED, SIGN_REQUEST_COMPLETED + })))); + } finally { + deleteFile(file); } - - @Test - public void updateWebHookInfoSucceeds() throws IOException { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = BoxFolder.getRootFolder(api); - String fileName = "[updateWebHookInfoSucceeds] Test File.txt"; - byte[] fileBytes = "Non-empty string".getBytes(StandardCharsets.UTF_8); - - InputStream uploadStream = new ByteArrayInputStream(fileBytes); - BoxFile uploadedFile = rootFolder.uploadFile(uploadStream, fileName).getResource(); - - try { - URL address = new URL("https://www.google.com"); - BoxWebHook webHook = BoxWebHook.create(uploadedFile, address, - BoxWebHook.Trigger.FILE_PREVIEWED, BoxWebHook.Trigger.FILE_LOCKED).getResource(); - - URL newAddress = new URL("https://www.yahoo.com"); - - BoxWebHook.Info newInfo = webHook.new Info(); - newInfo.setTriggers(BoxWebHook.Trigger.FILE_UNLOCKED); - newInfo.setAddress(newAddress); - - webHook.updateInfo(newInfo); - - assertThat(newInfo.getAddress(), is(equalTo(newAddress))); - assertThat(newInfo.getTriggers(), is(equalTo( - this.toSet(new BoxWebHook.Trigger[]{BoxWebHook.Trigger.FILE_UNLOCKED}) - ))); - - webHook.delete(); - } finally { - deleteFile(uploadedFile); - } + } + + @Test + public void createWebHookSignRequestOnFolderSucceeds() throws IOException { + BoxAPIConnection api = jwtApiForServiceAccount(); + + BoxFolder folder = null; + try { + folder = + getUniqueFolder(api) + .createFolder(randomizeName("createWebHookSignRequestOnFolderSucceeds")) + .getResource(); + URL address = new URL("https://www.google.com"); + + BoxWebHook.Info webHookInfo = + BoxWebHook.create( + folder, address, SIGN_REQUEST_DECLINED, SIGN_REQUEST_EXPIRED, SIGN_REQUEST_COMPLETED); + + assertThat(webHookInfo.getID(), is(notNullValue())); + assertThat(webHookInfo.getAddress(), is(equalTo(address))); + assertThat( + webHookInfo.getTarget().getType(), + is(equalTo(BoxResource.getResourceType(BoxFolder.class)))); + assertThat(webHookInfo.getTarget().getId(), is(equalTo(folder.getID()))); + assertThat( + webHookInfo.getTriggers(), + is( + equalTo( + this.toSet( + new BoxWebHook.Trigger[] { + SIGN_REQUEST_DECLINED, SIGN_REQUEST_EXPIRED, SIGN_REQUEST_COMPLETED + })))); + } finally { + deleteFolder(folder); } + } - @Test - public void createWebHookSignRequestOnFileSucceeds() throws IOException { - BoxAPIConnection api = jwtApiForServiceAccount(); - String fileName = "file_to_sign.pdf"; - - BoxFile file = null; - try { - file = uploadSampleFileToUniqueFolder(api, fileName); - URL address = new URL("https://www.google.com"); - - BoxWebHook.Info webHookInfo = BoxWebHook.create( - file, address, SIGN_REQUEST_DECLINED, SIGN_REQUEST_EXPIRED, SIGN_REQUEST_COMPLETED - ); - - assertThat(webHookInfo.getID(), is(notNullValue())); - assertThat(webHookInfo.getAddress(), is(equalTo(address))); - assertThat(webHookInfo.getTarget().getType(), is(equalTo(BoxResource.getResourceType(BoxFile.class)))); - assertThat(webHookInfo.getTarget().getId(), is(equalTo(file.getID()))); - assertThat(webHookInfo.getTriggers(), is(equalTo(this.toSet( - new BoxWebHook.Trigger[]{SIGN_REQUEST_DECLINED, SIGN_REQUEST_EXPIRED, SIGN_REQUEST_COMPLETED})))); - } finally { - deleteFile(file); - } - } - - @Test - public void createWebHookSignRequestOnFolderSucceeds() throws IOException { - BoxAPIConnection api = jwtApiForServiceAccount(); - - BoxFolder folder = null; - try { - folder = getUniqueFolder(api) - .createFolder(randomizeName("createWebHookSignRequestOnFolderSucceeds")) - .getResource(); - URL address = new URL("https://www.google.com"); - - BoxWebHook.Info webHookInfo = BoxWebHook.create( - folder, address, SIGN_REQUEST_DECLINED, SIGN_REQUEST_EXPIRED, SIGN_REQUEST_COMPLETED - ); - - assertThat(webHookInfo.getID(), is(notNullValue())); - assertThat(webHookInfo.getAddress(), is(equalTo(address))); - assertThat(webHookInfo.getTarget().getType(), is(equalTo(BoxResource.getResourceType(BoxFolder.class)))); - assertThat(webHookInfo.getTarget().getId(), is(equalTo(folder.getID()))); - assertThat(webHookInfo.getTriggers(), is(equalTo(this.toSet( - new BoxWebHook.Trigger[]{SIGN_REQUEST_DECLINED, SIGN_REQUEST_EXPIRED, SIGN_REQUEST_COMPLETED})))); - } finally { - deleteFolder(folder); - } - } - - private Set toSet(T[] values) { - return new HashSet<>(Arrays.asList(values)); - } + private Set toSet(T[] values) { + return new HashSet<>(Arrays.asList(values)); + } } diff --git a/src/intTest/java/com/box/sdk/BoxWebLinkIT.java b/src/intTest/java/com/box/sdk/BoxWebLinkIT.java index 7540cde6e..af97b1b2e 100644 --- a/src/intTest/java/com/box/sdk/BoxWebLinkIT.java +++ b/src/intTest/java/com/box/sdk/BoxWebLinkIT.java @@ -20,178 +20,183 @@ import org.junit.BeforeClass; import org.junit.Test; -/** - * {@link BoxWebLink} related integration tests. - */ +/** {@link BoxWebLink} related integration tests. */ public class BoxWebLinkIT { - @BeforeClass - public static void beforeClass() throws Exception { - setupUniqeFolder(); - } - - @AfterClass - public static void afterClass() throws Exception { - removeUniqueFolder(); - } - - @Test - public void copyWebLinkSucceeds() throws MalformedURLException { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - String originalFileName = "[copyWebLinkSucceeds] Original WebLink"; - String newFileName = "[copyWebLinkSucceeds] New WebLink"; - URL url = new URL("https://api.box.com"); - String description = "[copyWebLinkSucceeds] Original WebLink"; - - BoxWebLink uploadedWebLink = rootFolder.createWebLink(originalFileName, url, description).getResource(); - BoxWebLink.Info uploadedWebLinkInfo = uploadedWebLink.getInfo(); - - BoxWebLink.Info copiedWebLinkInfo = uploadedWebLink.copy(rootFolder, newFileName); - BoxWebLink copiedWebLink = copiedWebLinkInfo.getResource(); - - assertThat(copiedWebLinkInfo.getLinkURL(), equalTo(uploadedWebLinkInfo.getLinkURL())); - assertThat(copiedWebLinkInfo.getDescription(), equalTo(uploadedWebLinkInfo.getDescription())); - - uploadedWebLink.delete(); - copiedWebLink.delete(); - } - - @Test - public void moveWebLinkSucceeds() throws MalformedURLException { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - String fileName = "[moveWebLinkSucceeds] Test WebLink"; - URL url = new URL("https://api.box.com"); - String description = "[moveWebLinkSucceeds] Test WebLink"; - String folderName = "[moveWebLinkSucceeds] Destination Folder"; - - BoxWebLink uploadedWebLink = rootFolder.createWebLink(fileName, url, description).getResource(); - - BoxFolder destinationFolder = rootFolder.createFolder(folderName).getResource(); - uploadedWebLink.move(destinationFolder); - - assertThat(destinationFolder, - hasItem(Matchers.hasProperty("ID", equalTo(uploadedWebLink.getID())))); - - uploadedWebLink.delete(); - destinationFolder.delete(false); - } - - @Test - public void getInfoWithOnlyTheURLField() throws MalformedURLException { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - String fileName = "[getInfoWithOnlyTheURLField] Test WebLink"; - URL url = new URL("https://api.box.com"); - String description = "[getInfoWithOnlyTheURLField] Test WebLink"; - - BoxWebLink uploadedWebLink = rootFolder.createWebLink(fileName, url, description).getResource(); - BoxWebLink.Info uploadedLinkInfo = uploadedWebLink.getInfo("url"); - - assertThat(uploadedLinkInfo.getLinkURL(), is(equalTo(url))); - assertThat(uploadedLinkInfo.getDescription(), is(nullValue())); - - uploadedLinkInfo.getResource().delete(); - } - - @Test - public void getInfoWithAllFields() throws MalformedURLException { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - String fileName = "[getInfoWithAllFields] Test WebLink"; - URL url = new URL("https://api.box.com"); - String description = "[getInfoWithAllFields] Test WebLink"; - - BoxWebLink uploadedWebLink = rootFolder.createWebLink(fileName, url, description).getResource(); - BoxWebLink.Info uploadedLinkInfo = uploadedWebLink.getInfo(BoxWebLink.ALL_FIELDS); - - assertThat(uploadedLinkInfo.getName(), is(equalTo(fileName))); - assertThat(uploadedLinkInfo.getLinkURL(), is(equalTo(url))); - assertThat(uploadedLinkInfo.getDescription(), is(equalTo(description))); - - uploadedLinkInfo.getResource().delete(); - } - - @Test - public void updateLinkWithSpecialCharsInNameSucceeds() throws MalformedURLException { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - String originalFileName = "[updateLinkWithSpecialCharsInNameSucceeds] abc\";def"; - URL url = new URL("https://api.box.com"); - String description = "[updateLinkWithSpecialCharsInNameSucceeds] Test WebLink"; - - BoxWebLink.Info uploadedWebLinkInfo = rootFolder.createWebLink(originalFileName, url, description); - - assertThat(uploadedWebLinkInfo.getName(), is(equalTo(originalFileName))); - - uploadedWebLinkInfo.getResource().delete(); - } - - @Test - public void updateLinkInfoSucceeds() throws MalformedURLException { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - String originalFileName = "[updateLinkInfoSucceeds] Original Name"; - String newFileName = "[updateLinkInfoSucceeds] New Name"; - URL url = new URL("https://api.box.com"); - String description = "[updateLinkWithSpecialCharsInNameSucceeds] Test WebLink"; - - BoxWebLink uploadedWebLink = rootFolder.createWebLink(originalFileName, url, description).getResource(); - - BoxWebLink.Info newInfo = uploadedWebLink.new Info(); - newInfo.setName(newFileName); - uploadedWebLink.updateInfo(newInfo); - - assertThat(newInfo.getName(), is(equalTo(newFileName))); - - uploadedWebLink.delete(); - } - - @Test - public void renameWebLinkSucceeds() throws MalformedURLException { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - String originalFileName = "[updateLinkInfoSucceeds] Original Name"; - String newFileName = "[updateLinkInfoSucceeds] New Name"; - URL url = new URL("https://api.box.com"); - String description = "[updateLinkWithSpecialCharsInNameSucceeds] Test WebLink"; - - BoxWebLink uploadedWebLink = rootFolder.createWebLink(originalFileName, url, description).getResource(); - - uploadedWebLink.rename(newFileName); - BoxWebLink.Info newInfo = uploadedWebLink.getInfo(); - - assertThat(newInfo.getName(), is(equalTo(newFileName))); - - uploadedWebLink.delete(); - } - - @Test - public void setsVanityNameOnASharedLink() throws MalformedURLException { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = getUniqueFolder(api); - URL url = new URL("https://api.box.com"); - BoxFolder folder = null; - try { - folder = rootFolder.createFolder("setsVanityNameOnASharedLink").getResource(); - BoxWebLink weblink = folder - .createWebLink("[setsVanityNameOnASharedLink] web link", url, "description") - .getResource(); - - String vanityName = "myCustomName-" + System.currentTimeMillis(); - BoxSharedLinkWithoutPermissionsRequest request = new BoxSharedLinkWithoutPermissionsRequest() - .access(OPEN) - .vanityName(vanityName) - .password("my-very-secret-password"); - BoxSharedLink linkWithVanityName = weblink.createSharedLink(request); - - assertThat(linkWithVanityName.getVanityName(), is(vanityName)); - assertThat(weblink.getInfo().getSharedLink().getVanityName(), is(vanityName)); - assertThat(linkWithVanityName.getAccess(), is(OPEN)); - assertThat(linkWithVanityName.getIsPasswordEnabled(), is(true)); - } finally { - deleteFolder(folder); - } + @BeforeClass + public static void beforeClass() throws Exception { + setupUniqeFolder(); + } + + @AfterClass + public static void afterClass() throws Exception { + removeUniqueFolder(); + } + + @Test + public void copyWebLinkSucceeds() throws MalformedURLException { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + String originalFileName = "[copyWebLinkSucceeds] Original WebLink"; + String newFileName = "[copyWebLinkSucceeds] New WebLink"; + URL url = new URL("https://api.box.com"); + String description = "[copyWebLinkSucceeds] Original WebLink"; + + BoxWebLink uploadedWebLink = + rootFolder.createWebLink(originalFileName, url, description).getResource(); + BoxWebLink.Info uploadedWebLinkInfo = uploadedWebLink.getInfo(); + + BoxWebLink.Info copiedWebLinkInfo = uploadedWebLink.copy(rootFolder, newFileName); + BoxWebLink copiedWebLink = copiedWebLinkInfo.getResource(); + + assertThat(copiedWebLinkInfo.getLinkURL(), equalTo(uploadedWebLinkInfo.getLinkURL())); + assertThat(copiedWebLinkInfo.getDescription(), equalTo(uploadedWebLinkInfo.getDescription())); + + uploadedWebLink.delete(); + copiedWebLink.delete(); + } + + @Test + public void moveWebLinkSucceeds() throws MalformedURLException { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + String fileName = "[moveWebLinkSucceeds] Test WebLink"; + URL url = new URL("https://api.box.com"); + String description = "[moveWebLinkSucceeds] Test WebLink"; + String folderName = "[moveWebLinkSucceeds] Destination Folder"; + + BoxWebLink uploadedWebLink = rootFolder.createWebLink(fileName, url, description).getResource(); + + BoxFolder destinationFolder = rootFolder.createFolder(folderName).getResource(); + uploadedWebLink.move(destinationFolder); + + assertThat( + destinationFolder, + hasItem(Matchers.hasProperty("ID", equalTo(uploadedWebLink.getID())))); + + uploadedWebLink.delete(); + destinationFolder.delete(false); + } + + @Test + public void getInfoWithOnlyTheURLField() throws MalformedURLException { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + String fileName = "[getInfoWithOnlyTheURLField] Test WebLink"; + URL url = new URL("https://api.box.com"); + String description = "[getInfoWithOnlyTheURLField] Test WebLink"; + + BoxWebLink uploadedWebLink = rootFolder.createWebLink(fileName, url, description).getResource(); + BoxWebLink.Info uploadedLinkInfo = uploadedWebLink.getInfo("url"); + + assertThat(uploadedLinkInfo.getLinkURL(), is(equalTo(url))); + assertThat(uploadedLinkInfo.getDescription(), is(nullValue())); + + uploadedLinkInfo.getResource().delete(); + } + + @Test + public void getInfoWithAllFields() throws MalformedURLException { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + String fileName = "[getInfoWithAllFields] Test WebLink"; + URL url = new URL("https://api.box.com"); + String description = "[getInfoWithAllFields] Test WebLink"; + + BoxWebLink uploadedWebLink = rootFolder.createWebLink(fileName, url, description).getResource(); + BoxWebLink.Info uploadedLinkInfo = uploadedWebLink.getInfo(BoxWebLink.ALL_FIELDS); + + assertThat(uploadedLinkInfo.getName(), is(equalTo(fileName))); + assertThat(uploadedLinkInfo.getLinkURL(), is(equalTo(url))); + assertThat(uploadedLinkInfo.getDescription(), is(equalTo(description))); + + uploadedLinkInfo.getResource().delete(); + } + + @Test + public void updateLinkWithSpecialCharsInNameSucceeds() throws MalformedURLException { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + String originalFileName = "[updateLinkWithSpecialCharsInNameSucceeds] abc\";def"; + URL url = new URL("https://api.box.com"); + String description = "[updateLinkWithSpecialCharsInNameSucceeds] Test WebLink"; + + BoxWebLink.Info uploadedWebLinkInfo = + rootFolder.createWebLink(originalFileName, url, description); + + assertThat(uploadedWebLinkInfo.getName(), is(equalTo(originalFileName))); + + uploadedWebLinkInfo.getResource().delete(); + } + + @Test + public void updateLinkInfoSucceeds() throws MalformedURLException { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + String originalFileName = "[updateLinkInfoSucceeds] Original Name"; + String newFileName = "[updateLinkInfoSucceeds] New Name"; + URL url = new URL("https://api.box.com"); + String description = "[updateLinkWithSpecialCharsInNameSucceeds] Test WebLink"; + + BoxWebLink uploadedWebLink = + rootFolder.createWebLink(originalFileName, url, description).getResource(); + + BoxWebLink.Info newInfo = uploadedWebLink.new Info(); + newInfo.setName(newFileName); + uploadedWebLink.updateInfo(newInfo); + + assertThat(newInfo.getName(), is(equalTo(newFileName))); + + uploadedWebLink.delete(); + } + + @Test + public void renameWebLinkSucceeds() throws MalformedURLException { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + String originalFileName = "[updateLinkInfoSucceeds] Original Name"; + String newFileName = "[updateLinkInfoSucceeds] New Name"; + URL url = new URL("https://api.box.com"); + String description = "[updateLinkWithSpecialCharsInNameSucceeds] Test WebLink"; + + BoxWebLink uploadedWebLink = + rootFolder.createWebLink(originalFileName, url, description).getResource(); + + uploadedWebLink.rename(newFileName); + BoxWebLink.Info newInfo = uploadedWebLink.getInfo(); + + assertThat(newInfo.getName(), is(equalTo(newFileName))); + + uploadedWebLink.delete(); + } + + @Test + public void setsVanityNameOnASharedLink() throws MalformedURLException { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = getUniqueFolder(api); + URL url = new URL("https://api.box.com"); + BoxFolder folder = null; + try { + folder = rootFolder.createFolder("setsVanityNameOnASharedLink").getResource(); + BoxWebLink weblink = + folder + .createWebLink("[setsVanityNameOnASharedLink] web link", url, "description") + .getResource(); + + String vanityName = "myCustomName-" + System.currentTimeMillis(); + BoxSharedLinkWithoutPermissionsRequest request = + new BoxSharedLinkWithoutPermissionsRequest() + .access(OPEN) + .vanityName(vanityName) + .password("my-very-secret-password"); + BoxSharedLink linkWithVanityName = weblink.createSharedLink(request); + + assertThat(linkWithVanityName.getVanityName(), is(vanityName)); + assertThat(weblink.getInfo().getSharedLink().getVanityName(), is(vanityName)); + assertThat(linkWithVanityName.getAccess(), is(OPEN)); + assertThat(linkWithVanityName.getIsPasswordEnabled(), is(true)); + } finally { + deleteFolder(folder); } + } } diff --git a/src/intTest/java/com/box/sdk/BoxZipIT.java b/src/intTest/java/com/box/sdk/BoxZipIT.java index a00e7a29e..898faa532 100644 --- a/src/intTest/java/com/box/sdk/BoxZipIT.java +++ b/src/intTest/java/com/box/sdk/BoxZipIT.java @@ -1,6 +1,5 @@ package com.box.sdk; - import static com.box.sdk.BoxApiProvider.jwtApiForServiceAccount; import static com.box.sdk.BoxZipDownloadStatus.State.IN_PROGRESS; import static com.box.sdk.BoxZipDownloadStatus.State.SUCCEEDED; @@ -25,62 +24,59 @@ import org.junit.BeforeClass; import org.junit.Test; -/** - * {@link BoxZip} related integration tests. - */ +/** {@link BoxZip} related integration tests. */ public class BoxZipIT { - @BeforeClass - public static void setup() { - setupUniqeFolder(); - } + @BeforeClass + public static void setup() { + setupUniqeFolder(); + } - @AfterClass - public static void tearDown() { - removeUniqueFolder(); - } + @AfterClass + public static void tearDown() { + removeUniqueFolder(); + } - protected static byte[] readAllBytes(String fileName) throws IOException { - RandomAccessFile f = new RandomAccessFile(fileName, "r"); - byte[] b = new byte[(int) f.length()]; - f.read(b); - return b; - } + protected static byte[] readAllBytes(String fileName) throws IOException { + RandomAccessFile f = new RandomAccessFile(fileName, "r"); + byte[] b = new byte[(int) f.length()]; + f.read(b); + return b; + } - @Test - public void createAndDownloadZipSucceeds() throws IOException { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder folder = getUniqueFolder(api); - String fileName = "small_file.rtf"; - BoxFile uploadedFile = null; - BoxFolder createdFolder = null; - try { - createdFolder = folder.createFolder("Zip Test Folder").getResource(); - uploadedFile = uploadSampleFileToUniqueFolder(api, fileName); - uploadedFile.copy(createdFolder); + @Test + public void createAndDownloadZipSucceeds() throws IOException { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder folder = getUniqueFolder(api); + String fileName = "small_file.rtf"; + BoxFile uploadedFile = null; + BoxFolder createdFolder = null; + try { + createdFolder = folder.createFolder("Zip Test Folder").getResource(); + uploadedFile = uploadSampleFileToUniqueFolder(api, fileName); + uploadedFile.copy(createdFolder); - ArrayList items = new ArrayList<>(); - BoxZipItem file = new BoxZipItem("file", uploadedFile.getID()); - BoxZipItem subFolder = new BoxZipItem("folder", createdFolder.getID()); - items.add(file); - items.add(subFolder); + ArrayList items = new ArrayList<>(); + BoxZipItem file = new BoxZipItem("file", uploadedFile.getID()); + BoxZipItem subFolder = new BoxZipItem("folder", createdFolder.getID()); + items.add(file); + items.add(subFolder); - ByteArrayOutputStream downloadStream = new ByteArrayOutputStream(); - BoxZipDownloadStatus zipDownloadStatus = new BoxZip(api).download("zip_test", items, downloadStream); - byte[] downloadedFileContent = downloadStream.toByteArray(); + ByteArrayOutputStream downloadStream = new ByteArrayOutputStream(); + BoxZipDownloadStatus zipDownloadStatus = + new BoxZip(api).download("zip_test", items, downloadStream); + byte[] downloadedFileContent = downloadStream.toByteArray(); - // File bytes for zips will not always be equal since they are being generated by every test. - // To approximate that the files are equal, the assertion below checks the lengths. - String zipFileName = "zip_test.zip"; - URL zipFileURL = this.getClass().getResource("/sample-files/" + zipFileName); - String zipFilePath = URLDecoder.decode(zipFileURL.getFile(), "utf-8"); - byte[] zipFileContent = readAllBytes(zipFilePath); - Assert.assertEquals(zipFileContent.length, downloadedFileContent.length); - assertThat(zipDownloadStatus.getState(), anyOf(is(SUCCEEDED), is(IN_PROGRESS))); - } finally { - deleteFile(uploadedFile); - deleteFolder(createdFolder); - } + // File bytes for zips will not always be equal since they are being generated by every test. + // To approximate that the files are equal, the assertion below checks the lengths. + String zipFileName = "zip_test.zip"; + URL zipFileURL = this.getClass().getResource("/sample-files/" + zipFileName); + String zipFilePath = URLDecoder.decode(zipFileURL.getFile(), "utf-8"); + byte[] zipFileContent = readAllBytes(zipFilePath); + Assert.assertEquals(zipFileContent.length, downloadedFileContent.length); + assertThat(zipDownloadStatus.getState(), anyOf(is(SUCCEEDED), is(IN_PROGRESS))); + } finally { + deleteFile(uploadedFile); + deleteFolder(createdFolder); } - + } } - diff --git a/src/intTest/java/com/box/sdk/CleanupTools.java b/src/intTest/java/com/box/sdk/CleanupTools.java index 3d5bacf2a..f21f85c10 100644 --- a/src/intTest/java/com/box/sdk/CleanupTools.java +++ b/src/intTest/java/com/box/sdk/CleanupTools.java @@ -6,45 +6,45 @@ import java.util.Optional; final class CleanupTools { - private CleanupTools() { - // hiding constructor - } - - static void removeAllowedDomains(String... names) { - BoxCollaborationAllowlist.getAll(jwtApiForServiceAccount()) - .forEach(l -> { - Optional isDomainMatching = Arrays.stream(names) - .filter(n -> l.getDomain().contains(n)) - .findFirst(); - if (isDomainMatching.isPresent()) { - l.getResource().delete(); - } + private CleanupTools() { + // hiding constructor + } + + static void removeAllowedDomains(String... names) { + BoxCollaborationAllowlist.getAll(jwtApiForServiceAccount()) + .forEach( + l -> { + Optional isDomainMatching = + Arrays.stream(names).filter(n -> l.getDomain().contains(n)).findFirst(); + if (isDomainMatching.isPresent()) { + l.getResource().delete(); + } }); - } + } - static void removeAllGroups() { - for (BoxGroup.Info group : BoxGroup.getAllGroups(jwtApiForServiceAccount())) { - group.getResource().delete(); - } + static void removeAllGroups() { + for (BoxGroup.Info group : BoxGroup.getAllGroups(jwtApiForServiceAccount())) { + group.getResource().delete(); } + } - static void deleteFile(BoxFile file) { - Optional.ofNullable(file).ifPresent(BoxFile::delete); - } + static void deleteFile(BoxFile file) { + Optional.ofNullable(file).ifPresent(BoxFile::delete); + } - static void deleteFolder(BoxFolder folder) { - Optional.ofNullable(folder).ifPresent(f -> f.delete(true)); - } + static void deleteFolder(BoxFolder folder) { + Optional.ofNullable(folder).ifPresent(f -> f.delete(true)); + } - static void deleteGroup(BoxGroup group) { - if (group != null) { - group.delete(); - } + static void deleteGroup(BoxGroup group) { + if (group != null) { + group.delete(); } + } - static void deleteUser(BoxUser user) { - if (user != null) { - user.delete(false, false); - } + static void deleteUser(BoxUser user) { + if (user != null) { + user.delete(false, false); } + } } diff --git a/src/intTest/java/com/box/sdk/EventLogIT.java b/src/intTest/java/com/box/sdk/EventLogIT.java index 3eb6607d6..1e04d0406 100644 --- a/src/intTest/java/com/box/sdk/EventLogIT.java +++ b/src/intTest/java/com/box/sdk/EventLogIT.java @@ -12,105 +12,110 @@ public class EventLogIT { - @Test - public void getEnterpriseEventsReturnsAtLeastOneEvent() { - BoxAPIConnection api = jwtApiForServiceAccount(); - Date after = new Date(0L); - Date before = new Date(System.currentTimeMillis()); - - EnterpriseEventsRequest request = new EnterpriseEventsRequest().after(after).before(before); - EventLog events = EventLog.getEnterpriseEvents(api, request); - - assertThat(events.getSize(), is(not(0))); - assertThat(events.getStartDate(), is(equalTo(after))); - assertThat(events.getEndDate(), is(equalTo(before))); - } - - @Test - public void getEnterpriseEventsGmtPlus530() { - BoxAPIConnection api = jwtApiForServiceAccount(); - System.setProperty("user.timezone", "Asia/Calcutta"); - TimeZone.setDefault(null); - Date after = new Date(0L); - Date before = new Date(System.currentTimeMillis()); - - EnterpriseEventsRequest request = new EnterpriseEventsRequest().after(after).before(before); - EventLog events = EventLog.getEnterpriseEvents(api, request); - - assertThat(events.getSize(), is(not(0))); - assertThat(events.getStartDate(), is(equalTo(after))); - assertThat(events.getEndDate(), is(equalTo(before))); - } - - @Test - public void getEnterpriseEventsGmtPlus530WithLimit() { - BoxAPIConnection api = jwtApiForServiceAccount(); - System.setProperty("user.timezone", "Asia/Calcutta"); - TimeZone.setDefault(null); - Date after = new Date(0L); - Date before = new Date(System.currentTimeMillis()); - int limit = 5; - - EnterpriseEventsRequest request = new EnterpriseEventsRequest().after(after).before(before).limit(limit); - EventLog events = EventLog.getEnterpriseEvents(api, request); - - assertThat(events.getSize(), is(not(0))); - assertThat(events.getStartDate(), is(equalTo(after))); - assertThat(events.getEndDate(), is(equalTo(before))); - assertThat(events.getLimit(), is(equalTo(limit))); - } - - @Test - public void getEnterpriseEventsStreamReturnsAtLeastOneEvent() { - BoxAPIConnection api = jwtApiForServiceAccount(); - - EnterpriseEventsStreamRequest request = new EnterpriseEventsStreamRequest(); - EventLog events = EventLog.getEnterpriseEventsStream(api, request); - - assertThat(events.getSize(), is(not(0))); - } - - @Test - public void getEnterpriseEventsReturnsAtLeastOneEventDeprecated() { - BoxAPIConnection api = jwtApiForServiceAccount(); - Date after = new Date(0L); - Date before = new Date(System.currentTimeMillis()); - EventLog events = EventLog.getEnterpriseEvents(api, new EnterpriseEventsRequest().after(after).before(before)); - - assertThat(events.getSize(), is(not(0))); - assertThat(events.getStartDate(), is(equalTo(after))); - assertThat(events.getEndDate(), is(equalTo(before))); - } - - @Test - public void getEnterpriseEventsGmtPlus530Deprecated() { - BoxAPIConnection api = jwtApiForServiceAccount(); - System.setProperty("user.timezone", "Asia/Calcutta"); - TimeZone.setDefault(null); - Date after = new Date(0L); - Date before = new Date(System.currentTimeMillis()); - EventLog events = EventLog.getEnterpriseEvents(api, new EnterpriseEventsRequest().after(after).before(before)); - - assertThat(events.getSize(), is(not(0))); - assertThat(events.getStartDate(), is(equalTo(after))); - assertThat(events.getEndDate(), is(equalTo(before))); - } - - @Test - public void getEnterpriseEventsGmtPlus530WithLimitDeprecated() { - BoxAPIConnection api = jwtApiForServiceAccount(); - System.setProperty("user.timezone", "Asia/Calcutta"); - TimeZone.setDefault(null); - Date after = new Date(0L); - Date before = new Date(System.currentTimeMillis()); - int limit = 5; - EventLog events = EventLog.getEnterpriseEvents( - api, new EnterpriseEventsRequest().after(after).before(before).limit(limit) - ); - - assertThat(events.getSize(), is(not(0))); - assertThat(events.getStartDate(), is(equalTo(after))); - assertThat(events.getEndDate(), is(equalTo(before))); - assertThat(events.getLimit(), is(equalTo(limit))); - } + @Test + public void getEnterpriseEventsReturnsAtLeastOneEvent() { + BoxAPIConnection api = jwtApiForServiceAccount(); + Date after = new Date(0L); + Date before = new Date(System.currentTimeMillis()); + + EnterpriseEventsRequest request = new EnterpriseEventsRequest().after(after).before(before); + EventLog events = EventLog.getEnterpriseEvents(api, request); + + assertThat(events.getSize(), is(not(0))); + assertThat(events.getStartDate(), is(equalTo(after))); + assertThat(events.getEndDate(), is(equalTo(before))); + } + + @Test + public void getEnterpriseEventsGmtPlus530() { + BoxAPIConnection api = jwtApiForServiceAccount(); + System.setProperty("user.timezone", "Asia/Calcutta"); + TimeZone.setDefault(null); + Date after = new Date(0L); + Date before = new Date(System.currentTimeMillis()); + + EnterpriseEventsRequest request = new EnterpriseEventsRequest().after(after).before(before); + EventLog events = EventLog.getEnterpriseEvents(api, request); + + assertThat(events.getSize(), is(not(0))); + assertThat(events.getStartDate(), is(equalTo(after))); + assertThat(events.getEndDate(), is(equalTo(before))); + } + + @Test + public void getEnterpriseEventsGmtPlus530WithLimit() { + BoxAPIConnection api = jwtApiForServiceAccount(); + System.setProperty("user.timezone", "Asia/Calcutta"); + TimeZone.setDefault(null); + Date after = new Date(0L); + Date before = new Date(System.currentTimeMillis()); + int limit = 5; + + EnterpriseEventsRequest request = + new EnterpriseEventsRequest().after(after).before(before).limit(limit); + EventLog events = EventLog.getEnterpriseEvents(api, request); + + assertThat(events.getSize(), is(not(0))); + assertThat(events.getStartDate(), is(equalTo(after))); + assertThat(events.getEndDate(), is(equalTo(before))); + assertThat(events.getLimit(), is(equalTo(limit))); + } + + @Test + public void getEnterpriseEventsStreamReturnsAtLeastOneEvent() { + BoxAPIConnection api = jwtApiForServiceAccount(); + + EnterpriseEventsStreamRequest request = new EnterpriseEventsStreamRequest(); + EventLog events = EventLog.getEnterpriseEventsStream(api, request); + + assertThat(events.getSize(), is(not(0))); + } + + @Test + public void getEnterpriseEventsReturnsAtLeastOneEventDeprecated() { + BoxAPIConnection api = jwtApiForServiceAccount(); + Date after = new Date(0L); + Date before = new Date(System.currentTimeMillis()); + EventLog events = + EventLog.getEnterpriseEvents( + api, new EnterpriseEventsRequest().after(after).before(before)); + + assertThat(events.getSize(), is(not(0))); + assertThat(events.getStartDate(), is(equalTo(after))); + assertThat(events.getEndDate(), is(equalTo(before))); + } + + @Test + public void getEnterpriseEventsGmtPlus530Deprecated() { + BoxAPIConnection api = jwtApiForServiceAccount(); + System.setProperty("user.timezone", "Asia/Calcutta"); + TimeZone.setDefault(null); + Date after = new Date(0L); + Date before = new Date(System.currentTimeMillis()); + EventLog events = + EventLog.getEnterpriseEvents( + api, new EnterpriseEventsRequest().after(after).before(before)); + + assertThat(events.getSize(), is(not(0))); + assertThat(events.getStartDate(), is(equalTo(after))); + assertThat(events.getEndDate(), is(equalTo(before))); + } + + @Test + public void getEnterpriseEventsGmtPlus530WithLimitDeprecated() { + BoxAPIConnection api = jwtApiForServiceAccount(); + System.setProperty("user.timezone", "Asia/Calcutta"); + TimeZone.setDefault(null); + Date after = new Date(0L); + Date before = new Date(System.currentTimeMillis()); + int limit = 5; + EventLog events = + EventLog.getEnterpriseEvents( + api, new EnterpriseEventsRequest().after(after).before(before).limit(limit)); + + assertThat(events.getSize(), is(not(0))); + assertThat(events.getStartDate(), is(equalTo(after))); + assertThat(events.getEndDate(), is(equalTo(before))); + assertThat(events.getLimit(), is(equalTo(limit))); + } } diff --git a/src/intTest/java/com/box/sdk/EventStreamIT.java b/src/intTest/java/com/box/sdk/EventStreamIT.java index 1971bcd1a..0309407ff 100644 --- a/src/intTest/java/com/box/sdk/EventStreamIT.java +++ b/src/intTest/java/com/box/sdk/EventStreamIT.java @@ -12,73 +12,75 @@ public class EventStreamIT { - @Test - public void receiveEventsForFolderCreateAndFolderDelete() throws InterruptedException { - final LinkedBlockingQueue observedEvents = new LinkedBlockingQueue<>(); - BoxAPIConnection api = jwtApiForServiceAccount(); - EventStream stream = new EventStream(api); - stream.addListener(new EventListener() { - @Override - public void onEvent(BoxEvent event) { - observedEvents.add(event); - } + @Test + public void receiveEventsForFolderCreateAndFolderDelete() throws InterruptedException { + final LinkedBlockingQueue observedEvents = new LinkedBlockingQueue<>(); + BoxAPIConnection api = jwtApiForServiceAccount(); + EventStream stream = new EventStream(api); + stream.addListener( + new EventListener() { + @Override + public void onEvent(BoxEvent event) { + observedEvents.add(event); + } - @Override - public void onNextPosition(long position) { - } + @Override + public void onNextPosition(long position) {} - @Override - public boolean onException(Throwable e) { - return true; - } + @Override + public boolean onException(Throwable e) { + return true; + } }); - stream.start(); + stream.start(); - BoxFolder rootFolder = BoxFolder.getRootFolder(api); - BoxFolder childFolder = rootFolder.createFolder( - randomizeName("[receiveEventsForFolderCreateAndFolderDelete] Child Folder") - ).getResource(); - String expectedID = childFolder.getID(); - childFolder.delete(false); + BoxFolder rootFolder = BoxFolder.getRootFolder(api); + BoxFolder childFolder = + rootFolder + .createFolder( + randomizeName("[receiveEventsForFolderCreateAndFolderDelete] Child Folder")) + .getResource(); + String expectedID = childFolder.getID(); + childFolder.delete(false); - boolean createdEventFound = false; - boolean deletedEventFound = false; - int timeouts = 0; - while (timeouts < 3 && (!createdEventFound || !deletedEventFound)) { - BoxEvent event = observedEvents.poll(1, TimeUnit.MINUTES); - if (null == event) { - timeouts++; - System.out.println("Time outs: " + timeouts); - continue; - } - BoxResource.Info sourceInfo = event.getSourceInfo(); - // Some events may not have sourceInfo - if (sourceInfo == null) { - continue; - } - BoxResource source = sourceInfo.getResource(); - if (source instanceof BoxFolder) { - BoxFolder sourceFolder = (BoxFolder) source; - if (sourceFolder.getID().equals(expectedID)) { - if (event.getEventType() == BoxEvent.EventType.ITEM_CREATE) { - BoxFolder folder = (BoxFolder) event.getSourceInfo().getResource(); - final String eventFolderID = folder.getID(); - final String childFolderID = childFolder.getID(); - assertThat(eventFolderID, is(equalTo(childFolderID))); - createdEventFound = true; - } + boolean createdEventFound = false; + boolean deletedEventFound = false; + int timeouts = 0; + while (timeouts < 3 && (!createdEventFound || !deletedEventFound)) { + BoxEvent event = observedEvents.poll(1, TimeUnit.MINUTES); + if (null == event) { + timeouts++; + System.out.println("Time outs: " + timeouts); + continue; + } + BoxResource.Info sourceInfo = event.getSourceInfo(); + // Some events may not have sourceInfo + if (sourceInfo == null) { + continue; + } + BoxResource source = sourceInfo.getResource(); + if (source instanceof BoxFolder) { + BoxFolder sourceFolder = (BoxFolder) source; + if (sourceFolder.getID().equals(expectedID)) { + if (event.getEventType() == BoxEvent.EventType.ITEM_CREATE) { + BoxFolder folder = (BoxFolder) event.getSourceInfo().getResource(); + final String eventFolderID = folder.getID(); + final String childFolderID = childFolder.getID(); + assertThat(eventFolderID, is(equalTo(childFolderID))); + createdEventFound = true; + } - if (event.getEventType() == BoxEvent.EventType.ITEM_TRASH) { - BoxFolder folder = (BoxFolder) event.getSourceInfo().getResource(); - assertThat(folder.getID(), is(equalTo(childFolder.getID()))); - deletedEventFound = true; - } - } - } + if (event.getEventType() == BoxEvent.EventType.ITEM_TRASH) { + BoxFolder folder = (BoxFolder) event.getSourceInfo().getResource(); + assertThat(folder.getID(), is(equalTo(childFolder.getID()))); + deletedEventFound = true; + } } - - assertThat(createdEventFound, is(true)); - assertThat(deletedEventFound, is(true)); - stream.stop(); + } } + + assertThat(createdEventFound, is(true)); + assertThat(deletedEventFound, is(true)); + stream.stop(); + } } diff --git a/src/intTest/java/com/box/sdk/FileUtils.java b/src/intTest/java/com/box/sdk/FileUtils.java index 94f32c041..a12f31629 100644 --- a/src/intTest/java/com/box/sdk/FileUtils.java +++ b/src/intTest/java/com/box/sdk/FileUtils.java @@ -8,46 +8,47 @@ import java.util.Random; import java.util.stream.IntStream; -/** - * Utility class for working with test files - */ +/** Utility class for working with test files */ public final class FileUtils { - private static final int BUFFER_SIZE = 1000; + private static final int BUFFER_SIZE = 1000; - private FileUtils() { - // hide constructor in utility class - } + private FileUtils() { + // hide constructor in utility class + } - /** - * Generates file with random content. Uses BUFFER_SIZE to write generated content in batches. - * Generated file will be removed when JVM Terminates see {@link File#deleteOnExit()} - * - * @param fileName Name of the file to generate - * @param fileSizeInBytes Size of the file to generate. Cannot be lower than BUFFER_SIZE - * @return Generated files. - */ - public static File generate(String fileName, int fileSizeInBytes) { - if (fileSizeInBytes < BUFFER_SIZE) { - throw new IllegalArgumentException(format( - "Provides file size [%d]b must be larger than buffer [%d]b", fileSizeInBytes, BUFFER_SIZE - )); - } - File file = new File(fileName); - try (FileOutputStream outputStream = new FileOutputStream(file)) { - IntStream.range(0, fileSizeInBytes / BUFFER_SIZE + 1).forEach((i) -> { + /** + * Generates file with random content. Uses BUFFER_SIZE to write generated content in batches. + * Generated file will be removed when JVM Terminates see {@link File#deleteOnExit()} + * + * @param fileName Name of the file to generate + * @param fileSizeInBytes Size of the file to generate. Cannot be lower than BUFFER_SIZE + * @return Generated files. + */ + public static File generate(String fileName, int fileSizeInBytes) { + if (fileSizeInBytes < BUFFER_SIZE) { + throw new IllegalArgumentException( + format( + "Provides file size [%d]b must be larger than buffer [%d]b", + fileSizeInBytes, BUFFER_SIZE)); + } + File file = new File(fileName); + try (FileOutputStream outputStream = new FileOutputStream(file)) { + IntStream.range(0, fileSizeInBytes / BUFFER_SIZE + 1) + .forEach( + (i) -> { byte[] bytes = new byte[1000]; new Random().nextBytes(bytes); try { - outputStream.write(bytes); + outputStream.write(bytes); } catch (IOException e) { - throw new RuntimeException(e); + throw new RuntimeException(e); } - }); - } catch (IOException e) { - throw new RuntimeException(format("Failed to create file '%s'", file), e); - } - file.deleteOnExit(); - return file; + }); + } catch (IOException e) { + throw new RuntimeException(format("Failed to create file '%s'", file), e); } + file.deleteOnExit(); + return file; + } } diff --git a/src/intTest/java/com/box/sdk/MetadataIT.java b/src/intTest/java/com/box/sdk/MetadataIT.java index 41c860eb2..ddacf9426 100644 --- a/src/intTest/java/com/box/sdk/MetadataIT.java +++ b/src/intTest/java/com/box/sdk/MetadataIT.java @@ -21,203 +21,204 @@ public class MetadataIT { - @BeforeClass - public static void beforeClass() { - setupUniqeFolder(); + @BeforeClass + public static void beforeClass() { + setupUniqeFolder(); + } + + @AfterClass + public static void afterClass() { + removeUniqueFolder(); + } + + @Test + public void testMetadataPrecisionDouble() { + final double valueDouble = 233333333333333340.0; + BoxAPIConnection api = jwtApiForServiceAccount(); + + long timestamp = Calendar.getInstance().getTimeInMillis(); + String templateKey = "precision" + timestamp; + String fieldKey = "testPrecision"; + + List fields = new ArrayList<>(); + MetadataTemplate.Field valueField = new MetadataTemplate.Field(); + valueField.setKey(fieldKey); + valueField.setType("float"); + valueField.setDisplayName("Value Field"); + fields.add(valueField); + + MetadataTemplate template = + MetadataTemplate.createMetadataTemplate( + api, "enterprise", templateKey, "Precision " + timestamp, false, fields); + try { + 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); + + assertEquals(templateKey, actualMD.getTemplateName()); + assertEquals(valueDouble, actualMD.getDouble("/" + fieldKey), 0); + } finally { + this.deleteMetadata(api, template); } - - @AfterClass - public static void afterClass() { - removeUniqueFolder(); - } - - @Test - public void testMetadataPrecisionDouble() { - final double valueDouble = 233333333333333340.0; - BoxAPIConnection api = jwtApiForServiceAccount(); - - long timestamp = Calendar.getInstance().getTimeInMillis(); - String templateKey = "precision" + timestamp; - String fieldKey = "testPrecision"; - - List fields = new ArrayList<>(); - MetadataTemplate.Field valueField = new MetadataTemplate.Field(); - valueField.setKey(fieldKey); - valueField.setType("float"); - valueField.setDisplayName("Value Field"); - fields.add(valueField); - - MetadataTemplate template = MetadataTemplate.createMetadataTemplate(api, "enterprise", - templateKey, "Precision " + timestamp, false, fields); - try { - 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); - - assertEquals(templateKey, actualMD.getTemplateName()); - assertEquals(valueDouble, actualMD.getDouble("/" + fieldKey), 0); - } finally { - this.deleteMetadata(api, template); + } + + @Test + public void testMultiSelectMetadataCRUD() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder folder = null; + MetadataTemplate template = null; + + try { + long timestamp = Calendar.getInstance().getTimeInMillis(); + String templateKey = "multiselect" + timestamp; + String fieldKey = "testMultiSelect"; + + // Create new template with multiselect field + List fieldOptions = new ArrayList<>(); + fieldOptions.add("foo"); + fieldOptions.add("bar"); + fieldOptions.add("baz"); + fieldOptions.add("quux"); + + List fields = new ArrayList<>(); + MetadataTemplate.Field multiSelectField = new MetadataTemplate.Field(); + multiSelectField.setKey(fieldKey); + multiSelectField.setType("multiSelect"); + multiSelectField.setDisplayName("MultiSelect Field"); + multiSelectField.setOptions(fieldOptions); + fields.add(multiSelectField); + + template = + MetadataTemplate.createMetadataTemplate( + api, "enterprise", templateKey, "MultiSelect " + timestamp, false, fields); + + assertEquals("multiSelect", template.getFields().get(0).getType()); + List actualOptions = template.getFields().get(0).getOptions(); + assertEquals("foo", actualOptions.get(0)); + assertEquals("bar", actualOptions.get(1)); + assertEquals("baz", actualOptions.get(2)); + assertEquals("quux", actualOptions.get(3)); + + // Add template to item + Metadata mdValues = new Metadata(); + List values = new ArrayList<>(); + values.add("foo"); + values.add("bar"); + mdValues.add("/" + fieldKey, values); + folder = getUniqueFolder(api).createFolder("Metadata Test " + timestamp).getResource(); + Metadata actualMD = folder.createMetadata(templateKey, mdValues); + + assertEquals(templateKey, actualMD.getTemplateName()); + List multiSelectValues = actualMD.getMultiSelect("/" + fieldKey); + assertThat(multiSelectValues, hasSize(2)); + assertThat(multiSelectValues, containsInAnyOrder("foo", "bar")); + + // Update template with multiselect operations - change existing field and add another + // multiselect field + List updates = new ArrayList<>(); + + MetadataTemplate.Field newOption = new MetadataTemplate.Field(); + newOption.setKey("blargh"); + MetadataTemplate.FieldOperation add = new MetadataTemplate.FieldOperation(); + add.setOp(MetadataTemplate.Operation.addMultiSelectOption); + add.setFieldKey(fieldKey); + add.setData(newOption); + updates.add(add); + + MetadataTemplate.Field updatedField = new MetadataTemplate.Field(); + updatedField.setKey("foooooo"); + MetadataTemplate.FieldOperation edit = new MetadataTemplate.FieldOperation(); + edit.setOp(MetadataTemplate.Operation.editMultiSelectOption); + edit.setFieldKey(fieldKey); + edit.setMultiSelectOptionKey("foo"); + edit.setData(updatedField); + updates.add(edit); + + MetadataTemplate.FieldOperation remove = new MetadataTemplate.FieldOperation(); + remove.setOp(MetadataTemplate.Operation.removeMultiSelectOption); + remove.setFieldKey(fieldKey); + remove.setMultiSelectOptionKey("baz"); + updates.add(remove); + + MetadataTemplate.FieldOperation reorder = new MetadataTemplate.FieldOperation(); + reorder.setOp(MetadataTemplate.Operation.reorderMultiSelectOptions); + reorder.setFieldKey(fieldKey); + List reorderedFields = new ArrayList<>(); + reorderedFields.add("quux"); + reorderedFields.add("blargh"); + reorderedFields.add("bar"); + reorderedFields.add("foooooo"); + reorder.setMultiSelectOptionKeys(reorderedFields); + updates.add(reorder); + + MetadataTemplate.FieldOperation addField = new MetadataTemplate.FieldOperation(); + MetadataTemplate.Field newField = new MetadataTemplate.Field(); + List opts = new ArrayList<>(); + opts.add("one"); + opts.add("two"); + newField.setKey("otherMultiSelect"); + newField.setDisplayName("Another MultiSelect"); + newField.setType("multiSelect"); + newField.setOptions(opts); + addField.setOp(MetadataTemplate.Operation.addField); + addField.setData(newField); + updates.add(addField); + + MetadataTemplate updatedTemplate = + MetadataTemplate.updateMetadataTemplate(api, "enterprise", templateKey, updates); + + assertThat(updatedTemplate.getFields(), Matchers.hasSize(2)); + for (MetadataTemplate.Field field : updatedTemplate.getFields()) { + + if (field.getKey().equals(fieldKey)) { + assertEquals("multiSelect", field.getType()); + actualOptions = field.getOptions(); + assertEquals("quux", actualOptions.get(0)); + assertEquals("blargh", actualOptions.get(1)); + assertEquals("bar", actualOptions.get(2)); + assertEquals("foooooo", actualOptions.get(3)); + } else if (field.getKey().equals("otherMultiSelect")) { + assertEquals("multiSelect", field.getType()); + actualOptions = field.getOptions(); + assertEquals("one", actualOptions.get(0)); + assertEquals("two", actualOptions.get(1)); + } else { + fail("Incorrect field found on metadata template: " + field.getKey()); } + } + + // Update instance multiselect field + actualMD.test("/" + fieldKey + "/1", "bar"); + values = new ArrayList<>(); + values.add("two"); + values.add("one"); + actualMD.add("/otherMultiSelect", values); + actualMD.remove("/" + fieldKey + "/0"); + actualMD.add("/" + fieldKey + "/-", "blargh"); + Metadata updatedMD = folder.updateMetadata(actualMD); + + multiSelectValues = updatedMD.getMultiSelect("/" + fieldKey); + assertThat(multiSelectValues, Matchers.hasSize(2)); + assertThat(multiSelectValues, containsInAnyOrder("bar", "blargh")); + multiSelectValues = updatedMD.getMultiSelect("/otherMultiSelect"); + assertThat(multiSelectValues, hasSize(2)); + assertThat(multiSelectValues, containsInAnyOrder("one", "two")); + + // Delete metadata template and folder + } finally { + this.deleteMetadata(api, template); + deleteFolder(folder); } + } - @Test - public void testMultiSelectMetadataCRUD() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder folder = null; - MetadataTemplate template = null; - - try { - long timestamp = Calendar.getInstance().getTimeInMillis(); - String templateKey = "multiselect" + timestamp; - String fieldKey = "testMultiSelect"; - - // Create new template with multiselect field - List fieldOptions = new ArrayList<>(); - fieldOptions.add("foo"); - fieldOptions.add("bar"); - fieldOptions.add("baz"); - fieldOptions.add("quux"); - - List fields = new ArrayList<>(); - MetadataTemplate.Field multiSelectField = new MetadataTemplate.Field(); - multiSelectField.setKey(fieldKey); - multiSelectField.setType("multiSelect"); - multiSelectField.setDisplayName("MultiSelect Field"); - multiSelectField.setOptions(fieldOptions); - fields.add(multiSelectField); - - template = MetadataTemplate.createMetadataTemplate(api, "enterprise", - templateKey, "MultiSelect " + timestamp, false, fields); - - assertEquals("multiSelect", template.getFields().get(0).getType()); - List actualOptions = template.getFields().get(0).getOptions(); - assertEquals("foo", actualOptions.get(0)); - assertEquals("bar", actualOptions.get(1)); - assertEquals("baz", actualOptions.get(2)); - assertEquals("quux", actualOptions.get(3)); - - // Add template to item - Metadata mdValues = new Metadata(); - List values = new ArrayList<>(); - values.add("foo"); - values.add("bar"); - mdValues.add("/" + fieldKey, values); - folder = getUniqueFolder(api).createFolder("Metadata Test " + timestamp).getResource(); - Metadata actualMD = folder.createMetadata(templateKey, mdValues); - - assertEquals(templateKey, actualMD.getTemplateName()); - List multiSelectValues = actualMD.getMultiSelect("/" + fieldKey); - assertThat(multiSelectValues, hasSize(2)); - assertThat(multiSelectValues, containsInAnyOrder("foo", "bar")); - - // Update template with multiselect operations - change existing field and add another multiselect field - List updates = new ArrayList<>(); - - MetadataTemplate.Field newOption = new MetadataTemplate.Field(); - newOption.setKey("blargh"); - MetadataTemplate.FieldOperation add = new MetadataTemplate.FieldOperation(); - add.setOp(MetadataTemplate.Operation.addMultiSelectOption); - add.setFieldKey(fieldKey); - add.setData(newOption); - updates.add(add); - - MetadataTemplate.Field updatedField = new MetadataTemplate.Field(); - updatedField.setKey("foooooo"); - MetadataTemplate.FieldOperation edit = new MetadataTemplate.FieldOperation(); - edit.setOp(MetadataTemplate.Operation.editMultiSelectOption); - edit.setFieldKey(fieldKey); - edit.setMultiSelectOptionKey("foo"); - edit.setData(updatedField); - updates.add(edit); - - MetadataTemplate.FieldOperation remove = new MetadataTemplate.FieldOperation(); - remove.setOp(MetadataTemplate.Operation.removeMultiSelectOption); - remove.setFieldKey(fieldKey); - remove.setMultiSelectOptionKey("baz"); - updates.add(remove); - - MetadataTemplate.FieldOperation reorder = new MetadataTemplate.FieldOperation(); - reorder.setOp(MetadataTemplate.Operation.reorderMultiSelectOptions); - reorder.setFieldKey(fieldKey); - List reorderedFields = new ArrayList<>(); - reorderedFields.add("quux"); - reorderedFields.add("blargh"); - reorderedFields.add("bar"); - reorderedFields.add("foooooo"); - reorder.setMultiSelectOptionKeys(reorderedFields); - updates.add(reorder); - - MetadataTemplate.FieldOperation addField = new MetadataTemplate.FieldOperation(); - MetadataTemplate.Field newField = new MetadataTemplate.Field(); - List opts = new ArrayList<>(); - opts.add("one"); - opts.add("two"); - newField.setKey("otherMultiSelect"); - newField.setDisplayName("Another MultiSelect"); - newField.setType("multiSelect"); - newField.setOptions(opts); - addField.setOp(MetadataTemplate.Operation.addField); - addField.setData(newField); - updates.add(addField); - - MetadataTemplate updatedTemplate = - MetadataTemplate.updateMetadataTemplate(api, "enterprise", templateKey, updates); - - assertThat(updatedTemplate.getFields(), Matchers.hasSize(2)); - for (MetadataTemplate.Field field : updatedTemplate.getFields()) { - - if (field.getKey().equals(fieldKey)) { - assertEquals("multiSelect", field.getType()); - actualOptions = field.getOptions(); - assertEquals("quux", actualOptions.get(0)); - assertEquals("blargh", actualOptions.get(1)); - assertEquals("bar", actualOptions.get(2)); - assertEquals("foooooo", actualOptions.get(3)); - } else if (field.getKey().equals("otherMultiSelect")) { - assertEquals("multiSelect", field.getType()); - actualOptions = field.getOptions(); - assertEquals("one", actualOptions.get(0)); - assertEquals("two", actualOptions.get(1)); - } else { - fail("Incorrect field found on metadata template: " + field.getKey()); - } - } - - // Update instance multiselect field - actualMD.test("/" + fieldKey + "/1", "bar"); - values = new ArrayList<>(); - values.add("two"); - values.add("one"); - actualMD.add("/otherMultiSelect", values); - actualMD.remove("/" + fieldKey + "/0"); - actualMD.add("/" + fieldKey + "/-", "blargh"); - Metadata updatedMD = folder.updateMetadata(actualMD); - - multiSelectValues = updatedMD.getMultiSelect("/" + fieldKey); - assertThat(multiSelectValues, Matchers.hasSize(2)); - assertThat(multiSelectValues, containsInAnyOrder("bar", "blargh")); - multiSelectValues = updatedMD.getMultiSelect("/otherMultiSelect"); - assertThat(multiSelectValues, hasSize(2)); - assertThat(multiSelectValues, containsInAnyOrder("one", "two")); - - // Delete metadata template and folder - } finally { - this.deleteMetadata(api, template); - deleteFolder(folder); - - } + private void deleteMetadata(BoxAPIConnection api, MetadataTemplate template) { + if (template != null) { + MetadataTemplate.deleteMetadataTemplate(api, template.getScope(), template.getTemplateKey()); } - - private void deleteMetadata(BoxAPIConnection api, MetadataTemplate template) { - if (template != null) { - 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 e7a2c4f3d..3955516a3 100644 --- a/src/intTest/java/com/box/sdk/MetadataTemplateIT.java +++ b/src/intTest/java/com/box/sdk/MetadataTemplateIT.java @@ -23,303 +23,299 @@ import org.junit.BeforeClass; import org.junit.Test; -/** - * {@link MetadataTemplate} related integration tests. - */ +/** {@link MetadataTemplate} related integration tests. */ public class MetadataTemplateIT { - @BeforeClass - public static void setup() { - setupUniqeFolder(); + @BeforeClass + public static void setup() { + setupUniqeFolder(); + } + + @AfterClass + public static void tearDown() { + removeUniqueFolder(); + } + + @Test + public void createAndDeleteMetadataTemplateSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + + MetadataTemplate.Field ctField = new MetadataTemplate.Field(); + ctField.setType("string"); + ctField.setKey("customerTeam"); + ctField.setDisplayName("Customer Team"); + + MetadataTemplate.Field fyField = new MetadataTemplate.Field(); + fyField.setType("enum"); + fyField.setKey("fy"); + fyField.setDisplayName("FY"); + + List options = new ArrayList<>(); + options.add("FY16"); + options.add("FY17"); + fyField.setOptions(options); + + List fields = new ArrayList<>(); + fields.add(ctField); + fields.add(fyField); + + String scope = "enterprise"; + String templateKey = "documentFlow03"; + MetadataTemplate.createMetadataTemplate( + api, scope, templateKey, "Document Flow 03", false, fields); + + MetadataTemplate storedTemplate = MetadataTemplate.getMetadataTemplate(api, templateKey, scope); + Assert.assertNotNull(storedTemplate); + + MetadataTemplate.deleteMetadataTemplate(api, scope, templateKey); + try { + MetadataTemplate.getMetadataTemplate(api, templateKey, scope); + } catch (BoxAPIException e) { + assertEquals(e.getResponseCode(), e.getResponseCode()); } + } - @AfterClass - public static void tearDown() { - removeUniqueFolder(); - } - - @Test - public void createAndDeleteMetadataTemplateSucceeds() { - BoxAPIConnection api = jwtApiForServiceAccount(); - - MetadataTemplate.Field ctField = new MetadataTemplate.Field(); - ctField.setType("string"); - ctField.setKey("customerTeam"); - ctField.setDisplayName("Customer Team"); + @Test + public void updateMetadataTemplateFieldsSucceeds() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String scope = "enterprise"; + String templateKey = "documentFlow03"; - MetadataTemplate.Field fyField = new MetadataTemplate.Field(); - fyField.setType("enum"); - fyField.setKey("fy"); - fyField.setDisplayName("FY"); + MetadataTemplate template = + MetadataTemplate.createMetadataTemplate( + api, scope, templateKey, templateKey, false, new ArrayList<>()); + try { + // Test adding fields + List fieldOperations = this.addFieldsHelper(); + template = MetadataTemplate.updateMetadataTemplate(api, scope, templateKey, fieldOperations); + Assert.assertNotNull(template); + + boolean foundDeptField = false; + boolean foundCustField = false; + for (MetadataTemplate.Field field : template.getFields()) { + if ("department".equals(field.getKey())) { + assertEquals("enum", field.getType()); + assertEquals("Department", field.getDisplayName()); + assertEquals(2, field.getOptions().size()); + foundDeptField = true; + } else if ("customerTeam".equals(field.getKey())) { + foundCustField = true; + } + } + assertTrue("department field was not found", foundDeptField); + assertTrue("customer field was not found", foundCustField); + + // Test editing fields + fieldOperations.clear(); + + MetadataTemplate.FieldOperation customerFieldOp = new MetadataTemplate.FieldOperation(); + customerFieldOp.setOp(MetadataTemplate.Operation.editField); + customerFieldOp.setFieldKey("customerTeam"); + + MetadataTemplate.Field customerTeam = new MetadataTemplate.Field(); + customerTeam.setDisplayName("Customer Team Renamed"); + customerTeam.setKey("newCustomerTeamKey"); + customerFieldOp.setData(customerTeam); + fieldOperations.add(customerFieldOp); + + MetadataTemplate.FieldOperation editEnumOption = new MetadataTemplate.FieldOperation(); + editEnumOption.setOp(MetadataTemplate.Operation.editEnumOption); + editEnumOption.setFieldKey("department"); + editEnumOption.setEnumOptionKey("Shoes"); + + MetadataTemplate.Field deptField = new MetadataTemplate.Field(); + deptField.setKey("Baby"); + editEnumOption.setData(deptField); + + fieldOperations.add(editEnumOption); + + template = MetadataTemplate.updateMetadataTemplate(api, scope, templateKey, fieldOperations); + boolean foundBabyEnumOption = false; + for (MetadataTemplate.Field field : template.getFields()) { + if ("customerTeam".equals(field.getKey())) { + Assert.fail("'customerTeam' field key should have been changed to 'newCustomerTeamKey'"); + } else if ("department".equals(field.getKey())) { + for (String option : field.getOptions()) { + if ("Baby".equals(option)) { + foundBabyEnumOption = true; + break; + } + } + } else if ("newCustomerTeamKey".equals(field.getKey())) { + assertEquals( + "Display name should have been updated", + "Customer Team Renamed", + field.getDisplayName()); + } + } + assertTrue("Baby enum option was not found", foundBabyEnumOption); - List options = new ArrayList<>(); - options.add("FY16"); - options.add("FY17"); - fyField.setOptions(options); + // Test removing fields + fieldOperations.clear(); - List fields = new ArrayList<>(); - fields.add(ctField); - fields.add(fyField); + MetadataTemplate.FieldOperation deleteDeptField = new MetadataTemplate.FieldOperation(); + deleteDeptField.setOp(MetadataTemplate.Operation.removeField); + deleteDeptField.setFieldKey("newCustomerTeamKey"); + fieldOperations.add(deleteDeptField); - String scope = "enterprise"; - String templateKey = "documentFlow03"; - MetadataTemplate.createMetadataTemplate( - api, scope, templateKey, "Document Flow 03", false, fields - ); + MetadataTemplate.FieldOperation deleteEnumOption = new MetadataTemplate.FieldOperation(); + deleteEnumOption.setOp(MetadataTemplate.Operation.removeEnumOption); + deleteEnumOption.setFieldKey("department"); + deleteEnumOption.setEnumOptionKey("Baby"); - MetadataTemplate storedTemplate = MetadataTemplate.getMetadataTemplate(api, templateKey, scope); - Assert.assertNotNull(storedTemplate); + fieldOperations.add(deleteEnumOption); - MetadataTemplate.deleteMetadataTemplate(api, scope, templateKey); - try { - MetadataTemplate.getMetadataTemplate(api, templateKey, scope); - } catch (BoxAPIException e) { - assertEquals(e.getResponseCode(), e.getResponseCode()); - } - } + template = MetadataTemplate.updateMetadataTemplate(api, scope, templateKey, fieldOperations); - @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(); - template = MetadataTemplate.updateMetadataTemplate(api, - scope, templateKey, fieldOperations); - Assert.assertNotNull(template); - - boolean foundDeptField = false; - boolean foundCustField = false; - for (MetadataTemplate.Field field : template.getFields()) { - if ("department".equals(field.getKey())) { - assertEquals("enum", field.getType()); - assertEquals("Department", field.getDisplayName()); - assertEquals(2, field.getOptions().size()); - foundDeptField = true; - } else if ("customerTeam".equals(field.getKey())) { - foundCustField = true; - } + for (MetadataTemplate.Field field : template.getFields()) { + if ("newCustomerTeamKey".equals(field.getKey())) { + Assert.fail("newCustomerTeamKey field key should have been deleted"); + } else if ("department".equals(field.getKey())) { + for (String option : field.getOptions()) { + if ("Baby".equals(option)) { + Assert.fail("Baby enum option should have been deleted"); } - assertTrue("department field was not found", foundDeptField); - assertTrue("customer field was not found", foundCustField); - - //Test editing fields - fieldOperations.clear(); - - MetadataTemplate.FieldOperation customerFieldOp = new MetadataTemplate.FieldOperation(); - customerFieldOp.setOp(MetadataTemplate.Operation.editField); - customerFieldOp.setFieldKey("customerTeam"); - - MetadataTemplate.Field customerTeam = new MetadataTemplate.Field(); - customerTeam.setDisplayName("Customer Team Renamed"); - customerTeam.setKey("newCustomerTeamKey"); - customerFieldOp.setData(customerTeam); - fieldOperations.add(customerFieldOp); - - MetadataTemplate.FieldOperation editEnumOption = new MetadataTemplate.FieldOperation(); - editEnumOption.setOp(MetadataTemplate.Operation.editEnumOption); - editEnumOption.setFieldKey("department"); - editEnumOption.setEnumOptionKey("Shoes"); - - - MetadataTemplate.Field deptField = new MetadataTemplate.Field(); - deptField.setKey("Baby"); - editEnumOption.setData(deptField); - - fieldOperations.add(editEnumOption); - - template = MetadataTemplate.updateMetadataTemplate(api, - scope, templateKey, fieldOperations); - boolean foundBabyEnumOption = false; - for (MetadataTemplate.Field field : template.getFields()) { - if ("customerTeam".equals(field.getKey())) { - Assert.fail("'customerTeam' field key should have been changed to 'newCustomerTeamKey'"); - } else if ("department".equals(field.getKey())) { - for (String option : field.getOptions()) { - if ("Baby".equals(option)) { - foundBabyEnumOption = true; - break; - } - } - } else if ("newCustomerTeamKey".equals(field.getKey())) { - assertEquals("Display name should have been updated", - "Customer Team Renamed", field.getDisplayName()); - } - } - assertTrue("Baby enum option was not found", foundBabyEnumOption); - - //Test removing fields - fieldOperations.clear(); - - MetadataTemplate.FieldOperation deleteDeptField = new MetadataTemplate.FieldOperation(); - deleteDeptField.setOp(MetadataTemplate.Operation.removeField); - deleteDeptField.setFieldKey("newCustomerTeamKey"); - fieldOperations.add(deleteDeptField); - - MetadataTemplate.FieldOperation deleteEnumOption = new MetadataTemplate.FieldOperation(); - deleteEnumOption.setOp(MetadataTemplate.Operation.removeEnumOption); - deleteEnumOption.setFieldKey("department"); - deleteEnumOption.setEnumOptionKey("Baby"); - - fieldOperations.add(deleteEnumOption); - - template = MetadataTemplate.updateMetadataTemplate(api, scope, templateKey, fieldOperations); - - for (MetadataTemplate.Field field : template.getFields()) { - if ("newCustomerTeamKey".equals(field.getKey())) { - Assert.fail("newCustomerTeamKey field key should have been deleted"); - } else if ("department".equals(field.getKey())) { - for (String option : field.getOptions()) { - if ("Baby".equals(option)) { - Assert.fail("Baby enum option should have been deleted"); - } - } - } - } - } finally { - deleteMetadataTemplate(api, template); + } } + } + } finally { + deleteMetadataTemplate(api, template); } - - @Test - 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"; - byte[] fileBytes = "Non-empty string".getBytes(StandardCharsets.UTF_8); - - InputStream uploadStream = new ByteArrayInputStream(fileBytes); - uploadedFile = rootFolder.uploadFile(uploadStream, fileName).getResource(); - - uploadedFile.createMetadata(new Metadata().add("/firstName", "John").add("/lastName", "Smith")); - Metadata check1 = uploadedFile.getMetadata(); - Assert.assertNotNull(check1); - assertEquals("John", check1.getString("/firstName")); - assertEquals("Smith", check1.getString("/lastName")); - - //Create fields before test - MetadataTemplate.createMetadataTemplate(api, scope, templateKey, templateKey, false, new ArrayList<>()); - List fieldOperations = this.addFieldsHelper(); - - template = MetadataTemplate.updateMetadataTemplate( - api, scope, templateKey, fieldOperations - ); - Assert.assertNotNull(template); - - Metadata customerMetaData = new Metadata(); - customerMetaData.add("/customerTeam", "MyTeam"); - customerMetaData.add("/department", "Beauty"); - - uploadedFile.createMetadata(templateKey, scope, customerMetaData); - - Iterable allMetadata = uploadedFile.getAllMetadata("/firstName", "/lastName"); - Assert.assertNotNull(allMetadata); - Iterator iter = allMetadata.iterator(); - int numTemplates = 0; - while (iter.hasNext()) { - Metadata metadata = iter.next(); - numTemplates++; - if (metadata.getTemplateName().equals("properties")) { - assertEquals("John", metadata.getString("/firstName")); - assertEquals("Smith", metadata.getString("/lastName")); - } - if (metadata.getTemplateName().equals(templateKey)) { - assertEquals("MyTeam", metadata.getString("/customerTeam")); - assertEquals("Beauty", metadata.getString("/department")); - } - } - Assert.assertTrue("Should have at least 2 templates", numTemplates >= 2); - } finally { - deleteFile(uploadedFile); - deleteMetadataTemplate(api, template); + } + + @Test + 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"; + byte[] fileBytes = "Non-empty string".getBytes(StandardCharsets.UTF_8); + + InputStream uploadStream = new ByteArrayInputStream(fileBytes); + uploadedFile = rootFolder.uploadFile(uploadStream, fileName).getResource(); + + uploadedFile.createMetadata( + new Metadata().add("/firstName", "John").add("/lastName", "Smith")); + Metadata check1 = uploadedFile.getMetadata(); + Assert.assertNotNull(check1); + assertEquals("John", check1.getString("/firstName")); + assertEquals("Smith", check1.getString("/lastName")); + + // Create fields before test + MetadataTemplate.createMetadataTemplate( + api, scope, templateKey, templateKey, false, new ArrayList<>()); + List fieldOperations = this.addFieldsHelper(); + + template = MetadataTemplate.updateMetadataTemplate(api, scope, templateKey, fieldOperations); + Assert.assertNotNull(template); + + Metadata customerMetaData = new Metadata(); + customerMetaData.add("/customerTeam", "MyTeam"); + customerMetaData.add("/department", "Beauty"); + + uploadedFile.createMetadata(templateKey, scope, customerMetaData); + + Iterable allMetadata = uploadedFile.getAllMetadata("/firstName", "/lastName"); + Assert.assertNotNull(allMetadata); + Iterator iter = allMetadata.iterator(); + int numTemplates = 0; + while (iter.hasNext()) { + Metadata metadata = iter.next(); + numTemplates++; + if (metadata.getTemplateName().equals("properties")) { + assertEquals("John", metadata.getString("/firstName")); + assertEquals("Smith", metadata.getString("/lastName")); } - } - - @Test - public void executeMetadataTemplateQuery() { - BoxAPIConnection api = jwtApiForServiceAccount(); - String templateKey = "MyTemplate"; - 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 { - - BoxFolder rootFolder = getUniqueFolder(api); - one = rootFolder.createFolder("one").getResource(); - one.createMetadata(templateKey, "enterprise", new Metadata().add("/myField", 102d)); - two = rootFolder.createFolder("two").getResource(); - two.createMetadata(templateKey, "enterprise", new Metadata().add("/myField", 95d)); - - - MetadataQuery query = new MetadataQuery(format("enterprise_%s.MyTemplate", TestConfig.getEnterpriseID())) - .setQuery("myField > :val") - .addParameter("val", 100) - .setOrderBy(ascending("myField")); - BoxResourceIterable result = MetadataTemplate.executeMetadataQuery(api, query); - Iterator iterator = result.iterator(); - BoxItem.Info foundFolder = iterator.next(); - assertThat(foundFolder.getName(), is("one")); - assertThat(iterator.hasNext(), is(false)); - } finally { - deleteMetadataTemplate(api, template); - deleteFolder(one); - deleteFolder(two); + if (metadata.getTemplateName().equals(templateKey)) { + assertEquals("MyTeam", metadata.getString("/customerTeam")); + assertEquals("Beauty", metadata.getString("/department")); } + } + Assert.assertTrue("Should have at least 2 templates", numTemplates >= 2); + } finally { + deleteFile(uploadedFile); + deleteMetadataTemplate(api, template); } - - 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; + } + + @Test + public void executeMetadataTemplateQuery() { + BoxAPIConnection api = jwtApiForServiceAccount(); + String templateKey = "MyTemplate"; + 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 { + + BoxFolder rootFolder = getUniqueFolder(api); + one = rootFolder.createFolder("one").getResource(); + one.createMetadata(templateKey, "enterprise", new Metadata().add("/myField", 102d)); + two = rootFolder.createFolder("two").getResource(); + two.createMetadata(templateKey, "enterprise", new Metadata().add("/myField", 95d)); + + MetadataQuery query = + new MetadataQuery(format("enterprise_%s.MyTemplate", TestConfig.getEnterpriseID())) + .setQuery("myField > :val") + .addParameter("val", 100) + .setOrderBy(ascending("myField")); + BoxResourceIterable result = MetadataTemplate.executeMetadataQuery(api, query); + Iterator iterator = result.iterator(); + BoxItem.Info foundFolder = iterator.next(); + assertThat(foundFolder.getName(), is("one")); + assertThat(iterator.hasNext(), is(false)); + } finally { + deleteMetadataTemplate(api, template); + deleteFolder(one); + deleteFolder(two); } - - private static void deleteMetadataTemplate(BoxAPIConnection api, MetadataTemplate template) { - if (template != null) { - MetadataTemplate.deleteMetadataTemplate(api, template.getScope(), template.getTemplateKey()); - } + } + + 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; + } + + private static void deleteMetadataTemplate(BoxAPIConnection api, MetadataTemplate template) { + if (template != null) { + MetadataTemplate.deleteMetadataTemplate(api, template.getScope(), template.getTemplateKey()); } + } } diff --git a/src/intTest/java/com/box/sdk/RetentionPolicyUtils.java b/src/intTest/java/com/box/sdk/RetentionPolicyUtils.java index fa4644d82..16312e270 100644 --- a/src/intTest/java/com/box/sdk/RetentionPolicyUtils.java +++ b/src/intTest/java/com/box/sdk/RetentionPolicyUtils.java @@ -8,37 +8,37 @@ import java.util.stream.StreamSupport; final class RetentionPolicyUtils { - private RetentionPolicyUtils() { - // to hide default constructor - } + private RetentionPolicyUtils() { + // to hide default constructor + } - static BoxRetentionPolicy findOrCreate( - BoxAPIConnection api, String policyNamePrefix, Supplier createPolicy - ) { - Iterable policies = BoxRetentionPolicy.getAll(api, "policy_name", "status", - "can_owner_extend_retention"); - BoxRetentionPolicy.Info policy = StreamSupport.stream(policies.spliterator(), false) - .filter(p -> p.getPolicyName().startsWith(policyNamePrefix) - && p.getStatus().equals(STATUS_ACTIVE) && p.getCanOwnerExtendRetention()) + static BoxRetentionPolicy findOrCreate( + BoxAPIConnection api, + String policyNamePrefix, + Supplier createPolicy) { + Iterable policies = + BoxRetentionPolicy.getAll(api, "policy_name", "status", "can_owner_extend_retention"); + BoxRetentionPolicy.Info policy = + StreamSupport.stream(policies.spliterator(), false) + .filter( + p -> + p.getPolicyName().startsWith(policyNamePrefix) + && p.getStatus().equals(STATUS_ACTIVE) + && p.getCanOwnerExtendRetention()) .findFirst() .orElseGet(createPolicy); - return (BoxRetentionPolicy) policy.getResource(); - } + return (BoxRetentionPolicy) policy.getResource(); + } - static BoxRetentionPolicy getOneDayRetentionPolicy(BoxAPIConnection api) { - return findOrCreate( - api, - "One day modifiable", - () -> createModifiableFinitePolicy(api) - ); - } + static BoxRetentionPolicy getOneDayRetentionPolicy(BoxAPIConnection api) { + return findOrCreate(api, "One day modifiable", () -> createModifiableFinitePolicy(api)); + } - static BoxRetentionPolicy.Info createModifiableFinitePolicy(BoxAPIConnection api) { - RetentionPolicyParams optionalParams = new RetentionPolicyParams(); - optionalParams.setCanOwnerExtendRetention(true); - optionalParams.setRetentionType(RetentionPolicyParams.RetentionType.MODIFIABLE); - return BoxRetentionPolicy.createFinitePolicy( - api, randomizeName("One day modifiable"), 1, PermanentlyDelete, optionalParams - ); - } + static BoxRetentionPolicy.Info createModifiableFinitePolicy(BoxAPIConnection api) { + RetentionPolicyParams optionalParams = new RetentionPolicyParams(); + optionalParams.setCanOwnerExtendRetention(true); + optionalParams.setRetentionType(RetentionPolicyParams.RetentionType.MODIFIABLE); + return BoxRetentionPolicy.createFinitePolicy( + api, randomizeName("One day modifiable"), 1, PermanentlyDelete, optionalParams); + } } diff --git a/src/intTest/java/com/box/sdk/Retry.java b/src/intTest/java/com/box/sdk/Retry.java index 13ca95a88..312073798 100644 --- a/src/intTest/java/com/box/sdk/Retry.java +++ b/src/intTest/java/com/box/sdk/Retry.java @@ -2,39 +2,39 @@ import static java.lang.String.format; -/** - * Utility class to retry API actions - */ +/** Utility class to retry API actions */ public final class Retry { - private static final BoxLogger LOGGER = BoxLogger.defaultLogger(); + private static final BoxLogger LOGGER = BoxLogger.defaultLogger(); - private Retry() { - // hide constructor in utility class - } + private Retry() { + // hide constructor in utility class + } - /** - * Retries execution - * @param toExecute Runnable to retry - * @param retries how many times we want to retry - * @param sleep how much miliseconds to sleep between retries - * @throws InterruptedException when sleep was interuppted - */ - public static void retry(Runnable toExecute, int retries, int sleep) throws InterruptedException { - int retriesExecuted = 0; - while (retriesExecuted < retries) { - try { - toExecute.run(); - break; - } catch (Exception e) { - retriesExecuted++; - if (retriesExecuted >= retries) { - throw e; - } - LOGGER.debug( - format("Retrying [%d/%d] becasue of Exception '%s'", retriesExecuted, retries, e.getMessage()) - ); - Thread.sleep(sleep); - } + /** + * Retries execution + * + * @param toExecute Runnable to retry + * @param retries how many times we want to retry + * @param sleep how much miliseconds to sleep between retries + * @throws InterruptedException when sleep was interuppted + */ + public static void retry(Runnable toExecute, int retries, int sleep) throws InterruptedException { + int retriesExecuted = 0; + while (retriesExecuted < retries) { + try { + toExecute.run(); + break; + } catch (Exception e) { + retriesExecuted++; + if (retriesExecuted >= retries) { + throw e; } + LOGGER.debug( + format( + "Retrying [%d/%d] becasue of Exception '%s'", + retriesExecuted, retries, e.getMessage())); + Thread.sleep(sleep); + } } + } } diff --git a/src/intTest/java/com/box/sdk/TestConfig.java b/src/intTest/java/com/box/sdk/TestConfig.java index a2f5fde5a..10acca266 100644 --- a/src/intTest/java/com/box/sdk/TestConfig.java +++ b/src/intTest/java/com/box/sdk/TestConfig.java @@ -8,183 +8,179 @@ import java.nio.file.Paths; import java.util.Properties; - final class TestConfig { - private static Properties configProperties = null; - private static String accessToken = null; - private static String refreshToken = null; - private static String clientID = null; - private static String clientSecret = null; - private static String collaborator = null; - private static String collaboratorID = null; - private static String enterpriseID = null; - private static String privateKey = null; - private static String privateKeyPassword = null; - private static String publicKeyID = null; - private static String transactionalAccessToken = null; - private static String userID = null; - - private TestConfig() { - } + private static Properties configProperties = null; + private static String accessToken = null; + private static String refreshToken = null; + private static String clientID = null; + private static String clientSecret = null; + private static String collaborator = null; + private static String collaboratorID = null; + private static String enterpriseID = null; + private static String privateKey = null; + private static String privateKeyPassword = null; + private static String publicKeyID = null; + private static String transactionalAccessToken = null; + private static String userID = null; - public static String getAccessToken() { - if (accessToken == null || accessToken.equals("")) { - accessToken = getProperty("accessToken"); - } + private TestConfig() {} - return accessToken; + public static String getAccessToken() { + if (accessToken == null || accessToken.equals("")) { + accessToken = getProperty("accessToken"); } - public static void setAccessToken(String accessToken) { - TestConfig.accessToken = accessToken; - } + return accessToken; + } - public static String getRefreshToken() { - if (refreshToken == null || refreshToken.equals("")) { - refreshToken = getProperty("refreshToken"); - } + public static void setAccessToken(String accessToken) { + TestConfig.accessToken = accessToken; + } - return refreshToken; + public static String getRefreshToken() { + if (refreshToken == null || refreshToken.equals("")) { + refreshToken = getProperty("refreshToken"); } - public static void setRefreshToken(String refreshToken) { - TestConfig.refreshToken = refreshToken; - } + return refreshToken; + } - public static String getClientID() { - if (clientID == null || clientID.equals("")) { - clientID = getProperty("clientID"); - } + public static void setRefreshToken(String refreshToken) { + TestConfig.refreshToken = refreshToken; + } - return clientID; + public static String getClientID() { + if (clientID == null || clientID.equals("")) { + clientID = getProperty("clientID"); } - public static String getClientSecret() { - if (clientSecret == null || clientSecret.equals("")) { - clientSecret = getProperty("clientSecret"); - } + return clientID; + } - return clientSecret; + public static String getClientSecret() { + if (clientSecret == null || clientSecret.equals("")) { + clientSecret = getProperty("clientSecret"); } - public static String getCollaborator() { - if (collaborator == null || collaborator.isEmpty()) { - collaborator = System.getenv("JAVA_COLLABORATOR"); - } - if (collaborator == null || collaborator.isEmpty()) { - collaborator = getProperty("collaborator"); - } + return clientSecret; + } - return collaborator; + public static String getCollaborator() { + if (collaborator == null || collaborator.isEmpty()) { + collaborator = System.getenv("JAVA_COLLABORATOR"); + } + if (collaborator == null || collaborator.isEmpty()) { + collaborator = getProperty("collaborator"); } - public static String getCollaboratorID() { - if (collaboratorID == null || collaboratorID.isEmpty()) { - collaboratorID = System.getenv("JAVA_COLLABORATOR_ID"); - } - if (collaboratorID == null || collaboratorID.isEmpty()) { - collaboratorID = getProperty("collaboratorID"); - } + return collaborator; + } - return collaboratorID; + public static String getCollaboratorID() { + if (collaboratorID == null || collaboratorID.isEmpty()) { + collaboratorID = System.getenv("JAVA_COLLABORATOR_ID"); + } + if (collaboratorID == null || collaboratorID.isEmpty()) { + collaboratorID = getProperty("collaboratorID"); } - public static String getEnterpriseID() { - if (enterpriseID == null || enterpriseID.isEmpty()) { - enterpriseID = System.getenv("JAVA_ENTERPRISE_ID"); - } - if (enterpriseID == null || enterpriseID.isEmpty()) { - enterpriseID = getProperty("enterpriseID"); - } + return collaboratorID; + } - return enterpriseID; + public static String getEnterpriseID() { + if (enterpriseID == null || enterpriseID.isEmpty()) { + enterpriseID = System.getenv("JAVA_ENTERPRISE_ID"); + } + if (enterpriseID == null || enterpriseID.isEmpty()) { + enterpriseID = getProperty("enterpriseID"); } - public static String getPrivateKey() { - if (privateKey == null || privateKey.equals("")) { - privateKey = getProperty("privateKey"); - } + return enterpriseID; + } - return privateKey; + public static String getPrivateKey() { + if (privateKey == null || privateKey.equals("")) { + privateKey = getProperty("privateKey"); } - public static String getPrivateKeyPassword() { - if (privateKeyPassword == null || privateKeyPassword.equals("")) { - privateKeyPassword = getProperty("privateKeyPassword"); - } + return privateKey; + } - return privateKeyPassword; + public static String getPrivateKeyPassword() { + if (privateKeyPassword == null || privateKeyPassword.equals("")) { + privateKeyPassword = getProperty("privateKeyPassword"); } - public static String getPublicKeyID() { - if (publicKeyID == null || publicKeyID.equals("")) { - publicKeyID = getProperty("publicKeyID"); - } + return privateKeyPassword; + } - return publicKeyID; + public static String getPublicKeyID() { + if (publicKeyID == null || publicKeyID.equals("")) { + publicKeyID = getProperty("publicKeyID"); } - public static String getTransactionalAccessToken() { - if (transactionalAccessToken == null || transactionalAccessToken.equals("")) { - transactionalAccessToken = getProperty("transactionalAccessToken"); - } + return publicKeyID; + } - return transactionalAccessToken; + public static String getTransactionalAccessToken() { + if (transactionalAccessToken == null || transactionalAccessToken.equals("")) { + transactionalAccessToken = getProperty("transactionalAccessToken"); } - public static String getUserId() { - if (userID == null || userID.isEmpty()) { - userID = System.getenv("JAVA_USER_ID"); - } - if (userID == null || userID.isEmpty()) { - userID = getProperty("userID"); - } + return transactionalAccessToken; + } - return userID; + public static String getUserId() { + if (userID == null || userID.isEmpty()) { + userID = System.getenv("JAVA_USER_ID"); + } + if (userID == null || userID.isEmpty()) { + userID = getProperty("userID"); } - private static String getProperty(String name) { - Properties configProperties = loadProperties(); - String value = configProperties.getProperty(name); - if (value.equals("")) { - throw new IllegalStateException("The " + name + " property wasn't set in " - + "src/test/config/config.properties."); - } + return userID; + } - return value; + private static String getProperty(String name) { + Properties configProperties = loadProperties(); + String value = configProperties.getProperty(name); + if (value.equals("")) { + throw new IllegalStateException( + "The " + name + " property wasn't set in " + "src/test/config/config.properties."); } - private static Properties loadProperties() { - if (configProperties != null) { - return configProperties; - } + return value; + } - configProperties = new Properties(); + private static Properties loadProperties() { + if (configProperties != null) { + return configProperties; + } - try (InputStream input = Files.newInputStream(Paths.get("src/test/config/config.properties"))) { - configProperties.load(input); - } catch (IOException e) { - throw new IllegalStateException("Couldn't open \"src/test/config/config.properties\".", e); - } + configProperties = new Properties(); - return configProperties; + try (InputStream input = Files.newInputStream(Paths.get("src/test/config/config.properties"))) { + configProperties.load(input); + } catch (IOException e) { + throw new IllegalStateException("Couldn't open \"src/test/config/config.properties\".", e); } - /** - * Util function to help get JSON fixtures for tests. - */ - public static String getFixture(String fixtureName) throws IOException { - String fixtureFullPath = "./src/test/Fixtures/" + fixtureName + ".json"; - try (BufferedReader reader = new BufferedReader(new FileReader(fixtureFullPath))) { - StringBuilder builder = new StringBuilder(); - String line = reader.readLine(); + return configProperties; + } + + /** Util function to help get JSON fixtures for tests. */ + public static String getFixture(String fixtureName) throws IOException { + String fixtureFullPath = "./src/test/Fixtures/" + fixtureName + ".json"; + try (BufferedReader reader = new BufferedReader(new FileReader(fixtureFullPath))) { + StringBuilder builder = new StringBuilder(); + String line = reader.readLine(); - while (line != null) { - builder.append(line); - builder.append("\n"); - line = reader.readLine(); - } - return builder.toString(); - } + while (line != null) { + builder.append(line); + builder.append("\n"); + line = reader.readLine(); + } + return builder.toString(); } + } } diff --git a/src/intTest/java/com/box/sdk/UniqueTestFolder.java b/src/intTest/java/com/box/sdk/UniqueTestFolder.java index 08c51d79e..6763555c1 100644 --- a/src/intTest/java/com/box/sdk/UniqueTestFolder.java +++ b/src/intTest/java/com/box/sdk/UniqueTestFolder.java @@ -10,135 +10,130 @@ import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; -/** - * Use to create and delete unique folder for test. - */ +/** Use to create and delete unique folder for test. */ public final class UniqueTestFolder { - private static final AtomicReference UNIQUE_FOLDER_NAME = - new AtomicReference<>(UUID.randomUUID().toString()); - private static final AtomicReference UNIQUE_FOLDER = new AtomicReference<>(); - - private UniqueTestFolder() { - } - - /** - * Creates a unique folder in root folder. Unique name cames from UUID. - */ - public static void setupUniqeFolder() { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder rootFolder = BoxFolder.getRootFolder(api); - BoxFolder.Info folderInfo = rootFolder.createFolder(UNIQUE_FOLDER_NAME.get()); - UNIQUE_FOLDER.set(folderInfo.getID()); - } - - public static void removeUniqueFolder() { - if (UNIQUE_FOLDER.get() != null) { - BoxAPIConnection api = jwtApiForServiceAccount(); - BoxFolder folder = new BoxFolder(api, UNIQUE_FOLDER.get()); - folder.delete(true); - BoxTrash trash = new BoxTrash(api); - trash.deleteFolder(folder.getID()); - } - } - - /** - * Returns the unique folder. - * - * @param api Api used to get the unique folder - * @return BoxFolder representing unique folder - */ - public static BoxFolder getUniqueFolder(BoxAPIConnection api) { - return new BoxFolder(api, UNIQUE_FOLDER.get()); + private static final AtomicReference UNIQUE_FOLDER_NAME = + new AtomicReference<>(UUID.randomUUID().toString()); + private static final AtomicReference UNIQUE_FOLDER = new AtomicReference<>(); + + private UniqueTestFolder() {} + + /** Creates a unique folder in root folder. Unique name cames from UUID. */ + public static void setupUniqeFolder() { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder rootFolder = BoxFolder.getRootFolder(api); + BoxFolder.Info folderInfo = rootFolder.createFolder(UNIQUE_FOLDER_NAME.get()); + UNIQUE_FOLDER.set(folderInfo.getID()); + } + + public static void removeUniqueFolder() { + if (UNIQUE_FOLDER.get() != null) { + BoxAPIConnection api = jwtApiForServiceAccount(); + BoxFolder folder = new BoxFolder(api, UNIQUE_FOLDER.get()); + folder.delete(true); + BoxTrash trash = new BoxTrash(api); + trash.deleteFolder(folder.getID()); } - - /** - * Used to upload sample files to unique folder. - * - * @param api Api used to upload the file. - * @param fileName Sample file name. - * @return BoxFile Returns uploaded BoxFile. - */ - public static BoxFile uploadSampleFileToUniqueFolder(BoxAPIConnection api, String fileName) { - return uploadSampleFileToFolder(api, fileName, UNIQUE_FOLDER.get()); - } - - /** - * Used to upload sample files to specific folder. Sample files are located in src/test/resources/sample-files - * - * @param api Api used to upload the file. - * @param fileName Sample file name. Sample files are located in src/test/resources/sample-files. - * @param folderId ID of the folder file must be uplodaed to. - * @return BoxFile Returns uploaded BoxFile. - */ - public static BoxFile uploadSampleFileToFolder(BoxAPIConnection api, String fileName, String folderId) { - BoxFolder folder = new BoxFolder(api, folderId); - URL fileURL = UniqueTestFolder.class.getResource("/sample-files/" + fileName); - try { - String filePath = URLDecoder.decode(fileURL.getFile(), "utf-8"); - InputStream uploadStream = new FileInputStream(filePath); - return folder.uploadFile(uploadStream, fileName).getResource(); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - public static BoxFile uploadFileToUniqueFolder(BoxAPIConnection api, String fileName, String fileContent) { - return uploadFileWithContentToSpecifiedFolder(fileName, fileContent, getUniqueFolder(api)); - } - - public static BoxFile uploadFileToUniqueFolderWithSomeContent(BoxAPIConnection api, String fileName) { - return uploadFileWithContentToSpecifiedFolder(fileName, "Test file", getUniqueFolder(api)); - } - - public static BoxFile uploadFileWithSomeContent(String fileName, BoxFolder folder) { - return uploadFileWithContentToSpecifiedFolder(fileName, "Test file", folder); - } - - static BoxFile uploadFileWithContentToSpecifiedFolder( - String fileName, String fileContent, BoxFolder folder - ) { - byte[] fileBytes = fileContent.getBytes(StandardCharsets.UTF_8); - - InputStream uploadStream = new ByteArrayInputStream(fileBytes); - return folder.uploadFile(uploadStream, fileName).getResource(); - } - - public static String getUniqueFolderName() { - return UNIQUE_FOLDER_NAME.get(); - } - - public static BoxFile uploadTwoFileVersionsToUniqueFolder( - String fileName, - String version1Content, - String version2Content, - ProgressListener mockUploadListener - ) { - BoxAPIConnection api = jwtApiForServiceAccount(); - return uploadTwoFileVersionsToSpecifiedFolder( - fileName, version1Content, version2Content, getUniqueFolder(api), mockUploadListener - ); - } - - public static BoxFile uploadTwoFileVersionsToSpecifiedFolder( - String fileName, - String version1Content, - String version2Content, - BoxFolder folder, - ProgressListener mockUploadListener - ) { - byte[] version1Bytes = version1Content.getBytes(StandardCharsets.UTF_8); - byte[] version2Bytes = version2Content.getBytes(StandardCharsets.UTF_8); - long version2Size = version2Bytes.length; - - InputStream uploadStream = new ByteArrayInputStream(version1Bytes); - BoxFile uploadedFile = folder.uploadFile(uploadStream, fileName).getResource(); - - uploadStream = new ByteArrayInputStream(version2Bytes); - uploadedFile.uploadNewVersion(uploadStream, null, version2Size, mockUploadListener); - return uploadedFile; - } - - static String randomizeName(String name) { - return name + "_" + UUID.randomUUID(); + } + + /** + * Returns the unique folder. + * + * @param api Api used to get the unique folder + * @return BoxFolder representing unique folder + */ + public static BoxFolder getUniqueFolder(BoxAPIConnection api) { + return new BoxFolder(api, UNIQUE_FOLDER.get()); + } + + /** + * Used to upload sample files to unique folder. + * + * @param api Api used to upload the file. + * @param fileName Sample file name. + * @return BoxFile Returns uploaded BoxFile. + */ + public static BoxFile uploadSampleFileToUniqueFolder(BoxAPIConnection api, String fileName) { + return uploadSampleFileToFolder(api, fileName, UNIQUE_FOLDER.get()); + } + + /** + * Used to upload sample files to specific folder. Sample files are located in + * src/test/resources/sample-files + * + * @param api Api used to upload the file. + * @param fileName Sample file name. Sample files are located in src/test/resources/sample-files. + * @param folderId ID of the folder file must be uplodaed to. + * @return BoxFile Returns uploaded BoxFile. + */ + public static BoxFile uploadSampleFileToFolder( + BoxAPIConnection api, String fileName, String folderId) { + BoxFolder folder = new BoxFolder(api, folderId); + URL fileURL = UniqueTestFolder.class.getResource("/sample-files/" + fileName); + try { + String filePath = URLDecoder.decode(fileURL.getFile(), "utf-8"); + InputStream uploadStream = new FileInputStream(filePath); + return folder.uploadFile(uploadStream, fileName).getResource(); + } catch (Exception e) { + throw new RuntimeException(e); } + } + + public static BoxFile uploadFileToUniqueFolder( + BoxAPIConnection api, String fileName, String fileContent) { + return uploadFileWithContentToSpecifiedFolder(fileName, fileContent, getUniqueFolder(api)); + } + + public static BoxFile uploadFileToUniqueFolderWithSomeContent( + BoxAPIConnection api, String fileName) { + return uploadFileWithContentToSpecifiedFolder(fileName, "Test file", getUniqueFolder(api)); + } + + public static BoxFile uploadFileWithSomeContent(String fileName, BoxFolder folder) { + return uploadFileWithContentToSpecifiedFolder(fileName, "Test file", folder); + } + + static BoxFile uploadFileWithContentToSpecifiedFolder( + String fileName, String fileContent, BoxFolder folder) { + byte[] fileBytes = fileContent.getBytes(StandardCharsets.UTF_8); + + InputStream uploadStream = new ByteArrayInputStream(fileBytes); + return folder.uploadFile(uploadStream, fileName).getResource(); + } + + public static String getUniqueFolderName() { + return UNIQUE_FOLDER_NAME.get(); + } + + public static BoxFile uploadTwoFileVersionsToUniqueFolder( + String fileName, + String version1Content, + String version2Content, + ProgressListener mockUploadListener) { + BoxAPIConnection api = jwtApiForServiceAccount(); + return uploadTwoFileVersionsToSpecifiedFolder( + fileName, version1Content, version2Content, getUniqueFolder(api), mockUploadListener); + } + + public static BoxFile uploadTwoFileVersionsToSpecifiedFolder( + String fileName, + String version1Content, + String version2Content, + BoxFolder folder, + ProgressListener mockUploadListener) { + byte[] version1Bytes = version1Content.getBytes(StandardCharsets.UTF_8); + byte[] version2Bytes = version2Content.getBytes(StandardCharsets.UTF_8); + long version2Size = version2Bytes.length; + + InputStream uploadStream = new ByteArrayInputStream(version1Bytes); + BoxFile uploadedFile = folder.uploadFile(uploadStream, fileName).getResource(); + + uploadStream = new ByteArrayInputStream(version2Bytes); + uploadedFile.uploadNewVersion(uploadStream, null, version2Size, mockUploadListener); + return uploadedFile; + } + + static String randomizeName(String name) { + return name + "_" + UUID.randomUUID(); + } } diff --git a/src/intTest/java/com/box/sdkgen/ai/AiITest.java b/src/intTest/java/com/box/sdkgen/ai/AiITest.java new file mode 100644 index 000000000..4a5ac43e8 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/ai/AiITest.java @@ -0,0 +1,436 @@ +package com.box.sdkgen.ai; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.commons.CommonsManager.uploadNewFile; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.dateTimeFromString; +import static com.box.sdkgen.internal.utils.UtilsManager.delayInSeconds; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; +import static com.box.sdkgen.internal.utils.UtilsManager.getValueFromObjectRawData; +import static com.box.sdkgen.internal.utils.UtilsManager.stringToByteStream; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.ai.GetAiAgentDefaultConfigQueryParams; +import com.box.sdkgen.managers.ai.GetAiAgentDefaultConfigQueryParamsModeField; +import com.box.sdkgen.managers.metadatatemplates.CreateMetadataTemplateRequestBody; +import com.box.sdkgen.managers.metadatatemplates.CreateMetadataTemplateRequestBodyFieldsField; +import com.box.sdkgen.managers.metadatatemplates.CreateMetadataTemplateRequestBodyFieldsOptionsField; +import com.box.sdkgen.managers.metadatatemplates.CreateMetadataTemplateRequestBodyFieldsTypeField; +import com.box.sdkgen.managers.metadatatemplates.DeleteMetadataTemplateScope; +import com.box.sdkgen.managers.uploads.UploadFileRequestBody; +import com.box.sdkgen.managers.uploads.UploadFileRequestBodyAttributesField; +import com.box.sdkgen.managers.uploads.UploadFileRequestBodyAttributesParentField; +import com.box.sdkgen.schemas.aiagent.AiAgent; +import com.box.sdkgen.schemas.aiagentask.AiAgentAsk; +import com.box.sdkgen.schemas.aiagentextract.AiAgentExtract; +import com.box.sdkgen.schemas.aiagentextractstructured.AiAgentExtractStructured; +import com.box.sdkgen.schemas.aiagentlongtexttool.AiAgentLongTextTool; +import com.box.sdkgen.schemas.aiagenttextgen.AiAgentTextGen; +import com.box.sdkgen.schemas.aiask.AiAsk; +import com.box.sdkgen.schemas.aiask.AiAskModeField; +import com.box.sdkgen.schemas.aidialoguehistory.AiDialogueHistory; +import com.box.sdkgen.schemas.aiextract.AiExtract; +import com.box.sdkgen.schemas.aiextractstructured.AiExtractStructured; +import com.box.sdkgen.schemas.aiextractstructured.AiExtractStructuredFieldsField; +import com.box.sdkgen.schemas.aiextractstructured.AiExtractStructuredFieldsOptionsField; +import com.box.sdkgen.schemas.aiextractstructured.AiExtractStructuredMetadataTemplateField; +import com.box.sdkgen.schemas.aiextractstructuredresponse.AiExtractStructuredResponse; +import com.box.sdkgen.schemas.aiitemask.AiItemAsk; +import com.box.sdkgen.schemas.aiitemask.AiItemAskTypeField; +import com.box.sdkgen.schemas.aiitembase.AiItemBase; +import com.box.sdkgen.schemas.airesponse.AiResponse; +import com.box.sdkgen.schemas.airesponsefull.AiResponseFull; +import com.box.sdkgen.schemas.aitextgen.AiTextGen; +import com.box.sdkgen.schemas.aitextgen.AiTextGenItemsField; +import com.box.sdkgen.schemas.aitextgen.AiTextGenItemsTypeField; +import com.box.sdkgen.schemas.filefull.FileFull; +import com.box.sdkgen.schemas.files.Files; +import com.box.sdkgen.schemas.metadatatemplate.MetadataTemplate; +import java.util.Arrays; +import org.junit.jupiter.api.Test; + +public class AiITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testAskAiSingleItem() { + AiAgent aiAgentConfig = + client + .getAi() + .getAiAgentDefaultConfig( + new GetAiAgentDefaultConfigQueryParams.Builder( + GetAiAgentDefaultConfigQueryParamsModeField.ASK) + .language("en-US") + .build()); + AiAgentAsk aiAskAgentConfig = aiAgentConfig.getAiAgentAsk(); + FileFull fileToAsk = uploadNewFile(); + AiResponseFull response = + client + .getAi() + .createAiAsk( + new AiAsk.Builder( + AiAskModeField.SINGLE_ITEM_QA, + "which direction sun rises", + Arrays.asList( + new AiItemAsk.Builder(fileToAsk.getId(), AiItemAskTypeField.FILE) + .content("Sun rises in the East") + .build())) + .aiAgent(aiAskAgentConfig) + .build()); + assert response.getAnswer().contains("East"); + assert response.getCompletionReason().equals("done"); + client.getFiles().deleteFileById(fileToAsk.getId()); + } + + @Test + public void testAskAiMultipleItems() { + FileFull fileToAsk1 = uploadNewFile(); + FileFull fileToAsk2 = uploadNewFile(); + AiResponseFull response = + client + .getAi() + .createAiAsk( + new AiAsk( + AiAskModeField.MULTIPLE_ITEM_QA, + "Which direction sun rises?", + Arrays.asList( + new AiItemAsk.Builder(fileToAsk1.getId(), AiItemAskTypeField.FILE) + .content("Earth goes around the sun") + .build(), + new AiItemAsk.Builder(fileToAsk2.getId(), AiItemAskTypeField.FILE) + .content("Sun rises in the East in the morning") + .build()))); + assert response.getAnswer().contains("East"); + assert response.getCompletionReason().equals("done"); + client.getFiles().deleteFileById(fileToAsk1.getId()); + client.getFiles().deleteFileById(fileToAsk2.getId()); + } + + @Test + public void testAiTextGenWithDialogueHistory() { + FileFull fileToAsk = uploadNewFile(); + AiAgent aiAgentConfig = + client + .getAi() + .getAiAgentDefaultConfig( + new GetAiAgentDefaultConfigQueryParams.Builder( + GetAiAgentDefaultConfigQueryParamsModeField.TEXT_GEN) + .language("en-US") + .build()); + AiAgentTextGen aiTextGenAgentConfig = aiAgentConfig.getAiAgentTextGen(); + AiResponse response = + client + .getAi() + .createAiTextGen( + new AiTextGen.Builder( + "Parapharse the document.s", + Arrays.asList( + new AiTextGenItemsField.Builder(fileToAsk.getId()) + .type(AiTextGenItemsTypeField.FILE) + .content( + "The Earth goes around the sun. Sun rises in the East in the morning.") + .build())) + .dialogueHistory( + Arrays.asList( + new AiDialogueHistory.Builder() + .prompt("What does the earth go around?") + .answer("The sun") + .createdAt(dateTimeFromString("2021-01-01T00:00:00Z")) + .build(), + new AiDialogueHistory.Builder() + .prompt("On Earth, where does the sun rise?") + .answer("East") + .createdAt(dateTimeFromString("2021-01-01T00:00:00Z")) + .build())) + .aiAgent(aiTextGenAgentConfig) + .build()); + assert response.getAnswer().contains("sun"); + assert response.getCompletionReason().equals("done"); + client.getFiles().deleteFileById(fileToAsk.getId()); + } + + @Test + public void testGettingAiAskAgentConfig() { + AiAgent aiAgentConfig = + client + .getAi() + .getAiAgentDefaultConfig( + new GetAiAgentDefaultConfigQueryParams.Builder( + GetAiAgentDefaultConfigQueryParamsModeField.ASK) + .language("en-US") + .build()); + assert aiAgentConfig.getType().equals("ai_agent_ask"); + AiAgentAsk aiAgentAskConfig = aiAgentConfig.getAiAgentAsk(); + assert !(aiAgentAskConfig.getBasicText().getModel().equals("")); + assert !(aiAgentAskConfig.getBasicText().getPromptTemplate().equals("")); + assert aiAgentAskConfig.getBasicText().getNumTokensForCompletion() > -1; + assert !(aiAgentAskConfig.getBasicText().getLlmEndpointParams() == null); + assert !(aiAgentAskConfig.getBasicTextMulti().getModel().equals("")); + assert !(aiAgentAskConfig.getBasicTextMulti().getPromptTemplate().equals("")); + assert aiAgentAskConfig.getBasicTextMulti().getNumTokensForCompletion() > -1; + assert !(aiAgentAskConfig.getBasicTextMulti().getLlmEndpointParams() == null); + assert !(aiAgentAskConfig.getLongText().getModel().equals("")); + assert !(aiAgentAskConfig.getLongText().getPromptTemplate().equals("")); + assert aiAgentAskConfig.getLongText().getNumTokensForCompletion() > -1; + assert !(aiAgentAskConfig.getLongText().getEmbeddings().getModel().equals("")); + assert !(aiAgentAskConfig.getLongText().getEmbeddings().getStrategy().getId().equals("")); + assert !(aiAgentAskConfig.getLongText().getLlmEndpointParams() == null); + assert !(aiAgentAskConfig.getLongTextMulti().getModel().equals("")); + assert !(aiAgentAskConfig.getLongTextMulti().getPromptTemplate().equals("")); + assert aiAgentAskConfig.getLongTextMulti().getNumTokensForCompletion() > -1; + assert !(aiAgentAskConfig.getLongTextMulti().getEmbeddings().getModel().equals("")); + assert !(aiAgentAskConfig.getLongTextMulti().getEmbeddings().getStrategy().getId().equals("")); + assert !(aiAgentAskConfig.getLongTextMulti().getLlmEndpointParams() == null); + } + + @Test + public void testGettingAiTextGenAgentConfig() { + AiAgent aiAgentConfig = + client + .getAi() + .getAiAgentDefaultConfig( + new GetAiAgentDefaultConfigQueryParams.Builder( + GetAiAgentDefaultConfigQueryParamsModeField.TEXT_GEN) + .language("en-US") + .build()); + assert aiAgentConfig.getType().equals("ai_agent_text_gen"); + AiAgentTextGen aiAgentTextGenConfig = aiAgentConfig.getAiAgentTextGen(); + assert !(aiAgentTextGenConfig.getBasicGen().getLlmEndpointParams() == null); + assert !(aiAgentTextGenConfig.getBasicGen().getModel().equals("")); + assert !(aiAgentTextGenConfig.getBasicGen().getPromptTemplate().equals("")); + assert aiAgentTextGenConfig.getBasicGen().getNumTokensForCompletion() > -1; + assert !(aiAgentTextGenConfig.getBasicGen().getContentTemplate().equals("")); + assert !(aiAgentTextGenConfig.getBasicGen().getEmbeddings().getModel().equals("")); + assert !(aiAgentTextGenConfig.getBasicGen().getEmbeddings().getStrategy().getId().equals("")); + } + + @Test + public void testAiExtract() { + AiAgent aiAgentConfig = + client + .getAi() + .getAiAgentDefaultConfig( + new GetAiAgentDefaultConfigQueryParams.Builder( + GetAiAgentDefaultConfigQueryParamsModeField.EXTRACT) + .language("en-US") + .build()); + AiAgentExtract aiExtractAgentConfig = aiAgentConfig.getAiAgentExtract(); + AiAgentLongTextTool longTextConfigWithNoEmbeddings = + new AiAgentLongTextTool.Builder() + .systemMessage(aiExtractAgentConfig.getLongText().getSystemMessage()) + .promptTemplate(aiExtractAgentConfig.getLongText().getPromptTemplate()) + .model(aiExtractAgentConfig.getLongText().getModel()) + .numTokensForCompletion(aiExtractAgentConfig.getLongText().getNumTokensForCompletion()) + .llmEndpointParams(aiExtractAgentConfig.getLongText().getLlmEndpointParams()) + .build(); + AiAgentExtract agentIgnoringOverridingEmbeddingsModel = + new AiAgentExtract.Builder() + .longText(longTextConfigWithNoEmbeddings) + .basicText(aiExtractAgentConfig.getBasicText()) + .build(); + Files uploadedFiles = + client + .getUploads() + .uploadFile( + new UploadFileRequestBody( + new UploadFileRequestBodyAttributesField( + String.join("", getUuid(), ".txt"), + new UploadFileRequestBodyAttributesParentField("0")), + stringToByteStream( + "My name is John Doe. I live in San Francisco. I was born in 1990. I work at Box."))); + FileFull file = uploadedFiles.getEntries().get(0); + delayInSeconds(5); + AiResponse response = + client + .getAi() + .createAiExtract( + new AiExtract.Builder( + "firstName, lastName, location, yearOfBirth, company", + Arrays.asList(new AiItemBase(file.getId()))) + .aiAgent(agentIgnoringOverridingEmbeddingsModel) + .build()); + String expectedResponse = + "{\"firstName\": \"John\", \"lastName\": \"Doe\", \"location\": \"San Francisco\", \"yearOfBirth\": \"1990\", \"company\": \"Box\"}"; + assert response.getAnswer().equals(expectedResponse); + assert response.getCompletionReason().equals("done"); + client.getFiles().deleteFileById(file.getId()); + } + + @Test + public void testAiExtractStructuredWithFields() { + AiAgent aiAgentConfig = + client + .getAi() + .getAiAgentDefaultConfig( + new GetAiAgentDefaultConfigQueryParams.Builder( + GetAiAgentDefaultConfigQueryParamsModeField.EXTRACT_STRUCTURED) + .language("en-US") + .build()); + AiAgentExtractStructured aiExtractStructuredAgentConfig = + aiAgentConfig.getAiAgentExtractStructured(); + AiAgentLongTextTool longTextConfigWithNoEmbeddings = + new AiAgentLongTextTool.Builder() + .systemMessage(aiExtractStructuredAgentConfig.getLongText().getSystemMessage()) + .promptTemplate(aiExtractStructuredAgentConfig.getLongText().getPromptTemplate()) + .model(aiExtractStructuredAgentConfig.getLongText().getModel()) + .numTokensForCompletion( + aiExtractStructuredAgentConfig.getLongText().getNumTokensForCompletion()) + .llmEndpointParams(aiExtractStructuredAgentConfig.getLongText().getLlmEndpointParams()) + .build(); + AiAgentExtractStructured agentIgnoringOverridingEmbeddingsModel = + new AiAgentExtractStructured.Builder() + .longText(longTextConfigWithNoEmbeddings) + .basicText(aiExtractStructuredAgentConfig.getBasicText()) + .build(); + Files uploadedFiles = + client + .getUploads() + .uploadFile( + new UploadFileRequestBody( + new UploadFileRequestBodyAttributesField( + String.join("", getUuid(), ".txt"), + new UploadFileRequestBodyAttributesParentField("0")), + stringToByteStream( + "My name is John Doe. I was born in 4th July 1990. I am 34 years old. My hobby is guitar."))); + FileFull file = uploadedFiles.getEntries().get(0); + delayInSeconds(5); + AiExtractStructuredResponse response = + client + .getAi() + .createAiExtractStructured( + new AiExtractStructured.Builder(Arrays.asList(new AiItemBase(file.getId()))) + .fields( + Arrays.asList( + new AiExtractStructuredFieldsField.Builder("firstName") + .description("Person first name") + .displayName("First name") + .prompt("What is the your first name?") + .type("string") + .build(), + new AiExtractStructuredFieldsField.Builder("lastName") + .description("Person last name") + .displayName("Last name") + .prompt("What is the your last name?") + .type("string") + .build(), + new AiExtractStructuredFieldsField.Builder("dateOfBirth") + .description("Person date of birth") + .displayName("Birth date") + .prompt("What is the date of your birth?") + .type("date") + .build(), + new AiExtractStructuredFieldsField.Builder("age") + .description("Person age") + .displayName("Age") + .prompt("How old are you?") + .type("float") + .build(), + new AiExtractStructuredFieldsField.Builder("hobby") + .description("Person hobby") + .displayName("Hobby") + .prompt("What is your hobby?") + .type("multiSelect") + .options( + Arrays.asList( + new AiExtractStructuredFieldsOptionsField("guitar"), + new AiExtractStructuredFieldsOptionsField("books"))) + .build())) + .aiAgent(agentIgnoringOverridingEmbeddingsModel) + .build()); + assert convertToString(getValueFromObjectRawData(response, "answer.hobby")) + .equals(convertToString(Arrays.asList("guitar"))); + assert convertToString(getValueFromObjectRawData(response, "answer.firstName")).equals("John"); + assert convertToString(getValueFromObjectRawData(response, "answer.lastName")).equals("Doe"); + assert convertToString(getValueFromObjectRawData(response, "answer.dateOfBirth")) + .equals("1990-07-04"); + assert convertToString(getValueFromObjectRawData(response, "answer.age")).equals("34"); + assert response.getCompletionReason().equals("done"); + client.getFiles().deleteFileById(file.getId()); + } + + @Test + public void testAiExtractStructuredWithMetadataTemplate() { + Files uploadedFiles = + client + .getUploads() + .uploadFile( + new UploadFileRequestBody( + new UploadFileRequestBodyAttributesField( + String.join("", getUuid(), ".txt"), + new UploadFileRequestBodyAttributesParentField("0")), + stringToByteStream( + "My name is John Doe. I was born in 4th July 1990. I am 34 years old. My hobby is guitar."))); + FileFull file = uploadedFiles.getEntries().get(0); + delayInSeconds(5); + String templateKey = String.join("", "key", getUuid()); + MetadataTemplate template = + client + .getMetadataTemplates() + .createMetadataTemplate( + new CreateMetadataTemplateRequestBody.Builder("enterprise", templateKey) + .templateKey(templateKey) + .fields( + Arrays.asList( + new CreateMetadataTemplateRequestBodyFieldsField.Builder( + CreateMetadataTemplateRequestBodyFieldsTypeField.STRING, + "firstName", + "First name") + .description("Person first name") + .build(), + new CreateMetadataTemplateRequestBodyFieldsField.Builder( + CreateMetadataTemplateRequestBodyFieldsTypeField.STRING, + "lastName", + "Last name") + .description("Person last name") + .build(), + new CreateMetadataTemplateRequestBodyFieldsField.Builder( + CreateMetadataTemplateRequestBodyFieldsTypeField.DATE, + "dateOfBirth", + "Birth date") + .description("Person date of birth") + .build(), + new CreateMetadataTemplateRequestBodyFieldsField.Builder( + CreateMetadataTemplateRequestBodyFieldsTypeField.FLOAT, + "age", + "Age") + .description("Person age") + .build(), + new CreateMetadataTemplateRequestBodyFieldsField.Builder( + CreateMetadataTemplateRequestBodyFieldsTypeField.MULTISELECT, + "hobby", + "Hobby") + .description("Person hobby") + .options( + Arrays.asList( + new CreateMetadataTemplateRequestBodyFieldsOptionsField( + "guitar"), + new CreateMetadataTemplateRequestBodyFieldsOptionsField( + "books"))) + .build())) + .build()); + AiExtractStructuredResponse response = + client + .getAi() + .createAiExtractStructured( + new AiExtractStructured.Builder(Arrays.asList(new AiItemBase(file.getId()))) + .metadataTemplate( + new AiExtractStructuredMetadataTemplateField.Builder() + .templateKey(templateKey) + .scope("enterprise") + .build()) + .build()); + assert convertToString(getValueFromObjectRawData(response, "answer.firstName")).equals("John"); + assert convertToString(getValueFromObjectRawData(response, "answer.lastName")).equals("Doe"); + assert convertToString(getValueFromObjectRawData(response, "answer.dateOfBirth")) + .equals("1990-07-04T00:00:00Z"); + assert convertToString(getValueFromObjectRawData(response, "answer.age")).equals("34"); + assert convertToString(getValueFromObjectRawData(response, "answer.hobby")) + .equals(convertToString(Arrays.asList("guitar"))); + assert response.getCompletionReason().equals("done"); + client + .getMetadataTemplates() + .deleteMetadataTemplate(DeleteMetadataTemplateScope.ENTERPRISE, template.getTemplateKey()); + client.getFiles().deleteFileById(file.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/aistudio/AiStudioITest.java b/src/intTest/java/com/box/sdkgen/aistudio/AiStudioITest.java new file mode 100644 index 000000000..9ded2ffb1 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/aistudio/AiStudioITest.java @@ -0,0 +1,98 @@ +package com.box.sdkgen.aistudio; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.commons.CommonsManager.uploadNewFile; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.aistudio.GetAiAgentByIdQueryParams; +import com.box.sdkgen.schemas.aiagentreference.AiAgentReference; +import com.box.sdkgen.schemas.aiask.AiAsk; +import com.box.sdkgen.schemas.aiask.AiAskModeField; +import com.box.sdkgen.schemas.aiitemask.AiItemAsk; +import com.box.sdkgen.schemas.aiitemask.AiItemAskTypeField; +import com.box.sdkgen.schemas.aimultipleagentresponse.AiMultipleAgentResponse; +import com.box.sdkgen.schemas.airesponsefull.AiResponseFull; +import com.box.sdkgen.schemas.aisingleagentresponsefull.AiSingleAgentResponseFull; +import com.box.sdkgen.schemas.aistudioagentask.AiStudioAgentAsk; +import com.box.sdkgen.schemas.createaiagent.CreateAiAgent; +import com.box.sdkgen.schemas.filefull.FileFull; +import java.util.Arrays; +import org.junit.jupiter.api.Test; + +public class AiStudioITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testAiStudioCrud() { + String agentName = getUuid(); + AiSingleAgentResponseFull createdAgent = + client + .getAiStudio() + .createAiAgent( + new CreateAiAgent.Builder(agentName, "enabled") + .ask(new AiStudioAgentAsk("enabled", "desc1")) + .build()); + assert createdAgent.getName().equals(agentName); + AiMultipleAgentResponse agents = client.getAiStudio().getAiAgents(); + int numAgents = agents.getEntries().size(); + assert convertToString(agents.getEntries().get(0).getType()).equals("ai_agent"); + AiSingleAgentResponseFull retrievedAgent = + client + .getAiStudio() + .getAiAgentById( + createdAgent.getId(), + new GetAiAgentByIdQueryParams.Builder().fields(Arrays.asList("ask")).build()); + assert retrievedAgent.getName().equals(agentName); + assert convertToString(retrievedAgent.getAccessState()).equals("enabled"); + assert convertToString(retrievedAgent.getAsk().getAccessState()).equals("enabled"); + assert retrievedAgent.getAsk().getDescription().equals("desc1"); + AiSingleAgentResponseFull updatedAgent = + client + .getAiStudio() + .updateAiAgentById( + createdAgent.getId(), + new CreateAiAgent.Builder(agentName, "enabled") + .ask(new AiStudioAgentAsk("disabled", "desc2")) + .build()); + assert convertToString(updatedAgent.getAccessState()).equals("enabled"); + assert convertToString(updatedAgent.getAsk().getAccessState()).equals("disabled"); + assert updatedAgent.getAsk().getDescription().equals("desc2"); + client.getAiStudio().deleteAiAgentById(createdAgent.getId()); + AiMultipleAgentResponse agentsAfterDelete = client.getAiStudio().getAiAgents(); + assert agentsAfterDelete.getEntries().size() == numAgents - 1; + } + + @Test + public void testUseAiAgentReferenceInAiAsk() { + String agentName = getUuid(); + AiSingleAgentResponseFull createdAgent = + client + .getAiStudio() + .createAiAgent( + new CreateAiAgent.Builder(agentName, "enabled") + .ask(new AiStudioAgentAsk("enabled", "desc1")) + .build()); + FileFull fileToAsk = uploadNewFile(); + AiResponseFull response = + client + .getAi() + .createAiAsk( + new AiAsk.Builder( + AiAskModeField.SINGLE_ITEM_QA, + "which direction sun rises", + Arrays.asList( + new AiItemAsk.Builder(fileToAsk.getId(), AiItemAskTypeField.FILE) + .content("Sun rises in the East") + .build())) + .aiAgent(new AiAgentReference.Builder().id(createdAgent.getId()).build()) + .build()); + assert response.getAnswer().contains("East"); + assert response.getCompletionReason().equals("done"); + assert response.getAiAgentInfo().getModels().size() > 0; + client.getFiles().deleteFileById(fileToAsk.getId()); + client.getAiStudio().deleteAiAgentById(createdAgent.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/appitemassociations/AppItemAssociationsITest.java b/src/intTest/java/com/box/sdkgen/appitemassociations/AppItemAssociationsITest.java new file mode 100644 index 000000000..c776e8f86 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/appitemassociations/AppItemAssociationsITest.java @@ -0,0 +1,66 @@ +package com.box.sdkgen.appitemassociations; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClientWithUserSubject; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.getEnvVar; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.files.GetFileByIdQueryParams; +import com.box.sdkgen.managers.folders.GetFolderByIdQueryParams; +import com.box.sdkgen.schemas.appitemassociation.AppItemAssociation; +import com.box.sdkgen.schemas.appitemassociations.AppItemAssociations; +import com.box.sdkgen.schemas.filefull.FileFull; +import com.box.sdkgen.schemas.folderfull.FolderFull; +import java.util.Arrays; +import org.junit.jupiter.api.Test; + +public class AppItemAssociationsITest { + + @Test + public void testListFileAppItemAssocations() { + BoxClient client = getDefaultClientWithUserSubject(getEnvVar("USER_ID")); + String fileId = getEnvVar("APP_ITEM_ASSOCIATION_FILE_ID"); + AppItemAssociations fileAppItemAssociations = + client.getAppItemAssociations().getFileAppItemAssociations(fileId); + assert fileAppItemAssociations.getEntries().size() == 1; + AppItemAssociation association = fileAppItemAssociations.getEntries().get(0); + assert !(association.getId().equals("")); + assert convertToString(association.getAppItem().getApplicationType()).equals("hubs"); + assert convertToString(association.getAppItem().getType()).equals("app_item"); + assert convertToString(association.getItem().getType()).equals("file"); + assert association.getItem().getId().equals(fileId); + FileFull file = + client + .getFiles() + .getFileById( + fileId, + new GetFileByIdQueryParams.Builder() + .fields(Arrays.asList("is_associated_with_app_item")) + .build()); + assert file.getIsAssociatedWithAppItem() == true; + } + + @Test + public void testListFolderAppItemAssocations() { + BoxClient client = getDefaultClientWithUserSubject(getEnvVar("USER_ID")); + String folderId = getEnvVar("APP_ITEM_ASSOCIATION_FOLDER_ID"); + AppItemAssociations folderAppItemAssociations = + client.getAppItemAssociations().getFolderAppItemAssociations(folderId); + assert folderAppItemAssociations.getEntries().size() == 1; + AppItemAssociation association = folderAppItemAssociations.getEntries().get(0); + assert !(association.getId().equals("")); + assert convertToString(association.getAppItem().getApplicationType()).equals("hubs"); + assert convertToString(association.getAppItem().getType()).equals("app_item"); + assert convertToString(association.getItem().getType()).equals("folder"); + assert association.getItem().getId().equals(folderId); + FolderFull folder = + client + .getFolders() + .getFolderById( + folderId, + new GetFolderByIdQueryParams.Builder() + .fields(Arrays.asList("is_associated_with_app_item")) + .build()); + assert folder.getIsAssociatedWithAppItem() == true; + } +} diff --git a/src/intTest/java/com/box/sdkgen/archives/ArchivesITest.java b/src/intTest/java/com/box/sdkgen/archives/ArchivesITest.java new file mode 100644 index 000000000..77187839b --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/archives/ArchivesITest.java @@ -0,0 +1,39 @@ +package com.box.sdkgen.archives; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClientWithUserSubject; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.getEnvVar; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.archives.CreateArchiveV2025R0RequestBody; +import com.box.sdkgen.managers.archives.GetArchivesV2025R0QueryParams; +import com.box.sdkgen.schemas.v2025r0.archivesv2025r0.ArchivesV2025R0; +import com.box.sdkgen.schemas.v2025r0.archivev2025r0.ArchiveV2025R0; +import org.junit.jupiter.api.Test; + +public class ArchivesITest { + + private static final String userId = getEnvVar("USER_ID"); + + private static final BoxClient client = getDefaultClientWithUserSubject(userId); + + @Test + public void testArchivesCreateListDelete() { + String archiveName = getUuid(); + ArchiveV2025R0 archive = + client.getArchives().createArchiveV2025R0(new CreateArchiveV2025R0RequestBody(archiveName)); + assert convertToString(archive.getType()).equals("archive"); + assert archive.getName().equals(archiveName); + ArchivesV2025R0 archives = + client + .getArchives() + .getArchivesV2025R0(new GetArchivesV2025R0QueryParams.Builder().limit(100L).build()); + assert archives.getEntries().size() > 0; + client.getArchives().deleteArchiveByIdV2025R0(archive.getId()); + assertThrows( + RuntimeException.class, + () -> client.getArchives().deleteArchiveByIdV2025R0(archive.getId())); + } +} diff --git a/src/intTest/java/com/box/sdkgen/auth/AuthITest.java b/src/intTest/java/com/box/sdkgen/auth/AuthITest.java new file mode 100644 index 000000000..0698adfc0 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/auth/AuthITest.java @@ -0,0 +1,386 @@ +package com.box.sdkgen.auth; + +import static com.box.sdkgen.internal.utils.UtilsManager.decodeBase64; +import static com.box.sdkgen.internal.utils.UtilsManager.generateByteStream; +import static com.box.sdkgen.internal.utils.UtilsManager.getEnvVar; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.box.ccgauth.BoxCCGAuth; +import com.box.sdkgen.box.ccgauth.CCGConfig; +import com.box.sdkgen.box.developertokenauth.BoxDeveloperTokenAuth; +import com.box.sdkgen.box.developertokenauth.DeveloperTokenConfig; +import com.box.sdkgen.box.jwtauth.BoxJWTAuth; +import com.box.sdkgen.box.jwtauth.JWTConfig; +import com.box.sdkgen.box.oauth.BoxOAuth; +import com.box.sdkgen.box.oauth.OAuthConfig; +import com.box.sdkgen.box.tokenstorage.InMemoryTokenStorage; +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.files.UpdateFileByIdRequestBody; +import com.box.sdkgen.managers.folders.CreateFolderRequestBody; +import com.box.sdkgen.managers.folders.CreateFolderRequestBodyParentField; +import com.box.sdkgen.managers.folders.UpdateFolderByIdRequestBody; +import com.box.sdkgen.managers.uploads.UploadFileRequestBody; +import com.box.sdkgen.managers.uploads.UploadFileRequestBodyAttributesField; +import com.box.sdkgen.managers.uploads.UploadFileRequestBodyAttributesParentField; +import com.box.sdkgen.managers.users.GetUserMeQueryParams; +import com.box.sdkgen.schemas.accesstoken.AccessToken; +import com.box.sdkgen.schemas.filefull.FileFull; +import com.box.sdkgen.schemas.files.Files; +import com.box.sdkgen.schemas.folderfull.FolderFull; +import com.box.sdkgen.schemas.userfull.UserFull; +import java.util.Arrays; +import org.junit.jupiter.api.Test; + +public class AuthITest { + + public static AccessToken getAccessToken() { + String userId = getEnvVar("USER_ID"); + String enterpriseId = getEnvVar("ENTERPRISE_ID"); + CCGConfig ccgConfig = + new CCGConfig.Builder(getEnvVar("CLIENT_ID"), getEnvVar("CLIENT_SECRET")) + .enterpriseId(enterpriseId) + .userId(userId) + .build(); + BoxCCGAuth auth = new BoxCCGAuth(ccgConfig); + BoxCCGAuth authUser = auth.withUserSubject(userId); + return authUser.retrieveToken(); + } + + @Test + public void testJwtAuth() { + String userId = getEnvVar("USER_ID"); + String enterpriseId = getEnvVar("ENTERPRISE_ID"); + JWTConfig jwtConfig = + JWTConfig.fromConfigJsonString(decodeBase64(getEnvVar("JWT_CONFIG_BASE_64"))); + BoxJWTAuth auth = new BoxJWTAuth(jwtConfig); + BoxJWTAuth userAuth = auth.withUserSubject(userId); + BoxClient userClient = new BoxClient(userAuth); + UserFull currentUser = userClient.getUsers().getUserMe(); + assert currentUser.getId().equals(userId); + BoxJWTAuth enterpriseAuth = auth.withEnterpriseSubject(enterpriseId); + BoxClient enterpriseClient = new BoxClient(enterpriseAuth); + UserFull newUser = + enterpriseClient + .getUsers() + .getUserMe( + new GetUserMeQueryParams.Builder().fields(Arrays.asList("enterprise")).build()); + assert !(newUser.getEnterprise() == null); + assert newUser.getEnterprise().getId().equals(enterpriseId); + assert !(newUser.getId().equals(userId)); + } + + @Test + public void testJwtAuthDownscope() { + JWTConfig jwtConfig = + JWTConfig.fromConfigJsonString(decodeBase64(getEnvVar("JWT_CONFIG_BASE_64"))); + BoxJWTAuth auth = new BoxJWTAuth(jwtConfig); + BoxClient parentClient = new BoxClient(auth); + Files uploadedFiles = + parentClient + .getUploads() + .uploadFile( + new UploadFileRequestBody( + new UploadFileRequestBodyAttributesField( + getUuid(), new UploadFileRequestBodyAttributesParentField("0")), + generateByteStream(1024 * 1024))); + FileFull file = uploadedFiles.getEntries().get(0); + String resourcePath = String.join("", "https://api.box.com/2.0/files/", file.getId()); + AccessToken downscopedToken = + auth.downscopeToken(Arrays.asList("item_rename", "item_preview"), resourcePath, null, null); + assert !(downscopedToken.getAccessToken() == null); + BoxClient downscopedClient = + new BoxClient(new BoxDeveloperTokenAuth(downscopedToken.getAccessToken())); + downscopedClient + .getFiles() + .updateFileById( + file.getId(), new UpdateFileByIdRequestBody.Builder().name(getUuid()).build()); + assertThrows( + RuntimeException.class, () -> downscopedClient.getFiles().deleteFileById(file.getId())); + parentClient.getFiles().deleteFileById(file.getId()); + } + + @Test + public void testJwtDownscopeTokenSucceedsIfNoTokenAvailable() { + JWTConfig jwtConfig = + JWTConfig.fromConfigJsonString(decodeBase64(getEnvVar("JWT_CONFIG_BASE_64"))); + BoxJWTAuth auth = new BoxJWTAuth(jwtConfig); + AccessToken downscopedToken = + auth.downscopeToken(Arrays.asList("root_readonly"), null, null, null); + assert !(downscopedToken.getAccessToken() == null); + BoxClient downscopedClient = + new BoxClient(new BoxDeveloperTokenAuth(downscopedToken.getAccessToken())); + assertThrows( + RuntimeException.class, + () -> + downscopedClient + .getUploads() + .uploadFile( + new UploadFileRequestBody( + new UploadFileRequestBodyAttributesField( + getUuid(), new UploadFileRequestBodyAttributesParentField("0")), + generateByteStream(1024 * 1024)))); + } + + @Test + public void testJwtAuthRevoke() { + JWTConfig jwtConfig = + JWTConfig.fromConfigJsonString(decodeBase64(getEnvVar("JWT_CONFIG_BASE_64"))); + BoxJWTAuth auth = new BoxJWTAuth(jwtConfig); + AccessToken tokenFromStorageBeforeRevoke = auth.retrieveToken(); + assert !(tokenFromStorageBeforeRevoke == null); + auth.revokeToken(); + AccessToken tokenFromStorageAfterRevoke = auth.retrieveToken(); + assert !(tokenFromStorageBeforeRevoke + .getAccessToken() + .equals(tokenFromStorageAfterRevoke.getAccessToken())); + } + + @Test + public void testOauthAuthAuthorizeUrl() { + OAuthConfig config = new OAuthConfig("OAUTH_CLIENT_ID", "OAUTH_CLIENT_SECRET"); + BoxOAuth auth = new BoxOAuth(config); + String authUrl = auth.getAuthorizeUrl(); + assert authUrl.equals( + "https://account.box.com/api/oauth2/authorize?client_id=OAUTH_CLIENT_ID&response_type=code") + || authUrl.equals( + "https://account.box.com/api/oauth2/authorize?response_type=code&client_id=OAUTH_CLIENT_ID"); + } + + @Test + public void testOauthDownscopeTokenSucceedsIfNoTokenAvailable() { + OAuthConfig config = new OAuthConfig(getEnvVar("CLIENT_ID"), getEnvVar("CLIENT_SECRET")); + BoxOAuth auth = new BoxOAuth(config); + String resourcePath = String.join("", "https://api.box.com/2.0/files/12345"); + assertThrows( + RuntimeException.class, + () -> + auth.downscopeToken( + Arrays.asList("item_rename", "item_preview"), resourcePath, null, null)); + } + + @Test + public void testCcgAuth() { + String userId = getEnvVar("USER_ID"); + String enterpriseId = getEnvVar("ENTERPRISE_ID"); + CCGConfig ccgConfig = + new CCGConfig.Builder(getEnvVar("CLIENT_ID"), getEnvVar("CLIENT_SECRET")) + .enterpriseId(enterpriseId) + .userId(userId) + .build(); + BoxCCGAuth auth = new BoxCCGAuth(ccgConfig); + BoxCCGAuth userAuth = auth.withUserSubject(userId); + BoxClient userClient = new BoxClient(userAuth); + UserFull currentUser = userClient.getUsers().getUserMe(); + assert currentUser.getId().equals(userId); + BoxCCGAuth enterpriseAuth = auth.withEnterpriseSubject(enterpriseId); + BoxClient enterpriseClient = new BoxClient(enterpriseAuth); + UserFull newUser = + enterpriseClient + .getUsers() + .getUserMe( + new GetUserMeQueryParams.Builder().fields(Arrays.asList("enterprise")).build()); + assert !(newUser.getEnterprise() == null); + assert newUser.getEnterprise().getId().equals(enterpriseId); + assert !(newUser.getId().equals(userId)); + } + + @Test + public void testCcgAuthDownscope() { + CCGConfig ccgConfig = + new CCGConfig.Builder(getEnvVar("CLIENT_ID"), getEnvVar("CLIENT_SECRET")) + .userId(getEnvVar("USER_ID")) + .build(); + BoxCCGAuth auth = new BoxCCGAuth(ccgConfig); + BoxClient parentClient = new BoxClient(auth); + FolderFull folder = + parentClient + .getFolders() + .createFolder( + new CreateFolderRequestBody( + getUuid(), new CreateFolderRequestBodyParentField("0"))); + String resourcePath = String.join("", "https://api.box.com/2.0/folders/", folder.getId()); + AccessToken downscopedToken = + auth.downscopeToken(Arrays.asList("item_rename", "item_preview"), resourcePath, null, null); + assert !(downscopedToken.getAccessToken() == null); + BoxClient downscopedClient = + new BoxClient(new BoxDeveloperTokenAuth(downscopedToken.getAccessToken())); + downscopedClient + .getFolders() + .updateFolderById( + folder.getId(), new UpdateFolderByIdRequestBody.Builder().name(getUuid()).build()); + assertThrows( + RuntimeException.class, + () -> downscopedClient.getFolders().deleteFolderById(folder.getId())); + parentClient.getFolders().deleteFolderById(folder.getId()); + } + + @Test + public void testCcgDownscopeTokenSucceedsIfNoTokenAvailable() { + CCGConfig ccgConfig = + new CCGConfig.Builder(getEnvVar("CLIENT_ID"), getEnvVar("CLIENT_SECRET")) + .userId(getEnvVar("USER_ID")) + .build(); + BoxCCGAuth auth = new BoxCCGAuth(ccgConfig); + AccessToken downscopedToken = + auth.downscopeToken(Arrays.asList("root_readonly"), null, null, null); + assert !(downscopedToken.getAccessToken() == null); + BoxClient downscopedClient = + new BoxClient(new BoxDeveloperTokenAuth(downscopedToken.getAccessToken())); + assertThrows( + RuntimeException.class, + () -> + downscopedClient + .getUploads() + .uploadFile( + new UploadFileRequestBody( + new UploadFileRequestBodyAttributesField( + getUuid(), new UploadFileRequestBodyAttributesParentField("0")), + generateByteStream(1024 * 1024)))); + } + + @Test + public void testCcgAuthRevoke() { + CCGConfig ccgConfig = + new CCGConfig.Builder(getEnvVar("CLIENT_ID"), getEnvVar("CLIENT_SECRET")) + .userId(getEnvVar("USER_ID")) + .build(); + BoxCCGAuth auth = new BoxCCGAuth(ccgConfig); + AccessToken tokenFromStorageBeforeRevoke = auth.retrieveToken(); + assert !(tokenFromStorageBeforeRevoke == null); + auth.revokeToken(); + AccessToken tokenFromStorageAfterRevoke = auth.retrieveToken(); + assert !(tokenFromStorageBeforeRevoke + .getAccessToken() + .equals(tokenFromStorageAfterRevoke.getAccessToken())); + } + + @Test + public void testDeveloperDownscopeTokenSucceedsIfNoTokenAvailable() { + DeveloperTokenConfig developerTokenConfig = + new DeveloperTokenConfig.Builder() + .clientId(getEnvVar("CLIENT_ID")) + .clientSecret(getEnvVar("CLIENT_SECRET")) + .build(); + BoxDeveloperTokenAuth auth = + new BoxDeveloperTokenAuth.Builder("").config(developerTokenConfig).build(); + String resourcePath = String.join("", "https://api.box.com/2.0/folders/12345"); + assertThrows( + RuntimeException.class, + () -> + auth.downscopeToken( + Arrays.asList("item_rename", "item_preview"), resourcePath, null, null)); + } + + @Test + public void testDeveloperTokenAuthRevoke() { + DeveloperTokenConfig developerTokenConfig = + new DeveloperTokenConfig.Builder() + .clientId(getEnvVar("CLIENT_ID")) + .clientSecret(getEnvVar("CLIENT_SECRET")) + .build(); + AccessToken token = getAccessToken(); + BoxDeveloperTokenAuth auth = + new BoxDeveloperTokenAuth.Builder(token.getAccessToken()) + .config(developerTokenConfig) + .build(); + AccessToken tokenFromStorageBeforeRevoke = auth.retrieveToken(); + assert !(tokenFromStorageBeforeRevoke == null); + auth.revokeToken(); + assertThrows(RuntimeException.class, () -> auth.retrieveToken()); + } + + @Test + public void testDeveloperTokenAuthDownscope() { + DeveloperTokenConfig developerTokenConfig = + new DeveloperTokenConfig.Builder() + .clientId(getEnvVar("CLIENT_ID")) + .clientSecret(getEnvVar("CLIENT_SECRET")) + .build(); + AccessToken token = getAccessToken(); + BoxDeveloperTokenAuth auth = + new BoxDeveloperTokenAuth.Builder(token.getAccessToken()) + .config(developerTokenConfig) + .build(); + BoxClient parentClient = new BoxClient(auth); + FolderFull folder = + parentClient + .getFolders() + .createFolder( + new CreateFolderRequestBody( + getUuid(), new CreateFolderRequestBodyParentField("0"))); + String resourcePath = String.join("", "https://api.box.com/2.0/folders/", folder.getId()); + AccessToken downscopedToken = + auth.downscopeToken(Arrays.asList("item_rename", "item_preview"), resourcePath, null, null); + assert !(downscopedToken.getAccessToken() == null); + BoxClient downscopedClient = + new BoxClient(new BoxDeveloperTokenAuth(downscopedToken.getAccessToken())); + downscopedClient + .getFolders() + .updateFolderById( + folder.getId(), new UpdateFolderByIdRequestBody.Builder().name(getUuid()).build()); + assertThrows( + RuntimeException.class, + () -> downscopedClient.getFolders().deleteFolderById(folder.getId())); + parentClient.getFolders().deleteFolderById(folder.getId()); + } + + @Test + public void testDeveloperTokenAuth() { + String userId = getEnvVar("USER_ID"); + AccessToken token = getAccessToken(); + BoxDeveloperTokenAuth devAuth = new BoxDeveloperTokenAuth(token.getAccessToken()); + BoxClient client = new BoxClient(devAuth); + UserFull currentUser = client.getUsers().getUserMe(); + assert currentUser.getId().equals(userId); + } + + @Test + public void testOauthAuthRevoke() { + AccessToken token = getAccessToken(); + InMemoryTokenStorage tokenStorage = new InMemoryTokenStorage.Builder().token(token).build(); + OAuthConfig config = + new OAuthConfig.Builder(getEnvVar("CLIENT_ID"), getEnvVar("CLIENT_SECRET")) + .tokenStorage(tokenStorage) + .build(); + BoxOAuth auth = new BoxOAuth(config); + BoxClient client = new BoxClient(auth); + client.getUsers().getUserMe(); + auth.revokeToken(); + assertThrows(RuntimeException.class, () -> client.getUsers().getUserMe()); + } + + @Test + public void testOauthAuthDownscope() { + AccessToken token = getAccessToken(); + InMemoryTokenStorage tokenStorage = new InMemoryTokenStorage.Builder().token(token).build(); + OAuthConfig config = + new OAuthConfig.Builder(getEnvVar("CLIENT_ID"), getEnvVar("CLIENT_SECRET")) + .tokenStorage(tokenStorage) + .build(); + BoxOAuth auth = new BoxOAuth(config); + BoxClient parentClient = new BoxClient(auth); + Files uploadedFiles = + parentClient + .getUploads() + .uploadFile( + new UploadFileRequestBody( + new UploadFileRequestBodyAttributesField( + getUuid(), new UploadFileRequestBodyAttributesParentField("0")), + generateByteStream(1024 * 1024))); + FileFull file = uploadedFiles.getEntries().get(0); + String resourcePath = String.join("", "https://api.box.com/2.0/files/", file.getId()); + AccessToken downscopedToken = + auth.downscopeToken(Arrays.asList("item_rename", "item_preview"), resourcePath, null, null); + assert !(downscopedToken.getAccessToken() == null); + BoxClient downscopedClient = + new BoxClient(new BoxDeveloperTokenAuth(downscopedToken.getAccessToken())); + downscopedClient + .getFiles() + .updateFileById( + file.getId(), new UpdateFileByIdRequestBody.Builder().name(getUuid()).build()); + assertThrows( + RuntimeException.class, () -> downscopedClient.getFiles().deleteFileById(file.getId())); + parentClient.getFiles().deleteFileById(file.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/avatars/AvatarsITest.java b/src/intTest/java/com/box/sdkgen/avatars/AvatarsITest.java new file mode 100644 index 000000000..e8e5ebf73 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/avatars/AvatarsITest.java @@ -0,0 +1,43 @@ +package com.box.sdkgen.avatars; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.internal.utils.UtilsManager.bufferEquals; +import static com.box.sdkgen.internal.utils.UtilsManager.decodeBase64ByteStream; +import static com.box.sdkgen.internal.utils.UtilsManager.generateByteBuffer; +import static com.box.sdkgen.internal.utils.UtilsManager.readByteStream; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.avatars.CreateUserAvatarRequestBody; +import com.box.sdkgen.schemas.useravatar.UserAvatar; +import com.box.sdkgen.schemas.userfull.UserFull; +import java.io.InputStream; +import org.junit.jupiter.api.Test; + +public class AvatarsITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testAvatars() { + UserFull user = client.getUsers().getUserMe(); + UserAvatar createdAvatar = + client + .getAvatars() + .createUserAvatar( + user.getId(), + new CreateUserAvatarRequestBody.Builder( + decodeBase64ByteStream( + "iVBORw0KGgoAAAANSUhEUgAAAQAAAAEAAQMAAABmvDolAAAAA1BMVEW10NBjBBbqAAAAH0lEQVRoge3BAQ0AAADCoPdPbQ43oAAAAAAAAAAAvg0hAAABmmDh1QAAAABJRU5ErkJggg==")) + .picFileName("avatar.png") + .picContentType("image/png") + .build()); + assert !(createdAvatar.getPicUrls().getSmall() == null); + assert !(createdAvatar.getPicUrls().getLarge() == null); + assert !(createdAvatar.getPicUrls().getPreview() == null); + InputStream response = client.getAvatars().getUserAvatar(user.getId()); + assert bufferEquals(readByteStream(response), generateByteBuffer(0)) == false; + client.getAvatars().deleteUserAvatar(user.getId()); + assertThrows(RuntimeException.class, () -> client.getAvatars().getUserAvatar(user.getId())); + } +} diff --git a/src/intTest/java/com/box/sdkgen/chunkeduploads/ChunkedUploadsITest.java b/src/intTest/java/com/box/sdkgen/chunkeduploads/ChunkedUploadsITest.java new file mode 100644 index 000000000..1536763ee --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/chunkeduploads/ChunkedUploadsITest.java @@ -0,0 +1,239 @@ +package com.box.sdkgen.chunkeduploads; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.internal.utils.UtilsManager.bufferLength; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.generateByteStream; +import static com.box.sdkgen.internal.utils.UtilsManager.generateByteStreamFromBuffer; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; +import static com.box.sdkgen.internal.utils.UtilsManager.hexToBase64; +import static com.box.sdkgen.internal.utils.UtilsManager.iterateChunks; +import static com.box.sdkgen.internal.utils.UtilsManager.readByteStream; +import static com.box.sdkgen.internal.utils.UtilsManager.reduceIterator; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.internal.utils.Hash; +import com.box.sdkgen.internal.utils.HashName; +import com.box.sdkgen.managers.chunkeduploads.CreateFileUploadSessionCommitByUrlHeaders; +import com.box.sdkgen.managers.chunkeduploads.CreateFileUploadSessionCommitByUrlRequestBody; +import com.box.sdkgen.managers.chunkeduploads.CreateFileUploadSessionCommitHeaders; +import com.box.sdkgen.managers.chunkeduploads.CreateFileUploadSessionCommitRequestBody; +import com.box.sdkgen.managers.chunkeduploads.CreateFileUploadSessionRequestBody; +import com.box.sdkgen.managers.chunkeduploads.UploadFilePartByUrlHeaders; +import com.box.sdkgen.managers.chunkeduploads.UploadFilePartHeaders; +import com.box.sdkgen.schemas.file.File; +import com.box.sdkgen.schemas.files.Files; +import com.box.sdkgen.schemas.uploadedpart.UploadedPart; +import com.box.sdkgen.schemas.uploadpart.UploadPart; +import com.box.sdkgen.schemas.uploadparts.UploadParts; +import com.box.sdkgen.schemas.uploadsession.UploadSession; +import java.io.InputStream; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; + +public class ChunkedUploadsITest { + + private static final BoxClient client = getDefaultClient(); + + public static TestPartAccumulator reducerById(TestPartAccumulator acc, InputStream chunk) { + int lastIndex = acc.getLastIndex(); + List parts = acc.getParts(); + byte[] chunkBuffer = readByteStream(chunk); + Hash hash = new Hash(HashName.SHA1); + hash.updateHash(chunkBuffer); + String sha1 = hash.digestHash("base64"); + String digest = String.join("", "sha=", sha1); + int chunkSize = bufferLength(chunkBuffer); + int bytesStart = lastIndex + 1; + int bytesEnd = lastIndex + chunkSize; + String contentRange = + String.join( + "", + "bytes ", + convertToString(bytesStart), + "-", + convertToString(bytesEnd), + "/", + convertToString(acc.getFileSize())); + UploadedPart uploadedPart = + client + .getChunkedUploads() + .uploadFilePart( + acc.getUploadSessionId(), + generateByteStreamFromBuffer(chunkBuffer), + new UploadFilePartHeaders(digest, contentRange)); + UploadPart part = uploadedPart.getPart(); + String partSha1 = hexToBase64(part.getSha1()); + assert partSha1.equals(sha1); + assert part.getSize() == chunkSize; + assert part.getOffset() == bytesStart; + acc.getFileHash().updateHash(chunkBuffer); + return new TestPartAccumulator.Builder( + bytesEnd, + Stream.concat(parts.stream(), Arrays.asList(part).stream()) + .collect(Collectors.toList()), + acc.getFileSize(), + acc.getFileHash()) + .uploadSessionId(acc.getUploadSessionId()) + .build(); + } + + public static TestPartAccumulator reducerByUrl(TestPartAccumulator acc, InputStream chunk) { + int lastIndex = acc.getLastIndex(); + List parts = acc.getParts(); + byte[] chunkBuffer = readByteStream(chunk); + Hash hash = new Hash(HashName.SHA1); + hash.updateHash(chunkBuffer); + String sha1 = hash.digestHash("base64"); + String digest = String.join("", "sha=", sha1); + int chunkSize = bufferLength(chunkBuffer); + int bytesStart = lastIndex + 1; + int bytesEnd = lastIndex + chunkSize; + String contentRange = + String.join( + "", + "bytes ", + convertToString(bytesStart), + "-", + convertToString(bytesEnd), + "/", + convertToString(acc.getFileSize())); + UploadedPart uploadedPart = + client + .getChunkedUploads() + .uploadFilePartByUrl( + acc.getUploadPartUrl(), + generateByteStreamFromBuffer(chunkBuffer), + new UploadFilePartByUrlHeaders(digest, contentRange)); + UploadPart part = uploadedPart.getPart(); + String partSha1 = hexToBase64(part.getSha1()); + assert partSha1.equals(sha1); + assert part.getSize() == chunkSize; + assert part.getOffset() == bytesStart; + acc.getFileHash().updateHash(chunkBuffer); + return new TestPartAccumulator.Builder( + bytesEnd, + Stream.concat(parts.stream(), Arrays.asList(part).stream()) + .collect(Collectors.toList()), + acc.getFileSize(), + acc.getFileHash()) + .uploadPartUrl(acc.getUploadPartUrl()) + .build(); + } + + @Test + public void testChunkedManualProcessById() { + int fileSize = 20 * 1024 * 1024; + InputStream fileByteStream = generateByteStream(fileSize); + String fileName = getUuid(); + String parentFolderId = "0"; + UploadSession uploadSession = + client + .getChunkedUploads() + .createFileUploadSession( + new CreateFileUploadSessionRequestBody(parentFolderId, fileSize, fileName)); + String uploadSessionId = uploadSession.getId(); + long partSize = uploadSession.getPartSize(); + int totalParts = uploadSession.getTotalParts(); + assert partSize * totalParts >= fileSize; + assert uploadSession.getNumPartsProcessed() == 0; + Hash fileHash = new Hash(HashName.SHA1); + Iterator chunksIterator = iterateChunks(fileByteStream, partSize, fileSize); + TestPartAccumulator results = + reduceIterator( + chunksIterator, + (TestPartAccumulator acc, InputStream chunk) -> reducerById(acc, chunk), + new TestPartAccumulator.Builder(-1, Collections.emptyList(), fileSize, fileHash) + .uploadSessionId(uploadSessionId) + .build()); + List parts = results.getParts(); + UploadParts processedSessionParts = + client.getChunkedUploads().getFileUploadSessionParts(uploadSessionId); + assert processedSessionParts.getTotalCount() == totalParts; + UploadSession processedSession = + client.getChunkedUploads().getFileUploadSessionById(uploadSessionId); + assert processedSession.getId().equals(uploadSessionId); + String sha1 = fileHash.digestHash("base64"); + String digest = String.join("", "sha=", sha1); + Files committedSession = + client + .getChunkedUploads() + .createFileUploadSessionCommit( + uploadSessionId, + new CreateFileUploadSessionCommitRequestBody(parts), + new CreateFileUploadSessionCommitHeaders(digest)); + assert committedSession.getEntries().get(0).getName().equals(fileName); + client.getChunkedUploads().deleteFileUploadSessionById(uploadSessionId); + } + + @Test + public void testChunkedManualProcessByUrl() { + int fileSize = 20 * 1024 * 1024; + InputStream fileByteStream = generateByteStream(fileSize); + String fileName = getUuid(); + String parentFolderId = "0"; + UploadSession uploadSession = + client + .getChunkedUploads() + .createFileUploadSession( + new CreateFileUploadSessionRequestBody(parentFolderId, fileSize, fileName)); + String uploadPartUrl = uploadSession.getSessionEndpoints().getUploadPart(); + String commitUrl = uploadSession.getSessionEndpoints().getCommit(); + String listPartsUrl = uploadSession.getSessionEndpoints().getListParts(); + String statusUrl = uploadSession.getSessionEndpoints().getStatus(); + String abortUrl = uploadSession.getSessionEndpoints().getAbort(); + String uploadSessionId = uploadSession.getId(); + long partSize = uploadSession.getPartSize(); + int totalParts = uploadSession.getTotalParts(); + assert partSize * totalParts >= fileSize; + assert uploadSession.getNumPartsProcessed() == 0; + Hash fileHash = new Hash(HashName.SHA1); + Iterator chunksIterator = iterateChunks(fileByteStream, partSize, fileSize); + TestPartAccumulator results = + reduceIterator( + chunksIterator, + (TestPartAccumulator acc, InputStream chunk) -> reducerByUrl(acc, chunk), + new TestPartAccumulator.Builder(-1, Collections.emptyList(), fileSize, fileHash) + .uploadPartUrl(uploadPartUrl) + .build()); + List parts = results.getParts(); + UploadParts processedSessionParts = + client.getChunkedUploads().getFileUploadSessionPartsByUrl(listPartsUrl); + assert processedSessionParts.getTotalCount() == totalParts; + UploadSession processedSession = + client.getChunkedUploads().getFileUploadSessionByUrl(statusUrl); + assert processedSession.getId().equals(uploadSessionId); + String sha1 = fileHash.digestHash("base64"); + String digest = String.join("", "sha=", sha1); + Files committedSession = + client + .getChunkedUploads() + .createFileUploadSessionCommitByUrl( + commitUrl, + new CreateFileUploadSessionCommitByUrlRequestBody(parts), + new CreateFileUploadSessionCommitByUrlHeaders(digest)); + assert committedSession.getEntries().get(0).getName().equals(fileName); + client.getChunkedUploads().deleteFileUploadSessionByUrl(abortUrl); + } + + @Test + public void testChunkedUploadConvenienceMethod() { + int fileSize = 20 * 1024 * 1024; + InputStream fileByteStream = generateByteStream(fileSize); + String fileName = getUuid(); + String parentFolderId = "0"; + File uploadedFile = + client + .getChunkedUploads() + .uploadBigFile(fileByteStream, fileName, fileSize, parentFolderId); + assert uploadedFile.getName().equals(fileName); + assert uploadedFile.getSize() == fileSize; + assert uploadedFile.getParent().getId().equals(parentFolderId); + client.getFiles().deleteFileById(uploadedFile.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/chunkeduploads/TestPartAccumulator.java b/src/intTest/java/com/box/sdkgen/chunkeduploads/TestPartAccumulator.java new file mode 100644 index 000000000..dc09ee76d --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/chunkeduploads/TestPartAccumulator.java @@ -0,0 +1,100 @@ +package com.box.sdkgen.chunkeduploads; + +import com.box.sdkgen.internal.utils.Hash; +import com.box.sdkgen.schemas.uploadpart.UploadPart; +import java.util.List; + +public class TestPartAccumulator { + + public final int lastIndex; + + public final List parts; + + public final long fileSize; + + public String uploadPartUrl; + + public String uploadSessionId; + + public final Hash fileHash; + + public TestPartAccumulator(int lastIndex, List parts, long fileSize, Hash fileHash) { + this.lastIndex = lastIndex; + this.parts = parts; + this.fileSize = fileSize; + this.fileHash = fileHash; + this.uploadPartUrl = ""; + this.uploadSessionId = ""; + } + + protected TestPartAccumulator(Builder builder) { + this.lastIndex = builder.lastIndex; + this.parts = builder.parts; + this.fileSize = builder.fileSize; + this.uploadPartUrl = builder.uploadPartUrl; + this.uploadSessionId = builder.uploadSessionId; + this.fileHash = builder.fileHash; + } + + public int getLastIndex() { + return lastIndex; + } + + public List getParts() { + return parts; + } + + public long getFileSize() { + return fileSize; + } + + public String getUploadPartUrl() { + return uploadPartUrl; + } + + public String getUploadSessionId() { + return uploadSessionId; + } + + public Hash getFileHash() { + return fileHash; + } + + public static class Builder { + + protected final int lastIndex; + + protected final List parts; + + protected final long fileSize; + + protected String uploadPartUrl; + + protected String uploadSessionId; + + protected final Hash fileHash; + + public Builder(int lastIndex, List parts, long fileSize, Hash fileHash) { + this.lastIndex = lastIndex; + this.parts = parts; + this.fileSize = fileSize; + this.fileHash = fileHash; + this.uploadPartUrl = ""; + this.uploadSessionId = ""; + } + + public Builder uploadPartUrl(String uploadPartUrl) { + this.uploadPartUrl = uploadPartUrl; + return this; + } + + public Builder uploadSessionId(String uploadSessionId) { + this.uploadSessionId = uploadSessionId; + return this; + } + + public TestPartAccumulator build() { + return new TestPartAccumulator(this); + } + } +} diff --git a/src/intTest/java/com/box/sdkgen/classifications/ClassificationsITest.java b/src/intTest/java/com/box/sdkgen/classifications/ClassificationsITest.java new file mode 100644 index 000000000..de90b52c4 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/classifications/ClassificationsITest.java @@ -0,0 +1,68 @@ +package com.box.sdkgen.classifications; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.commons.CommonsManager.getOrCreateClassification; +import static com.box.sdkgen.commons.CommonsManager.getOrCreateClassificationTemplate; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.classifications.UpdateClassificationRequestBody; +import com.box.sdkgen.managers.classifications.UpdateClassificationRequestBodyDataField; +import com.box.sdkgen.managers.classifications.UpdateClassificationRequestBodyDataStaticConfigClassificationField; +import com.box.sdkgen.managers.classifications.UpdateClassificationRequestBodyDataStaticConfigField; +import com.box.sdkgen.schemas.classificationtemplate.ClassificationTemplate; +import com.box.sdkgen.schemas.classificationtemplate.ClassificationTemplateFieldsOptionsField; +import java.util.Arrays; +import java.util.List; +import org.junit.jupiter.api.Test; + +public class ClassificationsITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testClassifications() { + ClassificationTemplate classificationTemplate = getOrCreateClassificationTemplate(); + ClassificationTemplateFieldsOptionsField classification = + getOrCreateClassification(classificationTemplate); + assert !(classification.getKey().equals("")); + assert !(classification.getStaticConfig().getClassification().getColorId() == 100); + assert !(classification + .getStaticConfig() + .getClassification() + .getClassificationDefinition() + .equals("")); + String updatedClassificationName = getUuid(); + String updatedClassificationDescription = getUuid(); + ClassificationTemplate classificationTemplateWithUpdatedClassification = + client + .getClassifications() + .updateClassification( + Arrays.asList( + new UpdateClassificationRequestBody( + classification.getKey(), + new UpdateClassificationRequestBodyDataField.Builder( + updatedClassificationName) + .staticConfig( + new UpdateClassificationRequestBodyDataStaticConfigField.Builder() + .classification( + new UpdateClassificationRequestBodyDataStaticConfigClassificationField + .Builder() + .classificationDefinition( + updatedClassificationDescription) + .colorId(2L) + .build()) + .build()) + .build()))); + List updatedClassifications = + classificationTemplateWithUpdatedClassification.getFields().get(0).getOptions(); + ClassificationTemplateFieldsOptionsField updatedClassification = updatedClassifications.get(0); + assert updatedClassification.getKey().equals(updatedClassificationName); + assert updatedClassification.getStaticConfig().getClassification().getColorId() == 2; + assert updatedClassification + .getStaticConfig() + .getClassification() + .getClassificationDefinition() + .equals(updatedClassificationDescription); + } +} diff --git a/src/intTest/java/com/box/sdkgen/client/ClientITest.java b/src/intTest/java/com/box/sdkgen/client/ClientITest.java new file mode 100644 index 000000000..dcae23882 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/client/ClientITest.java @@ -0,0 +1,224 @@ +package com.box.sdkgen.client; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.internal.utils.UtilsManager.bufferEquals; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.entryOf; +import static com.box.sdkgen.internal.utils.UtilsManager.generateByteBuffer; +import static com.box.sdkgen.internal.utils.UtilsManager.generateByteStream; +import static com.box.sdkgen.internal.utils.UtilsManager.generateByteStreamFromBuffer; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; +import static com.box.sdkgen.internal.utils.UtilsManager.mapOf; +import static com.box.sdkgen.internal.utils.UtilsManager.readByteStream; +import static com.box.sdkgen.serialization.json.JsonManager.getSdValueByKey; +import static com.box.sdkgen.serialization.json.JsonManager.jsonToSerializedData; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.managers.folders.CreateFolderRequestBody; +import com.box.sdkgen.managers.folders.CreateFolderRequestBodyParentField; +import com.box.sdkgen.managers.folders.DeleteFolderByIdQueryParams; +import com.box.sdkgen.managers.uploads.UploadFileRequestBody; +import com.box.sdkgen.managers.uploads.UploadFileRequestBodyAttributesField; +import com.box.sdkgen.managers.uploads.UploadFileRequestBodyAttributesParentField; +import com.box.sdkgen.managers.users.CreateUserRequestBody; +import com.box.sdkgen.networking.baseurls.BaseUrls; +import com.box.sdkgen.networking.fetchoptions.FetchOptions; +import com.box.sdkgen.networking.fetchoptions.MultipartItem; +import com.box.sdkgen.networking.fetchoptions.ResponseFormat; +import com.box.sdkgen.networking.fetchresponse.FetchResponse; +import com.box.sdkgen.schemas.filefull.FileFull; +import com.box.sdkgen.schemas.files.Files; +import com.box.sdkgen.schemas.folderfull.FolderFull; +import com.box.sdkgen.schemas.userfull.UserFull; +import com.fasterxml.jackson.databind.JsonNode; +import java.io.InputStream; +import java.util.Arrays; +import org.junit.jupiter.api.Test; + +public class ClientITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testMakeRequestJsonCrud() { + String newFolderName = getUuid(); + String requestBodyPost = + String.join("", "{\"name\": \"", newFolderName, "\", \"parent\": { \"id\": \"0\"}}"); + FetchResponse createFolderResponse = + client.makeRequest( + new FetchOptions.Builder("https://api.box.com/2.0/folders", "post") + .data(jsonToSerializedData(requestBodyPost)) + .build()); + assert createFolderResponse.getStatus() == 201; + JsonNode createdFolder = createFolderResponse.getData(); + assert getSdValueByKey(createdFolder, "name").equals(newFolderName); + String updatedName = getUuid(); + String requestBodyPut = String.join("", "{\"name\": \"", updatedName, "\"}"); + FetchResponse updateFolderResponse = + client.makeRequest( + new FetchOptions.Builder( + String.join( + "", + "https://api.box.com/2.0/folders/", + getSdValueByKey(createdFolder, "id")), + "put") + .data(jsonToSerializedData(requestBodyPut)) + .build()); + assert updateFolderResponse.getStatus() == 200; + JsonNode updatedFolder = updateFolderResponse.getData(); + assert getSdValueByKey(updatedFolder, "name").equals(updatedName); + assert getSdValueByKey(updatedFolder, "id").equals(getSdValueByKey(createdFolder, "id")); + FetchResponse getFolderResponse = + client.makeRequest( + new FetchOptions( + String.join( + "", "https://api.box.com/2.0/folders/", getSdValueByKey(createdFolder, "id")), + "GET")); + assert getFolderResponse.getStatus() == 200; + JsonNode receivedFolder = getFolderResponse.getData(); + assert getSdValueByKey(receivedFolder, "name").equals(updatedName); + assert getSdValueByKey(receivedFolder, "id").equals(getSdValueByKey(updatedFolder, "id")); + FetchResponse deleteFolderResponse = + client.makeRequest( + new FetchOptions( + String.join( + "", "https://api.box.com/2.0/folders/", getSdValueByKey(receivedFolder, "id")), + "DELETE")); + assert deleteFolderResponse.getStatus() == 204; + } + + @Test + public void testMakeRequestMultipart() { + String newFolderName = getUuid(); + FolderFull newFolder = + client + .getFolders() + .createFolder( + new CreateFolderRequestBody( + newFolderName, new CreateFolderRequestBodyParentField("0"))); + String newFolderId = newFolder.getId(); + String newFileName = String.join("", getUuid(), ".pdf"); + InputStream fileContentStream = generateByteStream(1024 * 1024); + String multipartAttributes = + String.join( + "", "{\"name\": \"", newFileName, "\", \"parent\": { \"id\":", newFolderId, "}}"); + FetchResponse uploadFileResponse = + client.makeRequest( + new FetchOptions.Builder("https://upload.box.com/api/2.0/files/content", "POST") + .multipartData( + Arrays.asList( + new MultipartItem.Builder("attributes") + .data(jsonToSerializedData(multipartAttributes)) + .build(), + new MultipartItem.Builder("file").fileStream(fileContentStream).build())) + .contentType("multipart/form-data") + .build()); + assert uploadFileResponse.getStatus() == 201; + client + .getFolders() + .deleteFolderById( + newFolderId, new DeleteFolderByIdQueryParams.Builder().recursive(true).build()); + } + + @Test + public void testMakeRequestBinaryFormat() { + String newFileName = getUuid(); + byte[] fileBuffer = generateByteBuffer(1024 * 1024); + InputStream fileContentStream = generateByteStreamFromBuffer(fileBuffer); + Files uploadedFiles = + client + .getUploads() + .uploadFile( + new UploadFileRequestBody( + new UploadFileRequestBodyAttributesField( + newFileName, new UploadFileRequestBodyAttributesParentField("0")), + fileContentStream)); + FileFull uploadedFile = uploadedFiles.getEntries().get(0); + FetchResponse downloadFileResponse = + client.makeRequest( + new FetchOptions.Builder( + String.join( + "", "https://api.box.com/2.0/files/", uploadedFile.getId(), "/content"), + "GET") + .responseFormat(ResponseFormat.BINARY) + .build()); + assert downloadFileResponse.getStatus() == 200; + assert bufferEquals(readByteStream(downloadFileResponse.getContent()), fileBuffer); + client.getFiles().deleteFileById(uploadedFile.getId()); + } + + @Test + public void testWithAsUserHeader() { + String userName = getUuid(); + UserFull createdUser = + client + .getUsers() + .createUser( + new CreateUserRequestBody.Builder(userName).isPlatformAccessOnly(true).build()); + BoxClient asUserClient = client.withAsUserHeader(createdUser.getId()); + UserFull adminUser = client.getUsers().getUserMe(); + assert !(convertToString(adminUser.getName()).equals(userName)); + UserFull appUser = asUserClient.getUsers().getUserMe(); + assert convertToString(appUser.getName()).equals(userName); + client.getUsers().deleteUserById(createdUser.getId()); + } + + @Test + public void testWithSuppressedNotifications() { + BoxClient newClient = client.withSuppressedNotifications(); + UserFull user = newClient.getUsers().getUserMe(); + assert !(user.getId().equals("")); + } + + @Test + public void testWithExtraHeaders() { + String userName = getUuid(); + UserFull createdUser = + client + .getUsers() + .createUser( + new CreateUserRequestBody.Builder(userName).isPlatformAccessOnly(true).build()); + BoxClient asUserClient = + client.withExtraHeaders(mapOf(entryOf("As-User", createdUser.getId()))); + UserFull adminUser = client.getUsers().getUserMe(); + assert !(convertToString(adminUser.getName()).equals(userName)); + UserFull appUser = asUserClient.getUsers().getUserMe(); + assert convertToString(appUser.getName()).equals(userName); + client.getUsers().deleteUserById(createdUser.getId()); + } + + @Test + public void testWithCustomBaseUrls() { + BaseUrls newBaseUrls = + new BaseUrls.Builder() + .baseUrl("https://box.com/") + .uploadUrl("https://box.com/") + .oauth2Url("https://box.com/") + .build(); + BoxClient customBaseClient = client.withCustomBaseUrls(newBaseUrls); + assertThrows(RuntimeException.class, () -> customBaseClient.getUsers().getUserMe()); + } + + @Test + public void testWithInterceptors() { + UserFull user = client.getUsers().getUserMe(); + assert user.getRole() == null; + BoxClient clientWithInterceptor = + client.withInterceptors(Arrays.asList(new InterceptorAddingRoleToFields())); + UserFull newUser = clientWithInterceptor.getUsers().getUserMe(); + assert !(newUser.getRole() == null); + BoxClient clientWithTwoInterceptors = + clientWithInterceptor.withInterceptors(Arrays.asList(new InterceptorChangingResponse())); + UserFull superNewUser = clientWithTwoInterceptors.getUsers().getUserMe(); + assert superNewUser.getId().equals("123"); + } + + @Test + public void testWithFailingInterceptors() { + UserFull user = client.getUsers().getUserMe(); + assert !(user.getId() == null); + BoxClient clientWithInterceptor = + client.withInterceptors(Arrays.asList(new InterceptorThrowingError())); + assertThrows(RuntimeException.class, () -> clientWithInterceptor.getUsers().getUserMe()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/client/InterceptorAddingRoleToFields.java b/src/intTest/java/com/box/sdkgen/client/InterceptorAddingRoleToFields.java new file mode 100644 index 000000000..70444ac5b --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/client/InterceptorAddingRoleToFields.java @@ -0,0 +1,32 @@ +package com.box.sdkgen.client; + +import static com.box.sdkgen.internal.utils.UtilsManager.entryOf; +import static com.box.sdkgen.internal.utils.UtilsManager.mapOf; +import static com.box.sdkgen.internal.utils.UtilsManager.mergeMaps; + +import com.box.sdkgen.networking.fetchoptions.FetchOptions; +import com.box.sdkgen.networking.fetchresponse.FetchResponse; +import com.box.sdkgen.networking.interceptors.Interceptor; + +public class InterceptorAddingRoleToFields implements Interceptor { + + @Override + public FetchOptions beforeRequest(FetchOptions options) { + return new FetchOptions.Builder(options.getUrl(), options.getMethod()) + .params(mergeMaps(options.getParams(), mapOf(entryOf("fields", "role")))) + .headers(options.getHeaders()) + .data(options.getData()) + .fileStream(options.getFileStream()) + .multipartData(options.getMultipartData()) + .contentType(options.getContentType()) + .responseFormat(options.getResponseFormat()) + .auth(options.getAuth()) + .networkSession(options.getNetworkSession()) + .build(); + } + + @Override + public FetchResponse afterRequest(FetchResponse response) { + return response; + } +} diff --git a/src/intTest/java/com/box/sdkgen/client/InterceptorChangingResponse.java b/src/intTest/java/com/box/sdkgen/client/InterceptorChangingResponse.java new file mode 100644 index 000000000..a20bca9c7 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/client/InterceptorChangingResponse.java @@ -0,0 +1,24 @@ +package com.box.sdkgen.client; + +import static com.box.sdkgen.serialization.json.JsonManager.jsonToSerializedData; + +import com.box.sdkgen.networking.fetchoptions.FetchOptions; +import com.box.sdkgen.networking.fetchresponse.FetchResponse; +import com.box.sdkgen.networking.interceptors.Interceptor; + +public class InterceptorChangingResponse implements Interceptor { + + @Override + public FetchOptions beforeRequest(FetchOptions options) { + return options; + } + + @Override + public FetchResponse afterRequest(FetchResponse response) { + return new FetchResponse.Builder(response.getStatus(), response.getHeaders()) + .url(response.getUrl()) + .data(jsonToSerializedData("{\"id\": \"123\", \"type\": \"user\"}")) + .content(response.getContent()) + .build(); + } +} diff --git a/src/intTest/java/com/box/sdkgen/client/InterceptorThrowingError.java b/src/intTest/java/com/box/sdkgen/client/InterceptorThrowingError.java new file mode 100644 index 000000000..3521405ff --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/client/InterceptorThrowingError.java @@ -0,0 +1,22 @@ +package com.box.sdkgen.client; + +import com.box.sdkgen.networking.fetchoptions.FetchOptions; +import com.box.sdkgen.networking.fetchresponse.FetchResponse; +import com.box.sdkgen.networking.interceptors.Interceptor; + +public class InterceptorThrowingError implements Interceptor { + + @Override + public FetchOptions beforeRequest(FetchOptions options) { + return options; + } + + @Override + public FetchResponse afterRequest(FetchResponse response) { + return new FetchResponse.Builder(400, response.getHeaders()) + .url(response.getUrl()) + .data(response.getData()) + .content(response.getContent()) + .build(); + } +} diff --git a/src/intTest/java/com/box/sdkgen/collaborationallowlistentries/CollaborationAllowlistEntriesITest.java b/src/intTest/java/com/box/sdkgen/collaborationallowlistentries/CollaborationAllowlistEntriesITest.java new file mode 100644 index 000000000..087180736 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/collaborationallowlistentries/CollaborationAllowlistEntriesITest.java @@ -0,0 +1,49 @@ +package com.box.sdkgen.collaborationallowlistentries; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.collaborationallowlistentries.CreateCollaborationWhitelistEntryRequestBody; +import com.box.sdkgen.managers.collaborationallowlistentries.CreateCollaborationWhitelistEntryRequestBodyDirectionField; +import com.box.sdkgen.schemas.collaborationallowlistentries.CollaborationAllowlistEntries; +import com.box.sdkgen.schemas.collaborationallowlistentry.CollaborationAllowlistEntry; +import org.junit.jupiter.api.Test; + +public class CollaborationAllowlistEntriesITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testCollaborationAllowlistEntries() { + CollaborationAllowlistEntries allowlist = + client.getCollaborationAllowlistEntries().getCollaborationWhitelistEntries(); + assert allowlist.getEntries().size() >= 0; + String domain = String.join("", getUuid(), "example.com"); + CollaborationAllowlistEntry newEntry = + client + .getCollaborationAllowlistEntries() + .createCollaborationWhitelistEntry( + new CreateCollaborationWhitelistEntryRequestBody( + domain, CreateCollaborationWhitelistEntryRequestBodyDirectionField.INBOUND)); + assert convertToString(newEntry.getType()).equals("collaboration_whitelist_entry"); + assert convertToString(newEntry.getDirection()).equals("inbound"); + assert newEntry.getDomain().equals(domain); + CollaborationAllowlistEntry entry = + client + .getCollaborationAllowlistEntries() + .getCollaborationWhitelistEntryById(newEntry.getId()); + assert entry.getId().equals(newEntry.getId()); + assert convertToString(entry.getDirection()).equals(convertToString(newEntry.getDirection())); + assert entry.getDomain().equals(domain); + client.getCollaborationAllowlistEntries().deleteCollaborationWhitelistEntryById(entry.getId()); + assertThrows( + RuntimeException.class, + () -> + client + .getCollaborationAllowlistEntries() + .getCollaborationWhitelistEntryById(entry.getId())); + } +} diff --git a/src/intTest/java/com/box/sdkgen/collaborationallowlistexempttargets/CollaborationAllowlistExemptTargetsITest.java b/src/intTest/java/com/box/sdkgen/collaborationallowlistexempttargets/CollaborationAllowlistExemptTargetsITest.java new file mode 100644 index 000000000..983aaff9b --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/collaborationallowlistexempttargets/CollaborationAllowlistExemptTargetsITest.java @@ -0,0 +1,61 @@ +package com.box.sdkgen.collaborationallowlistexempttargets; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.collaborationallowlistexempttargets.CreateCollaborationWhitelistExemptTargetRequestBody; +import com.box.sdkgen.managers.collaborationallowlistexempttargets.CreateCollaborationWhitelistExemptTargetRequestBodyUserField; +import com.box.sdkgen.managers.users.CreateUserRequestBody; +import com.box.sdkgen.schemas.collaborationallowlistexempttarget.CollaborationAllowlistExemptTarget; +import com.box.sdkgen.schemas.collaborationallowlistexempttargets.CollaborationAllowlistExemptTargets; +import com.box.sdkgen.schemas.userfull.UserFull; +import org.junit.jupiter.api.Test; + +public class CollaborationAllowlistExemptTargetsITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testCollaborationAllowlistExemptTargets() { + CollaborationAllowlistExemptTargets exemptTargets = + client.getCollaborationAllowlistExemptTargets().getCollaborationWhitelistExemptTargets(); + assert exemptTargets.getEntries().size() >= 0; + UserFull user = + client + .getUsers() + .createUser( + new CreateUserRequestBody.Builder(getUuid()) + .login(String.join("", getUuid(), "@boxdemo.com")) + .isPlatformAccessOnly(true) + .build()); + CollaborationAllowlistExemptTarget newExemptTarget = + client + .getCollaborationAllowlistExemptTargets() + .createCollaborationWhitelistExemptTarget( + new CreateCollaborationWhitelistExemptTargetRequestBody( + new CreateCollaborationWhitelistExemptTargetRequestBodyUserField( + user.getId()))); + assert convertToString(newExemptTarget.getType()) + .equals("collaboration_whitelist_exempt_target"); + assert newExemptTarget.getUser().getId().equals(user.getId()); + CollaborationAllowlistExemptTarget exemptTarget = + client + .getCollaborationAllowlistExemptTargets() + .getCollaborationWhitelistExemptTargetById(newExemptTarget.getId()); + assert exemptTarget.getId().equals(newExemptTarget.getId()); + assert exemptTarget.getUser().getId().equals(user.getId()); + client + .getCollaborationAllowlistExemptTargets() + .deleteCollaborationWhitelistExemptTargetById(exemptTarget.getId()); + assertThrows( + RuntimeException.class, + () -> + client + .getCollaborationAllowlistExemptTargets() + .getCollaborationWhitelistExemptTargetById(exemptTarget.getId())); + client.getUsers().deleteUserById(user.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/comments/CommentsITest.java b/src/intTest/java/com/box/sdkgen/comments/CommentsITest.java new file mode 100644 index 000000000..582ac4d6d --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/comments/CommentsITest.java @@ -0,0 +1,81 @@ +package com.box.sdkgen.comments; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.internal.utils.UtilsManager.generateByteStream; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.comments.CreateCommentRequestBody; +import com.box.sdkgen.managers.comments.CreateCommentRequestBodyItemField; +import com.box.sdkgen.managers.comments.CreateCommentRequestBodyItemTypeField; +import com.box.sdkgen.managers.comments.UpdateCommentByIdRequestBody; +import com.box.sdkgen.managers.uploads.UploadFileRequestBody; +import com.box.sdkgen.managers.uploads.UploadFileRequestBodyAttributesField; +import com.box.sdkgen.managers.uploads.UploadFileRequestBodyAttributesParentField; +import com.box.sdkgen.schemas.commentfull.CommentFull; +import com.box.sdkgen.schemas.comments.Comments; +import com.box.sdkgen.schemas.files.Files; +import java.io.InputStream; +import org.junit.jupiter.api.Test; + +public class CommentsITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testComments() { + int fileSize = 256; + String fileName = getUuid(); + InputStream fileByteStream = generateByteStream(fileSize); + String parentId = "0"; + Files uploadedFiles = + client + .getUploads() + .uploadFile( + new UploadFileRequestBody( + new UploadFileRequestBodyAttributesField( + fileName, new UploadFileRequestBodyAttributesParentField(parentId)), + fileByteStream)); + String fileId = uploadedFiles.getEntries().get(0).getId(); + Comments comments = client.getComments().getFileComments(fileId); + assert comments.getTotalCount() == 0; + String message = "Hello there!"; + CommentFull newComment = + client + .getComments() + .createComment( + new CreateCommentRequestBody( + message, + new CreateCommentRequestBodyItemField( + fileId, CreateCommentRequestBodyItemTypeField.FILE))); + assert newComment.getMessage().equals(message); + assert newComment.getIsReplyComment() == false; + assert newComment.getItem().getId().equals(fileId); + CommentFull newReplyComment = + client + .getComments() + .createComment( + new CreateCommentRequestBody( + message, + new CreateCommentRequestBodyItemField( + newComment.getId(), CreateCommentRequestBodyItemTypeField.COMMENT))); + assert newReplyComment.getMessage().equals(message); + assert newReplyComment.getIsReplyComment() == true; + String newMessage = "Hi!"; + client + .getComments() + .updateCommentById( + newReplyComment.getId(), + new UpdateCommentByIdRequestBody.Builder().message(newMessage).build()); + Comments newComments = client.getComments().getFileComments(fileId); + assert newComments.getTotalCount() == 2; + assert newComments.getEntries().get(1).getMessage().equals(newMessage); + CommentFull receivedComment = client.getComments().getCommentById(newComment.getId()); + assert receivedComment.getMessage().equals(newComment.getMessage()); + client.getComments().deleteCommentById(newComment.getId()); + assertThrows( + RuntimeException.class, () -> client.getComments().getCommentById(newComment.getId())); + client.getFiles().deleteFileById(fileId); + } +} diff --git a/src/intTest/java/com/box/sdkgen/commons/CommonsManager.java b/src/intTest/java/com/box/sdkgen/commons/CommonsManager.java new file mode 100644 index 000000000..223cd43dc --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/commons/CommonsManager.java @@ -0,0 +1,187 @@ +package com.box.sdkgen.commons; + +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.decodeBase64; +import static com.box.sdkgen.internal.utils.UtilsManager.generateByteStream; +import static com.box.sdkgen.internal.utils.UtilsManager.getEnvVar; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; +import static com.box.sdkgen.internal.utils.UtilsManager.isBrowser; + +import com.box.sdkgen.box.ccgauth.BoxCCGAuth; +import com.box.sdkgen.box.ccgauth.CCGConfig; +import com.box.sdkgen.box.jwtauth.BoxJWTAuth; +import com.box.sdkgen.box.jwtauth.JWTConfig; +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.classifications.AddClassificationRequestBody; +import com.box.sdkgen.managers.classifications.AddClassificationRequestBodyDataField; +import com.box.sdkgen.managers.classifications.AddClassificationRequestBodyDataStaticConfigClassificationField; +import com.box.sdkgen.managers.classifications.AddClassificationRequestBodyDataStaticConfigField; +import com.box.sdkgen.managers.classifications.CreateClassificationTemplateRequestBody; +import com.box.sdkgen.managers.classifications.CreateClassificationTemplateRequestBodyFieldsField; +import com.box.sdkgen.managers.folders.CreateFolderRequestBody; +import com.box.sdkgen.managers.folders.CreateFolderRequestBodyParentField; +import com.box.sdkgen.managers.shieldinformationbarriers.CreateShieldInformationBarrierRequestBody; +import com.box.sdkgen.managers.termsofservices.CreateTermsOfServiceRequestBody; +import com.box.sdkgen.managers.termsofservices.CreateTermsOfServiceRequestBodyStatusField; +import com.box.sdkgen.managers.termsofservices.CreateTermsOfServiceRequestBodyTosTypeField; +import com.box.sdkgen.managers.uploads.UploadFileRequestBody; +import com.box.sdkgen.managers.uploads.UploadFileRequestBodyAttributesField; +import com.box.sdkgen.managers.uploads.UploadFileRequestBodyAttributesParentField; +import com.box.sdkgen.schemas.classificationtemplate.ClassificationTemplate; +import com.box.sdkgen.schemas.classificationtemplate.ClassificationTemplateFieldsOptionsField; +import com.box.sdkgen.schemas.enterprisebase.EnterpriseBase; +import com.box.sdkgen.schemas.filefull.FileFull; +import com.box.sdkgen.schemas.files.Files; +import com.box.sdkgen.schemas.folderfull.FolderFull; +import com.box.sdkgen.schemas.shieldinformationbarrier.ShieldInformationBarrier; +import com.box.sdkgen.schemas.shieldinformationbarriers.ShieldInformationBarriers; +import com.box.sdkgen.schemas.termsofservice.TermsOfService; +import com.box.sdkgen.schemas.termsofservices.TermsOfServices; +import java.io.InputStream; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public class CommonsManager { + + public static BoxCCGAuth getCcgAuth() { + CCGConfig ccgConfig = + new CCGConfig.Builder(getEnvVar("CLIENT_ID"), getEnvVar("CLIENT_SECRET")) + .enterpriseId(getEnvVar("ENTERPRISE_ID")) + .build(); + BoxCCGAuth auth = new BoxCCGAuth(ccgConfig); + return auth; + } + + public static BoxJWTAuth getJwtAuth() { + JWTConfig jwtConfig = + JWTConfig.fromConfigJsonString(decodeBase64(getEnvVar("JWT_CONFIG_BASE_64"))); + BoxJWTAuth auth = new BoxJWTAuth(jwtConfig); + return auth; + } + + public static BoxClient getDefaultClientWithUserSubject(String userId) { + if (isBrowser()) { + BoxCCGAuth ccgAuth = getCcgAuth(); + BoxCCGAuth ccgAuthUser = ccgAuth.withUserSubject(userId); + return new BoxClient(ccgAuthUser); + } + BoxJWTAuth auth = getJwtAuth(); + BoxJWTAuth authUser = auth.withUserSubject(userId); + return new BoxClient(authUser); + } + + public static BoxClient getDefaultClient() { + BoxClient client = new BoxClient((isBrowser() ? getCcgAuth() : getJwtAuth())); + return client; + } + + public static FolderFull createNewFolder() { + BoxClient client = getDefaultClient(); + String newFolderName = getUuid(); + return client + .getFolders() + .createFolder( + new CreateFolderRequestBody( + newFolderName, new CreateFolderRequestBodyParentField("0"))); + } + + public static FileFull uploadNewFile() { + BoxClient client = getDefaultClient(); + String newFileName = String.join("", getUuid(), ".pdf"); + InputStream fileContentStream = generateByteStream(1024 * 1024); + Files uploadedFiles = + client + .getUploads() + .uploadFile( + new UploadFileRequestBody( + new UploadFileRequestBodyAttributesField( + newFileName, new UploadFileRequestBodyAttributesParentField("0")), + fileContentStream)); + return uploadedFiles.getEntries().get(0); + } + + public static TermsOfService getOrCreateTermsOfServices() { + BoxClient client = getDefaultClient(); + TermsOfServices tos = client.getTermsOfServices().getTermsOfService(); + int numberOfTos = tos.getEntries().size(); + if (numberOfTos >= 1) { + TermsOfService firstTos = tos.getEntries().get(0); + if (convertToString(firstTos.getTosType()).equals("managed")) { + return firstTos; + } + } + if (numberOfTos >= 2) { + TermsOfService secondTos = tos.getEntries().get(1); + if (convertToString(secondTos.getTosType()).equals("managed")) { + return secondTos; + } + } + return client + .getTermsOfServices() + .createTermsOfService( + new CreateTermsOfServiceRequestBody.Builder( + CreateTermsOfServiceRequestBodyStatusField.DISABLED, "Test TOS") + .tosType(CreateTermsOfServiceRequestBodyTosTypeField.MANAGED) + .build()); + } + + public static ClassificationTemplateFieldsOptionsField getOrCreateClassification( + ClassificationTemplate classificationTemplate) { + BoxClient client = getDefaultClient(); + List classifications = + classificationTemplate.getFields().get(0).getOptions(); + int currentNumberOfClassifications = classifications.size(); + if (currentNumberOfClassifications == 0) { + ClassificationTemplate classificationTemplateWithNewClassification = + client + .getClassifications() + .addClassification( + Arrays.asList( + new AddClassificationRequestBody( + new AddClassificationRequestBodyDataField.Builder(getUuid()) + .staticConfig( + new AddClassificationRequestBodyDataStaticConfigField.Builder() + .classification( + new AddClassificationRequestBodyDataStaticConfigClassificationField + .Builder() + .classificationDefinition("Some description") + .colorId(3L) + .build()) + .build()) + .build()))); + return classificationTemplateWithNewClassification.getFields().get(0).getOptions().get(0); + } + return classifications.get(0); + } + + public static ClassificationTemplate getOrCreateClassificationTemplate() { + BoxClient client = getDefaultClient(); + try { + return client.getClassifications().getClassificationTemplate(); + } catch (Exception exception) { + return client + .getClassifications() + .createClassificationTemplate( + new CreateClassificationTemplateRequestBody( + Arrays.asList( + new CreateClassificationTemplateRequestBodyFieldsField( + Collections.emptyList())))); + } + } + + public static ShieldInformationBarrier getOrCreateShieldInformationBarrier( + BoxClient client, String enterpriseId) { + ShieldInformationBarriers barriers = + client.getShieldInformationBarriers().getShieldInformationBarriers(); + int numberOfBarriers = barriers.getEntries().size(); + if (numberOfBarriers == 0) { + return client + .getShieldInformationBarriers() + .createShieldInformationBarrier( + new CreateShieldInformationBarrierRequestBody( + new EnterpriseBase.Builder().id(enterpriseId).build())); + } + return barriers.getEntries().get(numberOfBarriers - 1); + } +} diff --git a/src/intTest/java/com/box/sdkgen/devicepinners/DevicePinnersITest.java b/src/intTest/java/com/box/sdkgen/devicepinners/DevicePinnersITest.java new file mode 100644 index 000000000..56af05e61 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/devicepinners/DevicePinnersITest.java @@ -0,0 +1,40 @@ +package com.box.sdkgen.devicepinners; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.internal.utils.UtilsManager.getEnvVar; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.devicepinners.GetEnterpriseDevicePinnersQueryParams; +import com.box.sdkgen.managers.devicepinners.GetEnterpriseDevicePinnersQueryParamsDirectionField; +import com.box.sdkgen.schemas.devicepinners.DevicePinners; +import org.junit.jupiter.api.Test; + +public class DevicePinnersITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testDevicePinners() { + String enterpriseId = getEnvVar("ENTERPRISE_ID"); + DevicePinners devicePinners = + client.getDevicePinners().getEnterpriseDevicePinners(enterpriseId); + assert devicePinners.getEntries().size() >= 0; + DevicePinners devicePinnersInDescDirection = + client + .getDevicePinners() + .getEnterpriseDevicePinners( + enterpriseId, + new GetEnterpriseDevicePinnersQueryParams.Builder() + .direction(GetEnterpriseDevicePinnersQueryParamsDirectionField.DESC) + .build()); + assert devicePinnersInDescDirection.getEntries().size() >= 0; + String devicePinnerId = "123456"; + assertThrows( + RuntimeException.class, + () -> client.getDevicePinners().getDevicePinnerById(devicePinnerId)); + assertThrows( + RuntimeException.class, + () -> client.getDevicePinners().deleteDevicePinnerById(devicePinnerId)); + } +} diff --git a/src/intTest/java/com/box/sdkgen/docgen/DocgenITest.java b/src/intTest/java/com/box/sdkgen/docgen/DocgenITest.java new file mode 100644 index 000000000..264b139c1 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/docgen/DocgenITest.java @@ -0,0 +1,106 @@ +package com.box.sdkgen.docgen; + +import static com.box.sdkgen.commons.CommonsManager.createNewFolder; +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.commons.CommonsManager.uploadNewFile; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.entryOf; +import static com.box.sdkgen.internal.utils.UtilsManager.mapOf; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.docgen.GetDocgenJobsV2025R0QueryParams; +import com.box.sdkgen.schemas.filefull.FileFull; +import com.box.sdkgen.schemas.folderfull.FolderFull; +import com.box.sdkgen.schemas.v2025r0.docgenbatchbasev2025r0.DocGenBatchBaseV2025R0; +import com.box.sdkgen.schemas.v2025r0.docgenbatchcreaterequestv2025r0.DocGenBatchCreateRequestV2025R0; +import com.box.sdkgen.schemas.v2025r0.docgenbatchcreaterequestv2025r0.DocGenBatchCreateRequestV2025R0DestinationFolderField; +import com.box.sdkgen.schemas.v2025r0.docgendocumentgenerationdatav2025r0.DocGenDocumentGenerationDataV2025R0; +import com.box.sdkgen.schemas.v2025r0.docgenjobfullv2025r0.DocGenJobFullV2025R0; +import com.box.sdkgen.schemas.v2025r0.docgenjobsfullv2025r0.DocGenJobsFullV2025R0; +import com.box.sdkgen.schemas.v2025r0.docgenjobsv2025r0.DocGenJobsV2025R0; +import com.box.sdkgen.schemas.v2025r0.docgenjobv2025r0.DocGenJobV2025R0; +import com.box.sdkgen.schemas.v2025r0.docgentemplatebasev2025r0.DocGenTemplateBaseV2025R0; +import com.box.sdkgen.schemas.v2025r0.docgentemplatecreaterequestv2025r0.DocGenTemplateCreateRequestV2025R0; +import com.box.sdkgen.schemas.v2025r0.filereferencev2025r0.FileReferenceV2025R0; +import java.util.Arrays; +import org.junit.jupiter.api.Test; + +public class DocgenITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testDocgenBatchAndJobs() { + FileFull uploadedFile = uploadNewFile(); + FolderFull folder = createNewFolder(); + DocGenTemplateBaseV2025R0 createdDocgenTemplate = + client + .getDocgenTemplate() + .createDocgenTemplateV2025R0( + new DocGenTemplateCreateRequestV2025R0( + new FileReferenceV2025R0(uploadedFile.getId()))); + DocGenBatchBaseV2025R0 docgenBatch = + client + .getDocgen() + .createDocgenBatchV2025R0( + new DocGenBatchCreateRequestV2025R0( + new FileReferenceV2025R0(uploadedFile.getId()), + "api", + new DocGenBatchCreateRequestV2025R0DestinationFolderField(folder.getId()), + "pdf", + Arrays.asList( + new DocGenDocumentGenerationDataV2025R0( + "test", mapOf(entryOf("abc", "xyz")))))); + assert !(docgenBatch.getId().equals("")); + assert convertToString(docgenBatch.getType()).equals("docgen_batch"); + DocGenJobsV2025R0 docgenBatchJobs = + client.getDocgen().getDocgenBatchJobByIdV2025R0(docgenBatch.getId()); + assert docgenBatchJobs.getEntries().size() >= 1; + assert !(docgenBatchJobs.getEntries().get(0).getId().equals("")); + assert convertToString(docgenBatchJobs.getEntries().get(0).getType()).equals("docgen_job"); + assert docgenBatchJobs.getEntries().get(0).getOutputType().equals("pdf"); + assert !(convertToString(docgenBatchJobs.getEntries().get(0).getStatus()).equals("")); + assert docgenBatchJobs + .getEntries() + .get(0) + .getTemplateFile() + .getId() + .equals(uploadedFile.getId()); + assert docgenBatchJobs.getEntries().get(0).getBatch().getId().equals(docgenBatch.getId()); + DocGenJobsFullV2025R0 docgenJobs = + client + .getDocgen() + .getDocgenJobsV2025R0( + new GetDocgenJobsV2025R0QueryParams.Builder().limit(10000L).build()); + assert docgenJobs.getEntries().size() >= 1; + assert !(docgenJobs.getEntries().get(0).getBatch().getId().equals("")); + assert !(docgenJobs.getEntries().get(0).getCreatedBy().getId().equals("")); + assert !(docgenJobs.getEntries().get(0).getEnterprise().getId().equals("")); + assert !(docgenJobs.getEntries().get(0).getId().equals("")); + assert !(docgenJobs.getEntries().get(0).getOutputType().equals("")); + assert !(docgenJobs.getEntries().get(0).getSource().equals("")); + assert !(convertToString(docgenJobs.getEntries().get(0).getStatus()).equals("")); + assert convertToString(docgenJobs.getEntries().get(0).getTemplateFile().getType()) + .equals("file"); + assert !(docgenJobs.getEntries().get(0).getTemplateFile().getId().equals("")); + assert convertToString(docgenJobs.getEntries().get(0).getTemplateFileVersion().getType()) + .equals("file_version"); + assert !(docgenJobs.getEntries().get(0).getTemplateFileVersion().getId().equals("")); + assert convertToString(docgenJobs.getEntries().get(0).getType()).equals("docgen_job"); + int indexOfItem = docgenJobs.getEntries().size() - 1; + DocGenJobFullV2025R0 docgenJobItemFromList = docgenJobs.getEntries().get(indexOfItem); + DocGenJobV2025R0 docgenJob = + client.getDocgen().getDocgenJobByIdV2025R0(docgenJobItemFromList.getId()); + assert !(docgenJob.getBatch().getId().equals("")); + assert !(docgenJob.getId().equals("")); + assert !(docgenJob.getOutputType().equals("")); + assert !(convertToString(docgenJob.getStatus()).equals("")); + assert convertToString(docgenJob.getTemplateFile().getType()).equals("file"); + assert !(docgenJob.getTemplateFile().getId().equals("")); + assert convertToString(docgenJob.getTemplateFileVersion().getType()).equals("file_version"); + assert !(docgenJob.getTemplateFileVersion().getId().equals("")); + assert convertToString(docgenJob.getType()).equals("docgen_job"); + client.getFolders().deleteFolderById(folder.getId()); + client.getFiles().deleteFileById(uploadedFile.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/docgentemplate/DocgenTemplateITest.java b/src/intTest/java/com/box/sdkgen/docgentemplate/DocgenTemplateITest.java new file mode 100644 index 000000000..9863f54c5 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/docgentemplate/DocgenTemplateITest.java @@ -0,0 +1,50 @@ +package com.box.sdkgen.docgentemplate; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.commons.CommonsManager.uploadNewFile; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.schemas.filefull.FileFull; +import com.box.sdkgen.schemas.v2025r0.docgenjobsv2025r0.DocGenJobsV2025R0; +import com.box.sdkgen.schemas.v2025r0.docgentagsv2025r0.DocGenTagsV2025R0; +import com.box.sdkgen.schemas.v2025r0.docgentemplatebasev2025r0.DocGenTemplateBaseV2025R0; +import com.box.sdkgen.schemas.v2025r0.docgentemplatecreaterequestv2025r0.DocGenTemplateCreateRequestV2025R0; +import com.box.sdkgen.schemas.v2025r0.docgentemplatesv2025r0.DocGenTemplatesV2025R0; +import com.box.sdkgen.schemas.v2025r0.docgentemplatev2025r0.DocGenTemplateV2025R0; +import com.box.sdkgen.schemas.v2025r0.filereferencev2025r0.FileReferenceV2025R0; +import org.junit.jupiter.api.Test; + +public class DocgenTemplateITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testDocgenTemplateCrud() { + FileFull file = uploadNewFile(); + DocGenTemplateBaseV2025R0 createdDocgenTemplate = + client + .getDocgenTemplate() + .createDocgenTemplateV2025R0( + new DocGenTemplateCreateRequestV2025R0(new FileReferenceV2025R0(file.getId()))); + DocGenTemplatesV2025R0 docgenTemplates = client.getDocgenTemplate().getDocgenTemplatesV2025R0(); + assert docgenTemplates.getEntries().size() > 0; + DocGenTemplateV2025R0 fetchedDocgenTemplate = + client + .getDocgenTemplate() + .getDocgenTemplateByIdV2025R0(createdDocgenTemplate.getFile().getId()); + assert fetchedDocgenTemplate.getFile().getId().equals(createdDocgenTemplate.getFile().getId()); + DocGenTagsV2025R0 docgenTemplateTags = + client + .getDocgenTemplate() + .getDocgenTemplateTagsV2025R0(fetchedDocgenTemplate.getFile().getId()); + DocGenJobsV2025R0 docgenTemplateJobs = + client + .getDocgenTemplate() + .getDocgenTemplateJobByIdV2025R0(fetchedDocgenTemplate.getFile().getId()); + assert docgenTemplateJobs.getEntries().size() == 0; + client + .getDocgenTemplate() + .deleteDocgenTemplateByIdV2025R0(createdDocgenTemplate.getFile().getId()); + client.getFiles().deleteFileById(file.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/downloads/DownloadsITest.java b/src/intTest/java/com/box/sdkgen/downloads/DownloadsITest.java new file mode 100644 index 000000000..6cf58861a --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/downloads/DownloadsITest.java @@ -0,0 +1,77 @@ +package com.box.sdkgen.downloads; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.commons.CommonsManager.uploadNewFile; +import static com.box.sdkgen.internal.utils.UtilsManager.bufferEquals; +import static com.box.sdkgen.internal.utils.UtilsManager.closeFileOutputStream; +import static com.box.sdkgen.internal.utils.UtilsManager.generateByteBuffer; +import static com.box.sdkgen.internal.utils.UtilsManager.generateByteStreamFromBuffer; +import static com.box.sdkgen.internal.utils.UtilsManager.getFileOutputStream; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; +import static com.box.sdkgen.internal.utils.UtilsManager.readBufferFromFile; +import static com.box.sdkgen.internal.utils.UtilsManager.readByteStream; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.uploads.UploadFileRequestBody; +import com.box.sdkgen.managers.uploads.UploadFileRequestBodyAttributesField; +import com.box.sdkgen.managers.uploads.UploadFileRequestBodyAttributesParentField; +import com.box.sdkgen.schemas.filefull.FileFull; +import com.box.sdkgen.schemas.files.Files; +import java.io.InputStream; +import java.io.OutputStream; +import org.junit.jupiter.api.Test; + +public class DownloadsITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testDownloadFile() { + String newFileName = getUuid(); + byte[] fileBuffer = generateByteBuffer(1024 * 1024); + InputStream fileContentStream = generateByteStreamFromBuffer(fileBuffer); + Files uploadedFiles = + client + .getUploads() + .uploadFile( + new UploadFileRequestBody( + new UploadFileRequestBodyAttributesField( + newFileName, new UploadFileRequestBodyAttributesParentField("0")), + fileContentStream)); + FileFull uploadedFile = uploadedFiles.getEntries().get(0); + InputStream downloadedFileContent = client.getDownloads().downloadFile(uploadedFile.getId()); + assert bufferEquals(readByteStream(downloadedFileContent), fileBuffer); + client.getFiles().deleteFileById(uploadedFile.getId()); + } + + @Test + public void testGetDownloadUrl() { + FileFull uploadedFile = uploadNewFile(); + String downloadUrl = client.getDownloads().getDownloadFileUrl(uploadedFile.getId()); + assert !(downloadUrl == null); + assert downloadUrl.contains("https://"); + client.getFiles().deleteFileById(uploadedFile.getId()); + } + + @Test + public void testDownloadFileToOutputStream() { + String newFileName = getUuid(); + byte[] fileBuffer = generateByteBuffer(1024 * 1024); + InputStream fileContentStream = generateByteStreamFromBuffer(fileBuffer); + Files uploadedFiles = + client + .getUploads() + .uploadFile( + new UploadFileRequestBody( + new UploadFileRequestBodyAttributesField( + newFileName, new UploadFileRequestBodyAttributesParentField("0")), + fileContentStream)); + FileFull uploadedFile = uploadedFiles.getEntries().get(0); + OutputStream fileOutputStream = getFileOutputStream(newFileName); + client.getDownloads().downloadFileToOutputStream(uploadedFile.getId(), fileOutputStream); + closeFileOutputStream(fileOutputStream); + byte[] downloadedFileContent = readBufferFromFile(newFileName); + assert bufferEquals(downloadedFileContent, fileBuffer); + client.getFiles().deleteFileById(uploadedFile.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/emailaliases/EmailAliasesITest.java b/src/intTest/java/com/box/sdkgen/emailaliases/EmailAliasesITest.java new file mode 100644 index 000000000..c537c9a50 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/emailaliases/EmailAliasesITest.java @@ -0,0 +1,42 @@ +package com.box.sdkgen.emailaliases; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.emailaliases.CreateUserEmailAliasRequestBody; +import com.box.sdkgen.managers.users.CreateUserRequestBody; +import com.box.sdkgen.schemas.emailalias.EmailAlias; +import com.box.sdkgen.schemas.emailaliases.EmailAliases; +import com.box.sdkgen.schemas.userfull.UserFull; +import org.junit.jupiter.api.Test; + +public class EmailAliasesITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testEmailAliases() { + String newUserName = getUuid(); + String newUserLogin = String.join("", getUuid(), "@boxdemo.com"); + UserFull newUser = + client + .getUsers() + .createUser(new CreateUserRequestBody.Builder(newUserName).login(newUserLogin).build()); + EmailAliases aliases = client.getEmailAliases().getUserEmailAliases(newUser.getId()); + assert aliases.getTotalCount() == 0; + String newAliasEmail = String.join("", newUser.getId(), "@boxdemo.com"); + EmailAlias newAlias = + client + .getEmailAliases() + .createUserEmailAlias( + newUser.getId(), new CreateUserEmailAliasRequestBody(newAliasEmail)); + EmailAliases updatedAliases = client.getEmailAliases().getUserEmailAliases(newUser.getId()); + assert updatedAliases.getTotalCount() == 1; + assert updatedAliases.getEntries().get(0).getEmail().equals(newAliasEmail); + client.getEmailAliases().deleteUserEmailAliasById(newUser.getId(), newAlias.getId()); + EmailAliases finalAliases = client.getEmailAliases().getUserEmailAliases(newUser.getId()); + assert finalAliases.getTotalCount() == 0; + client.getUsers().deleteUserById(newUser.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/events/EventsITest.java b/src/intTest/java/com/box/sdkgen/events/EventsITest.java new file mode 100644 index 000000000..f647163b7 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/events/EventsITest.java @@ -0,0 +1,119 @@ +package com.box.sdkgen.events; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.epochSecondsToDateTime; +import static com.box.sdkgen.internal.utils.UtilsManager.getEpochTimeInSeconds; + +import com.box.sdkgen.box.eventstream.EventStream; +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.events.GetEventsQueryParams; +import com.box.sdkgen.managers.events.GetEventsQueryParamsEventTypeField; +import com.box.sdkgen.managers.events.GetEventsQueryParamsStreamTypeField; +import com.box.sdkgen.schemas.event.Event; +import com.box.sdkgen.schemas.events.Events; +import com.box.sdkgen.schemas.eventsource.EventSource; +import com.box.sdkgen.schemas.realtimeserver.RealtimeServer; +import com.box.sdkgen.schemas.realtimeservers.RealtimeServers; +import com.box.sdkgen.schemas.user.User; +import java.time.OffsetDateTime; +import java.util.Arrays; +import org.junit.jupiter.api.Test; + +public class EventsITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testEvents() { + Events events = client.getEvents().getEvents(); + assert events.getEntries().size() > 0; + Event firstEvent = events.getEntries().get(0); + assert convertToString(firstEvent.getCreatedBy().getType()).equals("user"); + assert !(convertToString(firstEvent.getEventType()).equals("")); + } + + @Test + public void testEventUpload() { + Events events = + client + .getEvents() + .getEvents( + new GetEventsQueryParams.Builder() + .streamType(GetEventsQueryParamsStreamTypeField.ADMIN_LOGS) + .eventType(Arrays.asList(GetEventsQueryParamsEventTypeField.UPLOAD)) + .build()); + assert events.getEntries().size() > 0; + Event firstEvent = events.getEntries().get(0); + assert convertToString(firstEvent.getEventType()).equals("UPLOAD"); + EventSource source = firstEvent.getSource().getEventSource(); + assert convertToString(source.getItemType()).equals("file") + || convertToString(source.getItemType()).equals("folder"); + assert !(source.getItemId().equals("")); + assert !(source.getItemName().equals("")); + } + + @Test + public void testEventDeleteUser() { + Events events = + client + .getEvents() + .getEvents( + new GetEventsQueryParams.Builder() + .streamType(GetEventsQueryParamsStreamTypeField.ADMIN_LOGS) + .eventType(Arrays.asList(GetEventsQueryParamsEventTypeField.DELETE_USER)) + .build()); + assert events.getEntries().size() > 0; + Event firstEvent = events.getEntries().get(0); + assert convertToString(firstEvent.getEventType()).equals("DELETE_USER"); + User source = firstEvent.getSource().getUser(); + assert convertToString(source.getType()).equals("user"); + assert !(source.getId().equals("")); + } + + @Test + public void testEventSourceFileOrFolder() { + Events events = + client + .getEvents() + .getEvents( + new GetEventsQueryParams.Builder() + .streamType(GetEventsQueryParamsStreamTypeField.CHANGES) + .build()); + assert events.getEntries().size() > 0; + } + + @Test + public void testGetEventsWithLongPolling() { + RealtimeServers servers = client.getEvents().getEventsWithLongPolling(); + assert servers.getEntries().size() > 0; + RealtimeServer server = servers.getEntries().get(0); + assert convertToString(server.getType()).equals("realtime_server"); + assert !(server.getUrl().equals("")); + } + + @Test + public void testGetEventsWithDateFilters() { + long currentEpochTimeInSeconds = getEpochTimeInSeconds(); + long epochTimeInSecondsAWeekAgo = currentEpochTimeInSeconds - 7 * 24 * 60 * 60; + OffsetDateTime createdAfterDate = epochSecondsToDateTime(epochTimeInSecondsAWeekAgo); + OffsetDateTime createdBeforeDate = epochSecondsToDateTime(currentEpochTimeInSeconds); + Events servers = + client + .getEvents() + .getEvents( + new GetEventsQueryParams.Builder() + .streamType(GetEventsQueryParamsStreamTypeField.ADMIN_LOGS) + .limit(1L) + .createdAfter(createdAfterDate) + .createdBefore(createdBeforeDate) + .build()); + assert servers.getEntries().size() == 1; + } + + @Test + public void testGetEventStream() { + EventStream eventStream = client.getEvents().getEventStream(); + assert !(eventStream == null); + } +} diff --git a/src/intTest/java/com/box/sdkgen/externalusers/ExternalUsersITest.java b/src/intTest/java/com/box/sdkgen/externalusers/ExternalUsersITest.java new file mode 100644 index 000000000..be5260daa --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/externalusers/ExternalUsersITest.java @@ -0,0 +1,53 @@ +package com.box.sdkgen.externalusers; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClientWithUserSubject; +import static com.box.sdkgen.commons.CommonsManager.uploadNewFile; +import static com.box.sdkgen.internal.utils.UtilsManager.getEnvVar; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.usercollaborations.CreateCollaborationRequestBody; +import com.box.sdkgen.managers.usercollaborations.CreateCollaborationRequestBodyAccessibleByField; +import com.box.sdkgen.managers.usercollaborations.CreateCollaborationRequestBodyAccessibleByTypeField; +import com.box.sdkgen.managers.usercollaborations.CreateCollaborationRequestBodyItemField; +import com.box.sdkgen.managers.usercollaborations.CreateCollaborationRequestBodyItemTypeField; +import com.box.sdkgen.managers.usercollaborations.CreateCollaborationRequestBodyRoleField; +import com.box.sdkgen.schemas.collaboration.Collaboration; +import com.box.sdkgen.schemas.filefull.FileFull; +import com.box.sdkgen.schemas.v2025r0.externaluserssubmitdeletejobrequestv2025r0.ExternalUsersSubmitDeleteJobRequestV2025R0; +import com.box.sdkgen.schemas.v2025r0.externaluserssubmitdeletejobresponsev2025r0.ExternalUsersSubmitDeleteJobResponseV2025R0; +import com.box.sdkgen.schemas.v2025r0.userreferencev2025r0.UserReferenceV2025R0; +import java.util.Arrays; +import org.junit.jupiter.api.Test; + +public class ExternalUsersITest { + + private static final BoxClient client = getDefaultClientWithUserSubject(getEnvVar("USER_ID")); + + @Test + public void testSubmitJobToDeleteExternalUsers() { + FileFull file = uploadNewFile(); + Collaboration fileCollaboration = + client + .getUserCollaborations() + .createCollaboration( + new CreateCollaborationRequestBody( + new CreateCollaborationRequestBodyItemField.Builder() + .type(CreateCollaborationRequestBodyItemTypeField.FILE) + .id(file.getId()) + .build(), + new CreateCollaborationRequestBodyAccessibleByField.Builder( + CreateCollaborationRequestBodyAccessibleByTypeField.USER) + .id(getEnvVar("BOX_EXTERNAL_USER_ID")) + .build(), + CreateCollaborationRequestBodyRoleField.EDITOR)); + ExternalUsersSubmitDeleteJobResponseV2025R0 externalUsersJobDeleteResponse = + client + .getExternalUsers() + .submitJobToDeleteExternalUsersV2025R0( + new ExternalUsersSubmitDeleteJobRequestV2025R0( + Arrays.asList(new UserReferenceV2025R0(getEnvVar("BOX_EXTERNAL_USER_ID"))))); + assert externalUsersJobDeleteResponse.getEntries().size() == 1; + assert externalUsersJobDeleteResponse.getEntries().get(0).getStatus() == 202; + client.getFiles().deleteFileById(file.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/fileclassifications/FileClassificationsITest.java b/src/intTest/java/com/box/sdkgen/fileclassifications/FileClassificationsITest.java new file mode 100644 index 000000000..23b34cd4e --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/fileclassifications/FileClassificationsITest.java @@ -0,0 +1,98 @@ +package com.box.sdkgen.fileclassifications; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.commons.CommonsManager.getOrCreateClassification; +import static com.box.sdkgen.commons.CommonsManager.getOrCreateClassificationTemplate; +import static com.box.sdkgen.commons.CommonsManager.uploadNewFile; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.classifications.AddClassificationRequestBody; +import com.box.sdkgen.managers.classifications.AddClassificationRequestBodyDataField; +import com.box.sdkgen.managers.classifications.AddClassificationRequestBodyDataStaticConfigClassificationField; +import com.box.sdkgen.managers.classifications.AddClassificationRequestBodyDataStaticConfigField; +import com.box.sdkgen.managers.fileclassifications.AddClassificationToFileRequestBody; +import com.box.sdkgen.managers.fileclassifications.UpdateClassificationOnFileRequestBody; +import com.box.sdkgen.schemas.classification.Classification; +import com.box.sdkgen.schemas.classificationtemplate.ClassificationTemplate; +import com.box.sdkgen.schemas.classificationtemplate.ClassificationTemplateFieldsOptionsField; +import com.box.sdkgen.schemas.filefull.FileFull; +import java.util.Arrays; +import java.util.List; +import org.junit.jupiter.api.Test; + +public class FileClassificationsITest { + + private static final BoxClient client = getDefaultClient(); + + public static ClassificationTemplateFieldsOptionsField getOrCreateSecondClassification( + ClassificationTemplate classificationTemplate) { + List classifications = + classificationTemplate.getFields().get(0).getOptions(); + int currentNumberOfClassifications = classifications.size(); + if (currentNumberOfClassifications == 1) { + ClassificationTemplate classificationTemplateWithNewClassification = + client + .getClassifications() + .addClassification( + Arrays.asList( + new AddClassificationRequestBody( + new AddClassificationRequestBodyDataField.Builder(getUuid()) + .staticConfig( + new AddClassificationRequestBodyDataStaticConfigField.Builder() + .classification( + new AddClassificationRequestBodyDataStaticConfigClassificationField + .Builder() + .classificationDefinition("Other description") + .colorId(4L) + .build()) + .build()) + .build()))); + return classificationTemplateWithNewClassification.getFields().get(0).getOptions().get(1); + } + return classifications.get(1); + } + + @Test + public void testFileClassifications() { + ClassificationTemplate classificationTemplate = getOrCreateClassificationTemplate(); + ClassificationTemplateFieldsOptionsField classification = + getOrCreateClassification(classificationTemplate); + FileFull file = uploadNewFile(); + assertThrows( + RuntimeException.class, + () -> client.getFileClassifications().getClassificationOnFile(file.getId())); + Classification createdFileClassification = + client + .getFileClassifications() + .addClassificationToFile( + file.getId(), + new AddClassificationToFileRequestBody.Builder() + .boxSecurityClassificationKey(classification.getKey()) + .build()); + assert createdFileClassification + .getBoxSecurityClassificationKey() + .equals(classification.getKey()); + Classification fileClassification = + client.getFileClassifications().getClassificationOnFile(file.getId()); + assert fileClassification.getBoxSecurityClassificationKey().equals(classification.getKey()); + ClassificationTemplateFieldsOptionsField secondClassification = + getOrCreateSecondClassification(classificationTemplate); + Classification updatedFileClassification = + client + .getFileClassifications() + .updateClassificationOnFile( + file.getId(), + Arrays.asList( + new UpdateClassificationOnFileRequestBody(secondClassification.getKey()))); + assert updatedFileClassification + .getBoxSecurityClassificationKey() + .equals(secondClassification.getKey()); + client.getFileClassifications().deleteClassificationFromFile(file.getId()); + assertThrows( + RuntimeException.class, + () -> client.getFileClassifications().getClassificationOnFile(file.getId())); + client.getFiles().deleteFileById(file.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/filemetadata/FileMetadataITest.java b/src/intTest/java/com/box/sdkgen/filemetadata/FileMetadataITest.java new file mode 100644 index 000000000..d2104d3a8 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/filemetadata/FileMetadataITest.java @@ -0,0 +1,266 @@ +package com.box.sdkgen.filemetadata; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.commons.CommonsManager.uploadNewFile; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.entryOf; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; +import static com.box.sdkgen.internal.utils.UtilsManager.mapOf; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.filemetadata.CreateFileMetadataByIdScope; +import com.box.sdkgen.managers.filemetadata.DeleteFileMetadataByIdScope; +import com.box.sdkgen.managers.filemetadata.GetFileMetadataByIdScope; +import com.box.sdkgen.managers.filemetadata.UpdateFileMetadataByIdRequestBody; +import com.box.sdkgen.managers.filemetadata.UpdateFileMetadataByIdRequestBodyOpField; +import com.box.sdkgen.managers.filemetadata.UpdateFileMetadataByIdScope; +import com.box.sdkgen.managers.metadatatemplates.CreateMetadataTemplateRequestBody; +import com.box.sdkgen.managers.metadatatemplates.CreateMetadataTemplateRequestBodyFieldsField; +import com.box.sdkgen.managers.metadatatemplates.CreateMetadataTemplateRequestBodyFieldsOptionsField; +import com.box.sdkgen.managers.metadatatemplates.CreateMetadataTemplateRequestBodyFieldsTypeField; +import com.box.sdkgen.managers.metadatatemplates.DeleteMetadataTemplateScope; +import com.box.sdkgen.schemas.filefull.FileFull; +import com.box.sdkgen.schemas.metadatafull.MetadataFull; +import com.box.sdkgen.schemas.metadatas.Metadatas; +import com.box.sdkgen.schemas.metadatatemplate.MetadataTemplate; +import java.util.Arrays; +import org.junit.jupiter.api.Test; + +public class FileMetadataITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testUpdatingFileMetadata() { + FileFull file = uploadNewFile(); + String templateKey = String.join("", "key", getUuid()); + MetadataTemplate template = + client + .getMetadataTemplates() + .createMetadataTemplate( + new CreateMetadataTemplateRequestBody.Builder("enterprise", templateKey) + .templateKey(templateKey) + .fields( + Arrays.asList( + new CreateMetadataTemplateRequestBodyFieldsField( + CreateMetadataTemplateRequestBodyFieldsTypeField.STRING, + "name", + "name"), + new CreateMetadataTemplateRequestBodyFieldsField( + CreateMetadataTemplateRequestBodyFieldsTypeField.FLOAT, + "age", + "age"), + new CreateMetadataTemplateRequestBodyFieldsField( + CreateMetadataTemplateRequestBodyFieldsTypeField.DATE, + "birthDate", + "birthDate"), + new CreateMetadataTemplateRequestBodyFieldsField.Builder( + CreateMetadataTemplateRequestBodyFieldsTypeField.ENUM, + "countryCode", + "countryCode") + .options( + Arrays.asList( + new CreateMetadataTemplateRequestBodyFieldsOptionsField( + "US"), + new CreateMetadataTemplateRequestBodyFieldsOptionsField( + "CA"))) + .build(), + new CreateMetadataTemplateRequestBodyFieldsField.Builder( + CreateMetadataTemplateRequestBodyFieldsTypeField.MULTISELECT, + "sports", + "sports") + .options( + Arrays.asList( + new CreateMetadataTemplateRequestBodyFieldsOptionsField( + "basketball"), + new CreateMetadataTemplateRequestBodyFieldsOptionsField( + "football"), + new CreateMetadataTemplateRequestBodyFieldsOptionsField( + "tennis"))) + .build())) + .build()); + MetadataFull createdMetadata = + client + .getFileMetadata() + .createFileMetadataById( + file.getId(), + CreateFileMetadataByIdScope.ENTERPRISE, + templateKey, + mapOf( + entryOf("name", "John"), + entryOf("age", 23), + entryOf("birthDate", "2001-01-03T02:20:50.520Z"), + entryOf("countryCode", "US"), + entryOf("sports", Arrays.asList("basketball", "tennis")))); + MetadataFull updatedMetadata = + client + .getFileMetadata() + .updateFileMetadataById( + file.getId(), + UpdateFileMetadataByIdScope.ENTERPRISE, + templateKey, + Arrays.asList( + new UpdateFileMetadataByIdRequestBody.Builder() + .op(UpdateFileMetadataByIdRequestBodyOpField.REPLACE) + .path("/name") + .value("Jack") + .build(), + new UpdateFileMetadataByIdRequestBody.Builder() + .op(UpdateFileMetadataByIdRequestBodyOpField.REPLACE) + .path("/age") + .value(24L) + .build(), + new UpdateFileMetadataByIdRequestBody.Builder() + .op(UpdateFileMetadataByIdRequestBodyOpField.REPLACE) + .path("/birthDate") + .value("2000-01-03T02:20:50.520Z") + .build(), + new UpdateFileMetadataByIdRequestBody.Builder() + .op(UpdateFileMetadataByIdRequestBodyOpField.REPLACE) + .path("/countryCode") + .value("CA") + .build(), + new UpdateFileMetadataByIdRequestBody.Builder() + .op(UpdateFileMetadataByIdRequestBodyOpField.REPLACE) + .path("/sports") + .value(Arrays.asList("football")) + .build())); + assert convertToString(updatedMetadata.getTemplate()).equals(templateKey); + assert convertToString(updatedMetadata.getExtraData().get("name")).equals("Jack"); + assert convertToString(updatedMetadata.getExtraData().get("age")).equals("24"); + assert convertToString(updatedMetadata.getExtraData().get("birthDate")) + .equals("2000-01-03T02:20:50.520Z"); + assert convertToString(updatedMetadata.getExtraData().get("countryCode")).equals("CA"); + client + .getFileMetadata() + .deleteFileMetadataById(file.getId(), DeleteFileMetadataByIdScope.ENTERPRISE, templateKey); + client + .getMetadataTemplates() + .deleteMetadataTemplate(DeleteMetadataTemplateScope.ENTERPRISE, templateKey); + client.getFiles().deleteFileById(file.getId()); + } + + @Test + public void testGlobalFileMetadata() { + FileFull file = uploadNewFile(); + Metadatas fileMetadata = client.getFileMetadata().getFileMetadata(file.getId()); + assert fileMetadata.getEntries().size() == 0; + MetadataFull createdMetadata = + client + .getFileMetadata() + .createFileMetadataById( + file.getId(), + CreateFileMetadataByIdScope.GLOBAL, + "properties", + mapOf(entryOf("abc", "xyz"))); + assert convertToString(createdMetadata.getTemplate()).equals("properties"); + assert convertToString(createdMetadata.getScope()).equals("global"); + assert createdMetadata.getVersion() == 0; + MetadataFull receivedMetadata = + client + .getFileMetadata() + .getFileMetadataById(file.getId(), GetFileMetadataByIdScope.GLOBAL, "properties"); + assert convertToString(receivedMetadata.getExtraData().get("abc")).equals("xyz"); + String newValue = "bar"; + client + .getFileMetadata() + .updateFileMetadataById( + file.getId(), + UpdateFileMetadataByIdScope.GLOBAL, + "properties", + Arrays.asList( + new UpdateFileMetadataByIdRequestBody.Builder() + .op(UpdateFileMetadataByIdRequestBodyOpField.REPLACE) + .path("/abc") + .value(newValue) + .build())); + MetadataFull receivedUpdatedMetadata = + client + .getFileMetadata() + .getFileMetadataById(file.getId(), GetFileMetadataByIdScope.GLOBAL, "properties"); + assert convertToString(receivedUpdatedMetadata.getExtraData().get("abc")).equals(newValue); + client + .getFileMetadata() + .deleteFileMetadataById(file.getId(), DeleteFileMetadataByIdScope.GLOBAL, "properties"); + assertThrows( + RuntimeException.class, + () -> + client + .getFileMetadata() + .getFileMetadataById(file.getId(), GetFileMetadataByIdScope.GLOBAL, "properties")); + client.getFiles().deleteFileById(file.getId()); + } + + @Test + public void testEnterpriseFileMetadata() { + FileFull file = uploadNewFile(); + String templateKey = String.join("", "key", getUuid()); + client + .getMetadataTemplates() + .createMetadataTemplate( + new CreateMetadataTemplateRequestBody.Builder("enterprise", templateKey) + .templateKey(templateKey) + .fields( + Arrays.asList( + new CreateMetadataTemplateRequestBodyFieldsField( + CreateMetadataTemplateRequestBodyFieldsTypeField.STRING, + "name", + "name"), + new CreateMetadataTemplateRequestBodyFieldsField( + CreateMetadataTemplateRequestBodyFieldsTypeField.FLOAT, "age", "age"), + new CreateMetadataTemplateRequestBodyFieldsField( + CreateMetadataTemplateRequestBodyFieldsTypeField.DATE, + "birthDate", + "birthDate"), + new CreateMetadataTemplateRequestBodyFieldsField.Builder( + CreateMetadataTemplateRequestBodyFieldsTypeField.ENUM, + "countryCode", + "countryCode") + .options( + Arrays.asList( + new CreateMetadataTemplateRequestBodyFieldsOptionsField("US"), + new CreateMetadataTemplateRequestBodyFieldsOptionsField("CA"))) + .build(), + new CreateMetadataTemplateRequestBodyFieldsField.Builder( + CreateMetadataTemplateRequestBodyFieldsTypeField.MULTISELECT, + "sports", + "sports") + .options( + Arrays.asList( + new CreateMetadataTemplateRequestBodyFieldsOptionsField( + "basketball"), + new CreateMetadataTemplateRequestBodyFieldsOptionsField( + "football"), + new CreateMetadataTemplateRequestBodyFieldsOptionsField( + "tennis"))) + .build())) + .build()); + MetadataFull createdMetadata = + client + .getFileMetadata() + .createFileMetadataById( + file.getId(), + CreateFileMetadataByIdScope.ENTERPRISE, + templateKey, + mapOf( + entryOf("name", "John"), + entryOf("age", 23), + entryOf("birthDate", "2001-01-03T02:20:50.520Z"), + entryOf("countryCode", "US"), + entryOf("sports", Arrays.asList("basketball", "tennis")))); + assert convertToString(createdMetadata.getTemplate()).equals(templateKey); + assert convertToString(createdMetadata.getExtraData().get("name")).equals("John"); + assert convertToString(createdMetadata.getExtraData().get("age")).equals("23"); + assert convertToString(createdMetadata.getExtraData().get("birthDate")) + .equals("2001-01-03T02:20:50.520Z"); + assert convertToString(createdMetadata.getExtraData().get("countryCode")).equals("US"); + client + .getFileMetadata() + .deleteFileMetadataById(file.getId(), DeleteFileMetadataByIdScope.ENTERPRISE, templateKey); + client + .getMetadataTemplates() + .deleteMetadataTemplate(DeleteMetadataTemplateScope.ENTERPRISE, templateKey); + client.getFiles().deleteFileById(file.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/filerequests/FileRequestsITest.java b/src/intTest/java/com/box/sdkgen/filerequests/FileRequestsITest.java new file mode 100644 index 000000000..c481fc95c --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/filerequests/FileRequestsITest.java @@ -0,0 +1,55 @@ +package com.box.sdkgen.filerequests; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClientWithUserSubject; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.getEnvVar; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.schemas.filerequest.FileRequest; +import com.box.sdkgen.schemas.filerequestcopyrequest.FileRequestCopyRequest; +import com.box.sdkgen.schemas.filerequestcopyrequest.FileRequestCopyRequestFolderField; +import com.box.sdkgen.schemas.filerequestcopyrequest.FileRequestCopyRequestFolderTypeField; +import com.box.sdkgen.schemas.filerequestupdaterequest.FileRequestUpdateRequest; +import org.junit.jupiter.api.Test; + +public class FileRequestsITest { + + @Test + public void testGetCopyUpdateDeleteFileRequest() { + String fileRequestId = getEnvVar("BOX_FILE_REQUEST_ID"); + String userId = getEnvVar("USER_ID"); + BoxClient client = getDefaultClientWithUserSubject(userId); + FileRequest fileRequest = client.getFileRequests().getFileRequestById(fileRequestId); + assert fileRequest.getId().equals(fileRequestId); + assert convertToString(fileRequest.getType()).equals("file_request"); + FileRequest copiedFileRequest = + client + .getFileRequests() + .createFileRequestCopy( + fileRequestId, + new FileRequestCopyRequest( + new FileRequestCopyRequestFolderField.Builder(fileRequest.getFolder().getId()) + .type(FileRequestCopyRequestFolderTypeField.FOLDER) + .build())); + assert !(copiedFileRequest.getId().equals(fileRequestId)); + assert copiedFileRequest.getTitle().equals(fileRequest.getTitle()); + assert copiedFileRequest.getDescription().equals(fileRequest.getDescription()); + FileRequest updatedFileRequest = + client + .getFileRequests() + .updateFileRequestById( + copiedFileRequest.getId(), + new FileRequestUpdateRequest.Builder() + .title("updated title") + .description("updated description") + .build()); + assert updatedFileRequest.getId().equals(copiedFileRequest.getId()); + assert updatedFileRequest.getTitle().equals("updated title"); + assert updatedFileRequest.getDescription().equals("updated description"); + client.getFileRequests().deleteFileRequestById(updatedFileRequest.getId()); + assertThrows( + RuntimeException.class, + () -> client.getFileRequests().getFileRequestById(updatedFileRequest.getId())); + } +} diff --git a/src/intTest/java/com/box/sdkgen/files/FilesITest.java b/src/intTest/java/com/box/sdkgen/files/FilesITest.java new file mode 100644 index 000000000..54e7e9bd6 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/files/FilesITest.java @@ -0,0 +1,183 @@ +package com.box.sdkgen.files; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.commons.CommonsManager.uploadNewFile; +import static com.box.sdkgen.internal.utils.UtilsManager.bufferEquals; +import static com.box.sdkgen.internal.utils.UtilsManager.entryOf; +import static com.box.sdkgen.internal.utils.UtilsManager.generateByteBuffer; +import static com.box.sdkgen.internal.utils.UtilsManager.generateByteStream; +import static com.box.sdkgen.internal.utils.UtilsManager.generateByteStreamFromBuffer; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; +import static com.box.sdkgen.internal.utils.UtilsManager.mapOf; +import static com.box.sdkgen.internal.utils.UtilsManager.readByteStream; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.files.CopyFileRequestBody; +import com.box.sdkgen.managers.files.CopyFileRequestBodyParentField; +import com.box.sdkgen.managers.files.GetFileByIdHeaders; +import com.box.sdkgen.managers.files.GetFileByIdQueryParams; +import com.box.sdkgen.managers.files.GetFileThumbnailByIdExtension; +import com.box.sdkgen.managers.files.GetFileThumbnailUrlExtension; +import com.box.sdkgen.managers.files.UpdateFileByIdQueryParams; +import com.box.sdkgen.managers.files.UpdateFileByIdRequestBody; +import com.box.sdkgen.managers.files.UpdateFileByIdRequestBodyLockAccessField; +import com.box.sdkgen.managers.files.UpdateFileByIdRequestBodyLockField; +import com.box.sdkgen.managers.uploads.UploadFileRequestBody; +import com.box.sdkgen.managers.uploads.UploadFileRequestBodyAttributesField; +import com.box.sdkgen.managers.uploads.UploadFileRequestBodyAttributesParentField; +import com.box.sdkgen.schemas.filefull.FileFull; +import com.box.sdkgen.schemas.files.Files; +import com.box.sdkgen.schemas.trashfile.TrashFile; +import java.io.InputStream; +import java.util.Arrays; +import org.junit.jupiter.api.Test; + +public class FilesITest { + + private static final BoxClient client = getDefaultClient(); + + public static FileFull uploadFile(String fileName, InputStream fileStream) { + Files uploadedFiles = + client + .getUploads() + .uploadFile( + new UploadFileRequestBody( + new UploadFileRequestBodyAttributesField( + fileName, new UploadFileRequestBodyAttributesParentField("0")), + fileStream)); + return uploadedFiles.getEntries().get(0); + } + + @Test + public void testGetFileThumbnailUrl() { + String thumbnailFileName = getUuid(); + InputStream thumbnailContentStream = generateByteStream(1024 * 1024); + FileFull thumbnailFile = uploadFile(thumbnailFileName, thumbnailContentStream); + String downloadUrl = + client + .getFiles() + .getFileThumbnailUrl(thumbnailFile.getId(), GetFileThumbnailUrlExtension.PNG); + assert !(downloadUrl == null); + assert downloadUrl.contains("https://"); + client.getFiles().deleteFileById(thumbnailFile.getId()); + } + + @Test + public void testGetFileThumbnail() { + String thumbnailFileName = getUuid(); + byte[] thumbnailBuffer = generateByteBuffer(1024 * 1024); + InputStream thumbnailContentStream = generateByteStreamFromBuffer(thumbnailBuffer); + FileFull thumbnailFile = uploadFile(thumbnailFileName, thumbnailContentStream); + InputStream thumbnail = + client + .getFiles() + .getFileThumbnailById(thumbnailFile.getId(), GetFileThumbnailByIdExtension.PNG); + assert !(bufferEquals(readByteStream(thumbnail), thumbnailBuffer) == true); + client.getFiles().deleteFileById(thumbnailFile.getId()); + } + + @Test + public void testGetFileFullExtraFields() { + String newFileName = getUuid(); + InputStream fileStream = generateByteStream(1024 * 1024); + FileFull uploadedFile = uploadFile(newFileName, fileStream); + FileFull file = + client + .getFiles() + .getFileById( + uploadedFile.getId(), + new GetFileByIdQueryParams.Builder() + .fields(Arrays.asList("is_externally_owned", "has_collaborations")) + .build()); + assert file.getIsExternallyOwned() == false; + assert file.getHasCollaborations() == false; + client.getFiles().deleteFileById(file.getId()); + } + + @Test + public void testCreateGetAndDeleteFile() { + String newFileName = getUuid(); + InputStream updatedContentStream = generateByteStream(1024 * 1024); + FileFull uploadedFile = uploadFile(newFileName, updatedContentStream); + FileFull file = client.getFiles().getFileById(uploadedFile.getId()); + assertThrows( + RuntimeException.class, + () -> + client + .getFiles() + .getFileById( + uploadedFile.getId(), + new GetFileByIdQueryParams.Builder().fields(Arrays.asList("name")).build(), + new GetFileByIdHeaders.Builder() + .extraHeaders(mapOf(entryOf("if-none-match", file.getEtag()))) + .build())); + assert file.getName().equals(newFileName); + client.getFiles().deleteFileById(uploadedFile.getId()); + TrashFile trashedFile = client.getTrashedFiles().getTrashedFileById(uploadedFile.getId()); + assert file.getId().equals(trashedFile.getId()); + } + + @Test + public void testUpdateFile() { + FileFull fileToUpdate = uploadNewFile(); + String updatedName = getUuid(); + FileFull updatedFile = + client + .getFiles() + .updateFileById( + fileToUpdate.getId(), + new UpdateFileByIdRequestBody.Builder() + .name(updatedName) + .description("Updated description") + .build()); + assert updatedFile.getName().equals(updatedName); + assert updatedFile.getDescription().equals("Updated description"); + client.getFiles().deleteFileById(updatedFile.getId()); + } + + @Test + public void testFileLock() { + FileFull file = uploadNewFile(); + FileFull fileWithLock = + client + .getFiles() + .updateFileById( + file.getId(), + new UpdateFileByIdRequestBody.Builder() + .lock( + new UpdateFileByIdRequestBodyLockField.Builder() + .access(UpdateFileByIdRequestBodyLockAccessField.LOCK) + .build()) + .build(), + new UpdateFileByIdQueryParams.Builder().fields(Arrays.asList("lock")).build()); + assert !(fileWithLock.getLock() == null); + FileFull fileWithoutLock = + client + .getFiles() + .updateFileById( + file.getId(), + new UpdateFileByIdRequestBody.Builder().lock(null).build(), + new UpdateFileByIdQueryParams.Builder().fields(Arrays.asList("lock")).build()); + assert fileWithoutLock.getLock() == null; + client.getFiles().deleteFileById(file.getId()); + } + + @Test + public void testCopyFile() { + FileFull fileOrigin = uploadNewFile(); + String copiedFileName = getUuid(); + FileFull copiedFile = + client + .getFiles() + .copyFile( + fileOrigin.getId(), + new CopyFileRequestBody.Builder(new CopyFileRequestBodyParentField("0")) + .name(copiedFileName) + .build()); + assert copiedFile.getParent().getId().equals("0"); + assert copiedFile.getName().equals(copiedFileName); + client.getFiles().deleteFileById(fileOrigin.getId()); + client.getFiles().deleteFileById(copiedFile.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/fileversionlegalholds/FileVersionLegalHoldsITest.java b/src/intTest/java/com/box/sdkgen/fileversionlegalholds/FileVersionLegalHoldsITest.java new file mode 100644 index 000000000..0d58b06a3 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/fileversionlegalholds/FileVersionLegalHoldsITest.java @@ -0,0 +1,34 @@ +package com.box.sdkgen.fileversionlegalholds; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.fileversionlegalholds.GetFileVersionLegalHoldsQueryParams; +import com.box.sdkgen.schemas.fileversionlegalholds.FileVersionLegalHolds; +import org.junit.jupiter.api.Test; + +public class FileVersionLegalHoldsITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testGetFileVersionLegalHolds() { + String policyId = "1234567890"; + FileVersionLegalHolds fileVersionLegalHolds = + client + .getFileVersionLegalHolds() + .getFileVersionLegalHolds(new GetFileVersionLegalHoldsQueryParams(policyId)); + int fileVersionLegalHoldsCount = fileVersionLegalHolds.getEntries().size(); + assert fileVersionLegalHoldsCount >= 0; + } + + @Test + public void testGetFileVersionLegalHoldById() { + String fileVersionLegalHoldId = "987654321"; + assertThrows( + RuntimeException.class, + () -> + client.getFileVersionLegalHolds().getFileVersionLegalHoldById(fileVersionLegalHoldId)); + } +} diff --git a/src/intTest/java/com/box/sdkgen/fileversionretentions/FileVersionRetentionsITest.java b/src/intTest/java/com/box/sdkgen/fileversionretentions/FileVersionRetentionsITest.java new file mode 100644 index 000000000..26ab8f6e2 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/fileversionretentions/FileVersionRetentionsITest.java @@ -0,0 +1,111 @@ +package com.box.sdkgen.fileversionretentions; + +import static com.box.sdkgen.commons.CommonsManager.createNewFolder; +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.generateByteStream; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.folders.DeleteFolderByIdQueryParams; +import com.box.sdkgen.managers.retentionpolicies.CreateRetentionPolicyRequestBody; +import com.box.sdkgen.managers.retentionpolicies.CreateRetentionPolicyRequestBodyDispositionActionField; +import com.box.sdkgen.managers.retentionpolicies.CreateRetentionPolicyRequestBodyPolicyTypeField; +import com.box.sdkgen.managers.retentionpolicies.CreateRetentionPolicyRequestBodyRetentionTypeField; +import com.box.sdkgen.managers.retentionpolicyassignments.CreateRetentionPolicyAssignmentRequestBody; +import com.box.sdkgen.managers.retentionpolicyassignments.CreateRetentionPolicyAssignmentRequestBodyAssignToField; +import com.box.sdkgen.managers.retentionpolicyassignments.CreateRetentionPolicyAssignmentRequestBodyAssignToTypeField; +import com.box.sdkgen.managers.uploads.UploadFileRequestBody; +import com.box.sdkgen.managers.uploads.UploadFileRequestBodyAttributesField; +import com.box.sdkgen.managers.uploads.UploadFileRequestBodyAttributesParentField; +import com.box.sdkgen.managers.uploads.UploadFileVersionRequestBody; +import com.box.sdkgen.managers.uploads.UploadFileVersionRequestBodyAttributesField; +import com.box.sdkgen.schemas.filefull.FileFull; +import com.box.sdkgen.schemas.files.Files; +import com.box.sdkgen.schemas.fileversionretention.FileVersionRetention; +import com.box.sdkgen.schemas.fileversionretentions.FileVersionRetentions; +import com.box.sdkgen.schemas.folderfull.FolderFull; +import com.box.sdkgen.schemas.retentionpolicy.RetentionPolicy; +import com.box.sdkgen.schemas.retentionpolicyassignment.RetentionPolicyAssignment; +import org.junit.jupiter.api.Test; + +public class FileVersionRetentionsITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testCreateUpdateGetDeleteRetentionPolicy() { + String description = getUuid(); + RetentionPolicy retentionPolicy = + client + .getRetentionPolicies() + .createRetentionPolicy( + new CreateRetentionPolicyRequestBody.Builder( + getUuid(), + CreateRetentionPolicyRequestBodyPolicyTypeField.FINITE, + CreateRetentionPolicyRequestBodyDispositionActionField.REMOVE_RETENTION) + .description(description) + .retentionLength("1") + .retentionType(CreateRetentionPolicyRequestBodyRetentionTypeField.MODIFIABLE) + .canOwnerExtendRetention(false) + .build()); + assert retentionPolicy.getDescription().equals(description); + assert retentionPolicy.getCanOwnerExtendRetention() == false; + assert convertToString(retentionPolicy.getRetentionType()).equals("modifiable"); + FolderFull folder = createNewFolder(); + RetentionPolicyAssignment retentionPolicyAssignment = + client + .getRetentionPolicyAssignments() + .createRetentionPolicyAssignment( + new CreateRetentionPolicyAssignmentRequestBody( + retentionPolicy.getId(), + new CreateRetentionPolicyAssignmentRequestBodyAssignToField.Builder( + CreateRetentionPolicyAssignmentRequestBodyAssignToTypeField.FOLDER) + .id(folder.getId()) + .build())); + assert retentionPolicyAssignment.getRetentionPolicy().getId().equals(retentionPolicy.getId()); + assert retentionPolicyAssignment.getAssignedTo().getId().equals(folder.getId()); + assert convertToString(retentionPolicyAssignment.getAssignedTo().getType()) + .equals(convertToString(folder.getType())); + Files files = + client + .getUploads() + .uploadFile( + new UploadFileRequestBody( + new UploadFileRequestBodyAttributesField( + getUuid(), new UploadFileRequestBodyAttributesParentField(folder.getId())), + generateByteStream(10))); + FileFull file = files.getEntries().get(0); + Files newFiles = + client + .getUploads() + .uploadFileVersion( + file.getId(), + new UploadFileVersionRequestBody( + new UploadFileVersionRequestBodyAttributesField(file.getName()), + generateByteStream(20))); + FileFull newFile = newFiles.getEntries().get(0); + assert newFile.getId().equals(file.getId()); + FileVersionRetentions fileVersionRetentions = + client.getFileVersionRetentions().getFileVersionRetentions(); + int fileVersionRetentionsCount = fileVersionRetentions.getEntries().size(); + assert fileVersionRetentionsCount >= 0; + if (fileVersionRetentionsCount == 0) { + client.getRetentionPolicies().deleteRetentionPolicyById(retentionPolicy.getId()); + client + .getFolders() + .deleteFolderById( + folder.getId(), new DeleteFolderByIdQueryParams.Builder().recursive(true).build()); + return; + } + FileVersionRetention fileVersionRetention = fileVersionRetentions.getEntries().get(0); + FileVersionRetention fileVersionRetentionById = + client.getFileVersionRetentions().getFileVersionRetentionById(fileVersionRetention.getId()); + assert fileVersionRetentionById.getId().equals(fileVersionRetention.getId()); + client.getRetentionPolicies().deleteRetentionPolicyById(retentionPolicy.getId()); + client + .getFolders() + .deleteFolderById( + folder.getId(), new DeleteFolderByIdQueryParams.Builder().recursive(true).build()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/fileversions/FileVersionsITest.java b/src/intTest/java/com/box/sdkgen/fileversions/FileVersionsITest.java new file mode 100644 index 000000000..fda1e9a74 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/fileversions/FileVersionsITest.java @@ -0,0 +1,146 @@ +package com.box.sdkgen.fileversions; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.internal.utils.UtilsManager.generateByteStream; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.fileversions.GetFileVersionByIdQueryParams; +import com.box.sdkgen.managers.fileversions.PromoteFileVersionRequestBody; +import com.box.sdkgen.managers.fileversions.PromoteFileVersionRequestBodyTypeField; +import com.box.sdkgen.managers.fileversions.UpdateFileVersionByIdRequestBody; +import com.box.sdkgen.managers.uploads.UploadFileRequestBody; +import com.box.sdkgen.managers.uploads.UploadFileRequestBodyAttributesField; +import com.box.sdkgen.managers.uploads.UploadFileRequestBodyAttributesParentField; +import com.box.sdkgen.managers.uploads.UploadFileVersionRequestBody; +import com.box.sdkgen.managers.uploads.UploadFileVersionRequestBodyAttributesField; +import com.box.sdkgen.schemas.filefull.FileFull; +import com.box.sdkgen.schemas.files.Files; +import com.box.sdkgen.schemas.fileversionfull.FileVersionFull; +import com.box.sdkgen.schemas.fileversions.FileVersions; +import java.util.Arrays; +import org.junit.jupiter.api.Test; + +public class FileVersionsITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testCreateListGetPromoteFileVersion() { + String oldName = getUuid(); + String newName = getUuid(); + Files files = + client + .getUploads() + .uploadFile( + new UploadFileRequestBody( + new UploadFileRequestBodyAttributesField( + oldName, new UploadFileRequestBodyAttributesParentField("0")), + generateByteStream(10))); + FileFull file = files.getEntries().get(0); + assert file.getName().equals(oldName); + assert file.getSize() == 10; + Files newFiles = + client + .getUploads() + .uploadFileVersion( + file.getId(), + new UploadFileVersionRequestBody( + new UploadFileVersionRequestBodyAttributesField(newName), + generateByteStream(20))); + FileFull newFile = newFiles.getEntries().get(0); + assert newFile.getName().equals(newName); + assert newFile.getSize() == 20; + FileVersions fileVersions = client.getFileVersions().getFileVersions(file.getId()); + assert fileVersions.getTotalCount() == 1; + FileVersionFull fileVersion = + client + .getFileVersions() + .getFileVersionById(file.getId(), fileVersions.getEntries().get(0).getId()); + assert fileVersion.getId().equals(fileVersions.getEntries().get(0).getId()); + client + .getFileVersions() + .promoteFileVersion( + file.getId(), + new PromoteFileVersionRequestBody.Builder() + .id(fileVersions.getEntries().get(0).getId()) + .type(PromoteFileVersionRequestBodyTypeField.FILE_VERSION) + .build()); + FileFull fileWithPromotedVersion = client.getFiles().getFileById(file.getId()); + assert fileWithPromotedVersion.getName().equals(oldName); + assert fileWithPromotedVersion.getSize() == 10; + client.getFileVersions().deleteFileVersionById(file.getId(), fileVersion.getId()); + client.getFiles().deleteFileById(file.getId()); + } + + @Test + public void testRemoveAndRestoreFileVersion() { + String oldName = getUuid(); + String newName = getUuid(); + Files files = + client + .getUploads() + .uploadFile( + new UploadFileRequestBody( + new UploadFileRequestBodyAttributesField( + oldName, new UploadFileRequestBodyAttributesParentField("0")), + generateByteStream(10))); + FileFull file = files.getEntries().get(0); + client + .getUploads() + .uploadFileVersion( + file.getId(), + new UploadFileVersionRequestBody( + new UploadFileVersionRequestBodyAttributesField(newName), generateByteStream(20))); + FileVersions fileVersions = client.getFileVersions().getFileVersions(file.getId()); + assert fileVersions.getTotalCount() == 1; + FileVersionFull fileVersion = + client + .getFileVersions() + .getFileVersionById( + file.getId(), + fileVersions.getEntries().get(0).getId(), + new GetFileVersionByIdQueryParams.Builder() + .fields(Arrays.asList("trashed_at", "trashed_by", "restored_at", "restored_by")) + .build()); + assert fileVersion.getTrashedAt() == null; + assert fileVersion.getTrashedBy() == null; + assert fileVersion.getRestoredAt() == null; + assert fileVersion.getRestoredBy() == null; + client.getFileVersions().deleteFileVersionById(file.getId(), fileVersion.getId()); + FileVersionFull deletedFileVersion = + client + .getFileVersions() + .getFileVersionById( + file.getId(), + fileVersions.getEntries().get(0).getId(), + new GetFileVersionByIdQueryParams.Builder() + .fields(Arrays.asList("trashed_at", "trashed_by", "restored_at", "restored_by")) + .build()); + assert !(deletedFileVersion.getTrashedAt() == null); + assert !(deletedFileVersion.getTrashedBy() == null); + assert deletedFileVersion.getRestoredAt() == null; + assert deletedFileVersion.getRestoredBy() == null; + client + .getFileVersions() + .updateFileVersionById( + file.getId(), + fileVersion.getId(), + new UpdateFileVersionByIdRequestBody.Builder().trashedAt(null).build()); + FileVersionFull restoredFileVersion = + client + .getFileVersions() + .getFileVersionById( + file.getId(), + fileVersions.getEntries().get(0).getId(), + new GetFileVersionByIdQueryParams.Builder() + .fields(Arrays.asList("trashed_at", "trashed_by", "restored_at", "restored_by")) + .build()); + assert restoredFileVersion.getTrashedAt() == null; + assert restoredFileVersion.getTrashedBy() == null; + assert !(restoredFileVersion.getRestoredAt() == null); + assert !(restoredFileVersion.getRestoredBy() == null); + client.getFileVersions().deleteFileVersionById(file.getId(), fileVersion.getId()); + client.getFiles().deleteFileById(file.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/filewatermarks/FileWatermarksITest.java b/src/intTest/java/com/box/sdkgen/filewatermarks/FileWatermarksITest.java new file mode 100644 index 000000000..a3e16b18f --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/filewatermarks/FileWatermarksITest.java @@ -0,0 +1,51 @@ +package com.box.sdkgen.filewatermarks; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.internal.utils.UtilsManager.generateByteStream; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.filewatermarks.UpdateFileWatermarkRequestBody; +import com.box.sdkgen.managers.filewatermarks.UpdateFileWatermarkRequestBodyWatermarkField; +import com.box.sdkgen.managers.filewatermarks.UpdateFileWatermarkRequestBodyWatermarkImprintField; +import com.box.sdkgen.managers.uploads.UploadFileRequestBody; +import com.box.sdkgen.managers.uploads.UploadFileRequestBodyAttributesField; +import com.box.sdkgen.managers.uploads.UploadFileRequestBodyAttributesParentField; +import com.box.sdkgen.schemas.filefull.FileFull; +import com.box.sdkgen.schemas.files.Files; +import com.box.sdkgen.schemas.watermark.Watermark; +import org.junit.jupiter.api.Test; + +public class FileWatermarksITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testCreateGetDeleteFileWatermark() { + String fileName = String.join("", getUuid(), ".txt"); + Files uploadedFiles = + client + .getUploads() + .uploadFile( + new UploadFileRequestBody( + new UploadFileRequestBodyAttributesField( + fileName, new UploadFileRequestBodyAttributesParentField("0")), + generateByteStream(10))); + FileFull file = uploadedFiles.getEntries().get(0); + Watermark createdWatermark = + client + .getFileWatermarks() + .updateFileWatermark( + file.getId(), + new UpdateFileWatermarkRequestBody( + new UpdateFileWatermarkRequestBodyWatermarkField.Builder() + .imprint(UpdateFileWatermarkRequestBodyWatermarkImprintField.DEFAULT) + .build())); + Watermark watermark = client.getFileWatermarks().getFileWatermark(file.getId()); + client.getFileWatermarks().deleteFileWatermark(file.getId()); + assertThrows( + RuntimeException.class, () -> client.getFileWatermarks().getFileWatermark(file.getId())); + client.getFiles().deleteFileById(file.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/folderclassifications/FolderClassificationsITest.java b/src/intTest/java/com/box/sdkgen/folderclassifications/FolderClassificationsITest.java new file mode 100644 index 000000000..d26001dcc --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/folderclassifications/FolderClassificationsITest.java @@ -0,0 +1,98 @@ +package com.box.sdkgen.folderclassifications; + +import static com.box.sdkgen.commons.CommonsManager.createNewFolder; +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.commons.CommonsManager.getOrCreateClassification; +import static com.box.sdkgen.commons.CommonsManager.getOrCreateClassificationTemplate; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.classifications.AddClassificationRequestBody; +import com.box.sdkgen.managers.classifications.AddClassificationRequestBodyDataField; +import com.box.sdkgen.managers.classifications.AddClassificationRequestBodyDataStaticConfigClassificationField; +import com.box.sdkgen.managers.classifications.AddClassificationRequestBodyDataStaticConfigField; +import com.box.sdkgen.managers.folderclassifications.AddClassificationToFolderRequestBody; +import com.box.sdkgen.managers.folderclassifications.UpdateClassificationOnFolderRequestBody; +import com.box.sdkgen.schemas.classification.Classification; +import com.box.sdkgen.schemas.classificationtemplate.ClassificationTemplate; +import com.box.sdkgen.schemas.classificationtemplate.ClassificationTemplateFieldsOptionsField; +import com.box.sdkgen.schemas.folderfull.FolderFull; +import java.util.Arrays; +import java.util.List; +import org.junit.jupiter.api.Test; + +public class FolderClassificationsITest { + + private static final BoxClient client = getDefaultClient(); + + public static ClassificationTemplateFieldsOptionsField getOrCreateSecondClassification( + ClassificationTemplate classificationTemplate) { + List classifications = + classificationTemplate.getFields().get(0).getOptions(); + int currentNumberOfClassifications = classifications.size(); + if (currentNumberOfClassifications == 1) { + ClassificationTemplate classificationTemplateWithNewClassification = + client + .getClassifications() + .addClassification( + Arrays.asList( + new AddClassificationRequestBody( + new AddClassificationRequestBodyDataField.Builder(getUuid()) + .staticConfig( + new AddClassificationRequestBodyDataStaticConfigField.Builder() + .classification( + new AddClassificationRequestBodyDataStaticConfigClassificationField + .Builder() + .classificationDefinition("Other description") + .colorId(4L) + .build()) + .build()) + .build()))); + return classificationTemplateWithNewClassification.getFields().get(0).getOptions().get(1); + } + return classifications.get(1); + } + + @Test + public void testFolderClassifications() { + ClassificationTemplate classificationTemplate = getOrCreateClassificationTemplate(); + ClassificationTemplateFieldsOptionsField classification = + getOrCreateClassification(classificationTemplate); + FolderFull folder = createNewFolder(); + assertThrows( + RuntimeException.class, + () -> client.getFolderClassifications().getClassificationOnFolder(folder.getId())); + Classification createdFolderClassification = + client + .getFolderClassifications() + .addClassificationToFolder( + folder.getId(), + new AddClassificationToFolderRequestBody.Builder() + .boxSecurityClassificationKey(classification.getKey()) + .build()); + assert createdFolderClassification + .getBoxSecurityClassificationKey() + .equals(classification.getKey()); + Classification folderClassification = + client.getFolderClassifications().getClassificationOnFolder(folder.getId()); + assert folderClassification.getBoxSecurityClassificationKey().equals(classification.getKey()); + ClassificationTemplateFieldsOptionsField secondClassification = + getOrCreateSecondClassification(classificationTemplate); + Classification updatedFolderClassification = + client + .getFolderClassifications() + .updateClassificationOnFolder( + folder.getId(), + Arrays.asList( + new UpdateClassificationOnFolderRequestBody(secondClassification.getKey()))); + assert updatedFolderClassification + .getBoxSecurityClassificationKey() + .equals(secondClassification.getKey()); + client.getFolderClassifications().deleteClassificationFromFolder(folder.getId()); + assertThrows( + RuntimeException.class, + () -> client.getFolderClassifications().getClassificationOnFolder(folder.getId())); + client.getFolders().deleteFolderById(folder.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/folderlocks/FolderLocksITest.java b/src/intTest/java/com/box/sdkgen/folderlocks/FolderLocksITest.java new file mode 100644 index 000000000..90c02e608 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/folderlocks/FolderLocksITest.java @@ -0,0 +1,48 @@ +package com.box.sdkgen.folderlocks; + +import static com.box.sdkgen.commons.CommonsManager.createNewFolder; +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.folderlocks.CreateFolderLockRequestBody; +import com.box.sdkgen.managers.folderlocks.CreateFolderLockRequestBodyFolderField; +import com.box.sdkgen.managers.folderlocks.CreateFolderLockRequestBodyLockedOperationsField; +import com.box.sdkgen.managers.folderlocks.GetFolderLocksQueryParams; +import com.box.sdkgen.schemas.folderfull.FolderFull; +import com.box.sdkgen.schemas.folderlock.FolderLock; +import com.box.sdkgen.schemas.folderlocks.FolderLocks; +import org.junit.jupiter.api.Test; + +public class FolderLocksITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testFolderLocks() { + FolderFull folder = createNewFolder(); + FolderLocks folderLocks = + client.getFolderLocks().getFolderLocks(new GetFolderLocksQueryParams(folder.getId())); + assert folderLocks.getEntries().size() == 0; + FolderLock folderLock = + client + .getFolderLocks() + .createFolderLock( + new CreateFolderLockRequestBody.Builder( + new CreateFolderLockRequestBodyFolderField("folder", folder.getId())) + .lockedOperations( + new CreateFolderLockRequestBodyLockedOperationsField(true, true)) + .build()); + assert folderLock.getFolder().getId().equals(folder.getId()); + assert folderLock.getLockedOperations().getMove() == true; + assert folderLock.getLockedOperations().getDelete() == true; + client.getFolderLocks().deleteFolderLockById(folderLock.getId()); + assertThrows( + RuntimeException.class, + () -> client.getFolderLocks().deleteFolderLockById(folderLock.getId())); + FolderLocks newFolderLocks = + client.getFolderLocks().getFolderLocks(new GetFolderLocksQueryParams(folder.getId())); + assert newFolderLocks.getEntries().size() == 0; + client.getFolders().deleteFolderById(folder.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/foldermetadata/FolderMetadataITest.java b/src/intTest/java/com/box/sdkgen/foldermetadata/FolderMetadataITest.java new file mode 100644 index 000000000..aab180096 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/foldermetadata/FolderMetadataITest.java @@ -0,0 +1,275 @@ +package com.box.sdkgen.foldermetadata; + +import static com.box.sdkgen.commons.CommonsManager.createNewFolder; +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.entryOf; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; +import static com.box.sdkgen.internal.utils.UtilsManager.mapOf; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.foldermetadata.CreateFolderMetadataByIdScope; +import com.box.sdkgen.managers.foldermetadata.DeleteFolderMetadataByIdScope; +import com.box.sdkgen.managers.foldermetadata.GetFolderMetadataByIdScope; +import com.box.sdkgen.managers.foldermetadata.UpdateFolderMetadataByIdRequestBody; +import com.box.sdkgen.managers.foldermetadata.UpdateFolderMetadataByIdRequestBodyOpField; +import com.box.sdkgen.managers.foldermetadata.UpdateFolderMetadataByIdScope; +import com.box.sdkgen.managers.metadatatemplates.CreateMetadataTemplateRequestBody; +import com.box.sdkgen.managers.metadatatemplates.CreateMetadataTemplateRequestBodyFieldsField; +import com.box.sdkgen.managers.metadatatemplates.CreateMetadataTemplateRequestBodyFieldsOptionsField; +import com.box.sdkgen.managers.metadatatemplates.CreateMetadataTemplateRequestBodyFieldsTypeField; +import com.box.sdkgen.managers.metadatatemplates.DeleteMetadataTemplateScope; +import com.box.sdkgen.schemas.folderfull.FolderFull; +import com.box.sdkgen.schemas.metadatafull.MetadataFull; +import com.box.sdkgen.schemas.metadatas.Metadatas; +import com.box.sdkgen.schemas.metadatatemplate.MetadataTemplate; +import java.util.Arrays; +import org.junit.jupiter.api.Test; + +public class FolderMetadataITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testUpdatingFolderMetadata() { + FolderFull folder = createNewFolder(); + String templateKey = String.join("", "key", getUuid()); + MetadataTemplate template = + client + .getMetadataTemplates() + .createMetadataTemplate( + new CreateMetadataTemplateRequestBody.Builder("enterprise", templateKey) + .templateKey(templateKey) + .fields( + Arrays.asList( + new CreateMetadataTemplateRequestBodyFieldsField( + CreateMetadataTemplateRequestBodyFieldsTypeField.STRING, + "name", + "name"), + new CreateMetadataTemplateRequestBodyFieldsField( + CreateMetadataTemplateRequestBodyFieldsTypeField.FLOAT, + "age", + "age"), + new CreateMetadataTemplateRequestBodyFieldsField( + CreateMetadataTemplateRequestBodyFieldsTypeField.DATE, + "birthDate", + "birthDate"), + new CreateMetadataTemplateRequestBodyFieldsField.Builder( + CreateMetadataTemplateRequestBodyFieldsTypeField.ENUM, + "countryCode", + "countryCode") + .options( + Arrays.asList( + new CreateMetadataTemplateRequestBodyFieldsOptionsField( + "US"), + new CreateMetadataTemplateRequestBodyFieldsOptionsField( + "CA"))) + .build(), + new CreateMetadataTemplateRequestBodyFieldsField.Builder( + CreateMetadataTemplateRequestBodyFieldsTypeField.MULTISELECT, + "sports", + "sports") + .options( + Arrays.asList( + new CreateMetadataTemplateRequestBodyFieldsOptionsField( + "basketball"), + new CreateMetadataTemplateRequestBodyFieldsOptionsField( + "football"), + new CreateMetadataTemplateRequestBodyFieldsOptionsField( + "tennis"))) + .build())) + .build()); + MetadataFull createdMetadata = + client + .getFolderMetadata() + .createFolderMetadataById( + folder.getId(), + CreateFolderMetadataByIdScope.ENTERPRISE, + templateKey, + mapOf( + entryOf("name", "John"), + entryOf("age", 23), + entryOf("birthDate", "2001-01-03T02:20:50.520Z"), + entryOf("countryCode", "US"), + entryOf("sports", Arrays.asList("basketball", "tennis")))); + MetadataFull updatedMetadata = + client + .getFolderMetadata() + .updateFolderMetadataById( + folder.getId(), + UpdateFolderMetadataByIdScope.ENTERPRISE, + templateKey, + Arrays.asList( + new UpdateFolderMetadataByIdRequestBody.Builder() + .op(UpdateFolderMetadataByIdRequestBodyOpField.REPLACE) + .path("/name") + .value("Jack") + .build(), + new UpdateFolderMetadataByIdRequestBody.Builder() + .op(UpdateFolderMetadataByIdRequestBodyOpField.REPLACE) + .path("/age") + .value(24L) + .build(), + new UpdateFolderMetadataByIdRequestBody.Builder() + .op(UpdateFolderMetadataByIdRequestBodyOpField.REPLACE) + .path("/birthDate") + .value("2000-01-03T02:20:50.520Z") + .build(), + new UpdateFolderMetadataByIdRequestBody.Builder() + .op(UpdateFolderMetadataByIdRequestBodyOpField.REPLACE) + .path("/countryCode") + .value("CA") + .build(), + new UpdateFolderMetadataByIdRequestBody.Builder() + .op(UpdateFolderMetadataByIdRequestBodyOpField.REPLACE) + .path("/sports") + .value(Arrays.asList("football")) + .build())); + assert convertToString(updatedMetadata.getTemplate()).equals(templateKey); + assert convertToString(updatedMetadata.getExtraData().get("name")).equals("Jack"); + assert convertToString(updatedMetadata.getExtraData().get("age")).equals("24"); + assert convertToString(updatedMetadata.getExtraData().get("birthDate")) + .equals("2000-01-03T02:20:50.520Z"); + assert convertToString(updatedMetadata.getExtraData().get("countryCode")).equals("CA"); + client + .getFolderMetadata() + .deleteFolderMetadataById( + folder.getId(), DeleteFolderMetadataByIdScope.ENTERPRISE, templateKey); + client + .getMetadataTemplates() + .deleteMetadataTemplate(DeleteMetadataTemplateScope.ENTERPRISE, templateKey); + client.getFolders().deleteFolderById(folder.getId()); + } + + @Test + public void testGlobalFolderMetadata() { + FolderFull folder = createNewFolder(); + Metadatas folderMetadata = client.getFolderMetadata().getFolderMetadata(folder.getId()); + assert folderMetadata.getEntries().size() == 0; + MetadataFull createdMetadata = + client + .getFolderMetadata() + .createFolderMetadataById( + folder.getId(), + CreateFolderMetadataByIdScope.GLOBAL, + "properties", + mapOf(entryOf("abc", "xyz"))); + assert convertToString(createdMetadata.getTemplate()).equals("properties"); + assert convertToString(createdMetadata.getScope()).equals("global"); + assert createdMetadata.getVersion() == 0; + MetadataFull receivedMetadata = + client + .getFolderMetadata() + .getFolderMetadataById(folder.getId(), GetFolderMetadataByIdScope.GLOBAL, "properties"); + assert convertToString(receivedMetadata.getExtraData().get("abc")).equals("xyz"); + String newValue = "bar"; + client + .getFolderMetadata() + .updateFolderMetadataById( + folder.getId(), + UpdateFolderMetadataByIdScope.GLOBAL, + "properties", + Arrays.asList( + new UpdateFolderMetadataByIdRequestBody.Builder() + .op(UpdateFolderMetadataByIdRequestBodyOpField.REPLACE) + .path("/abc") + .value(newValue) + .build())); + MetadataFull receivedUpdatedMetadata = + client + .getFolderMetadata() + .getFolderMetadataById(folder.getId(), GetFolderMetadataByIdScope.GLOBAL, "properties"); + assert convertToString(receivedUpdatedMetadata.getExtraData().get("abc")).equals(newValue); + client + .getFolderMetadata() + .deleteFolderMetadataById( + folder.getId(), DeleteFolderMetadataByIdScope.GLOBAL, "properties"); + assertThrows( + RuntimeException.class, + () -> + client + .getFolderMetadata() + .getFolderMetadataById( + folder.getId(), GetFolderMetadataByIdScope.GLOBAL, "properties")); + client.getFolders().deleteFolderById(folder.getId()); + } + + @Test + public void testEnterpriseFolderMetadata() { + FolderFull folder = createNewFolder(); + String templateKey = String.join("", "key", getUuid()); + MetadataTemplate template = + client + .getMetadataTemplates() + .createMetadataTemplate( + new CreateMetadataTemplateRequestBody.Builder("enterprise", templateKey) + .templateKey(templateKey) + .fields( + Arrays.asList( + new CreateMetadataTemplateRequestBodyFieldsField( + CreateMetadataTemplateRequestBodyFieldsTypeField.STRING, + "name", + "name"), + new CreateMetadataTemplateRequestBodyFieldsField( + CreateMetadataTemplateRequestBodyFieldsTypeField.FLOAT, + "age", + "age"), + new CreateMetadataTemplateRequestBodyFieldsField( + CreateMetadataTemplateRequestBodyFieldsTypeField.DATE, + "birthDate", + "birthDate"), + new CreateMetadataTemplateRequestBodyFieldsField.Builder( + CreateMetadataTemplateRequestBodyFieldsTypeField.ENUM, + "countryCode", + "countryCode") + .options( + Arrays.asList( + new CreateMetadataTemplateRequestBodyFieldsOptionsField( + "US"), + new CreateMetadataTemplateRequestBodyFieldsOptionsField( + "CA"))) + .build(), + new CreateMetadataTemplateRequestBodyFieldsField.Builder( + CreateMetadataTemplateRequestBodyFieldsTypeField.MULTISELECT, + "sports", + "sports") + .options( + Arrays.asList( + new CreateMetadataTemplateRequestBodyFieldsOptionsField( + "basketball"), + new CreateMetadataTemplateRequestBodyFieldsOptionsField( + "football"), + new CreateMetadataTemplateRequestBodyFieldsOptionsField( + "tennis"))) + .build())) + .build()); + MetadataFull createdMetadata = + client + .getFolderMetadata() + .createFolderMetadataById( + folder.getId(), + CreateFolderMetadataByIdScope.ENTERPRISE, + templateKey, + mapOf( + entryOf("name", "John"), + entryOf("age", 23), + entryOf("birthDate", "2001-01-03T02:20:50.520Z"), + entryOf("countryCode", "US"), + entryOf("sports", Arrays.asList("basketball", "tennis")))); + assert convertToString(createdMetadata.getTemplate()).equals(templateKey); + assert convertToString(createdMetadata.getExtraData().get("name")).equals("John"); + assert convertToString(createdMetadata.getExtraData().get("age")).equals("23"); + assert convertToString(createdMetadata.getExtraData().get("birthDate")) + .equals("2001-01-03T02:20:50.520Z"); + assert convertToString(createdMetadata.getExtraData().get("countryCode")).equals("US"); + client + .getFolderMetadata() + .deleteFolderMetadataById( + folder.getId(), DeleteFolderMetadataByIdScope.ENTERPRISE, templateKey); + client + .getMetadataTemplates() + .deleteMetadataTemplate(DeleteMetadataTemplateScope.ENTERPRISE, templateKey); + client.getFolders().deleteFolderById(folder.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/folders/FoldersITest.java b/src/intTest/java/com/box/sdkgen/folders/FoldersITest.java new file mode 100644 index 000000000..24bb41757 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/folders/FoldersITest.java @@ -0,0 +1,128 @@ +package com.box.sdkgen.folders; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.folders.CopyFolderRequestBody; +import com.box.sdkgen.managers.folders.CopyFolderRequestBodyParentField; +import com.box.sdkgen.managers.folders.CreateFolderRequestBody; +import com.box.sdkgen.managers.folders.CreateFolderRequestBodyParentField; +import com.box.sdkgen.managers.folders.GetFolderByIdQueryParams; +import com.box.sdkgen.managers.folders.UpdateFolderByIdRequestBody; +import com.box.sdkgen.managers.folders.UpdateFolderByIdRequestBodyParentField; +import com.box.sdkgen.schemas.folderfull.FolderFull; +import com.box.sdkgen.schemas.items.Items; +import java.util.Arrays; +import org.junit.jupiter.api.Test; + +public class FoldersITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testGetFolderInfo() { + FolderFull rootFolder = client.getFolders().getFolderById("0"); + assert rootFolder.getId().equals("0"); + assert rootFolder.getName().equals("All Files"); + assert convertToString(rootFolder.getType()).equals("folder"); + } + + @Test + public void testGetFolderFullInfoWithExtraFields() { + FolderFull rootFolder = + client + .getFolders() + .getFolderById( + "0", + new GetFolderByIdQueryParams.Builder() + .fields(Arrays.asList("has_collaborations", "tags")) + .build()); + assert rootFolder.getId().equals("0"); + assert rootFolder.getHasCollaborations() == false; + int tagsLength = rootFolder.getTags().size(); + assert tagsLength == 0; + } + + @Test + public void testCreateAndDeleteFolder() { + String newFolderName = getUuid(); + FolderFull newFolder = + client + .getFolders() + .createFolder( + new CreateFolderRequestBody( + newFolderName, new CreateFolderRequestBodyParentField("0"))); + FolderFull createdFolder = client.getFolders().getFolderById(newFolder.getId()); + assert createdFolder.getName().equals(newFolderName); + client.getFolders().deleteFolderById(newFolder.getId()); + assertThrows( + RuntimeException.class, () -> client.getFolders().getFolderById(newFolder.getId())); + } + + @Test + public void testUpdateFolder() { + String folderToUpdateName = getUuid(); + FolderFull folderToUpdate = + client + .getFolders() + .createFolder( + new CreateFolderRequestBody( + folderToUpdateName, new CreateFolderRequestBodyParentField("0"))); + String updatedName = getUuid(); + FolderFull updatedFolder = + client + .getFolders() + .updateFolderById( + folderToUpdate.getId(), + new UpdateFolderByIdRequestBody.Builder() + .name(updatedName) + .description("Updated description") + .build()); + assert updatedFolder.getName().equals(updatedName); + assert updatedFolder.getDescription().equals("Updated description"); + client.getFolders().deleteFolderById(updatedFolder.getId()); + } + + @Test + public void testCopyMoveFolderAndListFolderItems() { + String folderOriginName = getUuid(); + FolderFull folderOrigin = + client + .getFolders() + .createFolder( + new CreateFolderRequestBody( + folderOriginName, new CreateFolderRequestBodyParentField("0"))); + String copiedFolderName = getUuid(); + FolderFull copiedFolder = + client + .getFolders() + .copyFolder( + folderOrigin.getId(), + new CopyFolderRequestBody.Builder(new CopyFolderRequestBodyParentField("0")) + .name(copiedFolderName) + .build()); + assert copiedFolder.getParent().getId().equals("0"); + String movedFolderName = getUuid(); + FolderFull movedFolder = + client + .getFolders() + .updateFolderById( + copiedFolder.getId(), + new UpdateFolderByIdRequestBody.Builder() + .name(movedFolderName) + .parent( + new UpdateFolderByIdRequestBodyParentField.Builder() + .id(folderOrigin.getId()) + .build()) + .build()); + assert movedFolder.getParent().getId().equals(folderOrigin.getId()); + Items folderItems = client.getFolders().getFolderItems(folderOrigin.getId()); + assert folderItems.getEntries().get(0).getId().equals(movedFolder.getId()); + assert folderItems.getEntries().get(0).getName().equals(movedFolderName); + client.getFolders().deleteFolderById(movedFolder.getId()); + client.getFolders().deleteFolderById(folderOrigin.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/folderwatermarks/FolderWatermarksITest.java b/src/intTest/java/com/box/sdkgen/folderwatermarks/FolderWatermarksITest.java new file mode 100644 index 000000000..6690c5ba2 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/folderwatermarks/FolderWatermarksITest.java @@ -0,0 +1,46 @@ +package com.box.sdkgen.folderwatermarks; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.folders.CreateFolderRequestBody; +import com.box.sdkgen.managers.folders.CreateFolderRequestBodyParentField; +import com.box.sdkgen.managers.folderwatermarks.UpdateFolderWatermarkRequestBody; +import com.box.sdkgen.managers.folderwatermarks.UpdateFolderWatermarkRequestBodyWatermarkField; +import com.box.sdkgen.managers.folderwatermarks.UpdateFolderWatermarkRequestBodyWatermarkImprintField; +import com.box.sdkgen.schemas.folderfull.FolderFull; +import com.box.sdkgen.schemas.watermark.Watermark; +import org.junit.jupiter.api.Test; + +public class FolderWatermarksITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testCreateGetDeleteFolderWatermark() { + String folderName = getUuid(); + FolderFull folder = + client + .getFolders() + .createFolder( + new CreateFolderRequestBody( + folderName, new CreateFolderRequestBodyParentField("0"))); + Watermark createdWatermark = + client + .getFolderWatermarks() + .updateFolderWatermark( + folder.getId(), + new UpdateFolderWatermarkRequestBody( + new UpdateFolderWatermarkRequestBodyWatermarkField.Builder() + .imprint(UpdateFolderWatermarkRequestBodyWatermarkImprintField.DEFAULT) + .build())); + Watermark watermark = client.getFolderWatermarks().getFolderWatermark(folder.getId()); + client.getFolderWatermarks().deleteFolderWatermark(folder.getId()); + assertThrows( + RuntimeException.class, + () -> client.getFolderWatermarks().getFolderWatermark(folder.getId())); + client.getFolders().deleteFolderById(folder.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/groups/GroupsITest.java b/src/intTest/java/com/box/sdkgen/groups/GroupsITest.java new file mode 100644 index 000000000..2d98c9772 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/groups/GroupsITest.java @@ -0,0 +1,59 @@ +package com.box.sdkgen.groups; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.groups.CreateGroupRequestBody; +import com.box.sdkgen.managers.groups.GetGroupByIdQueryParams; +import com.box.sdkgen.managers.groups.UpdateGroupByIdRequestBody; +import com.box.sdkgen.schemas.groupfull.GroupFull; +import com.box.sdkgen.schemas.groups.Groups; +import java.util.Arrays; +import org.junit.jupiter.api.Test; + +public class GroupsITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testGetGroups() { + Groups groups = client.getGroups().getGroups(); + assert groups.getTotalCount() >= 0; + } + + @Test + public void testCreateGetDeleteGroup() { + String groupName = getUuid(); + String groupDescription = "Group description"; + GroupFull group = + client + .getGroups() + .createGroup( + new CreateGroupRequestBody.Builder(groupName) + .description(groupDescription) + .build()); + assert group.getName().equals(groupName); + GroupFull groupById = + client + .getGroups() + .getGroupById( + group.getId(), + new GetGroupByIdQueryParams.Builder() + .fields(Arrays.asList("id", "name", "description", "group_type")) + .build()); + assert groupById.getId().equals(group.getId()); + assert groupById.getDescription().equals(groupDescription); + String updatedGroupName = getUuid(); + GroupFull updatedGroup = + client + .getGroups() + .updateGroupById( + group.getId(), + new UpdateGroupByIdRequestBody.Builder().name(updatedGroupName).build()); + assert updatedGroup.getName().equals(updatedGroupName); + client.getGroups().deleteGroupById(group.getId()); + assertThrows(RuntimeException.class, () -> client.getGroups().getGroupById(group.getId())); + } +} diff --git a/src/intTest/java/com/box/sdkgen/hubcollaborations/HubCollaborationsITest.java b/src/intTest/java/com/box/sdkgen/hubcollaborations/HubCollaborationsITest.java new file mode 100644 index 000000000..54f5d6e01 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/hubcollaborations/HubCollaborationsITest.java @@ -0,0 +1,94 @@ +package com.box.sdkgen.hubcollaborations; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClientWithUserSubject; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.getEnvVar; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.hubcollaborations.GetHubCollaborationsV2025R0QueryParams; +import com.box.sdkgen.managers.hubs.GetHubsV2025R0QueryParams; +import com.box.sdkgen.managers.hubs.GetHubsV2025R0QueryParamsDirectionField; +import com.box.sdkgen.managers.users.CreateUserRequestBody; +import com.box.sdkgen.schemas.userfull.UserFull; +import com.box.sdkgen.schemas.v2025r0.hubcollaborationcreaterequestv2025r0.HubCollaborationCreateRequestV2025R0; +import com.box.sdkgen.schemas.v2025r0.hubcollaborationcreaterequestv2025r0.HubCollaborationCreateRequestV2025R0AccessibleByField; +import com.box.sdkgen.schemas.v2025r0.hubcollaborationcreaterequestv2025r0.HubCollaborationCreateRequestV2025R0HubField; +import com.box.sdkgen.schemas.v2025r0.hubcollaborationsv2025r0.HubCollaborationsV2025R0; +import com.box.sdkgen.schemas.v2025r0.hubcollaborationupdaterequestv2025r0.HubCollaborationUpdateRequestV2025R0; +import com.box.sdkgen.schemas.v2025r0.hubcollaborationv2025r0.HubCollaborationV2025R0; +import com.box.sdkgen.schemas.v2025r0.hubsv2025r0.HubsV2025R0; +import com.box.sdkgen.schemas.v2025r0.hubv2025r0.HubV2025R0; +import org.junit.jupiter.api.Test; + +public class HubCollaborationsITest { + + private static final BoxClient client = getDefaultClientWithUserSubject(getEnvVar("USER_ID")); + + @Test + public void testCrudHubCollaboration() { + HubsV2025R0 hubs = + client + .getHubs() + .getHubsV2025R0( + new GetHubsV2025R0QueryParams.Builder() + .scope("all") + .sort("name") + .direction(GetHubsV2025R0QueryParamsDirectionField.ASC) + .build()); + HubV2025R0 hub = hubs.getEntries().get(0); + String userName = getUuid(); + String userLogin = String.join("", getUuid(), "@gmail.com"); + UserFull user = + client + .getUsers() + .createUser( + new CreateUserRequestBody.Builder(userName) + .login(userLogin) + .isPlatformAccessOnly(true) + .build()); + HubCollaborationV2025R0 createdCollaboration = + client + .getHubCollaborations() + .createHubCollaborationV2025R0( + new HubCollaborationCreateRequestV2025R0( + new HubCollaborationCreateRequestV2025R0HubField(hub.getId()), + new HubCollaborationCreateRequestV2025R0AccessibleByField.Builder("user") + .id(user.getId()) + .build(), + "viewer")); + assert !(createdCollaboration.getId().equals("")); + assert convertToString(createdCollaboration.getType()).equals("hub_collaboration"); + assert createdCollaboration.getHub().getId().equals(hub.getId()); + assert convertToString(createdCollaboration.getAccessibleBy().getType()).equals("user"); + assert createdCollaboration.getAccessibleBy().getId().equals(user.getId()); + assert createdCollaboration.getRole().equals("viewer"); + HubCollaborationV2025R0 updatedCollaboration = + client + .getHubCollaborations() + .updateHubCollaborationByIdV2025R0( + createdCollaboration.getId(), + new HubCollaborationUpdateRequestV2025R0.Builder().role("editor").build()); + assert !(updatedCollaboration.getId().equals("")); + assert convertToString(updatedCollaboration.getType()).equals("hub_collaboration"); + assert updatedCollaboration.getHub().getId().equals(hub.getId()); + assert convertToString(updatedCollaboration.getAccessibleBy().getType()).equals("user"); + assert updatedCollaboration.getAccessibleBy().getId().equals(user.getId()); + assert updatedCollaboration.getRole().equals("editor"); + HubCollaborationsV2025R0 collaborations = + client + .getHubCollaborations() + .getHubCollaborationsV2025R0(new GetHubCollaborationsV2025R0QueryParams(hub.getId())); + assert collaborations.getEntries().size() >= 1; + HubCollaborationV2025R0 retrievedCollaboration = + client.getHubCollaborations().getHubCollaborationByIdV2025R0(createdCollaboration.getId()); + assert retrievedCollaboration.getId().equals(createdCollaboration.getId()); + assert convertToString(retrievedCollaboration.getType()).equals("hub_collaboration"); + assert retrievedCollaboration.getHub().getId().equals(hub.getId()); + assert convertToString(retrievedCollaboration.getAccessibleBy().getType()).equals("user"); + assert retrievedCollaboration.getAccessibleBy().getId().equals(user.getId()); + assert retrievedCollaboration.getRole().equals("editor"); + client.getHubCollaborations().deleteHubCollaborationByIdV2025R0(createdCollaboration.getId()); + client.getUsers().deleteUserById(user.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/hubitems/HubItemsITest.java b/src/intTest/java/com/box/sdkgen/hubitems/HubItemsITest.java new file mode 100644 index 000000000..9b09ef64c --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/hubitems/HubItemsITest.java @@ -0,0 +1,92 @@ +package com.box.sdkgen.hubitems; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClientWithUserSubject; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.getEnvVar; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.folders.CreateFolderRequestBody; +import com.box.sdkgen.managers.folders.CreateFolderRequestBodyParentField; +import com.box.sdkgen.managers.hubitems.GetHubItemsV2025R0QueryParams; +import com.box.sdkgen.schemas.folderfull.FolderFull; +import com.box.sdkgen.schemas.v2025r0.folderreferencev2025r0.FolderReferenceV2025R0; +import com.box.sdkgen.schemas.v2025r0.hubcreaterequestv2025r0.HubCreateRequestV2025R0; +import com.box.sdkgen.schemas.v2025r0.hubitemoperationresultv2025r0.HubItemOperationResultV2025R0; +import com.box.sdkgen.schemas.v2025r0.hubitemoperationv2025r0.HubItemOperationV2025R0; +import com.box.sdkgen.schemas.v2025r0.hubitemoperationv2025r0.HubItemOperationV2025R0ActionField; +import com.box.sdkgen.schemas.v2025r0.hubitemsmanagerequestv2025r0.HubItemsManageRequestV2025R0; +import com.box.sdkgen.schemas.v2025r0.hubitemsmanageresponsev2025r0.HubItemsManageResponseV2025R0; +import com.box.sdkgen.schemas.v2025r0.hubitemsv2025r0.HubItemsV2025R0; +import com.box.sdkgen.schemas.v2025r0.hubv2025r0.HubV2025R0; +import java.util.Arrays; +import org.junit.jupiter.api.Test; + +public class HubItemsITest { + + private static final BoxClient client = getDefaultClientWithUserSubject(getEnvVar("USER_ID")); + + @Test + public void testCreateDeleteGetHubItems() { + String hubTitle = getUuid(); + FolderFull folder = + client + .getFolders() + .createFolder( + new CreateFolderRequestBody( + getUuid(), new CreateFolderRequestBodyParentField("0"))); + HubV2025R0 createdHub = + client.getHubs().createHubV2025R0(new HubCreateRequestV2025R0(hubTitle)); + HubItemsV2025R0 hubItemsBeforeAdd = + client + .getHubItems() + .getHubItemsV2025R0(new GetHubItemsV2025R0QueryParams(createdHub.getId())); + assert hubItemsBeforeAdd.getEntries().size() == 0; + HubItemsManageResponseV2025R0 addedHubItems = + client + .getHubItems() + .manageHubItemsV2025R0( + createdHub.getId(), + new HubItemsManageRequestV2025R0.Builder() + .operations( + Arrays.asList( + new HubItemOperationV2025R0( + HubItemOperationV2025R0ActionField.ADD, + new FolderReferenceV2025R0(folder.getId())))) + .build()); + HubItemOperationResultV2025R0 addedHubItem = addedHubItems.getOperations().get(0); + assert convertToString(addedHubItem.getAction()).equals("add"); + assert addedHubItem.getStatus() == 200; + assert addedHubItem.getItem().getId().equals(folder.getId()); + assert addedHubItem.getItem().getType().equals("folder"); + HubItemsV2025R0 hubItemsAfterAdd = + client + .getHubItems() + .getHubItemsV2025R0(new GetHubItemsV2025R0QueryParams(createdHub.getId())); + assert hubItemsAfterAdd.getEntries().size() == 1; + HubItemsManageResponseV2025R0 removedHubItems = + client + .getHubItems() + .manageHubItemsV2025R0( + createdHub.getId(), + new HubItemsManageRequestV2025R0.Builder() + .operations( + Arrays.asList( + new HubItemOperationV2025R0( + HubItemOperationV2025R0ActionField.REMOVE, + new FolderReferenceV2025R0(folder.getId())))) + .build()); + HubItemOperationResultV2025R0 removedHubItem = removedHubItems.getOperations().get(0); + assert convertToString(removedHubItem.getAction()).equals("remove"); + assert removedHubItem.getStatus() == 200; + assert removedHubItem.getItem().getId().equals(folder.getId()); + assert removedHubItem.getItem().getType().equals("folder"); + HubItemsV2025R0 hubItemsAfterRemove = + client + .getHubItems() + .getHubItemsV2025R0(new GetHubItemsV2025R0QueryParams(createdHub.getId())); + assert hubItemsAfterRemove.getEntries().size() == 0; + client.getHubs().deleteHubByIdV2025R0(createdHub.getId()); + client.getFolders().deleteFolderById(folder.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/hubs/HubsITest.java b/src/intTest/java/com/box/sdkgen/hubs/HubsITest.java new file mode 100644 index 000000000..913d02863 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/hubs/HubsITest.java @@ -0,0 +1,105 @@ +package com.box.sdkgen.hubs; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClientWithUserSubject; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.getEnvVar; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.hubs.GetEnterpriseHubsV2025R0QueryParams; +import com.box.sdkgen.managers.hubs.GetEnterpriseHubsV2025R0QueryParamsDirectionField; +import com.box.sdkgen.managers.hubs.GetHubsV2025R0QueryParams; +import com.box.sdkgen.managers.hubs.GetHubsV2025R0QueryParamsDirectionField; +import com.box.sdkgen.schemas.v2025r0.hubcopyrequestv2025r0.HubCopyRequestV2025R0; +import com.box.sdkgen.schemas.v2025r0.hubcreaterequestv2025r0.HubCreateRequestV2025R0; +import com.box.sdkgen.schemas.v2025r0.hubsv2025r0.HubsV2025R0; +import com.box.sdkgen.schemas.v2025r0.hubupdaterequestv2025r0.HubUpdateRequestV2025R0; +import com.box.sdkgen.schemas.v2025r0.hubv2025r0.HubV2025R0; +import org.junit.jupiter.api.Test; + +public class HubsITest { + + private static final BoxClient client = getDefaultClientWithUserSubject(getEnvVar("USER_ID")); + + @Test + public void testCreateUpdateGetAndDeleteHubs() { + String hubTitle = getUuid(); + String hubDescription = "new Hub description"; + HubV2025R0 createdHub = + client + .getHubs() + .createHubV2025R0( + new HubCreateRequestV2025R0.Builder(hubTitle).description(hubDescription).build()); + assert createdHub.getTitle().equals(hubTitle); + assert createdHub.getDescription().equals(hubDescription); + assert convertToString(createdHub.getType()).equals("hubs"); + String hubId = createdHub.getId(); + HubsV2025R0 usersHubs = + client + .getHubs() + .getHubsV2025R0( + new GetHubsV2025R0QueryParams.Builder() + .scope("all") + .sort("name") + .direction(GetHubsV2025R0QueryParamsDirectionField.ASC) + .build()); + assert usersHubs.getEntries().size() > 0; + HubsV2025R0 enterpriseHubs = + client + .getHubs() + .getEnterpriseHubsV2025R0( + new GetEnterpriseHubsV2025R0QueryParams.Builder() + .sort("name") + .direction(GetEnterpriseHubsV2025R0QueryParamsDirectionField.ASC) + .build()); + assert enterpriseHubs.getEntries().size() > 0; + HubV2025R0 hubById = client.getHubs().getHubByIdV2025R0(hubId); + assert hubById.getId().equals(hubId); + assert hubById.getTitle().equals(hubTitle); + assert hubById.getDescription().equals(hubDescription); + assert convertToString(hubById.getType()).equals("hubs"); + String newHubTitle = getUuid(); + String newHubDescription = "updated Hub description"; + HubV2025R0 updatedHub = + client + .getHubs() + .updateHubByIdV2025R0( + hubId, + new HubUpdateRequestV2025R0.Builder() + .title(newHubTitle) + .description(newHubDescription) + .build()); + assert updatedHub.getTitle().equals(newHubTitle); + assert updatedHub.getDescription().equals(newHubDescription); + client.getHubs().deleteHubByIdV2025R0(hubId); + assertThrows(RuntimeException.class, () -> client.getHubs().deleteHubByIdV2025R0(hubId)); + } + + @Test + public void copyHub() { + String hubTitle = getUuid(); + String hubDescription = "new Hub description"; + HubV2025R0 createdHub = + client + .getHubs() + .createHubV2025R0( + new HubCreateRequestV2025R0.Builder(hubTitle).description(hubDescription).build()); + String copiedHubTitle = getUuid(); + String copiedHubDescription = "copied Hub description"; + HubV2025R0 copiedHub = + client + .getHubs() + .copyHubV2025R0( + createdHub.getId(), + new HubCopyRequestV2025R0.Builder() + .title(copiedHubTitle) + .description(copiedHubDescription) + .build()); + assert !(copiedHub.getId().equals(createdHub.getId())); + assert copiedHub.getTitle().equals(copiedHubTitle); + assert copiedHub.getDescription().equals(copiedHubDescription); + client.getHubs().deleteHubByIdV2025R0(createdHub.getId()); + client.getHubs().deleteHubByIdV2025R0(copiedHub.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/integrationmappings/IntegrationMappingsITest.java b/src/intTest/java/com/box/sdkgen/integrationmappings/IntegrationMappingsITest.java new file mode 100644 index 000000000..78edeb454 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/integrationmappings/IntegrationMappingsITest.java @@ -0,0 +1,151 @@ +package com.box.sdkgen.integrationmappings; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.commons.CommonsManager.getDefaultClientWithUserSubject; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.getEnvVar; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.folders.CreateFolderRequestBody; +import com.box.sdkgen.managers.folders.CreateFolderRequestBodyParentField; +import com.box.sdkgen.managers.integrationmappings.UpdateSlackIntegrationMappingByIdRequestBody; +import com.box.sdkgen.managers.integrationmappings.UpdateTeamsIntegrationMappingByIdRequestBody; +import com.box.sdkgen.managers.usercollaborations.CreateCollaborationRequestBody; +import com.box.sdkgen.managers.usercollaborations.CreateCollaborationRequestBodyAccessibleByField; +import com.box.sdkgen.managers.usercollaborations.CreateCollaborationRequestBodyAccessibleByTypeField; +import com.box.sdkgen.managers.usercollaborations.CreateCollaborationRequestBodyItemField; +import com.box.sdkgen.managers.usercollaborations.CreateCollaborationRequestBodyItemTypeField; +import com.box.sdkgen.managers.usercollaborations.CreateCollaborationRequestBodyRoleField; +import com.box.sdkgen.schemas.folderfull.FolderFull; +import com.box.sdkgen.schemas.folderreference.FolderReference; +import com.box.sdkgen.schemas.integrationmapping.IntegrationMapping; +import com.box.sdkgen.schemas.integrationmappingboxitemslack.IntegrationMappingBoxItemSlack; +import com.box.sdkgen.schemas.integrationmappingpartneritemslack.IntegrationMappingPartnerItemSlack; +import com.box.sdkgen.schemas.integrationmappingpartneritemteamscreaterequest.IntegrationMappingPartnerItemTeamsCreateRequest; +import com.box.sdkgen.schemas.integrationmappingpartneritemteamscreaterequest.IntegrationMappingPartnerItemTeamsCreateRequestTypeField; +import com.box.sdkgen.schemas.integrationmappings.IntegrationMappings; +import com.box.sdkgen.schemas.integrationmappingslackcreaterequest.IntegrationMappingSlackCreateRequest; +import com.box.sdkgen.schemas.integrationmappingteamscreaterequest.IntegrationMappingTeamsCreateRequest; +import org.junit.jupiter.api.Test; + +public class IntegrationMappingsITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testSlackIntegrationMappings() { + String userId = getEnvVar("USER_ID"); + String slackAutomationUserId = getEnvVar("SLACK_AUTOMATION_USER_ID"); + String slackOrgId = getEnvVar("SLACK_ORG_ID"); + String slackPartnerItemId = getEnvVar("SLACK_PARTNER_ITEM_ID"); + BoxClient userClient = getDefaultClientWithUserSubject(userId); + FolderFull folder = + userClient + .getFolders() + .createFolder( + new CreateFolderRequestBody( + getUuid(), new CreateFolderRequestBodyParentField("0"))); + userClient + .getUserCollaborations() + .createCollaboration( + new CreateCollaborationRequestBody( + new CreateCollaborationRequestBodyItemField.Builder() + .type(CreateCollaborationRequestBodyItemTypeField.FOLDER) + .id(folder.getId()) + .build(), + new CreateCollaborationRequestBodyAccessibleByField.Builder( + CreateCollaborationRequestBodyAccessibleByTypeField.USER) + .id(slackAutomationUserId) + .build(), + CreateCollaborationRequestBodyRoleField.CO_OWNER)); + IntegrationMappings slackIntegrations = + userClient.getIntegrationMappings().getSlackIntegrationMapping(); + if (slackIntegrations.getEntries().size() == 0) { + userClient + .getIntegrationMappings() + .createSlackIntegrationMapping( + new IntegrationMappingSlackCreateRequest( + new IntegrationMappingPartnerItemSlack.Builder(slackPartnerItemId) + .slackOrgId(slackOrgId) + .build(), + new IntegrationMappingBoxItemSlack(folder.getId()))); + } + IntegrationMappings slackMappings = + userClient.getIntegrationMappings().getSlackIntegrationMapping(); + assert slackMappings.getEntries().size() >= 1; + IntegrationMapping slackIntegrationMapping = slackMappings.getEntries().get(0); + assert convertToString(slackIntegrationMapping.getIntegrationType()).equals("slack"); + assert convertToString(slackIntegrationMapping.getType()).equals("integration_mapping"); + assert convertToString(slackIntegrationMapping.getBoxItem().getType()).equals("folder"); + assert slackIntegrationMapping.getPartnerItem().getId().equals(slackPartnerItemId); + assert slackIntegrationMapping.getPartnerItem().getSlackWorkspaceId().equals(slackOrgId); + assert convertToString(slackIntegrationMapping.getPartnerItem().getType()).equals("channel"); + IntegrationMapping updatedSlackMapping = + userClient + .getIntegrationMappings() + .updateSlackIntegrationMappingById( + slackIntegrationMapping.getId(), + new UpdateSlackIntegrationMappingByIdRequestBody.Builder() + .boxItem(new IntegrationMappingBoxItemSlack(folder.getId())) + .build()); + assert convertToString(updatedSlackMapping.getBoxItem().getType()).equals("folder"); + assert updatedSlackMapping.getBoxItem().getId().equals(folder.getId()); + if (slackMappings.getEntries().size() > 2) { + userClient + .getIntegrationMappings() + .deleteSlackIntegrationMappingById(slackIntegrationMapping.getId()); + } + userClient.getFolders().deleteFolderById(folder.getId()); + } + + @Test + public void testTeamsIntegrationMappings() { + FolderFull folder = + client + .getFolders() + .createFolder( + new CreateFolderRequestBody( + getUuid(), new CreateFolderRequestBodyParentField("0"))); + String tenantId = "1"; + String teamId = "2"; + String partnerItemId = "3"; + String userId = getEnvVar("USER_ID"); + BoxClient userClient = getDefaultClientWithUserSubject(userId); + assertThrows( + RuntimeException.class, + () -> + userClient + .getIntegrationMappings() + .createTeamsIntegrationMapping( + new IntegrationMappingTeamsCreateRequest( + new IntegrationMappingPartnerItemTeamsCreateRequest( + IntegrationMappingPartnerItemTeamsCreateRequestTypeField.CHANNEL, + partnerItemId, + tenantId, + teamId), + new FolderReference(folder.getId())))); + assertThrows( + RuntimeException.class, + () -> userClient.getIntegrationMappings().getTeamsIntegrationMapping()); + String integrationMappingId = "123456"; + assertThrows( + RuntimeException.class, + () -> + userClient + .getIntegrationMappings() + .updateTeamsIntegrationMappingById( + integrationMappingId, + new UpdateTeamsIntegrationMappingByIdRequestBody.Builder() + .boxItem(new FolderReference("1234567")) + .build())); + assertThrows( + RuntimeException.class, + () -> + userClient + .getIntegrationMappings() + .deleteTeamsIntegrationMappingById(integrationMappingId)); + client.getFolders().deleteFolderById(folder.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/invites/InvitesITest.java b/src/intTest/java/com/box/sdkgen/invites/InvitesITest.java new file mode 100644 index 000000000..b2e144fae --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/invites/InvitesITest.java @@ -0,0 +1,42 @@ +package com.box.sdkgen.invites; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClientWithUserSubject; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.getEnvVar; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.invites.CreateInviteRequestBody; +import com.box.sdkgen.managers.invites.CreateInviteRequestBodyActionableByField; +import com.box.sdkgen.managers.invites.CreateInviteRequestBodyEnterpriseField; +import com.box.sdkgen.managers.users.GetUserMeQueryParams; +import com.box.sdkgen.schemas.invite.Invite; +import com.box.sdkgen.schemas.userfull.UserFull; +import java.util.Arrays; +import org.junit.jupiter.api.Test; + +public class InvitesITest { + + @Test + public void testInvites() { + String userId = getEnvVar("USER_ID"); + BoxClient client = getDefaultClientWithUserSubject(userId); + UserFull currentUser = + client + .getUsers() + .getUserMe( + new GetUserMeQueryParams.Builder().fields(Arrays.asList("enterprise")).build()); + String email = getEnvVar("BOX_EXTERNAL_USER_EMAIL"); + Invite invitation = + client + .getInvites() + .createInvite( + new CreateInviteRequestBody( + new CreateInviteRequestBodyEnterpriseField(currentUser.getEnterprise().getId()), + new CreateInviteRequestBodyActionableByField.Builder().login(email).build())); + assert convertToString(invitation.getType()).equals("invite"); + assert invitation.getInvitedTo().getId().equals(currentUser.getEnterprise().getId()); + assert invitation.getActionableBy().getLogin().equals(email); + Invite getInvitation = client.getInvites().getInviteById(invitation.getId()); + assert getInvitation.getId().equals(invitation.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/legalholdpolicies/LegalHoldPoliciesITest.java b/src/intTest/java/com/box/sdkgen/legalholdpolicies/LegalHoldPoliciesITest.java new file mode 100644 index 000000000..3634ba4ff --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/legalholdpolicies/LegalHoldPoliciesITest.java @@ -0,0 +1,77 @@ +package com.box.sdkgen.legalholdpolicies; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.internal.utils.UtilsManager.dateTimeFromString; +import static com.box.sdkgen.internal.utils.UtilsManager.dateTimeToString; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.legalholdpolicies.CreateLegalHoldPolicyRequestBody; +import com.box.sdkgen.managers.legalholdpolicies.UpdateLegalHoldPolicyByIdRequestBody; +import com.box.sdkgen.schemas.legalholdpolicies.LegalHoldPolicies; +import com.box.sdkgen.schemas.legalholdpolicy.LegalHoldPolicy; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; + +public class LegalHoldPoliciesITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testCreateNotOngoingLegalHoldPolicy() { + String legalHoldPolicyName = getUuid(); + String legalHoldDescription = "test description"; + OffsetDateTime filterStartedAt = dateTimeFromString("2021-01-01T00:00:00-08:00"); + OffsetDateTime filterEndedAt = dateTimeFromString("2022-01-01T00:00:00-08:00"); + LegalHoldPolicy legalHoldPolicy = + client + .getLegalHoldPolicies() + .createLegalHoldPolicy( + new CreateLegalHoldPolicyRequestBody.Builder(legalHoldPolicyName) + .description(legalHoldDescription) + .filterStartedAt(filterStartedAt) + .filterEndedAt(filterEndedAt) + .isOngoing(false) + .build()); + assert legalHoldPolicy.getPolicyName().equals(legalHoldPolicyName); + assert legalHoldPolicy.getDescription().equals(legalHoldDescription); + assert dateTimeToString(legalHoldPolicy.getFilterStartedAt()) + .equals(dateTimeToString(filterStartedAt)); + assert dateTimeToString(legalHoldPolicy.getFilterEndedAt()) + .equals(dateTimeToString(filterEndedAt)); + client.getLegalHoldPolicies().deleteLegalHoldPolicyById(legalHoldPolicy.getId()); + } + + @Test + public void testCreateUpdateGetDeleteLegalHoldPolicy() { + String legalHoldPolicyName = getUuid(); + String legalHoldDescription = "test description"; + LegalHoldPolicy legalHoldPolicy = + client + .getLegalHoldPolicies() + .createLegalHoldPolicy( + new CreateLegalHoldPolicyRequestBody.Builder(legalHoldPolicyName) + .description(legalHoldDescription) + .isOngoing(true) + .build()); + assert legalHoldPolicy.getPolicyName().equals(legalHoldPolicyName); + assert legalHoldPolicy.getDescription().equals(legalHoldDescription); + String legalHoldPolicyId = legalHoldPolicy.getId(); + LegalHoldPolicy legalHoldPolicyById = + client.getLegalHoldPolicies().getLegalHoldPolicyById(legalHoldPolicyId); + assert legalHoldPolicyById.getId().equals(legalHoldPolicyId); + LegalHoldPolicies legalHoldPolicies = client.getLegalHoldPolicies().getLegalHoldPolicies(); + assert legalHoldPolicies.getEntries().size() > 0; + String updatedLegalHoldPolicyName = getUuid(); + LegalHoldPolicy updatedLegalHoldPolicy = + client + .getLegalHoldPolicies() + .updateLegalHoldPolicyById( + legalHoldPolicyId, + new UpdateLegalHoldPolicyByIdRequestBody.Builder() + .policyName(updatedLegalHoldPolicyName) + .build()); + assert updatedLegalHoldPolicy.getPolicyName().equals(updatedLegalHoldPolicyName); + client.getLegalHoldPolicies().deleteLegalHoldPolicyById(legalHoldPolicyId); + } +} diff --git a/src/intTest/java/com/box/sdkgen/legalholdpolicyassignments/LegalHoldPolicyAssignmentsITest.java b/src/intTest/java/com/box/sdkgen/legalholdpolicyassignments/LegalHoldPolicyAssignmentsITest.java new file mode 100644 index 000000000..658b5a25b --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/legalholdpolicyassignments/LegalHoldPolicyAssignmentsITest.java @@ -0,0 +1,86 @@ +package com.box.sdkgen.legalholdpolicyassignments; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.commons.CommonsManager.uploadNewFile; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.legalholdpolicies.CreateLegalHoldPolicyRequestBody; +import com.box.sdkgen.managers.legalholdpolicyassignments.CreateLegalHoldPolicyAssignmentRequestBody; +import com.box.sdkgen.managers.legalholdpolicyassignments.CreateLegalHoldPolicyAssignmentRequestBodyAssignToField; +import com.box.sdkgen.managers.legalholdpolicyassignments.CreateLegalHoldPolicyAssignmentRequestBodyAssignToTypeField; +import com.box.sdkgen.managers.legalholdpolicyassignments.GetLegalHoldPolicyAssignmentsQueryParams; +import com.box.sdkgen.schemas.filefull.FileFull; +import com.box.sdkgen.schemas.filesonhold.FilesOnHold; +import com.box.sdkgen.schemas.legalholdpolicy.LegalHoldPolicy; +import com.box.sdkgen.schemas.legalholdpolicyassignment.LegalHoldPolicyAssignment; +import com.box.sdkgen.schemas.legalholdpolicyassignments.LegalHoldPolicyAssignments; +import org.junit.jupiter.api.Test; + +public class LegalHoldPolicyAssignmentsITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testLegalHoldPolicyAssignments() { + String legalHoldPolicyName = getUuid(); + String legalHoldDescription = "test description"; + LegalHoldPolicy legalHoldPolicy = + client + .getLegalHoldPolicies() + .createLegalHoldPolicy( + new CreateLegalHoldPolicyRequestBody.Builder(legalHoldPolicyName) + .description(legalHoldDescription) + .isOngoing(true) + .build()); + String legalHoldPolicyId = legalHoldPolicy.getId(); + FileFull file = uploadNewFile(); + String fileId = file.getId(); + LegalHoldPolicyAssignment legalHoldPolicyAssignment = + client + .getLegalHoldPolicyAssignments() + .createLegalHoldPolicyAssignment( + new CreateLegalHoldPolicyAssignmentRequestBody( + legalHoldPolicyId, + new CreateLegalHoldPolicyAssignmentRequestBodyAssignToField( + CreateLegalHoldPolicyAssignmentRequestBodyAssignToTypeField.FILE, fileId))); + assert convertToString(legalHoldPolicyAssignment.getLegalHoldPolicy().getType()) + .equals("legal_hold_policy"); + String legalHoldPolicyAssignmentId = legalHoldPolicyAssignment.getId(); + LegalHoldPolicyAssignment legalHoldPolicyAssignmentFromApi = + client + .getLegalHoldPolicyAssignments() + .getLegalHoldPolicyAssignmentById(legalHoldPolicyAssignmentId); + assert legalHoldPolicyAssignmentFromApi.getId().equals(legalHoldPolicyAssignmentId); + LegalHoldPolicyAssignments legalPolicyAssignments = + client + .getLegalHoldPolicyAssignments() + .getLegalHoldPolicyAssignments( + new GetLegalHoldPolicyAssignmentsQueryParams(legalHoldPolicyId)); + assert legalPolicyAssignments.getEntries().size() == 1; + FilesOnHold filesOnHold = + client + .getLegalHoldPolicyAssignments() + .getLegalHoldPolicyAssignmentFileOnHold(legalHoldPolicyAssignmentId); + assert filesOnHold.getEntries().size() == 1; + assert filesOnHold.getEntries().get(0).getId().equals(fileId); + client + .getLegalHoldPolicyAssignments() + .deleteLegalHoldPolicyAssignmentById(legalHoldPolicyAssignmentId); + assertThrows( + RuntimeException.class, + () -> + client + .getLegalHoldPolicyAssignments() + .deleteLegalHoldPolicyAssignmentById(legalHoldPolicyAssignmentId)); + client.getFiles().deleteFileById(fileId); + try { + client.getLegalHoldPolicies().deleteLegalHoldPolicyById(legalHoldPolicyId); + } catch (Exception exception) { + System.out.print( + String.join("", "Could not delete Legal Policy with id: ", legalHoldPolicyId)); + } + } +} diff --git a/src/intTest/java/com/box/sdkgen/listcollaborations/ListCollaborationsITest.java b/src/intTest/java/com/box/sdkgen/listcollaborations/ListCollaborationsITest.java new file mode 100644 index 000000000..fca83bdb8 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/listcollaborations/ListCollaborationsITest.java @@ -0,0 +1,86 @@ +package com.box.sdkgen.listcollaborations; + +import static com.box.sdkgen.commons.CommonsManager.createNewFolder; +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.commons.CommonsManager.uploadNewFile; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.getEnvVar; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.groups.CreateGroupRequestBody; +import com.box.sdkgen.managers.listcollaborations.GetCollaborationsQueryParams; +import com.box.sdkgen.managers.listcollaborations.GetCollaborationsQueryParamsStatusField; +import com.box.sdkgen.managers.usercollaborations.CreateCollaborationRequestBody; +import com.box.sdkgen.managers.usercollaborations.CreateCollaborationRequestBodyAccessibleByField; +import com.box.sdkgen.managers.usercollaborations.CreateCollaborationRequestBodyAccessibleByTypeField; +import com.box.sdkgen.managers.usercollaborations.CreateCollaborationRequestBodyItemField; +import com.box.sdkgen.managers.usercollaborations.CreateCollaborationRequestBodyItemTypeField; +import com.box.sdkgen.managers.usercollaborations.CreateCollaborationRequestBodyRoleField; +import com.box.sdkgen.schemas.collaboration.Collaboration; +import com.box.sdkgen.schemas.collaborations.Collaborations; +import com.box.sdkgen.schemas.collaborationsoffsetpaginated.CollaborationsOffsetPaginated; +import com.box.sdkgen.schemas.filefull.FileFull; +import com.box.sdkgen.schemas.folderfull.FolderFull; +import com.box.sdkgen.schemas.groupfull.GroupFull; +import org.junit.jupiter.api.Test; + +public class ListCollaborationsITest { + + @Test + public void testListCollaborations() { + BoxClient client = getDefaultClient(); + FolderFull folder = createNewFolder(); + FileFull file = uploadNewFile(); + GroupFull group = client.getGroups().createGroup(new CreateGroupRequestBody(getUuid())); + Collaboration groupCollaboration = + client + .getUserCollaborations() + .createCollaboration( + new CreateCollaborationRequestBody( + new CreateCollaborationRequestBodyItemField.Builder() + .type(CreateCollaborationRequestBodyItemTypeField.FOLDER) + .id(folder.getId()) + .build(), + new CreateCollaborationRequestBodyAccessibleByField.Builder( + CreateCollaborationRequestBodyAccessibleByTypeField.GROUP) + .id(group.getId()) + .build(), + CreateCollaborationRequestBodyRoleField.EDITOR)); + Collaboration fileCollaboration = + client + .getUserCollaborations() + .createCollaboration( + new CreateCollaborationRequestBody( + new CreateCollaborationRequestBodyItemField.Builder() + .type(CreateCollaborationRequestBodyItemTypeField.FILE) + .id(file.getId()) + .build(), + new CreateCollaborationRequestBodyAccessibleByField.Builder( + CreateCollaborationRequestBodyAccessibleByTypeField.USER) + .id(getEnvVar("USER_ID")) + .build(), + CreateCollaborationRequestBodyRoleField.EDITOR)); + assert convertToString(groupCollaboration.getRole()).equals("editor"); + assert convertToString(groupCollaboration.getType()).equals("collaboration"); + Collaborations fileCollaborations = + client.getListCollaborations().getFileCollaborations(file.getId()); + assert fileCollaborations.getEntries().size() > 0; + Collaborations folderCollaborations = + client.getListCollaborations().getFolderCollaborations(folder.getId()); + assert folderCollaborations.getEntries().size() > 0; + CollaborationsOffsetPaginated pendingCollaborations = + client + .getListCollaborations() + .getCollaborations( + new GetCollaborationsQueryParams(GetCollaborationsQueryParamsStatusField.PENDING)); + assert pendingCollaborations.getEntries().size() >= 0; + CollaborationsOffsetPaginated groupCollaborations = + client.getListCollaborations().getGroupCollaborations(group.getId()); + assert groupCollaborations.getEntries().size() > 0; + client.getUserCollaborations().deleteCollaborationById(groupCollaboration.getId()); + client.getFiles().deleteFileById(file.getId()); + client.getFolders().deleteFolderById(folder.getId()); + client.getGroups().deleteGroupById(group.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/memberships/MembershipsITest.java b/src/intTest/java/com/box/sdkgen/memberships/MembershipsITest.java new file mode 100644 index 000000000..d49317cfb --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/memberships/MembershipsITest.java @@ -0,0 +1,70 @@ +package com.box.sdkgen.memberships; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.groups.CreateGroupRequestBody; +import com.box.sdkgen.managers.memberships.CreateGroupMembershipRequestBody; +import com.box.sdkgen.managers.memberships.CreateGroupMembershipRequestBodyGroupField; +import com.box.sdkgen.managers.memberships.CreateGroupMembershipRequestBodyUserField; +import com.box.sdkgen.managers.memberships.UpdateGroupMembershipByIdRequestBody; +import com.box.sdkgen.managers.memberships.UpdateGroupMembershipByIdRequestBodyRoleField; +import com.box.sdkgen.managers.users.CreateUserRequestBody; +import com.box.sdkgen.schemas.groupfull.GroupFull; +import com.box.sdkgen.schemas.groupmembership.GroupMembership; +import com.box.sdkgen.schemas.groupmemberships.GroupMemberships; +import com.box.sdkgen.schemas.userfull.UserFull; +import org.junit.jupiter.api.Test; + +public class MembershipsITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testMemberships() { + UserFull user = + client + .getUsers() + .createUser( + new CreateUserRequestBody.Builder(getUuid()) + .login(String.join("", getUuid(), "@boxdemo.com")) + .build()); + GroupMemberships userMemberships = client.getMemberships().getUserMemberships(user.getId()); + assert userMemberships.getTotalCount() == 0; + GroupFull group = client.getGroups().createGroup(new CreateGroupRequestBody(getUuid())); + GroupMemberships groupMemberships = client.getMemberships().getGroupMemberships(group.getId()); + assert groupMemberships.getTotalCount() == 0; + GroupMembership groupMembership = + client + .getMemberships() + .createGroupMembership( + new CreateGroupMembershipRequestBody( + new CreateGroupMembershipRequestBodyUserField(user.getId()), + new CreateGroupMembershipRequestBodyGroupField(group.getId()))); + assert groupMembership.getUser().getId().equals(user.getId()); + assert groupMembership.getGroup().getId().equals(group.getId()); + assert convertToString(groupMembership.getRole()).equals("member"); + GroupMembership getGroupMembership = + client.getMemberships().getGroupMembershipById(groupMembership.getId()); + assert getGroupMembership.getId().equals(groupMembership.getId()); + GroupMembership updatedGroupMembership = + client + .getMemberships() + .updateGroupMembershipById( + groupMembership.getId(), + new UpdateGroupMembershipByIdRequestBody.Builder() + .role(UpdateGroupMembershipByIdRequestBodyRoleField.ADMIN) + .build()); + assert updatedGroupMembership.getId().equals(groupMembership.getId()); + assert convertToString(updatedGroupMembership.getRole()).equals("admin"); + client.getMemberships().deleteGroupMembershipById(groupMembership.getId()); + assertThrows( + RuntimeException.class, + () -> client.getMemberships().getGroupMembershipById(groupMembership.getId())); + client.getGroups().deleteGroupById(group.getId()); + client.getUsers().deleteUserById(user.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/metadatacascadepolicies/MetadataCascadePoliciesITest.java b/src/intTest/java/com/box/sdkgen/metadatacascadepolicies/MetadataCascadePoliciesITest.java new file mode 100644 index 000000000..9bcfe10a3 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/metadatacascadepolicies/MetadataCascadePoliciesITest.java @@ -0,0 +1,106 @@ +package com.box.sdkgen.metadatacascadepolicies; + +import static com.box.sdkgen.commons.CommonsManager.createNewFolder; +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.entryOf; +import static com.box.sdkgen.internal.utils.UtilsManager.getEnvVar; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; +import static com.box.sdkgen.internal.utils.UtilsManager.mapOf; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.foldermetadata.CreateFolderMetadataByIdScope; +import com.box.sdkgen.managers.metadatacascadepolicies.ApplyMetadataCascadePolicyRequestBody; +import com.box.sdkgen.managers.metadatacascadepolicies.ApplyMetadataCascadePolicyRequestBodyConflictResolutionField; +import com.box.sdkgen.managers.metadatacascadepolicies.CreateMetadataCascadePolicyRequestBody; +import com.box.sdkgen.managers.metadatacascadepolicies.CreateMetadataCascadePolicyRequestBodyScopeField; +import com.box.sdkgen.managers.metadatacascadepolicies.GetMetadataCascadePoliciesQueryParams; +import com.box.sdkgen.managers.metadatatemplates.CreateMetadataTemplateRequestBody; +import com.box.sdkgen.managers.metadatatemplates.CreateMetadataTemplateRequestBodyFieldsField; +import com.box.sdkgen.managers.metadatatemplates.CreateMetadataTemplateRequestBodyFieldsTypeField; +import com.box.sdkgen.managers.metadatatemplates.DeleteMetadataTemplateScope; +import com.box.sdkgen.schemas.folderfull.FolderFull; +import com.box.sdkgen.schemas.metadatacascadepolicies.MetadataCascadePolicies; +import com.box.sdkgen.schemas.metadatacascadepolicy.MetadataCascadePolicy; +import java.util.Arrays; +import org.junit.jupiter.api.Test; + +public class MetadataCascadePoliciesITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testMetadataCascadePolicies() { + String templateKey = String.join("", "key", getUuid()); + client + .getMetadataTemplates() + .createMetadataTemplate( + new CreateMetadataTemplateRequestBody.Builder("enterprise", templateKey) + .templateKey(templateKey) + .fields( + Arrays.asList( + new CreateMetadataTemplateRequestBodyFieldsField( + CreateMetadataTemplateRequestBodyFieldsTypeField.STRING, + "testName", + "testName"))) + .build()); + FolderFull folder = createNewFolder(); + String enterpriseId = getEnvVar("ENTERPRISE_ID"); + MetadataCascadePolicy cascadePolicy = + client + .getMetadataCascadePolicies() + .createMetadataCascadePolicy( + new CreateMetadataCascadePolicyRequestBody( + folder.getId(), + CreateMetadataCascadePolicyRequestBodyScopeField.ENTERPRISE, + templateKey)); + assert convertToString(cascadePolicy.getType()).equals("metadata_cascade_policy"); + assert convertToString(cascadePolicy.getOwnerEnterprise().getType()).equals("enterprise"); + assert convertToString(cascadePolicy.getOwnerEnterprise().getId()).equals(enterpriseId); + assert convertToString(cascadePolicy.getParent().getType()).equals("folder"); + assert cascadePolicy.getParent().getId().equals(folder.getId()); + assert convertToString(cascadePolicy.getScope()) + .equals(String.join("", "enterprise_", enterpriseId)); + assert cascadePolicy.getTemplateKey().equals(templateKey); + String cascadePolicyId = cascadePolicy.getId(); + MetadataCascadePolicy policyFromTheApi = + client.getMetadataCascadePolicies().getMetadataCascadePolicyById(cascadePolicyId); + assert cascadePolicyId.equals(policyFromTheApi.getId()); + MetadataCascadePolicies policies = + client + .getMetadataCascadePolicies() + .getMetadataCascadePolicies(new GetMetadataCascadePoliciesQueryParams(folder.getId())); + assert policies.getEntries().size() == 1; + assertThrows( + RuntimeException.class, + () -> + client + .getMetadataCascadePolicies() + .applyMetadataCascadePolicy( + cascadePolicyId, + new ApplyMetadataCascadePolicyRequestBody( + ApplyMetadataCascadePolicyRequestBodyConflictResolutionField.OVERWRITE))); + client + .getFolderMetadata() + .createFolderMetadataById( + folder.getId(), + CreateFolderMetadataByIdScope.ENTERPRISE, + templateKey, + mapOf(entryOf("testName", "xyz"))); + client + .getMetadataCascadePolicies() + .applyMetadataCascadePolicy( + cascadePolicyId, + new ApplyMetadataCascadePolicyRequestBody( + ApplyMetadataCascadePolicyRequestBodyConflictResolutionField.OVERWRITE)); + client.getMetadataCascadePolicies().deleteMetadataCascadePolicyById(cascadePolicyId); + assertThrows( + RuntimeException.class, + () -> client.getMetadataCascadePolicies().getMetadataCascadePolicyById(cascadePolicyId)); + client + .getMetadataTemplates() + .deleteMetadataTemplate(DeleteMetadataTemplateScope.ENTERPRISE, templateKey); + client.getFolders().deleteFolderById(folder.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/metadatatemplates/MetadataTemplatesITest.java b/src/intTest/java/com/box/sdkgen/metadatatemplates/MetadataTemplatesITest.java new file mode 100644 index 000000000..9fa9b29f5 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/metadatatemplates/MetadataTemplatesITest.java @@ -0,0 +1,185 @@ +package com.box.sdkgen.metadatatemplates; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.commons.CommonsManager.uploadNewFile; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.entryOf; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; +import static com.box.sdkgen.internal.utils.UtilsManager.mapOf; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.filemetadata.CreateFileMetadataByIdScope; +import com.box.sdkgen.managers.filemetadata.DeleteFileMetadataByIdScope; +import com.box.sdkgen.managers.metadatatemplates.CreateMetadataTemplateRequestBody; +import com.box.sdkgen.managers.metadatatemplates.CreateMetadataTemplateRequestBodyFieldsField; +import com.box.sdkgen.managers.metadatatemplates.CreateMetadataTemplateRequestBodyFieldsOptionsField; +import com.box.sdkgen.managers.metadatatemplates.CreateMetadataTemplateRequestBodyFieldsTypeField; +import com.box.sdkgen.managers.metadatatemplates.DeleteMetadataTemplateScope; +import com.box.sdkgen.managers.metadatatemplates.GetMetadataTemplateScope; +import com.box.sdkgen.managers.metadatatemplates.GetMetadataTemplatesByInstanceIdQueryParams; +import com.box.sdkgen.managers.metadatatemplates.UpdateMetadataTemplateRequestBody; +import com.box.sdkgen.managers.metadatatemplates.UpdateMetadataTemplateRequestBodyOpField; +import com.box.sdkgen.managers.metadatatemplates.UpdateMetadataTemplateScope; +import com.box.sdkgen.schemas.filefull.FileFull; +import com.box.sdkgen.schemas.metadatafull.MetadataFull; +import com.box.sdkgen.schemas.metadatatemplate.MetadataTemplate; +import com.box.sdkgen.schemas.metadatatemplates.MetadataTemplates; +import java.util.Arrays; +import org.junit.jupiter.api.Test; + +public class MetadataTemplatesITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testMetadataTemplates() { + String templateKey = String.join("", "key", getUuid()); + MetadataTemplate template = + client + .getMetadataTemplates() + .createMetadataTemplate( + new CreateMetadataTemplateRequestBody.Builder("enterprise", templateKey) + .templateKey(templateKey) + .fields( + Arrays.asList( + new CreateMetadataTemplateRequestBodyFieldsField( + CreateMetadataTemplateRequestBodyFieldsTypeField.STRING, + "testName", + "testName"), + new CreateMetadataTemplateRequestBodyFieldsField( + CreateMetadataTemplateRequestBodyFieldsTypeField.FLOAT, + "age", + "age"), + new CreateMetadataTemplateRequestBodyFieldsField( + CreateMetadataTemplateRequestBodyFieldsTypeField.DATE, + "birthDate", + "birthDate"), + new CreateMetadataTemplateRequestBodyFieldsField.Builder( + CreateMetadataTemplateRequestBodyFieldsTypeField.ENUM, + "countryCode", + "countryCode") + .options( + Arrays.asList( + new CreateMetadataTemplateRequestBodyFieldsOptionsField( + "US"), + new CreateMetadataTemplateRequestBodyFieldsOptionsField( + "CA"))) + .build(), + new CreateMetadataTemplateRequestBodyFieldsField.Builder( + CreateMetadataTemplateRequestBodyFieldsTypeField.MULTISELECT, + "sports", + "sports") + .options( + Arrays.asList( + new CreateMetadataTemplateRequestBodyFieldsOptionsField( + "basketball"), + new CreateMetadataTemplateRequestBodyFieldsOptionsField( + "football"), + new CreateMetadataTemplateRequestBodyFieldsOptionsField( + "tennis"))) + .build())) + .build()); + assert template.getTemplateKey().equals(templateKey); + assert template.getDisplayName().equals(templateKey); + assert template.getFields().size() == 5; + assert template.getFields().get(0).getKey().equals("testName"); + assert template.getFields().get(0).getDisplayName().equals("testName"); + assert convertToString(template.getFields().get(0).getType()).equals("string"); + assert template.getFields().get(1).getKey().equals("age"); + assert template.getFields().get(1).getDisplayName().equals("age"); + assert convertToString(template.getFields().get(1).getType()).equals("float"); + assert template.getFields().get(2).getKey().equals("birthDate"); + assert template.getFields().get(2).getDisplayName().equals("birthDate"); + assert convertToString(template.getFields().get(2).getType()).equals("date"); + assert template.getFields().get(3).getKey().equals("countryCode"); + assert template.getFields().get(3).getDisplayName().equals("countryCode"); + assert convertToString(template.getFields().get(3).getType()).equals("enum"); + assert template.getFields().get(4).getKey().equals("sports"); + assert template.getFields().get(4).getDisplayName().equals("sports"); + assert convertToString(template.getFields().get(4).getType()).equals("multiSelect"); + MetadataTemplate updatedTemplate = + client + .getMetadataTemplates() + .updateMetadataTemplate( + UpdateMetadataTemplateScope.ENTERPRISE, + templateKey, + Arrays.asList( + new UpdateMetadataTemplateRequestBody.Builder( + UpdateMetadataTemplateRequestBodyOpField.ADDFIELD) + .data( + mapOf( + entryOf("type", "string"), entryOf("displayName", "newFieldName"))) + .fieldKey("newfieldname") + .build())); + assert updatedTemplate.getFields().size() == 6; + assert updatedTemplate.getFields().get(5).getKey().equals("newfieldname"); + assert updatedTemplate.getFields().get(5).getDisplayName().equals("newFieldName"); + MetadataTemplate getMetadataTemplate = + client.getMetadataTemplates().getMetadataTemplateById(template.getId()); + assert getMetadataTemplate.getId().equals(template.getId()); + MetadataTemplate getMetadataTemplateSchema = + client + .getMetadataTemplates() + .getMetadataTemplate(GetMetadataTemplateScope.ENTERPRISE, template.getTemplateKey()); + assert getMetadataTemplateSchema.getId().equals(template.getId()); + MetadataTemplates enterpriseMetadataTemplates = + client.getMetadataTemplates().getEnterpriseMetadataTemplates(); + assert enterpriseMetadataTemplates.getEntries().size() > 0; + MetadataTemplates globalMetadataTemplates = + client.getMetadataTemplates().getGlobalMetadataTemplates(); + assert globalMetadataTemplates.getEntries().size() > 0; + client + .getMetadataTemplates() + .deleteMetadataTemplate(DeleteMetadataTemplateScope.ENTERPRISE, template.getTemplateKey()); + assertThrows( + RuntimeException.class, + () -> + client + .getMetadataTemplates() + .deleteMetadataTemplate( + DeleteMetadataTemplateScope.ENTERPRISE, template.getTemplateKey())); + } + + @Test + public void testGetMetadataTemplateByInstance() { + FileFull file = uploadNewFile(); + String templateKey = String.join("", "key", getUuid()); + MetadataTemplate template = + client + .getMetadataTemplates() + .createMetadataTemplate( + new CreateMetadataTemplateRequestBody.Builder("enterprise", templateKey) + .templateKey(templateKey) + .fields( + Arrays.asList( + new CreateMetadataTemplateRequestBodyFieldsField( + CreateMetadataTemplateRequestBodyFieldsTypeField.STRING, + "testName", + "testName"))) + .build()); + MetadataFull createdMetadataInstance = + client + .getFileMetadata() + .createFileMetadataById( + file.getId(), + CreateFileMetadataByIdScope.ENTERPRISE, + templateKey, + mapOf(entryOf("testName", "xyz"))); + MetadataTemplates metadataTemplates = + client + .getMetadataTemplates() + .getMetadataTemplatesByInstanceId( + new GetMetadataTemplatesByInstanceIdQueryParams(createdMetadataInstance.getId())); + assert metadataTemplates.getEntries().size() == 1; + assert metadataTemplates.getEntries().get(0).getDisplayName().equals(templateKey); + assert metadataTemplates.getEntries().get(0).getTemplateKey().equals(templateKey); + client + .getFileMetadata() + .deleteFileMetadataById(file.getId(), DeleteFileMetadataByIdScope.ENTERPRISE, templateKey); + client + .getMetadataTemplates() + .deleteMetadataTemplate(DeleteMetadataTemplateScope.ENTERPRISE, template.getTemplateKey()); + client.getFiles().deleteFileById(file.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/recentitems/RecentItemsITest.java b/src/intTest/java/com/box/sdkgen/recentitems/RecentItemsITest.java new file mode 100644 index 000000000..c41ad66f8 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/recentitems/RecentItemsITest.java @@ -0,0 +1,18 @@ +package com.box.sdkgen.recentitems; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClientWithUserSubject; +import static com.box.sdkgen.internal.utils.UtilsManager.getEnvVar; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.schemas.recentitems.RecentItems; +import org.junit.jupiter.api.Test; + +public class RecentItemsITest { + + @Test + public void testRecentItems() { + BoxClient client = getDefaultClientWithUserSubject(getEnvVar("USER_ID")); + RecentItems recentItems = client.getRecentItems().getRecentItems(); + assert recentItems.getEntries().size() >= 0; + } +} diff --git a/src/intTest/java/com/box/sdkgen/retentionpolicies/RetentionPoliciesITest.java b/src/intTest/java/com/box/sdkgen/retentionpolicies/RetentionPoliciesITest.java new file mode 100644 index 000000000..19304c31f --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/retentionpolicies/RetentionPoliciesITest.java @@ -0,0 +1,57 @@ +package com.box.sdkgen.retentionpolicies; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.retentionpolicies.CreateRetentionPolicyRequestBody; +import com.box.sdkgen.managers.retentionpolicies.CreateRetentionPolicyRequestBodyDispositionActionField; +import com.box.sdkgen.managers.retentionpolicies.CreateRetentionPolicyRequestBodyPolicyTypeField; +import com.box.sdkgen.managers.retentionpolicies.CreateRetentionPolicyRequestBodyRetentionTypeField; +import com.box.sdkgen.managers.retentionpolicies.UpdateRetentionPolicyByIdRequestBody; +import com.box.sdkgen.schemas.retentionpolicies.RetentionPolicies; +import com.box.sdkgen.schemas.retentionpolicy.RetentionPolicy; +import org.junit.jupiter.api.Test; + +public class RetentionPoliciesITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testCreateUpdateGetDeleteRetentionPolicy() { + String retentionPolicyName = getUuid(); + String retentionDescription = "test description"; + RetentionPolicy retentionPolicy = + client + .getRetentionPolicies() + .createRetentionPolicy( + new CreateRetentionPolicyRequestBody.Builder( + retentionPolicyName, + CreateRetentionPolicyRequestBodyPolicyTypeField.FINITE, + CreateRetentionPolicyRequestBodyDispositionActionField.REMOVE_RETENTION) + .description(retentionDescription) + .retentionLength("1") + .retentionType(CreateRetentionPolicyRequestBodyRetentionTypeField.MODIFIABLE) + .canOwnerExtendRetention(true) + .areOwnersNotified(true) + .build()); + assert retentionPolicy.getPolicyName().equals(retentionPolicyName); + assert retentionPolicy.getDescription().equals(retentionDescription); + RetentionPolicy retentionPolicyById = + client.getRetentionPolicies().getRetentionPolicyById(retentionPolicy.getId()); + assert retentionPolicyById.getId().equals(retentionPolicy.getId()); + RetentionPolicies retentionPolicies = client.getRetentionPolicies().getRetentionPolicies(); + assert retentionPolicies.getEntries().size() > 0; + String updatedRetentionPolicyName = getUuid(); + RetentionPolicy updatedRetentionPolicy = + client + .getRetentionPolicies() + .updateRetentionPolicyById( + retentionPolicy.getId(), + new UpdateRetentionPolicyByIdRequestBody.Builder() + .policyName(updatedRetentionPolicyName) + .build()); + assert updatedRetentionPolicy.getPolicyName().equals(updatedRetentionPolicyName); + client.getRetentionPolicies().deleteRetentionPolicyById(retentionPolicy.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/retentionpolicyassignments/RetentionPolicyAssignmentsITest.java b/src/intTest/java/com/box/sdkgen/retentionpolicyassignments/RetentionPolicyAssignmentsITest.java new file mode 100644 index 000000000..540a482af --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/retentionpolicyassignments/RetentionPolicyAssignmentsITest.java @@ -0,0 +1,115 @@ +package com.box.sdkgen.retentionpolicyassignments; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.internal.utils.UtilsManager.generateByteStream; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.folders.CreateFolderRequestBody; +import com.box.sdkgen.managers.folders.CreateFolderRequestBodyParentField; +import com.box.sdkgen.managers.retentionpolicies.CreateRetentionPolicyRequestBody; +import com.box.sdkgen.managers.retentionpolicies.CreateRetentionPolicyRequestBodyDispositionActionField; +import com.box.sdkgen.managers.retentionpolicies.CreateRetentionPolicyRequestBodyPolicyTypeField; +import com.box.sdkgen.managers.retentionpolicies.CreateRetentionPolicyRequestBodyRetentionTypeField; +import com.box.sdkgen.managers.retentionpolicyassignments.CreateRetentionPolicyAssignmentRequestBody; +import com.box.sdkgen.managers.retentionpolicyassignments.CreateRetentionPolicyAssignmentRequestBodyAssignToField; +import com.box.sdkgen.managers.retentionpolicyassignments.CreateRetentionPolicyAssignmentRequestBodyAssignToTypeField; +import com.box.sdkgen.managers.uploads.UploadFileRequestBody; +import com.box.sdkgen.managers.uploads.UploadFileRequestBodyAttributesField; +import com.box.sdkgen.managers.uploads.UploadFileRequestBodyAttributesParentField; +import com.box.sdkgen.managers.uploads.UploadFileVersionRequestBody; +import com.box.sdkgen.managers.uploads.UploadFileVersionRequestBodyAttributesField; +import com.box.sdkgen.schemas.filefull.FileFull; +import com.box.sdkgen.schemas.files.Files; +import com.box.sdkgen.schemas.filesunderretention.FilesUnderRetention; +import com.box.sdkgen.schemas.folderfull.FolderFull; +import com.box.sdkgen.schemas.retentionpolicy.RetentionPolicy; +import com.box.sdkgen.schemas.retentionpolicyassignment.RetentionPolicyAssignment; +import com.box.sdkgen.schemas.retentionpolicyassignments.RetentionPolicyAssignments; +import org.junit.jupiter.api.Test; + +public class RetentionPolicyAssignmentsITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testCreateUpdateGetDeleteRetentionPolicyAssignment() { + String retentionPolicyName = getUuid(); + String retentionDescription = "test description"; + RetentionPolicy retentionPolicy = + client + .getRetentionPolicies() + .createRetentionPolicy( + new CreateRetentionPolicyRequestBody.Builder( + retentionPolicyName, + CreateRetentionPolicyRequestBodyPolicyTypeField.FINITE, + CreateRetentionPolicyRequestBodyDispositionActionField.REMOVE_RETENTION) + .description(retentionDescription) + .retentionLength("1") + .retentionType(CreateRetentionPolicyRequestBodyRetentionTypeField.MODIFIABLE) + .canOwnerExtendRetention(true) + .areOwnersNotified(true) + .build()); + FolderFull folder = + client + .getFolders() + .createFolder( + new CreateFolderRequestBody( + getUuid(), new CreateFolderRequestBodyParentField("0"))); + Files files = + client + .getUploads() + .uploadFile( + new UploadFileRequestBody( + new UploadFileRequestBodyAttributesField( + getUuid(), new UploadFileRequestBodyAttributesParentField(folder.getId())), + generateByteStream(10))); + FileFull file = files.getEntries().get(0); + Files newVersions = + client + .getUploads() + .uploadFileVersion( + file.getId(), + new UploadFileVersionRequestBody( + new UploadFileVersionRequestBodyAttributesField(getUuid()), + generateByteStream(20))); + FileFull newVersion = newVersions.getEntries().get(0); + RetentionPolicyAssignment retentionPolicyAssignment = + client + .getRetentionPolicyAssignments() + .createRetentionPolicyAssignment( + new CreateRetentionPolicyAssignmentRequestBody( + retentionPolicy.getId(), + new CreateRetentionPolicyAssignmentRequestBodyAssignToField.Builder( + CreateRetentionPolicyAssignmentRequestBodyAssignToTypeField.FOLDER) + .id(folder.getId()) + .build())); + assert retentionPolicyAssignment.getRetentionPolicy().getId().equals(retentionPolicy.getId()); + assert retentionPolicyAssignment.getAssignedTo().getId().equals(folder.getId()); + RetentionPolicyAssignment retentionPolicyAssignmentById = + client + .getRetentionPolicyAssignments() + .getRetentionPolicyAssignmentById(retentionPolicyAssignment.getId()); + assert retentionPolicyAssignmentById.getId().equals(retentionPolicyAssignment.getId()); + RetentionPolicyAssignments retentionPolicyAssignments = + client + .getRetentionPolicyAssignments() + .getRetentionPolicyAssignments(retentionPolicy.getId()); + assert retentionPolicyAssignments.getEntries().size() == 1; + FilesUnderRetention filesUnderRetention = + client + .getRetentionPolicyAssignments() + .getFilesUnderRetentionPolicyAssignment(retentionPolicyAssignment.getId()); + assert filesUnderRetention.getEntries().size() == 1; + client + .getRetentionPolicyAssignments() + .deleteRetentionPolicyAssignmentById(retentionPolicyAssignment.getId()); + RetentionPolicyAssignments retentionPolicyAssignmentsAfterDelete = + client + .getRetentionPolicyAssignments() + .getRetentionPolicyAssignments(retentionPolicy.getId()); + assert retentionPolicyAssignmentsAfterDelete.getEntries().size() == 0; + client.getRetentionPolicies().deleteRetentionPolicyById(retentionPolicy.getId()); + client.getFiles().deleteFileById(file.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/search/SearchITest.java b/src/intTest/java/com/box/sdkgen/search/SearchITest.java new file mode 100644 index 000000000..77d279f89 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/search/SearchITest.java @@ -0,0 +1,284 @@ +package com.box.sdkgen.search; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.dateTimeFromString; +import static com.box.sdkgen.internal.utils.UtilsManager.delayInSeconds; +import static com.box.sdkgen.internal.utils.UtilsManager.entryOf; +import static com.box.sdkgen.internal.utils.UtilsManager.generateByteStream; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; +import static com.box.sdkgen.internal.utils.UtilsManager.mapOf; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.filemetadata.CreateFileMetadataByIdScope; +import com.box.sdkgen.managers.metadatatemplates.CreateMetadataTemplateRequestBody; +import com.box.sdkgen.managers.metadatatemplates.CreateMetadataTemplateRequestBodyFieldsField; +import com.box.sdkgen.managers.metadatatemplates.CreateMetadataTemplateRequestBodyFieldsOptionsField; +import com.box.sdkgen.managers.metadatatemplates.CreateMetadataTemplateRequestBodyFieldsTypeField; +import com.box.sdkgen.managers.metadatatemplates.DeleteMetadataTemplateScope; +import com.box.sdkgen.managers.search.SearchForContentQueryParams; +import com.box.sdkgen.managers.search.SearchForContentQueryParamsTrashContentField; +import com.box.sdkgen.managers.uploads.UploadFileRequestBody; +import com.box.sdkgen.managers.uploads.UploadFileRequestBodyAttributesField; +import com.box.sdkgen.managers.uploads.UploadFileRequestBodyAttributesParentField; +import com.box.sdkgen.schemas.filefull.FileFull; +import com.box.sdkgen.schemas.files.Files; +import com.box.sdkgen.schemas.metadatafieldfilterdaterange.MetadataFieldFilterDateRange; +import com.box.sdkgen.schemas.metadatafieldfilterfloatrange.MetadataFieldFilterFloatRange; +import com.box.sdkgen.schemas.metadatafilter.MetadataFilter; +import com.box.sdkgen.schemas.metadatafilter.MetadataFilterScopeField; +import com.box.sdkgen.schemas.metadatafiltervalue.MetadataFilterValue; +import com.box.sdkgen.schemas.metadatafull.MetadataFull; +import com.box.sdkgen.schemas.metadataquery.MetadataQuery; +import com.box.sdkgen.schemas.metadataqueryresults.MetadataQueryResults; +import com.box.sdkgen.schemas.metadatatemplate.MetadataTemplate; +import com.box.sdkgen.schemas.searchresults.SearchResults; +import com.box.sdkgen.schemas.searchresultsresponse.SearchResultsResponse; +import com.box.sdkgen.schemas.searchresultswithsharedlinks.SearchResultsWithSharedLinks; +import java.util.Arrays; +import java.util.Map; +import org.junit.jupiter.api.Test; + +public class SearchITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testCreateMetaDataQueryExecuteRead() { + String templateKey = String.join("", "key", getUuid()); + MetadataTemplate template = + client + .getMetadataTemplates() + .createMetadataTemplate( + new CreateMetadataTemplateRequestBody.Builder("enterprise", templateKey) + .templateKey(templateKey) + .fields( + Arrays.asList( + new CreateMetadataTemplateRequestBodyFieldsField( + CreateMetadataTemplateRequestBodyFieldsTypeField.STRING, + "name", + "name"), + new CreateMetadataTemplateRequestBodyFieldsField( + CreateMetadataTemplateRequestBodyFieldsTypeField.FLOAT, + "age", + "age"), + new CreateMetadataTemplateRequestBodyFieldsField( + CreateMetadataTemplateRequestBodyFieldsTypeField.DATE, + "birthDate", + "birthDate"), + new CreateMetadataTemplateRequestBodyFieldsField.Builder( + CreateMetadataTemplateRequestBodyFieldsTypeField.ENUM, + "countryCode", + "countryCode") + .options( + Arrays.asList( + new CreateMetadataTemplateRequestBodyFieldsOptionsField( + "US"), + new CreateMetadataTemplateRequestBodyFieldsOptionsField( + "CA"))) + .build(), + new CreateMetadataTemplateRequestBodyFieldsField.Builder( + CreateMetadataTemplateRequestBodyFieldsTypeField.MULTISELECT, + "sports", + "sports") + .options( + Arrays.asList( + new CreateMetadataTemplateRequestBodyFieldsOptionsField( + "basketball"), + new CreateMetadataTemplateRequestBodyFieldsOptionsField( + "football"), + new CreateMetadataTemplateRequestBodyFieldsOptionsField( + "tennis"))) + .build())) + .build()); + assert template.getTemplateKey().equals(templateKey); + Files files = + client + .getUploads() + .uploadFile( + new UploadFileRequestBody( + new UploadFileRequestBodyAttributesField( + getUuid(), new UploadFileRequestBodyAttributesParentField("0")), + generateByteStream(10))); + FileFull file = files.getEntries().get(0); + MetadataFull metadata = + client + .getFileMetadata() + .createFileMetadataById( + file.getId(), + CreateFileMetadataByIdScope.ENTERPRISE, + templateKey, + mapOf( + entryOf("name", "John"), + entryOf("age", 23), + entryOf("birthDate", "2001-01-03T02:20:50.520Z"), + entryOf("countryCode", "US"), + entryOf("sports", Arrays.asList("basketball", "tennis")))); + assert metadata.getTemplate().equals(templateKey); + assert metadata.getScope().equals(template.getScope()); + delayInSeconds(5); + String searchFrom = String.join("", template.getScope(), ".", template.getTemplateKey()); + MetadataQueryResults query = + client + .getSearch() + .searchByMetadataQuery( + new MetadataQuery.Builder(searchFrom, "0") + .query( + "name = :name AND age < :age AND birthDate >= :birthDate AND countryCode = :countryCode AND sports = :sports") + .queryParams( + mapOf( + entryOf("name", "John"), + entryOf("age", 50), + entryOf("birthDate", "2001-01-01T02:20:10.120Z"), + entryOf("countryCode", "US"), + entryOf("sports", Arrays.asList("basketball", "tennis")))) + .build()); + assert query.getEntries().size() >= 0; + client + .getMetadataTemplates() + .deleteMetadataTemplate(DeleteMetadataTemplateScope.ENTERPRISE, template.getTemplateKey()); + client.getFiles().deleteFileById(file.getId()); + } + + @Test + public void testMetadataFilters() { + String templateKey = String.join("", "key", getUuid()); + MetadataTemplate template = + client + .getMetadataTemplates() + .createMetadataTemplate( + new CreateMetadataTemplateRequestBody.Builder("enterprise", templateKey) + .templateKey(templateKey) + .fields( + Arrays.asList( + new CreateMetadataTemplateRequestBodyFieldsField( + CreateMetadataTemplateRequestBodyFieldsTypeField.FLOAT, + "floatField", + "floatField"), + new CreateMetadataTemplateRequestBodyFieldsField( + CreateMetadataTemplateRequestBodyFieldsTypeField.STRING, + "stringField", + "stringField"), + new CreateMetadataTemplateRequestBodyFieldsField( + CreateMetadataTemplateRequestBodyFieldsTypeField.DATE, + "dateField", + "dateField"), + new CreateMetadataTemplateRequestBodyFieldsField.Builder( + CreateMetadataTemplateRequestBodyFieldsTypeField.ENUM, + "enumField", + "enumField") + .options( + Arrays.asList( + new CreateMetadataTemplateRequestBodyFieldsOptionsField( + "enumValue1"), + new CreateMetadataTemplateRequestBodyFieldsOptionsField( + "enumValue2"))) + .build(), + new CreateMetadataTemplateRequestBodyFieldsField.Builder( + CreateMetadataTemplateRequestBodyFieldsTypeField.MULTISELECT, + "multiSelectField", + "multiSelectField") + .options( + Arrays.asList( + new CreateMetadataTemplateRequestBodyFieldsOptionsField( + "multiSelectValue1"), + new CreateMetadataTemplateRequestBodyFieldsOptionsField( + "multiSelectValue2"))) + .build())) + .build()); + Files files = + client + .getUploads() + .uploadFile( + new UploadFileRequestBody( + new UploadFileRequestBodyAttributesField( + getUuid(), new UploadFileRequestBodyAttributesParentField("0")), + generateByteStream(10))); + FileFull file = files.getEntries().get(0); + MetadataFull metadata = + client + .getFileMetadata() + .createFileMetadataById( + file.getId(), + CreateFileMetadataByIdScope.ENTERPRISE, + templateKey, + mapOf( + entryOf("floatField", 10), + entryOf("stringField", "stringValue"), + entryOf("dateField", "2035-01-02T00:00:00Z"), + entryOf("enumField", "enumValue2"), + entryOf( + "multiSelectField", + Arrays.asList("multiSelectValue1", "multiSelectValue2")))); + Map searchFilters = + mapOf( + entryOf("stringField", new MetadataFilterValue("stringValue")), + entryOf( + "dateField", + new MetadataFilterValue( + new MetadataFieldFilterDateRange.Builder() + .lt(dateTimeFromString("2035-01-01T00:00:00Z")) + .gt(dateTimeFromString("2035-01-03T00:00:00Z")) + .build())), + entryOf( + "floatField", + new MetadataFilterValue( + new MetadataFieldFilterFloatRange.Builder().lt(9.5).gt(10.5).build())), + entryOf("enumField", new MetadataFilterValue("enumValue2")), + entryOf( + "multiSelectField", + new MetadataFilterValue(Arrays.asList("multiSelectValue1", "multiSelectValue2")))); + SearchResultsResponse query = + client + .getSearch() + .searchForContent( + new SearchForContentQueryParams.Builder() + .ancestorFolderIds(Arrays.asList("0")) + .mdfilters( + Arrays.asList( + new MetadataFilter.Builder() + .scope(MetadataFilterScopeField.ENTERPRISE) + .templateKey(templateKey) + .filters(searchFilters) + .build())) + .build()); + SearchResults queryResults = query.getSearchResults(); + assert queryResults.getEntries().size() >= 0; + client + .getMetadataTemplates() + .deleteMetadataTemplate(DeleteMetadataTemplateScope.ENTERPRISE, template.getTemplateKey()); + client.getFiles().deleteFileById(file.getId()); + } + + @Test + public void testGetSearch() { + String keyword = "test"; + SearchResultsResponse search = + client + .getSearch() + .searchForContent( + new SearchForContentQueryParams.Builder() + .query(keyword) + .ancestorFolderIds(Arrays.asList("0")) + .trashContent(SearchForContentQueryParamsTrashContentField.NON_TRASHED_ONLY) + .build()); + assert convertToString(search.getType()).equals("search_results_items"); + SearchResults searchResults = search.getSearchResults(); + assert searchResults.getEntries().size() >= 0; + SearchResultsResponse searchWithSharedLink = + client + .getSearch() + .searchForContent( + new SearchForContentQueryParams.Builder() + .query(keyword) + .ancestorFolderIds(Arrays.asList("0")) + .trashContent(SearchForContentQueryParamsTrashContentField.NON_TRASHED_ONLY) + .includeRecentSharedLinks(true) + .build()); + assert convertToString(searchWithSharedLink.getType()) + .equals("search_results_with_shared_links"); + SearchResultsWithSharedLinks searchResultsWithSharedLink = + searchWithSharedLink.getSearchResultsWithSharedLinks(); + assert searchResultsWithSharedLink.getEntries().size() >= 0; + } +} diff --git a/src/intTest/java/com/box/sdkgen/sessiontermination/SessionTerminationITest.java b/src/intTest/java/com/box/sdkgen/sessiontermination/SessionTerminationITest.java new file mode 100644 index 000000000..82c26c812 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/sessiontermination/SessionTerminationITest.java @@ -0,0 +1,51 @@ +package com.box.sdkgen.sessiontermination; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.commons.CommonsManager.getDefaultClientWithUserSubject; +import static com.box.sdkgen.internal.utils.UtilsManager.getEnvVar; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.groups.CreateGroupRequestBody; +import com.box.sdkgen.managers.sessiontermination.TerminateGroupsSessionsRequestBody; +import com.box.sdkgen.managers.sessiontermination.TerminateUsersSessionsRequestBody; +import com.box.sdkgen.schemas.groupfull.GroupFull; +import com.box.sdkgen.schemas.sessionterminationmessage.SessionTerminationMessage; +import com.box.sdkgen.schemas.userfull.UserFull; +import java.util.Arrays; +import org.junit.jupiter.api.Test; + +public class SessionTerminationITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testSessionTerminationUser() { + BoxClient adminClient = getDefaultClientWithUserSubject(getEnvVar("USER_ID")); + UserFull user = adminClient.getUsers().getUserMe(); + SessionTerminationMessage result = + client + .getSessionTermination() + .terminateUsersSessions( + new TerminateUsersSessionsRequestBody( + Arrays.asList(getEnvVar("USER_ID")), Arrays.asList(user.getLogin()))); + assert result + .getMessage() + .equals("Request is successful, please check the admin events for the status of the job"); + } + + @Test + public void testSessionTerminationGroup() { + String groupName = getUuid(); + GroupFull group = client.getGroups().createGroup(new CreateGroupRequestBody(groupName)); + SessionTerminationMessage result = + client + .getSessionTermination() + .terminateGroupsSessions( + new TerminateGroupsSessionsRequestBody(Arrays.asList(group.getId()))); + assert result + .getMessage() + .equals("Request is successful, please check the admin events for the status of the job"); + client.getGroups().deleteGroupById(group.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/sharedlinksappitems/SharedLinksAppItemsITest.java b/src/intTest/java/com/box/sdkgen/sharedlinksappitems/SharedLinksAppItemsITest.java new file mode 100644 index 000000000..ea0b330d8 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/sharedlinksappitems/SharedLinksAppItemsITest.java @@ -0,0 +1,28 @@ +package com.box.sdkgen.sharedlinksappitems; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.getEnvVar; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.sharedlinksappitems.FindAppItemForSharedLinkHeaders; +import com.box.sdkgen.schemas.appitem.AppItem; +import org.junit.jupiter.api.Test; + +public class SharedLinksAppItemsITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testSharedLinksAppItems() { + String appItemSharedLink = getEnvVar("APP_ITEM_SHARED_LINK"); + AppItem appItem = + client + .getSharedLinksAppItems() + .findAppItemForSharedLink( + new FindAppItemForSharedLinkHeaders( + String.join("", "shared_link=", appItemSharedLink))); + assert convertToString(appItem.getType()).equals("app_item"); + assert appItem.getApplicationType().equals("hubs"); + } +} diff --git a/src/intTest/java/com/box/sdkgen/sharedlinksfiles/SharedLinksFilesITest.java b/src/intTest/java/com/box/sdkgen/sharedlinksfiles/SharedLinksFilesITest.java new file mode 100644 index 000000000..015969ec6 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/sharedlinksfiles/SharedLinksFilesITest.java @@ -0,0 +1,119 @@ +package com.box.sdkgen.sharedlinksfiles; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.commons.CommonsManager.getDefaultClientWithUserSubject; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.generateByteStream; +import static com.box.sdkgen.internal.utils.UtilsManager.getEnvVar; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.sharedlinksfiles.AddShareLinkToFileQueryParams; +import com.box.sdkgen.managers.sharedlinksfiles.AddShareLinkToFileRequestBody; +import com.box.sdkgen.managers.sharedlinksfiles.AddShareLinkToFileRequestBodySharedLinkAccessField; +import com.box.sdkgen.managers.sharedlinksfiles.AddShareLinkToFileRequestBodySharedLinkField; +import com.box.sdkgen.managers.sharedlinksfiles.FindFileForSharedLinkHeaders; +import com.box.sdkgen.managers.sharedlinksfiles.FindFileForSharedLinkQueryParams; +import com.box.sdkgen.managers.sharedlinksfiles.GetSharedLinkForFileQueryParams; +import com.box.sdkgen.managers.sharedlinksfiles.RemoveSharedLinkFromFileQueryParams; +import com.box.sdkgen.managers.sharedlinksfiles.RemoveSharedLinkFromFileRequestBody; +import com.box.sdkgen.managers.sharedlinksfiles.UpdateSharedLinkOnFileQueryParams; +import com.box.sdkgen.managers.sharedlinksfiles.UpdateSharedLinkOnFileRequestBody; +import com.box.sdkgen.managers.sharedlinksfiles.UpdateSharedLinkOnFileRequestBodySharedLinkAccessField; +import com.box.sdkgen.managers.sharedlinksfiles.UpdateSharedLinkOnFileRequestBodySharedLinkField; +import com.box.sdkgen.managers.uploads.UploadFileRequestBody; +import com.box.sdkgen.managers.uploads.UploadFileRequestBodyAttributesField; +import com.box.sdkgen.managers.uploads.UploadFileRequestBodyAttributesParentField; +import com.box.sdkgen.schemas.filefull.FileFull; +import com.box.sdkgen.schemas.files.Files; +import org.junit.jupiter.api.Test; + +public class SharedLinksFilesITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testSharedLinksFiles() { + Files uploadedFiles = + client + .getUploads() + .uploadFile( + new UploadFileRequestBody( + new UploadFileRequestBodyAttributesField( + getUuid(), new UploadFileRequestBodyAttributesParentField("0")), + generateByteStream(10))); + String fileId = uploadedFiles.getEntries().get(0).getId(); + client + .getSharedLinksFiles() + .addShareLinkToFile( + fileId, + new AddShareLinkToFileRequestBody.Builder() + .sharedLink( + new AddShareLinkToFileRequestBodySharedLinkField.Builder() + .access(AddShareLinkToFileRequestBodySharedLinkAccessField.OPEN) + .password("Secret123@") + .build()) + .build(), + new AddShareLinkToFileQueryParams("shared_link")); + FileFull fileFromApi = + client + .getSharedLinksFiles() + .getSharedLinkForFile(fileId, new GetSharedLinkForFileQueryParams("shared_link")); + assert convertToString(fileFromApi.getSharedLink().getAccess()).equals("open"); + String userId = getEnvVar("USER_ID"); + BoxClient userClient = getDefaultClientWithUserSubject(userId); + FileFull fileFromSharedLinkPassword = + userClient + .getSharedLinksFiles() + .findFileForSharedLink( + new FindFileForSharedLinkQueryParams(), + new FindFileForSharedLinkHeaders( + String.join( + "", + "shared_link=", + fileFromApi.getSharedLink().getUrl(), + "&shared_link_password=Secret123@"))); + assert fileId.equals(fileFromSharedLinkPassword.getId()); + assertThrows( + RuntimeException.class, + () -> + userClient + .getSharedLinksFiles() + .findFileForSharedLink( + new FindFileForSharedLinkQueryParams(), + new FindFileForSharedLinkHeaders( + String.join( + "", + "shared_link=", + fileFromApi.getSharedLink().getUrl(), + "&shared_link_password=incorrectPassword")))); + FileFull updatedFile = + client + .getSharedLinksFiles() + .updateSharedLinkOnFile( + fileId, + new UpdateSharedLinkOnFileRequestBody.Builder() + .sharedLink( + new UpdateSharedLinkOnFileRequestBodySharedLinkField.Builder() + .access( + UpdateSharedLinkOnFileRequestBodySharedLinkAccessField + .COLLABORATORS) + .build()) + .build(), + new UpdateSharedLinkOnFileQueryParams("shared_link")); + assert convertToString(updatedFile.getSharedLink().getAccess()).equals("collaborators"); + client + .getSharedLinksFiles() + .removeSharedLinkFromFile( + fileId, + new RemoveSharedLinkFromFileRequestBody.Builder().sharedLink(null).build(), + new RemoveSharedLinkFromFileQueryParams("shared_link")); + FileFull fileFromApiAfterRemove = + client + .getSharedLinksFiles() + .getSharedLinkForFile(fileId, new GetSharedLinkForFileQueryParams("shared_link")); + assert fileFromApiAfterRemove.getSharedLink() == null; + client.getFiles().deleteFileById(fileId); + } +} diff --git a/src/intTest/java/com/box/sdkgen/sharedlinksfolders/SharedLinksFoldersITest.java b/src/intTest/java/com/box/sdkgen/sharedlinksfolders/SharedLinksFoldersITest.java new file mode 100644 index 000000000..06eb3581c --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/sharedlinksfolders/SharedLinksFoldersITest.java @@ -0,0 +1,115 @@ +package com.box.sdkgen.sharedlinksfolders; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.commons.CommonsManager.getDefaultClientWithUserSubject; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.getEnvVar; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.folders.CreateFolderRequestBody; +import com.box.sdkgen.managers.folders.CreateFolderRequestBodyParentField; +import com.box.sdkgen.managers.sharedlinksfolders.AddShareLinkToFolderQueryParams; +import com.box.sdkgen.managers.sharedlinksfolders.AddShareLinkToFolderRequestBody; +import com.box.sdkgen.managers.sharedlinksfolders.AddShareLinkToFolderRequestBodySharedLinkAccessField; +import com.box.sdkgen.managers.sharedlinksfolders.AddShareLinkToFolderRequestBodySharedLinkField; +import com.box.sdkgen.managers.sharedlinksfolders.FindFolderForSharedLinkHeaders; +import com.box.sdkgen.managers.sharedlinksfolders.FindFolderForSharedLinkQueryParams; +import com.box.sdkgen.managers.sharedlinksfolders.GetSharedLinkForFolderQueryParams; +import com.box.sdkgen.managers.sharedlinksfolders.RemoveSharedLinkFromFolderQueryParams; +import com.box.sdkgen.managers.sharedlinksfolders.RemoveSharedLinkFromFolderRequestBody; +import com.box.sdkgen.managers.sharedlinksfolders.UpdateSharedLinkOnFolderQueryParams; +import com.box.sdkgen.managers.sharedlinksfolders.UpdateSharedLinkOnFolderRequestBody; +import com.box.sdkgen.managers.sharedlinksfolders.UpdateSharedLinkOnFolderRequestBodySharedLinkAccessField; +import com.box.sdkgen.managers.sharedlinksfolders.UpdateSharedLinkOnFolderRequestBodySharedLinkField; +import com.box.sdkgen.schemas.folderfull.FolderFull; +import org.junit.jupiter.api.Test; + +public class SharedLinksFoldersITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testSharedLinksFolders() { + FolderFull folder = + client + .getFolders() + .createFolder( + new CreateFolderRequestBody( + getUuid(), new CreateFolderRequestBodyParentField("0"))); + client + .getSharedLinksFolders() + .addShareLinkToFolder( + folder.getId(), + new AddShareLinkToFolderRequestBody.Builder() + .sharedLink( + new AddShareLinkToFolderRequestBodySharedLinkField.Builder() + .access(AddShareLinkToFolderRequestBodySharedLinkAccessField.OPEN) + .password("Secret123@") + .build()) + .build(), + new AddShareLinkToFolderQueryParams("shared_link")); + FolderFull folderFromApi = + client + .getSharedLinksFolders() + .getSharedLinkForFolder( + folder.getId(), new GetSharedLinkForFolderQueryParams("shared_link")); + assert convertToString(folderFromApi.getSharedLink().getAccess()).equals("open"); + String userId = getEnvVar("USER_ID"); + BoxClient userClient = getDefaultClientWithUserSubject(userId); + FolderFull folderFromSharedLinkPassword = + userClient + .getSharedLinksFolders() + .findFolderForSharedLink( + new FindFolderForSharedLinkQueryParams(), + new FindFolderForSharedLinkHeaders( + String.join( + "", + "shared_link=", + folderFromApi.getSharedLink().getUrl(), + "&shared_link_password=Secret123@"))); + assert folder.getId().equals(folderFromSharedLinkPassword.getId()); + assertThrows( + RuntimeException.class, + () -> + userClient + .getSharedLinksFolders() + .findFolderForSharedLink( + new FindFolderForSharedLinkQueryParams(), + new FindFolderForSharedLinkHeaders( + String.join( + "", + "shared_link=", + folderFromApi.getSharedLink().getUrl(), + "&shared_link_password=incorrectPassword")))); + FolderFull updatedFolder = + client + .getSharedLinksFolders() + .updateSharedLinkOnFolder( + folder.getId(), + new UpdateSharedLinkOnFolderRequestBody.Builder() + .sharedLink( + new UpdateSharedLinkOnFolderRequestBodySharedLinkField.Builder() + .access( + UpdateSharedLinkOnFolderRequestBodySharedLinkAccessField + .COLLABORATORS) + .build()) + .build(), + new UpdateSharedLinkOnFolderQueryParams("shared_link")); + assert convertToString(updatedFolder.getSharedLink().getAccess()).equals("collaborators"); + client + .getSharedLinksFolders() + .removeSharedLinkFromFolder( + folder.getId(), + new RemoveSharedLinkFromFolderRequestBody.Builder().sharedLink(null).build(), + new RemoveSharedLinkFromFolderQueryParams("shared_link")); + FolderFull folderFromApiAfterRemove = + client + .getSharedLinksFolders() + .getSharedLinkForFolder( + folder.getId(), new GetSharedLinkForFolderQueryParams("shared_link")); + assert folderFromApiAfterRemove.getSharedLink() == null; + client.getFolders().deleteFolderById(folder.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/sharedlinksweblinks/SharedLinksWebLinksITest.java b/src/intTest/java/com/box/sdkgen/sharedlinksweblinks/SharedLinksWebLinksITest.java new file mode 100644 index 000000000..50f4048f3 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/sharedlinksweblinks/SharedLinksWebLinksITest.java @@ -0,0 +1,122 @@ +package com.box.sdkgen.sharedlinksweblinks; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.commons.CommonsManager.getDefaultClientWithUserSubject; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.getEnvVar; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.sharedlinksweblinks.AddShareLinkToWebLinkQueryParams; +import com.box.sdkgen.managers.sharedlinksweblinks.AddShareLinkToWebLinkRequestBody; +import com.box.sdkgen.managers.sharedlinksweblinks.AddShareLinkToWebLinkRequestBodySharedLinkAccessField; +import com.box.sdkgen.managers.sharedlinksweblinks.AddShareLinkToWebLinkRequestBodySharedLinkField; +import com.box.sdkgen.managers.sharedlinksweblinks.FindWebLinkForSharedLinkHeaders; +import com.box.sdkgen.managers.sharedlinksweblinks.FindWebLinkForSharedLinkQueryParams; +import com.box.sdkgen.managers.sharedlinksweblinks.GetSharedLinkForWebLinkQueryParams; +import com.box.sdkgen.managers.sharedlinksweblinks.RemoveSharedLinkFromWebLinkQueryParams; +import com.box.sdkgen.managers.sharedlinksweblinks.RemoveSharedLinkFromWebLinkRequestBody; +import com.box.sdkgen.managers.sharedlinksweblinks.UpdateSharedLinkOnWebLinkQueryParams; +import com.box.sdkgen.managers.sharedlinksweblinks.UpdateSharedLinkOnWebLinkRequestBody; +import com.box.sdkgen.managers.sharedlinksweblinks.UpdateSharedLinkOnWebLinkRequestBodySharedLinkAccessField; +import com.box.sdkgen.managers.sharedlinksweblinks.UpdateSharedLinkOnWebLinkRequestBodySharedLinkField; +import com.box.sdkgen.managers.weblinks.CreateWebLinkRequestBody; +import com.box.sdkgen.managers.weblinks.CreateWebLinkRequestBodyParentField; +import com.box.sdkgen.schemas.folderfull.FolderFull; +import com.box.sdkgen.schemas.weblink.WebLink; +import org.junit.jupiter.api.Test; + +public class SharedLinksWebLinksITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testSharedLinksWebLinks() { + FolderFull parent = client.getFolders().getFolderById("0"); + WebLink webLink = + client + .getWebLinks() + .createWebLink( + new CreateWebLinkRequestBody.Builder( + "https://www.box.com", + new CreateWebLinkRequestBodyParentField(parent.getId())) + .name(getUuid()) + .description("Weblink description") + .build()); + String webLinkId = webLink.getId(); + client + .getSharedLinksWebLinks() + .addShareLinkToWebLink( + webLinkId, + new AddShareLinkToWebLinkRequestBody.Builder() + .sharedLink( + new AddShareLinkToWebLinkRequestBodySharedLinkField.Builder() + .access(AddShareLinkToWebLinkRequestBodySharedLinkAccessField.OPEN) + .password("Secret123@") + .build()) + .build(), + new AddShareLinkToWebLinkQueryParams("shared_link")); + WebLink webLinkFromApi = + client + .getSharedLinksWebLinks() + .getSharedLinkForWebLink( + webLinkId, new GetSharedLinkForWebLinkQueryParams("shared_link")); + assert convertToString(webLinkFromApi.getSharedLink().getAccess()).equals("open"); + String userId = getEnvVar("USER_ID"); + BoxClient userClient = getDefaultClientWithUserSubject(userId); + WebLink webLinkFromSharedLinkPassword = + userClient + .getSharedLinksWebLinks() + .findWebLinkForSharedLink( + new FindWebLinkForSharedLinkQueryParams(), + new FindWebLinkForSharedLinkHeaders( + String.join( + "", + "shared_link=", + webLinkFromApi.getSharedLink().getUrl(), + "&shared_link_password=Secret123@"))); + assert webLinkId.equals(webLinkFromSharedLinkPassword.getId()); + assertThrows( + RuntimeException.class, + () -> + userClient + .getSharedLinksWebLinks() + .findWebLinkForSharedLink( + new FindWebLinkForSharedLinkQueryParams(), + new FindWebLinkForSharedLinkHeaders( + String.join( + "", + "shared_link=", + webLinkFromApi.getSharedLink().getUrl(), + "&shared_link_password=incorrectPassword")))); + WebLink updatedWebLink = + client + .getSharedLinksWebLinks() + .updateSharedLinkOnWebLink( + webLinkId, + new UpdateSharedLinkOnWebLinkRequestBody.Builder() + .sharedLink( + new UpdateSharedLinkOnWebLinkRequestBodySharedLinkField.Builder() + .access( + UpdateSharedLinkOnWebLinkRequestBodySharedLinkAccessField + .COLLABORATORS) + .build()) + .build(), + new UpdateSharedLinkOnWebLinkQueryParams("shared_link")); + assert convertToString(updatedWebLink.getSharedLink().getAccess()).equals("collaborators"); + client + .getSharedLinksWebLinks() + .removeSharedLinkFromWebLink( + webLinkId, + new RemoveSharedLinkFromWebLinkRequestBody.Builder().sharedLink(null).build(), + new RemoveSharedLinkFromWebLinkQueryParams("shared_link")); + WebLink webLinkFromApiAfterRemove = + client + .getSharedLinksWebLinks() + .getSharedLinkForWebLink( + webLinkId, new GetSharedLinkForWebLinkQueryParams("shared_link")); + assert webLinkFromApiAfterRemove.getSharedLink() == null; + client.getWebLinks().deleteWebLinkById(webLinkId); + } +} diff --git a/src/intTest/java/com/box/sdkgen/shieldinformationbarrierreports/ShieldInformationBarrierReportsITest.java b/src/intTest/java/com/box/sdkgen/shieldinformationbarrierreports/ShieldInformationBarrierReportsITest.java new file mode 100644 index 000000000..e2991fe9f --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/shieldinformationbarrierreports/ShieldInformationBarrierReportsITest.java @@ -0,0 +1,66 @@ +package com.box.sdkgen.shieldinformationbarrierreports; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClientWithUserSubject; +import static com.box.sdkgen.commons.CommonsManager.getOrCreateShieldInformationBarrier; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.getEnvVar; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.shieldinformationbarrierreports.GetShieldInformationBarrierReportsQueryParams; +import com.box.sdkgen.schemas.shieldinformationbarrier.ShieldInformationBarrier; +import com.box.sdkgen.schemas.shieldinformationbarrierbase.ShieldInformationBarrierBase; +import com.box.sdkgen.schemas.shieldinformationbarrierbase.ShieldInformationBarrierBaseTypeField; +import com.box.sdkgen.schemas.shieldinformationbarrierreference.ShieldInformationBarrierReference; +import com.box.sdkgen.schemas.shieldinformationbarrierreport.ShieldInformationBarrierReport; +import com.box.sdkgen.schemas.shieldinformationbarrierreports.ShieldInformationBarrierReports; +import org.junit.jupiter.api.Test; + +public class ShieldInformationBarrierReportsITest { + + @Test + public void testShieldInformationBarrierReports() { + BoxClient client = getDefaultClientWithUserSubject(getEnvVar("USER_ID")); + String enterpriseId = getEnvVar("ENTERPRISE_ID"); + ShieldInformationBarrier barrier = getOrCreateShieldInformationBarrier(client, enterpriseId); + assert convertToString(barrier.getStatus()).equals("draft"); + assert convertToString(barrier.getType()).equals("shield_information_barrier"); + assert barrier.getEnterprise().getId().equals(enterpriseId); + assert convertToString(barrier.getEnterprise().getType()).equals("enterprise"); + String barrierId = barrier.getId(); + ShieldInformationBarrierReports existingReports = + client + .getShieldInformationBarrierReports() + .getShieldInformationBarrierReports( + new GetShieldInformationBarrierReportsQueryParams(barrierId)); + if (existingReports.getEntries().size() > 0) { + return; + } + ShieldInformationBarrierReport createdReport = + client + .getShieldInformationBarrierReports() + .createShieldInformationBarrierReport( + new ShieldInformationBarrierReference.Builder() + .shieldInformationBarrier( + new ShieldInformationBarrierBase.Builder() + .id(barrierId) + .type(ShieldInformationBarrierBaseTypeField.SHIELD_INFORMATION_BARRIER) + .build()) + .build()); + assert createdReport + .getShieldInformationBarrier() + .getShieldInformationBarrier() + .getId() + .equals(barrierId); + ShieldInformationBarrierReport retrievedReport = + client + .getShieldInformationBarrierReports() + .getShieldInformationBarrierReportById(createdReport.getId()); + assert retrievedReport.getId().equals(createdReport.getId()); + ShieldInformationBarrierReports retrievedReports = + client + .getShieldInformationBarrierReports() + .getShieldInformationBarrierReports( + new GetShieldInformationBarrierReportsQueryParams(barrierId)); + assert retrievedReports.getEntries().size() > 0; + } +} diff --git a/src/intTest/java/com/box/sdkgen/shieldinformationbarriers/ShieldInformationBarriersITest.java b/src/intTest/java/com/box/sdkgen/shieldinformationbarriers/ShieldInformationBarriersITest.java new file mode 100644 index 000000000..b35126a26 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/shieldinformationbarriers/ShieldInformationBarriersITest.java @@ -0,0 +1,44 @@ +package com.box.sdkgen.shieldinformationbarriers; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClientWithUserSubject; +import static com.box.sdkgen.commons.CommonsManager.getOrCreateShieldInformationBarrier; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.getEnvVar; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.shieldinformationbarriers.UpdateShieldInformationBarrierStatusRequestBody; +import com.box.sdkgen.managers.shieldinformationbarriers.UpdateShieldInformationBarrierStatusRequestBodyStatusField; +import com.box.sdkgen.schemas.shieldinformationbarrier.ShieldInformationBarrier; +import com.box.sdkgen.schemas.shieldinformationbarriers.ShieldInformationBarriers; +import org.junit.jupiter.api.Test; + +public class ShieldInformationBarriersITest { + + @Test + public void testShieldInformationBarriers() { + BoxClient client = getDefaultClientWithUserSubject(getEnvVar("USER_ID")); + String enterpriseId = getEnvVar("ENTERPRISE_ID"); + ShieldInformationBarrier barrier = getOrCreateShieldInformationBarrier(client, enterpriseId); + assert convertToString(barrier.getStatus()).equals("draft"); + assert convertToString(barrier.getType()).equals("shield_information_barrier"); + assert barrier.getEnterprise().getId().equals(enterpriseId); + assert convertToString(barrier.getEnterprise().getType()).equals("enterprise"); + String barrierId = barrier.getId(); + ShieldInformationBarrier barrierFromApi = + client.getShieldInformationBarriers().getShieldInformationBarrierById(barrierId); + assert barrierFromApi.getId().equals(barrierId); + ShieldInformationBarriers barriers = + client.getShieldInformationBarriers().getShieldInformationBarriers(); + assert barriers.getEntries().size() == 1; + assertThrows( + RuntimeException.class, + () -> + client + .getShieldInformationBarriers() + .updateShieldInformationBarrierStatus( + new UpdateShieldInformationBarrierStatusRequestBody( + barrierId, + UpdateShieldInformationBarrierStatusRequestBodyStatusField.DISABLED))); + } +} diff --git a/src/intTest/java/com/box/sdkgen/shieldinformationbarriersegmentmembers/ShieldInformationBarrierSegmentMembersITest.java b/src/intTest/java/com/box/sdkgen/shieldinformationbarriersegmentmembers/ShieldInformationBarrierSegmentMembersITest.java new file mode 100644 index 000000000..6d5c59e3e --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/shieldinformationbarriersegmentmembers/ShieldInformationBarrierSegmentMembersITest.java @@ -0,0 +1,83 @@ +package com.box.sdkgen.shieldinformationbarriersegmentmembers; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClientWithUserSubject; +import static com.box.sdkgen.commons.CommonsManager.getOrCreateShieldInformationBarrier; +import static com.box.sdkgen.internal.utils.UtilsManager.getEnvVar; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.shieldinformationbarriersegmentmembers.CreateShieldInformationBarrierSegmentMemberRequestBody; +import com.box.sdkgen.managers.shieldinformationbarriersegmentmembers.CreateShieldInformationBarrierSegmentMemberRequestBodyShieldInformationBarrierSegmentField; +import com.box.sdkgen.managers.shieldinformationbarriersegmentmembers.CreateShieldInformationBarrierSegmentMemberRequestBodyShieldInformationBarrierSegmentTypeField; +import com.box.sdkgen.managers.shieldinformationbarriersegmentmembers.GetShieldInformationBarrierSegmentMembersQueryParams; +import com.box.sdkgen.managers.shieldinformationbarriersegments.CreateShieldInformationBarrierSegmentRequestBody; +import com.box.sdkgen.schemas.shieldinformationbarrier.ShieldInformationBarrier; +import com.box.sdkgen.schemas.shieldinformationbarrierbase.ShieldInformationBarrierBase; +import com.box.sdkgen.schemas.shieldinformationbarrierbase.ShieldInformationBarrierBaseTypeField; +import com.box.sdkgen.schemas.shieldinformationbarriersegment.ShieldInformationBarrierSegment; +import com.box.sdkgen.schemas.shieldinformationbarriersegmentmember.ShieldInformationBarrierSegmentMember; +import com.box.sdkgen.schemas.shieldinformationbarriersegmentmembers.ShieldInformationBarrierSegmentMembers; +import com.box.sdkgen.schemas.userbase.UserBase; +import org.junit.jupiter.api.Test; + +public class ShieldInformationBarrierSegmentMembersITest { + + @Test + public void testShieldInformationBarrierSegmentMembers() { + BoxClient client = getDefaultClientWithUserSubject(getEnvVar("USER_ID")); + String enterpriseId = getEnvVar("ENTERPRISE_ID"); + ShieldInformationBarrier barrier = getOrCreateShieldInformationBarrier(client, enterpriseId); + String barrierId = barrier.getId(); + String segmentName = getUuid(); + ShieldInformationBarrierSegment segment = + client + .getShieldInformationBarrierSegments() + .createShieldInformationBarrierSegment( + new CreateShieldInformationBarrierSegmentRequestBody( + new ShieldInformationBarrierBase.Builder() + .id(barrierId) + .type(ShieldInformationBarrierBaseTypeField.SHIELD_INFORMATION_BARRIER) + .build(), + segmentName)); + assert segment.getName().equals(segmentName); + ShieldInformationBarrierSegmentMember segmentMember = + client + .getShieldInformationBarrierSegmentMembers() + .createShieldInformationBarrierSegmentMember( + new CreateShieldInformationBarrierSegmentMemberRequestBody( + new CreateShieldInformationBarrierSegmentMemberRequestBodyShieldInformationBarrierSegmentField + .Builder() + .id(segment.getId()) + .type( + CreateShieldInformationBarrierSegmentMemberRequestBodyShieldInformationBarrierSegmentTypeField + .SHIELD_INFORMATION_BARRIER_SEGMENT) + .build(), + new UserBase(getEnvVar("USER_ID")))); + assert segmentMember.getUser().getId().equals(getEnvVar("USER_ID")); + assert segmentMember.getShieldInformationBarrierSegment().getId().equals(segment.getId()); + ShieldInformationBarrierSegmentMembers segmentMembers = + client + .getShieldInformationBarrierSegmentMembers() + .getShieldInformationBarrierSegmentMembers( + new GetShieldInformationBarrierSegmentMembersQueryParams(segment.getId())); + assert segmentMembers.getEntries().size() > 0; + ShieldInformationBarrierSegmentMember segmentMemberGet = + client + .getShieldInformationBarrierSegmentMembers() + .getShieldInformationBarrierSegmentMemberById(segmentMember.getId()); + assert segmentMemberGet.getId().equals(segmentMember.getId()); + client + .getShieldInformationBarrierSegmentMembers() + .deleteShieldInformationBarrierSegmentMemberById(segmentMember.getId()); + assertThrows( + RuntimeException.class, + () -> + client + .getShieldInformationBarrierSegmentMembers() + .getShieldInformationBarrierSegmentMemberById(segmentMember.getId())); + client + .getShieldInformationBarrierSegments() + .deleteShieldInformationBarrierSegmentById(segment.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/shieldinformationbarriersegmentrestrictions/ShieldInformationBarrierSegmentRestrictionsITest.java b/src/intTest/java/com/box/sdkgen/shieldinformationbarriersegmentrestrictions/ShieldInformationBarrierSegmentRestrictionsITest.java new file mode 100644 index 000000000..2b5f36c04 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/shieldinformationbarriersegmentrestrictions/ShieldInformationBarrierSegmentRestrictionsITest.java @@ -0,0 +1,115 @@ +package com.box.sdkgen.shieldinformationbarriersegmentrestrictions; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClientWithUserSubject; +import static com.box.sdkgen.commons.CommonsManager.getOrCreateShieldInformationBarrier; +import static com.box.sdkgen.internal.utils.UtilsManager.getEnvVar; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.shieldinformationbarriersegmentrestrictions.CreateShieldInformationBarrierSegmentRestrictionRequestBody; +import com.box.sdkgen.managers.shieldinformationbarriersegmentrestrictions.CreateShieldInformationBarrierSegmentRestrictionRequestBodyRestrictedSegmentField; +import com.box.sdkgen.managers.shieldinformationbarriersegmentrestrictions.CreateShieldInformationBarrierSegmentRestrictionRequestBodyRestrictedSegmentTypeField; +import com.box.sdkgen.managers.shieldinformationbarriersegmentrestrictions.CreateShieldInformationBarrierSegmentRestrictionRequestBodyShieldInformationBarrierSegmentField; +import com.box.sdkgen.managers.shieldinformationbarriersegmentrestrictions.CreateShieldInformationBarrierSegmentRestrictionRequestBodyShieldInformationBarrierSegmentTypeField; +import com.box.sdkgen.managers.shieldinformationbarriersegmentrestrictions.CreateShieldInformationBarrierSegmentRestrictionRequestBodyTypeField; +import com.box.sdkgen.managers.shieldinformationbarriersegmentrestrictions.GetShieldInformationBarrierSegmentRestrictionsQueryParams; +import com.box.sdkgen.managers.shieldinformationbarriersegments.CreateShieldInformationBarrierSegmentRequestBody; +import com.box.sdkgen.schemas.shieldinformationbarrier.ShieldInformationBarrier; +import com.box.sdkgen.schemas.shieldinformationbarrierbase.ShieldInformationBarrierBase; +import com.box.sdkgen.schemas.shieldinformationbarrierbase.ShieldInformationBarrierBaseTypeField; +import com.box.sdkgen.schemas.shieldinformationbarriersegment.ShieldInformationBarrierSegment; +import com.box.sdkgen.schemas.shieldinformationbarriersegmentrestriction.ShieldInformationBarrierSegmentRestriction; +import com.box.sdkgen.schemas.shieldinformationbarriersegmentrestrictions.ShieldInformationBarrierSegmentRestrictions; +import org.junit.jupiter.api.Test; + +public class ShieldInformationBarrierSegmentRestrictionsITest { + + @Test + public void testShieldInformationBarrierSegmentRestrictions() { + BoxClient client = getDefaultClientWithUserSubject(getEnvVar("USER_ID")); + String enterpriseId = getEnvVar("ENTERPRISE_ID"); + ShieldInformationBarrier barrier = getOrCreateShieldInformationBarrier(client, enterpriseId); + String barrierId = barrier.getId(); + ShieldInformationBarrierSegment segment = + client + .getShieldInformationBarrierSegments() + .createShieldInformationBarrierSegment( + new CreateShieldInformationBarrierSegmentRequestBody.Builder( + new ShieldInformationBarrierBase.Builder() + .id(barrierId) + .type(ShieldInformationBarrierBaseTypeField.SHIELD_INFORMATION_BARRIER) + .build(), + getUuid()) + .description("barrier segment description") + .build()); + String segmentId = segment.getId(); + ShieldInformationBarrierSegment segmentToRestrict = + client + .getShieldInformationBarrierSegments() + .createShieldInformationBarrierSegment( + new CreateShieldInformationBarrierSegmentRequestBody.Builder( + new ShieldInformationBarrierBase.Builder() + .id(barrierId) + .type(ShieldInformationBarrierBaseTypeField.SHIELD_INFORMATION_BARRIER) + .build(), + getUuid()) + .description("barrier segment description") + .build()); + String segmentToRestrictId = segmentToRestrict.getId(); + ShieldInformationBarrierSegmentRestriction segmentRestriction = + client + .getShieldInformationBarrierSegmentRestrictions() + .createShieldInformationBarrierSegmentRestriction( + new CreateShieldInformationBarrierSegmentRestrictionRequestBody.Builder( + new CreateShieldInformationBarrierSegmentRestrictionRequestBodyShieldInformationBarrierSegmentField + .Builder() + .id(segmentId) + .type( + CreateShieldInformationBarrierSegmentRestrictionRequestBodyShieldInformationBarrierSegmentTypeField + .SHIELD_INFORMATION_BARRIER_SEGMENT) + .build(), + new CreateShieldInformationBarrierSegmentRestrictionRequestBodyRestrictedSegmentField + .Builder() + .id(segmentToRestrictId) + .type( + CreateShieldInformationBarrierSegmentRestrictionRequestBodyRestrictedSegmentTypeField + .SHIELD_INFORMATION_BARRIER_SEGMENT) + .build()) + .type( + CreateShieldInformationBarrierSegmentRestrictionRequestBodyTypeField + .SHIELD_INFORMATION_BARRIER_SEGMENT_RESTRICTION) + .build()); + String segmentRestrictionId = segmentRestriction.getId(); + assert segmentRestriction.getShieldInformationBarrierSegment().getId().equals(segmentId); + ShieldInformationBarrierSegmentRestrictions segmentRestrictions = + client + .getShieldInformationBarrierSegmentRestrictions() + .getShieldInformationBarrierSegmentRestrictions( + new GetShieldInformationBarrierSegmentRestrictionsQueryParams(segmentId)); + assert segmentRestrictions.getEntries().size() > 0; + ShieldInformationBarrierSegmentRestriction segmentRestrictionFromApi = + client + .getShieldInformationBarrierSegmentRestrictions() + .getShieldInformationBarrierSegmentRestrictionById(segmentRestrictionId); + assert segmentRestrictionFromApi.getId().equals(segmentRestrictionId); + assert segmentRestrictionFromApi.getShieldInformationBarrierSegment().getId().equals(segmentId); + assert segmentRestrictionFromApi.getRestrictedSegment().getId().equals(segmentToRestrictId); + assert segmentRestrictionFromApi.getShieldInformationBarrier().getId().equals(barrierId); + client + .getShieldInformationBarrierSegmentRestrictions() + .deleteShieldInformationBarrierSegmentRestrictionById(segmentRestrictionId); + assertThrows( + RuntimeException.class, + () -> + client + .getShieldInformationBarrierSegmentRestrictions() + .getShieldInformationBarrierSegmentRestrictionById(segmentRestrictionId)); + client + .getShieldInformationBarrierSegments() + .deleteShieldInformationBarrierSegmentById(segmentId); + client + .getShieldInformationBarrierSegments() + .deleteShieldInformationBarrierSegmentById(segmentToRestrictId); + } +} diff --git a/src/intTest/java/com/box/sdkgen/shieldinformationbarriersegments/ShieldInformationBarrierSegmentsITest.java b/src/intTest/java/com/box/sdkgen/shieldinformationbarriersegments/ShieldInformationBarrierSegmentsITest.java new file mode 100644 index 000000000..6a94707b5 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/shieldinformationbarriersegments/ShieldInformationBarrierSegmentsITest.java @@ -0,0 +1,80 @@ +package com.box.sdkgen.shieldinformationbarriersegments; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClientWithUserSubject; +import static com.box.sdkgen.commons.CommonsManager.getOrCreateShieldInformationBarrier; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.getEnvVar; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.shieldinformationbarriersegments.CreateShieldInformationBarrierSegmentRequestBody; +import com.box.sdkgen.managers.shieldinformationbarriersegments.GetShieldInformationBarrierSegmentsQueryParams; +import com.box.sdkgen.managers.shieldinformationbarriersegments.UpdateShieldInformationBarrierSegmentByIdRequestBody; +import com.box.sdkgen.schemas.shieldinformationbarrier.ShieldInformationBarrier; +import com.box.sdkgen.schemas.shieldinformationbarrierbase.ShieldInformationBarrierBase; +import com.box.sdkgen.schemas.shieldinformationbarrierbase.ShieldInformationBarrierBaseTypeField; +import com.box.sdkgen.schemas.shieldinformationbarriersegment.ShieldInformationBarrierSegment; +import com.box.sdkgen.schemas.shieldinformationbarriersegments.ShieldInformationBarrierSegments; +import org.junit.jupiter.api.Test; + +public class ShieldInformationBarrierSegmentsITest { + + @Test + public void testShieldInformationBarrierSegments() { + BoxClient client = getDefaultClientWithUserSubject(getEnvVar("USER_ID")); + String enterpriseId = getEnvVar("ENTERPRISE_ID"); + ShieldInformationBarrier barrier = getOrCreateShieldInformationBarrier(client, enterpriseId); + String barrierId = barrier.getId(); + String segmentName = getUuid(); + String segmentDescription = "barrier segment description"; + ShieldInformationBarrierSegment segment = + client + .getShieldInformationBarrierSegments() + .createShieldInformationBarrierSegment( + new CreateShieldInformationBarrierSegmentRequestBody.Builder( + new ShieldInformationBarrierBase.Builder() + .id(barrierId) + .type(ShieldInformationBarrierBaseTypeField.SHIELD_INFORMATION_BARRIER) + .build(), + segmentName) + .description(segmentDescription) + .build()); + assert segment.getName().equals(segmentName); + ShieldInformationBarrierSegments segments = + client + .getShieldInformationBarrierSegments() + .getShieldInformationBarrierSegments( + new GetShieldInformationBarrierSegmentsQueryParams(barrierId)); + assert segments.getEntries().size() > 0; + String segmentId = segment.getId(); + ShieldInformationBarrierSegment segmentFromApi = + client + .getShieldInformationBarrierSegments() + .getShieldInformationBarrierSegmentById(segmentId); + assert convertToString(segmentFromApi.getType()).equals("shield_information_barrier_segment"); + assert segmentFromApi.getId().equals(segmentId); + assert segmentFromApi.getName().equals(segmentName); + assert segmentFromApi.getDescription().equals(segmentDescription); + assert segmentFromApi.getShieldInformationBarrier().getId().equals(barrierId); + String updatedSegmentDescription = "updated barrier segment description"; + ShieldInformationBarrierSegment updatedSegment = + client + .getShieldInformationBarrierSegments() + .updateShieldInformationBarrierSegmentById( + segmentId, + new UpdateShieldInformationBarrierSegmentByIdRequestBody.Builder() + .description(updatedSegmentDescription) + .build()); + assert updatedSegment.getDescription().equals(updatedSegmentDescription); + client + .getShieldInformationBarrierSegments() + .deleteShieldInformationBarrierSegmentById(segmentId); + assertThrows( + RuntimeException.class, + () -> + client + .getShieldInformationBarrierSegments() + .getShieldInformationBarrierSegmentById(segmentId)); + } +} diff --git a/src/intTest/java/com/box/sdkgen/shieldlists/ShieldListsITest.java b/src/intTest/java/com/box/sdkgen/shieldlists/ShieldListsITest.java new file mode 100644 index 000000000..ee7984dce --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/shieldlists/ShieldListsITest.java @@ -0,0 +1,107 @@ +package com.box.sdkgen.shieldlists; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClientWithUserSubject; +import static com.box.sdkgen.internal.utils.UtilsManager.getEnvVar; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.schemas.v2025r0.shieldlistcontentcountryv2025r0.ShieldListContentCountryV2025R0; +import com.box.sdkgen.schemas.v2025r0.shieldlistcontentcountryv2025r0.ShieldListContentCountryV2025R0TypeField; +import com.box.sdkgen.schemas.v2025r0.shieldlistcontentdomainv2025r0.ShieldListContentDomainV2025R0; +import com.box.sdkgen.schemas.v2025r0.shieldlistcontentdomainv2025r0.ShieldListContentDomainV2025R0TypeField; +import com.box.sdkgen.schemas.v2025r0.shieldlistcontentemailv2025r0.ShieldListContentEmailV2025R0; +import com.box.sdkgen.schemas.v2025r0.shieldlistcontentemailv2025r0.ShieldListContentEmailV2025R0TypeField; +import com.box.sdkgen.schemas.v2025r0.shieldlistcontentipv2025r0.ShieldListContentIpV2025R0; +import com.box.sdkgen.schemas.v2025r0.shieldlistcontentipv2025r0.ShieldListContentIpV2025R0TypeField; +import com.box.sdkgen.schemas.v2025r0.shieldlistscreatev2025r0.ShieldListsCreateV2025R0; +import com.box.sdkgen.schemas.v2025r0.shieldlistsupdatev2025r0.ShieldListsUpdateV2025R0; +import com.box.sdkgen.schemas.v2025r0.shieldlistsv2025r0.ShieldListsV2025R0; +import com.box.sdkgen.schemas.v2025r0.shieldlistv2025r0.ShieldListV2025R0; +import java.util.Arrays; +import org.junit.jupiter.api.Test; + +public class ShieldListsITest { + + private static final String userId = getEnvVar("USER_ID"); + + private static final BoxClient client = getDefaultClientWithUserSubject(userId); + + @Test + public void testCreateGetUpdateDeleteShieldList() { + String shieldListCountryName = String.join("", getUuid(), "shieldListCountry"); + ShieldListV2025R0 shieldListCountry = + client + .getShieldLists() + .createShieldListV2025R0( + new ShieldListsCreateV2025R0.Builder( + shieldListCountryName, + new ShieldListContentCountryV2025R0.Builder(Arrays.asList("US", "PL")) + .type(ShieldListContentCountryV2025R0TypeField.COUNTRY) + .build()) + .description("A list of things that are shielded") + .build()); + String shieldListContentDomainName = String.join("", getUuid(), "shieldListContentDomain"); + ShieldListV2025R0 shieldListContentDomain = + client + .getShieldLists() + .createShieldListV2025R0( + new ShieldListsCreateV2025R0.Builder( + shieldListContentDomainName, + new ShieldListContentDomainV2025R0.Builder( + Arrays.asList("box.com", "example.com")) + .type(ShieldListContentDomainV2025R0TypeField.DOMAIN) + .build()) + .description("A list of things that are shielded") + .build()); + String shieldListContentEmailName = String.join("", getUuid(), "shieldListContentEmail"); + ShieldListV2025R0 shieldListContentEmail = + client + .getShieldLists() + .createShieldListV2025R0( + new ShieldListsCreateV2025R0.Builder( + shieldListContentEmailName, + new ShieldListContentEmailV2025R0.Builder( + Arrays.asList("test@box.com", "test@example.com")) + .type(ShieldListContentEmailV2025R0TypeField.EMAIL) + .build()) + .description("A list of things that are shielded") + .build()); + String shieldListContentIpName = String.join("", getUuid(), "shieldListContentIp"); + ShieldListV2025R0 shieldListContentIp = + client + .getShieldLists() + .createShieldListV2025R0( + new ShieldListsCreateV2025R0.Builder( + shieldListContentIpName, + new ShieldListContentIpV2025R0.Builder( + Arrays.asList("127.0.0.1", "80.12.12.12/24")) + .type(ShieldListContentIpV2025R0TypeField.IP) + .build()) + .description("A list of things that are shielded") + .build()); + ShieldListsV2025R0 shieldLists = client.getShieldLists().getShieldListsV2025R0(); + assert shieldLists.getEntries().size() > 0; + ShieldListV2025R0 getShieldListCountry = + client.getShieldLists().getShieldListByIdV2025R0(shieldListCountry.getId()); + assert getShieldListCountry.getName().equals(shieldListCountryName); + assert getShieldListCountry.getDescription().equals("A list of things that are shielded"); + client + .getShieldLists() + .updateShieldListByIdV2025R0( + shieldListCountry.getId(), + new ShieldListsUpdateV2025R0.Builder( + shieldListCountryName, + new ShieldListContentCountryV2025R0.Builder(Arrays.asList("US")) + .type(ShieldListContentCountryV2025R0TypeField.COUNTRY) + .build()) + .description("Updated description") + .build()); + ShieldListV2025R0 getShieldListCountryUpdated = + client.getShieldLists().getShieldListByIdV2025R0(shieldListCountry.getId()); + assert getShieldListCountryUpdated.getDescription().equals("Updated description"); + client.getShieldLists().deleteShieldListByIdV2025R0(shieldListCountry.getId()); + client.getShieldLists().deleteShieldListByIdV2025R0(shieldListContentDomain.getId()); + client.getShieldLists().deleteShieldListByIdV2025R0(shieldListContentEmail.getId()); + client.getShieldLists().deleteShieldListByIdV2025R0(shieldListContentIp.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/signrequests/SignRequestsITest.java b/src/intTest/java/com/box/sdkgen/signrequests/SignRequestsITest.java new file mode 100644 index 000000000..a0ab3d6c9 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/signrequests/SignRequestsITest.java @@ -0,0 +1,162 @@ +package com.box.sdkgen.signrequests; + +import static com.box.sdkgen.commons.CommonsManager.createNewFolder; +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.commons.CommonsManager.uploadNewFile; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.dateFromString; +import static com.box.sdkgen.internal.utils.UtilsManager.dateToString; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.folders.DeleteFolderByIdQueryParams; +import com.box.sdkgen.schemas.filebase.FileBase; +import com.box.sdkgen.schemas.filefull.FileFull; +import com.box.sdkgen.schemas.folderfull.FolderFull; +import com.box.sdkgen.schemas.foldermini.FolderMini; +import com.box.sdkgen.schemas.signrequest.SignRequest; +import com.box.sdkgen.schemas.signrequestcreaterequest.SignRequestCreateRequest; +import com.box.sdkgen.schemas.signrequestcreatesigner.SignRequestCreateSigner; +import com.box.sdkgen.schemas.signrequestcreatesigner.SignRequestCreateSignerRoleField; +import com.box.sdkgen.schemas.signrequestprefilltag.SignRequestPrefillTag; +import com.box.sdkgen.schemas.signrequests.SignRequests; +import java.util.Arrays; +import org.junit.jupiter.api.Test; + +public class SignRequestsITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testCreateGetCancelAndListSignRequest() { + String signerEmail = String.join("", getUuid(), "@box.com"); + FileFull fileToSign = uploadNewFile(); + FolderFull destinationFolder = createNewFolder(); + SignRequest createdSignRequest = + client + .getSignRequests() + .createSignRequest( + new SignRequestCreateRequest.Builder( + Arrays.asList( + new SignRequestCreateSigner.Builder() + .email(signerEmail) + .role(SignRequestCreateSignerRoleField.SIGNER) + .isInPerson(false) + .embedUrlExternalUserId("123") + .declinedRedirectUrl("https://www.box.com") + .loginRequired(false) + .password("password") + .suppressNotifications(true) + .build())) + .sourceFiles(Arrays.asList(new FileBase(fileToSign.getId()))) + .parentFolder(new FolderMini(destinationFolder.getId())) + .isDocumentPreparationNeeded(false) + .redirectUrl("https://www.box.com") + .declinedRedirectUrl("https://www.box.com") + .areTextSignaturesEnabled(true) + .emailSubject("Sign this document") + .emailMessage("Please sign this document") + .areRemindersEnabled(true) + .name("Sign Request") + .prefillTags( + Arrays.asList( + new SignRequestPrefillTag.Builder() + .documentTagId("0") + .dateValue(dateFromString("2035-01-01")) + .build())) + .daysValid(30L) + .externalId("123") + .externalSystemName("BoxSignIntegration") + .build()); + assert createdSignRequest.getAreRemindersEnabled() == true; + assert createdSignRequest.getAreTextSignaturesEnabled() == true; + assert createdSignRequest.getDaysValid() == 30; + assert createdSignRequest.getDeclinedRedirectUrl().equals("https://www.box.com"); + assert createdSignRequest.getEmailMessage().equals("Please sign this document"); + assert createdSignRequest.getEmailSubject().equals("Sign this document"); + assert createdSignRequest.getExternalId().equals("123"); + assert createdSignRequest.getExternalSystemName().equals("BoxSignIntegration"); + assert createdSignRequest.getIsDocumentPreparationNeeded() == false; + assert createdSignRequest.getName().equals("Sign Request.pdf"); + assert createdSignRequest.getRedirectUrl().equals("https://www.box.com"); + assert createdSignRequest + .getSignFiles() + .getFiles() + .get(0) + .getName() + .equals(createdSignRequest.getName()); + assert createdSignRequest.getSigners().get(1).getEmail().equals(signerEmail); + assert createdSignRequest.getSigners().get(1).getSuppressNotifications() == true; + assert createdSignRequest + .getSigners() + .get(1) + .getDeclinedRedirectUrl() + .equals("https://www.box.com"); + assert createdSignRequest.getSigners().get(1).getEmbedUrlExternalUserId().equals("123"); + assert createdSignRequest.getSigners().get(1).getIsInPerson() == false; + assert createdSignRequest.getSigners().get(1).getLoginRequired() == false; + assert convertToString(createdSignRequest.getSigners().get(1).getRole()).equals("signer"); + assert createdSignRequest.getParentFolder().getId().equals(destinationFolder.getId()); + assert dateToString(createdSignRequest.getPrefillTags().get(0).getDateValue()) + .equals("2035-01-01"); + SignRequest newSignRequest = + client.getSignRequests().getSignRequestById(createdSignRequest.getId()); + assert newSignRequest + .getSignFiles() + .getFiles() + .get(0) + .getName() + .equals(createdSignRequest.getName()); + assert newSignRequest.getSigners().get(1).getEmail().equals(signerEmail); + assert newSignRequest.getParentFolder().getId().equals(destinationFolder.getId()); + SignRequest cancelledSignRequest = + client.getSignRequests().cancelSignRequest(createdSignRequest.getId()); + assert convertToString(cancelledSignRequest.getStatus()).equals("cancelled"); + SignRequests signRequests = client.getSignRequests().getSignRequests(); + assert convertToString(signRequests.getEntries().get(0).getType()).equals("sign-request"); + client + .getFolders() + .deleteFolderById( + destinationFolder.getId(), + new DeleteFolderByIdQueryParams.Builder().recursive(true).build()); + client.getFiles().deleteFileById(fileToSign.getId()); + } + + @Test + public void testCreateSignRequestWithSignerGroupId() { + String signer1Email = String.join("", getUuid(), "@box.com"); + String signer2Email = String.join("", getUuid(), "@box.com"); + FileFull fileToSign = uploadNewFile(); + FolderFull destinationFolder = createNewFolder(); + SignRequest createdSignRequest = + client + .getSignRequests() + .createSignRequest( + new SignRequestCreateRequest.Builder( + Arrays.asList( + new SignRequestCreateSigner.Builder() + .email(signer1Email) + .signerGroupId("user") + .build(), + new SignRequestCreateSigner.Builder() + .email(signer2Email) + .signerGroupId("user") + .build())) + .sourceFiles(Arrays.asList(new FileBase(fileToSign.getId()))) + .parentFolder(new FolderMini(destinationFolder.getId())) + .build()); + assert createdSignRequest.getSigners().size() == 3; + assert !(createdSignRequest.getSigners().get(1).getSignerGroupId() == null); + assert createdSignRequest + .getSigners() + .get(1) + .getSignerGroupId() + .equals(createdSignRequest.getSigners().get(2).getSignerGroupId()); + client + .getFolders() + .deleteFolderById( + destinationFolder.getId(), + new DeleteFolderByIdQueryParams.Builder().recursive(true).build()); + client.getFiles().deleteFileById(fileToSign.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/signtemplates/SignTemplatesITest.java b/src/intTest/java/com/box/sdkgen/signtemplates/SignTemplatesITest.java new file mode 100644 index 000000000..ad1049767 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/signtemplates/SignTemplatesITest.java @@ -0,0 +1,41 @@ +package com.box.sdkgen.signtemplates; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClientWithUserSubject; +import static com.box.sdkgen.internal.utils.UtilsManager.getEnvVar; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.signtemplates.GetSignTemplatesQueryParams; +import com.box.sdkgen.schemas.signtemplate.SignTemplate; +import com.box.sdkgen.schemas.signtemplates.SignTemplates; +import org.junit.jupiter.api.Test; + +public class SignTemplatesITest { + + @Test + public void testGetSignTemplates() { + BoxClient client = getDefaultClientWithUserSubject(getEnvVar("USER_ID")); + SignTemplates signTemplates = + client + .getSignTemplates() + .getSignTemplates(new GetSignTemplatesQueryParams.Builder().limit(2L).build()); + assert signTemplates.getEntries().size() >= 0; + } + + @Test + public void testGetSignTemplate() { + BoxClient client = getDefaultClientWithUserSubject(getEnvVar("USER_ID")); + SignTemplates signTemplates = + client + .getSignTemplates() + .getSignTemplates(new GetSignTemplatesQueryParams.Builder().limit(2L).build()); + assert signTemplates.getEntries().size() >= 0; + if (signTemplates.getEntries().size() > 0) { + SignTemplate signTemplate = + client.getSignTemplates().getSignTemplateById(signTemplates.getEntries().get(0).getId()); + assert signTemplate.getId().equals(signTemplates.getEntries().get(0).getId()); + assert signTemplate.getSourceFiles().size() > 0; + assert !(signTemplate.getName().equals("")); + assert !(signTemplate.getParentFolder().getId().equals("")); + } + } +} diff --git a/src/intTest/java/com/box/sdkgen/skills/SkillsITest.java b/src/intTest/java/com/box/sdkgen/skills/SkillsITest.java new file mode 100644 index 000000000..e2d56ff50 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/skills/SkillsITest.java @@ -0,0 +1,103 @@ +package com.box.sdkgen.skills; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.commons.CommonsManager.uploadNewFile; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.skills.CreateBoxSkillCardsOnFileRequestBody; +import com.box.sdkgen.managers.skills.UpdateBoxSkillCardsOnFileRequestBody; +import com.box.sdkgen.managers.skills.UpdateBoxSkillCardsOnFileRequestBodyOpField; +import com.box.sdkgen.schemas.filefull.FileFull; +import com.box.sdkgen.schemas.keywordskillcard.KeywordSkillCard; +import com.box.sdkgen.schemas.keywordskillcard.KeywordSkillCardEntriesField; +import com.box.sdkgen.schemas.keywordskillcard.KeywordSkillCardInvocationField; +import com.box.sdkgen.schemas.keywordskillcard.KeywordSkillCardInvocationTypeField; +import com.box.sdkgen.schemas.keywordskillcard.KeywordSkillCardSkillCardTitleField; +import com.box.sdkgen.schemas.keywordskillcard.KeywordSkillCardSkillCardTypeField; +import com.box.sdkgen.schemas.keywordskillcard.KeywordSkillCardSkillField; +import com.box.sdkgen.schemas.keywordskillcard.KeywordSkillCardSkillTypeField; +import com.box.sdkgen.schemas.keywordskillcard.KeywordSkillCardTypeField; +import com.box.sdkgen.schemas.skillcard.SkillCard; +import com.box.sdkgen.schemas.skillcardsmetadata.SkillCardsMetadata; +import java.util.Arrays; +import java.util.List; +import org.junit.jupiter.api.Test; + +public class SkillsITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testSkillsCardsCrud() { + FileFull file = uploadNewFile(); + String skillId = getUuid(); + String invocationId = getUuid(); + String titleMessage = "License Plates"; + KeywordSkillCard cardToCreate = + new KeywordSkillCard.Builder( + new KeywordSkillCardSkillField.Builder(skillId) + .type(KeywordSkillCardSkillTypeField.SERVICE) + .build(), + new KeywordSkillCardInvocationField.Builder(invocationId) + .type(KeywordSkillCardInvocationTypeField.SKILL_INVOCATION) + .build(), + Arrays.asList(new KeywordSkillCardEntriesField.Builder().text("DN86 BOX").build())) + .type(KeywordSkillCardTypeField.SKILL_CARD) + .skillCardType(KeywordSkillCardSkillCardTypeField.KEYWORD) + .skillCardTitle( + new KeywordSkillCardSkillCardTitleField.Builder(titleMessage) + .code("license-plates") + .build()) + .build(); + List cardsToCreate = Arrays.asList(new SkillCard(cardToCreate)); + SkillCardsMetadata skillCardsMetadata = + client + .getSkills() + .createBoxSkillCardsOnFile( + file.getId(), new CreateBoxSkillCardsOnFileRequestBody(cardsToCreate)); + assert skillCardsMetadata.getCards().size() == 1; + KeywordSkillCard keywordSkillCard = skillCardsMetadata.getCards().get(0).getKeywordSkillCard(); + assert keywordSkillCard.getSkill().getId().equals(skillId); + assert keywordSkillCard.getSkillCardTitle().getMessage().equals(titleMessage); + String updatedTitleMessage = "Updated License Plates"; + KeywordSkillCard cardToUpdate = + new KeywordSkillCard.Builder( + new KeywordSkillCardSkillField.Builder(skillId) + .type(KeywordSkillCardSkillTypeField.SERVICE) + .build(), + new KeywordSkillCardInvocationField.Builder(invocationId) + .type(KeywordSkillCardInvocationTypeField.SKILL_INVOCATION) + .build(), + Arrays.asList(new KeywordSkillCardEntriesField.Builder().text("DN86 BOX").build())) + .type(KeywordSkillCardTypeField.SKILL_CARD) + .skillCardType(KeywordSkillCardSkillCardTypeField.KEYWORD) + .skillCardTitle( + new KeywordSkillCardSkillCardTitleField.Builder(updatedTitleMessage) + .code("license-plates") + .build()) + .build(); + SkillCardsMetadata updatedSkillCardsMetadata = + client + .getSkills() + .updateBoxSkillCardsOnFile( + file.getId(), + Arrays.asList( + new UpdateBoxSkillCardsOnFileRequestBody.Builder() + .op(UpdateBoxSkillCardsOnFileRequestBodyOpField.REPLACE) + .path("/cards/0") + .value(cardToUpdate) + .build())); + KeywordSkillCard updatedKeywordSkillCard = + updatedSkillCardsMetadata.getCards().get(0).getKeywordSkillCard(); + assert updatedKeywordSkillCard.getSkill().getId().equals(skillId); + assert updatedKeywordSkillCard.getSkillCardTitle().getMessage().equals(updatedTitleMessage); + SkillCardsMetadata receivedSkillCardsMetadata = + client.getSkills().getBoxSkillCardsOnFile(file.getId()); + KeywordSkillCard receivedKeywordSkillCard = + receivedSkillCardsMetadata.getCards().get(0).getKeywordSkillCard(); + assert receivedKeywordSkillCard.getSkill().getId().equals(skillId); + client.getSkills().deleteBoxSkillCardsFromFile(file.getId()); + client.getFiles().deleteFileById(file.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/storagepolicicyassignments/StoragePolicicyAssignmentsITest.java b/src/intTest/java/com/box/sdkgen/storagepolicicyassignments/StoragePolicicyAssignmentsITest.java new file mode 100644 index 000000000..83df9db7e --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/storagepolicicyassignments/StoragePolicicyAssignmentsITest.java @@ -0,0 +1,90 @@ +package com.box.sdkgen.storagepolicicyassignments; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClientWithUserSubject; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.getEnvVar; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.storagepolicyassignments.CreateStoragePolicyAssignmentRequestBody; +import com.box.sdkgen.managers.storagepolicyassignments.CreateStoragePolicyAssignmentRequestBodyAssignedToField; +import com.box.sdkgen.managers.storagepolicyassignments.CreateStoragePolicyAssignmentRequestBodyAssignedToTypeField; +import com.box.sdkgen.managers.storagepolicyassignments.CreateStoragePolicyAssignmentRequestBodyStoragePolicyField; +import com.box.sdkgen.managers.storagepolicyassignments.GetStoragePolicyAssignmentsQueryParams; +import com.box.sdkgen.managers.storagepolicyassignments.GetStoragePolicyAssignmentsQueryParamsResolvedForTypeField; +import com.box.sdkgen.managers.storagepolicyassignments.UpdateStoragePolicyAssignmentByIdRequestBody; +import com.box.sdkgen.managers.storagepolicyassignments.UpdateStoragePolicyAssignmentByIdRequestBodyStoragePolicyField; +import com.box.sdkgen.managers.users.CreateUserRequestBody; +import com.box.sdkgen.schemas.storagepolicies.StoragePolicies; +import com.box.sdkgen.schemas.storagepolicy.StoragePolicy; +import com.box.sdkgen.schemas.storagepolicyassignment.StoragePolicyAssignment; +import com.box.sdkgen.schemas.storagepolicyassignments.StoragePolicyAssignments; +import com.box.sdkgen.schemas.userfull.UserFull; +import org.junit.jupiter.api.Test; + +public class StoragePolicicyAssignmentsITest { + + private static final String adminUserId = getEnvVar("USER_ID"); + + public static StoragePolicyAssignment getOrCreateStoragePolicyAssignment( + BoxClient client, String policyId, String userId) { + StoragePolicyAssignments storagePolicyAssignments = + client + .getStoragePolicyAssignments() + .getStoragePolicyAssignments( + new GetStoragePolicyAssignmentsQueryParams( + GetStoragePolicyAssignmentsQueryParamsResolvedForTypeField.USER, userId)); + if (storagePolicyAssignments.getEntries().size() > 0) { + if (convertToString(storagePolicyAssignments.getEntries().get(0).getAssignedTo().getType()) + .equals("user")) { + return storagePolicyAssignments.getEntries().get(0); + } + } + StoragePolicyAssignment storagePolicyAssignment = + client + .getStoragePolicyAssignments() + .createStoragePolicyAssignment( + new CreateStoragePolicyAssignmentRequestBody( + new CreateStoragePolicyAssignmentRequestBodyStoragePolicyField(policyId), + new CreateStoragePolicyAssignmentRequestBodyAssignedToField( + CreateStoragePolicyAssignmentRequestBodyAssignedToTypeField.USER, userId))); + return storagePolicyAssignment; + } + + @Test + public void testGetStoragePolicyAssignments() { + BoxClient client = getDefaultClientWithUserSubject(adminUserId); + String userName = getUuid(); + UserFull newUser = + client + .getUsers() + .createUser( + new CreateUserRequestBody.Builder(userName).isPlatformAccessOnly(true).build()); + StoragePolicies storagePolicies = client.getStoragePolicies().getStoragePolicies(); + StoragePolicy storagePolicy1 = storagePolicies.getEntries().get(0); + StoragePolicy storagePolicy2 = storagePolicies.getEntries().get(1); + StoragePolicyAssignment storagePolicyAssignment = + getOrCreateStoragePolicyAssignment(client, storagePolicy1.getId(), newUser.getId()); + assert convertToString(storagePolicyAssignment.getType()).equals("storage_policy_assignment"); + assert convertToString(storagePolicyAssignment.getAssignedTo().getType()).equals("user"); + assert storagePolicyAssignment.getAssignedTo().getId().equals(newUser.getId()); + StoragePolicyAssignment getStoragePolicyAssignment = + client + .getStoragePolicyAssignments() + .getStoragePolicyAssignmentById(storagePolicyAssignment.getId()); + assert getStoragePolicyAssignment.getId().equals(storagePolicyAssignment.getId()); + StoragePolicyAssignment updatedStoragePolicyAssignment = + client + .getStoragePolicyAssignments() + .updateStoragePolicyAssignmentById( + storagePolicyAssignment.getId(), + new UpdateStoragePolicyAssignmentByIdRequestBody( + new UpdateStoragePolicyAssignmentByIdRequestBodyStoragePolicyField( + storagePolicy2.getId()))); + assert updatedStoragePolicyAssignment.getStoragePolicy().getId().equals(storagePolicy2.getId()); + client + .getStoragePolicyAssignments() + .deleteStoragePolicyAssignmentById(storagePolicyAssignment.getId()); + client.getUsers().deleteUserById(newUser.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/storagepolicies/StoragePoliciesITest.java b/src/intTest/java/com/box/sdkgen/storagepolicies/StoragePoliciesITest.java new file mode 100644 index 000000000..0e0042ace --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/storagepolicies/StoragePoliciesITest.java @@ -0,0 +1,26 @@ +package com.box.sdkgen.storagepolicies; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClientWithUserSubject; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.getEnvVar; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.schemas.storagepolicies.StoragePolicies; +import com.box.sdkgen.schemas.storagepolicy.StoragePolicy; +import org.junit.jupiter.api.Test; + +public class StoragePoliciesITest { + + private static final String userId = getEnvVar("USER_ID"); + + @Test + public void testGetStoragePolicies() { + BoxClient client = getDefaultClientWithUserSubject(userId); + StoragePolicies storagePolicies = client.getStoragePolicies().getStoragePolicies(); + StoragePolicy storagePolicy = storagePolicies.getEntries().get(0); + assert convertToString(storagePolicy.getType()).equals("storage_policy"); + StoragePolicy getStoragePolicy = + client.getStoragePolicies().getStoragePolicyById(storagePolicy.getId()); + assert getStoragePolicy.getId().equals(storagePolicy.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/taskassignments/TaskAssignmentsITest.java b/src/intTest/java/com/box/sdkgen/taskassignments/TaskAssignmentsITest.java new file mode 100644 index 000000000..fe0ba9b83 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/taskassignments/TaskAssignmentsITest.java @@ -0,0 +1,90 @@ +package com.box.sdkgen.taskassignments; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.commons.CommonsManager.uploadNewFile; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.dateTimeFromString; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.taskassignments.CreateTaskAssignmentRequestBody; +import com.box.sdkgen.managers.taskassignments.CreateTaskAssignmentRequestBodyAssignToField; +import com.box.sdkgen.managers.taskassignments.CreateTaskAssignmentRequestBodyTaskField; +import com.box.sdkgen.managers.taskassignments.CreateTaskAssignmentRequestBodyTaskTypeField; +import com.box.sdkgen.managers.taskassignments.UpdateTaskAssignmentByIdRequestBody; +import com.box.sdkgen.managers.taskassignments.UpdateTaskAssignmentByIdRequestBodyResolutionStateField; +import com.box.sdkgen.managers.tasks.CreateTaskRequestBody; +import com.box.sdkgen.managers.tasks.CreateTaskRequestBodyActionField; +import com.box.sdkgen.managers.tasks.CreateTaskRequestBodyCompletionRuleField; +import com.box.sdkgen.managers.tasks.CreateTaskRequestBodyItemField; +import com.box.sdkgen.managers.tasks.CreateTaskRequestBodyItemTypeField; +import com.box.sdkgen.schemas.filefull.FileFull; +import com.box.sdkgen.schemas.task.Task; +import com.box.sdkgen.schemas.taskassignment.TaskAssignment; +import com.box.sdkgen.schemas.taskassignments.TaskAssignments; +import com.box.sdkgen.schemas.userfull.UserFull; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; + +public class TaskAssignmentsITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testCreateUpdateGetDeleteTaskAssignment() { + FileFull file = uploadNewFile(); + OffsetDateTime date = dateTimeFromString("2035-01-01T00:00:00Z"); + Task task = + client + .getTasks() + .createTask( + new CreateTaskRequestBody.Builder( + new CreateTaskRequestBodyItemField.Builder() + .id(file.getId()) + .type(CreateTaskRequestBodyItemTypeField.FILE) + .build()) + .action(CreateTaskRequestBodyActionField.REVIEW) + .message("test message") + .dueAt(date) + .completionRule(CreateTaskRequestBodyCompletionRuleField.ALL_ASSIGNEES) + .build()); + assert task.getMessage().equals("test message"); + assert task.getItem().getId().equals(file.getId()); + UserFull currentUser = client.getUsers().getUserMe(); + TaskAssignment taskAssignment = + client + .getTaskAssignments() + .createTaskAssignment( + new CreateTaskAssignmentRequestBody( + new CreateTaskAssignmentRequestBodyTaskField.Builder(task.getId()) + .type(CreateTaskAssignmentRequestBodyTaskTypeField.TASK) + .build(), + new CreateTaskAssignmentRequestBodyAssignToField.Builder() + .id(currentUser.getId()) + .build())); + assert taskAssignment.getItem().getId().equals(file.getId()); + assert taskAssignment.getAssignedTo().getId().equals(currentUser.getId()); + TaskAssignment taskAssignmentById = + client.getTaskAssignments().getTaskAssignmentById(taskAssignment.getId()); + assert taskAssignmentById.getId().equals(taskAssignment.getId()); + TaskAssignments taskAssignmentsOnTask = + client.getTaskAssignments().getTaskAssignments(task.getId()); + assert taskAssignmentsOnTask.getTotalCount() == 1; + TaskAssignment updatedTaskAssignment = + client + .getTaskAssignments() + .updateTaskAssignmentById( + taskAssignment.getId(), + new UpdateTaskAssignmentByIdRequestBody.Builder() + .message("updated message") + .resolutionState( + UpdateTaskAssignmentByIdRequestBodyResolutionStateField.APPROVED) + .build()); + assert updatedTaskAssignment.getMessage().equals("updated message"); + assert convertToString(updatedTaskAssignment.getResolutionState()).equals("approved"); + assertThrows( + RuntimeException.class, + () -> client.getTaskAssignments().deleteTaskAssignmentById(taskAssignment.getId())); + client.getFiles().deleteFileById(file.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/tasks/TasksITest.java b/src/intTest/java/com/box/sdkgen/tasks/TasksITest.java new file mode 100644 index 000000000..37f8d2b61 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/tasks/TasksITest.java @@ -0,0 +1,73 @@ +package com.box.sdkgen.tasks; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.internal.utils.UtilsManager.dateTimeFromString; +import static com.box.sdkgen.internal.utils.UtilsManager.dateTimeToString; +import static com.box.sdkgen.internal.utils.UtilsManager.generateByteStream; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.tasks.CreateTaskRequestBody; +import com.box.sdkgen.managers.tasks.CreateTaskRequestBodyActionField; +import com.box.sdkgen.managers.tasks.CreateTaskRequestBodyCompletionRuleField; +import com.box.sdkgen.managers.tasks.CreateTaskRequestBodyItemField; +import com.box.sdkgen.managers.tasks.CreateTaskRequestBodyItemTypeField; +import com.box.sdkgen.managers.tasks.UpdateTaskByIdRequestBody; +import com.box.sdkgen.managers.uploads.UploadFileRequestBody; +import com.box.sdkgen.managers.uploads.UploadFileRequestBodyAttributesField; +import com.box.sdkgen.managers.uploads.UploadFileRequestBodyAttributesParentField; +import com.box.sdkgen.schemas.filefull.FileFull; +import com.box.sdkgen.schemas.files.Files; +import com.box.sdkgen.schemas.task.Task; +import com.box.sdkgen.schemas.tasks.Tasks; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; + +public class TasksITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testCreateUpdateGetDeleteTask() { + Files files = + client + .getUploads() + .uploadFile( + new UploadFileRequestBody( + new UploadFileRequestBodyAttributesField( + getUuid(), new UploadFileRequestBodyAttributesParentField("0")), + generateByteStream(10))); + FileFull file = files.getEntries().get(0); + OffsetDateTime dateTime = dateTimeFromString("2035-01-01T00:00:00Z"); + Task task = + client + .getTasks() + .createTask( + new CreateTaskRequestBody.Builder( + new CreateTaskRequestBodyItemField.Builder() + .id(file.getId()) + .type(CreateTaskRequestBodyItemTypeField.FILE) + .build()) + .action(CreateTaskRequestBodyActionField.REVIEW) + .message("test message") + .dueAt(dateTime) + .completionRule(CreateTaskRequestBodyCompletionRuleField.ALL_ASSIGNEES) + .build()); + assert task.getMessage().equals("test message"); + assert task.getItem().getId().equals(file.getId()); + assert dateTimeToString(task.getDueAt()).equals(dateTimeToString(dateTime)); + Task taskById = client.getTasks().getTaskById(task.getId()); + assert taskById.getId().equals(task.getId()); + Tasks taskOnFile = client.getTasks().getFileTasks(file.getId()); + assert taskOnFile.getTotalCount() == 1; + Task updatedTask = + client + .getTasks() + .updateTaskById( + task.getId(), + new UpdateTaskByIdRequestBody.Builder().message("updated message").build()); + assert updatedTask.getMessage().equals("updated message"); + client.getTasks().deleteTaskById(task.getId()); + client.getFiles().deleteFileById(file.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/termsofservices/TermsOfServicesITest.java b/src/intTest/java/com/box/sdkgen/termsofservices/TermsOfServicesITest.java new file mode 100644 index 000000000..c363eca9a --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/termsofservices/TermsOfServicesITest.java @@ -0,0 +1,42 @@ +package com.box.sdkgen.termsofservices; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.commons.CommonsManager.getOrCreateTermsOfServices; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.termsofservices.UpdateTermsOfServiceByIdRequestBody; +import com.box.sdkgen.managers.termsofservices.UpdateTermsOfServiceByIdRequestBodyStatusField; +import com.box.sdkgen.schemas.termsofservice.TermsOfService; +import com.box.sdkgen.schemas.termsofservices.TermsOfServices; +import org.junit.jupiter.api.Test; + +public class TermsOfServicesITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testGetTermsOfServices() { + TermsOfService tos = getOrCreateTermsOfServices(); + TermsOfService updatedTos1 = + client + .getTermsOfServices() + .updateTermsOfServiceById( + tos.getId(), + new UpdateTermsOfServiceByIdRequestBody( + UpdateTermsOfServiceByIdRequestBodyStatusField.DISABLED, "TOS")); + assert convertToString(updatedTos1.getStatus()).equals("disabled"); + assert updatedTos1.getText().equals("TOS"); + TermsOfService updatedTos2 = + client + .getTermsOfServices() + .updateTermsOfServiceById( + tos.getId(), + new UpdateTermsOfServiceByIdRequestBody( + UpdateTermsOfServiceByIdRequestBodyStatusField.DISABLED, "Updated TOS")); + assert convertToString(updatedTos2.getStatus()).equals("disabled"); + assert updatedTos2.getText().equals("Updated TOS"); + TermsOfServices listTos = client.getTermsOfServices().getTermsOfService(); + assert listTos.getTotalCount() > 0; + } +} diff --git a/src/intTest/java/com/box/sdkgen/termsofserviceuserstatuses/TermsOfServiceUserStatusesITest.java b/src/intTest/java/com/box/sdkgen/termsofserviceuserstatuses/TermsOfServiceUserStatusesITest.java new file mode 100644 index 000000000..893e06081 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/termsofserviceuserstatuses/TermsOfServiceUserStatusesITest.java @@ -0,0 +1,68 @@ +package com.box.sdkgen.termsofserviceuserstatuses; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClientWithUserSubject; +import static com.box.sdkgen.commons.CommonsManager.getOrCreateTermsOfServices; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.getEnvVar; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.termsofserviceuserstatuses.CreateTermsOfServiceStatusForUserRequestBody; +import com.box.sdkgen.managers.termsofserviceuserstatuses.CreateTermsOfServiceStatusForUserRequestBodyTosField; +import com.box.sdkgen.managers.termsofserviceuserstatuses.CreateTermsOfServiceStatusForUserRequestBodyUserField; +import com.box.sdkgen.managers.termsofserviceuserstatuses.GetTermsOfServiceUserStatusesQueryParams; +import com.box.sdkgen.managers.termsofserviceuserstatuses.UpdateTermsOfServiceStatusForUserByIdRequestBody; +import com.box.sdkgen.managers.users.CreateUserRequestBody; +import com.box.sdkgen.schemas.termsofservice.TermsOfService; +import com.box.sdkgen.schemas.termsofserviceuserstatus.TermsOfServiceUserStatus; +import com.box.sdkgen.schemas.termsofserviceuserstatuses.TermsOfServiceUserStatuses; +import com.box.sdkgen.schemas.userfull.UserFull; +import org.junit.jupiter.api.Test; + +public class TermsOfServiceUserStatusesITest { + + @Test + public void testGetTermsOfServiceUserStatuses() { + String adminUserId = getEnvVar("USER_ID"); + BoxClient client = getDefaultClientWithUserSubject(adminUserId); + TermsOfService tos = getOrCreateTermsOfServices(); + UserFull user = + client + .getUsers() + .createUser( + new CreateUserRequestBody.Builder(getUuid()) + .login(String.join("", getUuid(), "@boxdemo.com")) + .isPlatformAccessOnly(true) + .build()); + TermsOfServiceUserStatus createdTosUserStatus = + client + .getTermsOfServiceUserStatuses() + .createTermsOfServiceStatusForUser( + new CreateTermsOfServiceStatusForUserRequestBody( + new CreateTermsOfServiceStatusForUserRequestBodyTosField(tos.getId()), + new CreateTermsOfServiceStatusForUserRequestBodyUserField(user.getId()), + false)); + assert createdTosUserStatus.getIsAccepted() == false; + assert convertToString(createdTosUserStatus.getType()).equals("terms_of_service_user_status"); + assert convertToString(createdTosUserStatus.getTos().getType()).equals("terms_of_service"); + assert convertToString(createdTosUserStatus.getUser().getType()).equals("user"); + assert createdTosUserStatus.getTos().getId().equals(tos.getId()); + assert createdTosUserStatus.getUser().getId().equals(user.getId()); + TermsOfServiceUserStatus updatedTosUserStatus = + client + .getTermsOfServiceUserStatuses() + .updateTermsOfServiceStatusForUserById( + createdTosUserStatus.getId(), + new UpdateTermsOfServiceStatusForUserByIdRequestBody(true)); + assert updatedTosUserStatus.getIsAccepted() == true; + TermsOfServiceUserStatuses listTosUserStatuses = + client + .getTermsOfServiceUserStatuses() + .getTermsOfServiceUserStatuses( + new GetTermsOfServiceUserStatusesQueryParams.Builder(tos.getId()) + .userId(user.getId()) + .build()); + assert listTosUserStatuses.getTotalCount() > 0; + client.getUsers().deleteUserById(user.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/transfer/TransferITest.java b/src/intTest/java/com/box/sdkgen/transfer/TransferITest.java new file mode 100644 index 000000000..c9981af86 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/transfer/TransferITest.java @@ -0,0 +1,52 @@ +package com.box.sdkgen.transfer; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.folders.DeleteFolderByIdQueryParams; +import com.box.sdkgen.managers.transfer.TransferOwnedFolderQueryParams; +import com.box.sdkgen.managers.transfer.TransferOwnedFolderRequestBody; +import com.box.sdkgen.managers.transfer.TransferOwnedFolderRequestBodyOwnedByField; +import com.box.sdkgen.managers.users.CreateUserRequestBody; +import com.box.sdkgen.managers.users.DeleteUserByIdQueryParams; +import com.box.sdkgen.schemas.folderfull.FolderFull; +import com.box.sdkgen.schemas.userfull.UserFull; +import org.junit.jupiter.api.Test; + +public class TransferITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testTransferUserContent() { + String sourceUserName = getUuid(); + UserFull sourceUser = + client + .getUsers() + .createUser( + new CreateUserRequestBody.Builder(sourceUserName) + .isPlatformAccessOnly(true) + .build()); + UserFull targetUser = client.getUsers().getUserMe(); + FolderFull transferredFolder = + client + .getTransfer() + .transferOwnedFolder( + sourceUser.getId(), + new TransferOwnedFolderRequestBody( + new TransferOwnedFolderRequestBodyOwnedByField(targetUser.getId())), + new TransferOwnedFolderQueryParams.Builder().notify(false).build()); + assert transferredFolder.getOwnedBy().getId().equals(targetUser.getId()); + client + .getFolders() + .deleteFolderById( + transferredFolder.getId(), + new DeleteFolderByIdQueryParams.Builder().recursive(true).build()); + client + .getUsers() + .deleteUserById( + sourceUser.getId(), + new DeleteUserByIdQueryParams.Builder().notify(false).force(true).build()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/trashedfiles/TrashedFilesITest.java b/src/intTest/java/com/box/sdkgen/trashedfiles/TrashedFilesITest.java new file mode 100644 index 000000000..eed2e343c --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/trashedfiles/TrashedFilesITest.java @@ -0,0 +1,54 @@ +package com.box.sdkgen.trashedfiles; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.generateByteStream; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.uploads.UploadFileRequestBody; +import com.box.sdkgen.managers.uploads.UploadFileRequestBodyAttributesField; +import com.box.sdkgen.managers.uploads.UploadFileRequestBodyAttributesParentField; +import com.box.sdkgen.schemas.filefull.FileFull; +import com.box.sdkgen.schemas.files.Files; +import com.box.sdkgen.schemas.trashfile.TrashFile; +import com.box.sdkgen.schemas.trashfilerestored.TrashFileRestored; +import java.io.InputStream; +import org.junit.jupiter.api.Test; + +public class TrashedFilesITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testTrashedFiles() { + int fileSize = 1024 * 1024; + String fileName = getUuid(); + InputStream fileByteStream = generateByteStream(fileSize); + Files files = + client + .getUploads() + .uploadFile( + new UploadFileRequestBody( + new UploadFileRequestBodyAttributesField( + fileName, new UploadFileRequestBodyAttributesParentField("0")), + fileByteStream)); + FileFull file = files.getEntries().get(0); + client.getFiles().deleteFileById(file.getId()); + TrashFile fromTrash = client.getTrashedFiles().getTrashedFileById(file.getId()); + assert fromTrash.getId().equals(file.getId()); + assert fromTrash.getName().equals(file.getName()); + FileFull fromApiAfterTrashed = client.getFiles().getFileById(file.getId()); + assert convertToString(fromApiAfterTrashed.getItemStatus()).equals("trashed"); + TrashFileRestored restoredFile = client.getTrashedFiles().restoreFileFromTrash(file.getId()); + FileFull fromApiAfterRestore = client.getFiles().getFileById(file.getId()); + assert restoredFile.getId().equals(fromApiAfterRestore.getId()); + assert restoredFile.getName().equals(fromApiAfterRestore.getName()); + assert convertToString(fromApiAfterRestore.getItemStatus()).equals("active"); + client.getFiles().deleteFileById(file.getId()); + client.getTrashedFiles().deleteTrashedFileById(file.getId()); + assertThrows( + RuntimeException.class, () -> client.getTrashedFiles().getTrashedFileById(file.getId())); + } +} diff --git a/src/intTest/java/com/box/sdkgen/trashedfolders/TrashedFoldersITest.java b/src/intTest/java/com/box/sdkgen/trashedfolders/TrashedFoldersITest.java new file mode 100644 index 000000000..fd6c5de2c --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/trashedfolders/TrashedFoldersITest.java @@ -0,0 +1,43 @@ +package com.box.sdkgen.trashedfolders; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.folders.CreateFolderRequestBody; +import com.box.sdkgen.managers.folders.CreateFolderRequestBodyParentField; +import com.box.sdkgen.schemas.folderfull.FolderFull; +import com.box.sdkgen.schemas.trashfolder.TrashFolder; +import com.box.sdkgen.schemas.trashfolderrestored.TrashFolderRestored; +import org.junit.jupiter.api.Test; + +public class TrashedFoldersITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testTrashedFolders() { + FolderFull folder = + client + .getFolders() + .createFolder( + new CreateFolderRequestBody( + getUuid(), new CreateFolderRequestBodyParentField("0"))); + client.getFolders().deleteFolderById(folder.getId()); + TrashFolder fromTrash = client.getTrashedFolders().getTrashedFolderById(folder.getId()); + assert fromTrash.getId().equals(folder.getId()); + assert fromTrash.getName().equals(folder.getName()); + assertThrows(RuntimeException.class, () -> client.getFolders().getFolderById(folder.getId())); + TrashFolderRestored restoredFolder = + client.getTrashedFolders().restoreFolderFromTrash(folder.getId()); + FolderFull fromApi = client.getFolders().getFolderById(folder.getId()); + assert restoredFolder.getId().equals(fromApi.getId()); + assert restoredFolder.getName().equals(fromApi.getName()); + client.getFolders().deleteFolderById(folder.getId()); + client.getTrashedFolders().deleteTrashedFolderById(folder.getId()); + assertThrows( + RuntimeException.class, + () -> client.getTrashedFolders().getTrashedFolderById(folder.getId())); + } +} diff --git a/src/intTest/java/com/box/sdkgen/trasheditems/TrashedItemsITest.java b/src/intTest/java/com/box/sdkgen/trasheditems/TrashedItemsITest.java new file mode 100644 index 000000000..210f80ef7 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/trasheditems/TrashedItemsITest.java @@ -0,0 +1,22 @@ +package com.box.sdkgen.trasheditems; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.commons.CommonsManager.uploadNewFile; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.schemas.filefull.FileFull; +import com.box.sdkgen.schemas.items.Items; +import org.junit.jupiter.api.Test; + +public class TrashedItemsITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testListTrashedItems() { + FileFull file = uploadNewFile(); + client.getFiles().deleteFileById(file.getId()); + Items trashedItems = client.getTrashedItems().getTrashedItems(); + assert trashedItems.getEntries().size() > 0; + } +} diff --git a/src/intTest/java/com/box/sdkgen/trashedweblinks/TrashedWebLinksITest.java b/src/intTest/java/com/box/sdkgen/trashedweblinks/TrashedWebLinksITest.java new file mode 100644 index 000000000..23790e53a --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/trashedweblinks/TrashedWebLinksITest.java @@ -0,0 +1,53 @@ +package com.box.sdkgen.trashedweblinks; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.weblinks.CreateWebLinkRequestBody; +import com.box.sdkgen.managers.weblinks.CreateWebLinkRequestBodyParentField; +import com.box.sdkgen.schemas.folderfull.FolderFull; +import com.box.sdkgen.schemas.trashweblink.TrashWebLink; +import com.box.sdkgen.schemas.trashweblinkrestored.TrashWebLinkRestored; +import com.box.sdkgen.schemas.weblink.WebLink; +import org.junit.jupiter.api.Test; + +public class TrashedWebLinksITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testTrashedWebLinks() { + String url = "https://www.box.com"; + FolderFull parent = client.getFolders().getFolderById("0"); + String name = getUuid(); + String description = "Weblink description"; + WebLink weblink = + client + .getWebLinks() + .createWebLink( + new CreateWebLinkRequestBody.Builder( + url, new CreateWebLinkRequestBodyParentField(parent.getId())) + .name(name) + .description(description) + .build()); + client.getWebLinks().deleteWebLinkById(weblink.getId()); + TrashWebLink fromTrash = client.getTrashedWebLinks().getTrashedWebLinkById(weblink.getId()); + assert fromTrash.getId().equals(weblink.getId()); + assert fromTrash.getName().equals(weblink.getName()); + WebLink fromApiAfterTrashed = client.getWebLinks().getWebLinkById(weblink.getId()); + assert convertToString(fromApiAfterTrashed.getItemStatus()).equals("trashed"); + TrashWebLinkRestored restoredWeblink = + client.getTrashedWebLinks().restoreWeblinkFromTrash(weblink.getId()); + WebLink fromApi = client.getWebLinks().getWebLinkById(weblink.getId()); + assert restoredWeblink.getId().equals(fromApi.getId()); + assert restoredWeblink.getName().equals(fromApi.getName()); + client.getWebLinks().deleteWebLinkById(weblink.getId()); + client.getTrashedWebLinks().deleteTrashedWebLinkById(weblink.getId()); + assertThrows( + RuntimeException.class, + () -> client.getTrashedWebLinks().getTrashedWebLinkById(weblink.getId())); + } +} diff --git a/src/intTest/java/com/box/sdkgen/uploads/UploadsITest.java b/src/intTest/java/com/box/sdkgen/uploads/UploadsITest.java new file mode 100644 index 000000000..cb010c05a --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/uploads/UploadsITest.java @@ -0,0 +1,119 @@ +package com.box.sdkgen.uploads; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.internal.utils.UtilsManager.generateByteStream; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.uploads.PreflightFileUploadCheckRequestBody; +import com.box.sdkgen.managers.uploads.PreflightFileUploadCheckRequestBodyParentField; +import com.box.sdkgen.managers.uploads.UploadFileRequestBody; +import com.box.sdkgen.managers.uploads.UploadFileRequestBodyAttributesField; +import com.box.sdkgen.managers.uploads.UploadFileRequestBodyAttributesParentField; +import com.box.sdkgen.managers.uploads.UploadFileVersionRequestBody; +import com.box.sdkgen.managers.uploads.UploadFileVersionRequestBodyAttributesField; +import com.box.sdkgen.managers.uploads.UploadWithPreflightCheckRequestBody; +import com.box.sdkgen.managers.uploads.UploadWithPreflightCheckRequestBodyAttributesField; +import com.box.sdkgen.managers.uploads.UploadWithPreflightCheckRequestBodyAttributesParentField; +import com.box.sdkgen.schemas.filefull.FileFull; +import com.box.sdkgen.schemas.files.Files; +import com.box.sdkgen.schemas.uploadurl.UploadUrl; +import java.io.InputStream; +import org.junit.jupiter.api.Test; + +public class UploadsITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testUploadFileAndFileVersion() { + String newFileName = getUuid(); + InputStream fileContentStream = generateByteStream(1024 * 1024); + Files uploadedFiles = + client + .getUploads() + .uploadFile( + new UploadFileRequestBody( + new UploadFileRequestBodyAttributesField( + newFileName, new UploadFileRequestBodyAttributesParentField("0")), + fileContentStream)); + FileFull uploadedFile = uploadedFiles.getEntries().get(0); + assert uploadedFile.getName().equals(newFileName); + String newFileVersionName = getUuid(); + InputStream newFileContentStream = generateByteStream(1024 * 1024); + Files uploadedFilesVersion = + client + .getUploads() + .uploadFileVersion( + uploadedFile.getId(), + new UploadFileVersionRequestBody( + new UploadFileVersionRequestBodyAttributesField(newFileVersionName), + newFileContentStream)); + FileFull newFileVersion = uploadedFilesVersion.getEntries().get(0); + assert newFileVersion.getName().equals(newFileVersionName); + client.getFiles().deleteFileById(newFileVersion.getId()); + } + + @Test + public void testUploadFileWithPreflightCheck() { + String newFileName = getUuid(); + InputStream fileContentStream = generateByteStream(1024 * 1024); + assertThrows( + RuntimeException.class, + () -> + client + .getUploads() + .uploadWithPreflightCheck( + new UploadWithPreflightCheckRequestBody( + new UploadWithPreflightCheckRequestBodyAttributesField( + newFileName, + new UploadWithPreflightCheckRequestBodyAttributesParentField("0"), + -1), + fileContentStream))); + Files uploadFilesWithPreflight = + client + .getUploads() + .uploadWithPreflightCheck( + new UploadWithPreflightCheckRequestBody( + new UploadWithPreflightCheckRequestBodyAttributesField( + newFileName, + new UploadWithPreflightCheckRequestBodyAttributesParentField("0"), + 1024 * 1024), + fileContentStream)); + FileFull file = uploadFilesWithPreflight.getEntries().get(0); + assert file.getName().equals(newFileName); + assert file.getSize() == 1024 * 1024; + assertThrows( + RuntimeException.class, + () -> + client + .getUploads() + .uploadWithPreflightCheck( + new UploadWithPreflightCheckRequestBody( + new UploadWithPreflightCheckRequestBodyAttributesField( + newFileName, + new UploadWithPreflightCheckRequestBodyAttributesParentField("0"), + 1024 * 1024), + fileContentStream))); + client.getFiles().deleteFileById(file.getId()); + } + + @Test + public void testPreflightCheck() { + String newFileName = getUuid(); + UploadUrl preflightCheckResult = + client + .getUploads() + .preflightFileUploadCheck( + new PreflightFileUploadCheckRequestBody.Builder() + .name(newFileName) + .size(1024 * 1024) + .parent( + new PreflightFileUploadCheckRequestBodyParentField.Builder() + .id("0") + .build()) + .build()); + assert !(preflightCheckResult.getUploadUrl().equals("")); + } +} diff --git a/src/intTest/java/com/box/sdkgen/usercollaborations/UserCollaborationsITest.java b/src/intTest/java/com/box/sdkgen/usercollaborations/UserCollaborationsITest.java new file mode 100644 index 000000000..c9fc1381f --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/usercollaborations/UserCollaborationsITest.java @@ -0,0 +1,167 @@ +package com.box.sdkgen.usercollaborations; + +import static com.box.sdkgen.commons.CommonsManager.createNewFolder; +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.usercollaborations.CreateCollaborationRequestBody; +import com.box.sdkgen.managers.usercollaborations.CreateCollaborationRequestBodyAccessibleByField; +import com.box.sdkgen.managers.usercollaborations.CreateCollaborationRequestBodyAccessibleByTypeField; +import com.box.sdkgen.managers.usercollaborations.CreateCollaborationRequestBodyItemField; +import com.box.sdkgen.managers.usercollaborations.CreateCollaborationRequestBodyItemTypeField; +import com.box.sdkgen.managers.usercollaborations.CreateCollaborationRequestBodyRoleField; +import com.box.sdkgen.managers.usercollaborations.UpdateCollaborationByIdRequestBody; +import com.box.sdkgen.managers.usercollaborations.UpdateCollaborationByIdRequestBodyRoleField; +import com.box.sdkgen.managers.users.CreateUserRequestBody; +import com.box.sdkgen.schemas.collaboration.Collaboration; +import com.box.sdkgen.schemas.collaborations.Collaborations; +import com.box.sdkgen.schemas.folderfull.FolderFull; +import com.box.sdkgen.schemas.userfull.UserFull; +import org.junit.jupiter.api.Test; + +public class UserCollaborationsITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testUserCollaborations() { + String userName = getUuid(); + String userLogin = String.join("", getUuid(), "@gmail.com"); + UserFull user = + client + .getUsers() + .createUser( + new CreateUserRequestBody.Builder(userName) + .login(userLogin) + .isPlatformAccessOnly(true) + .build()); + FolderFull folder = createNewFolder(); + Collaboration collaboration = + client + .getUserCollaborations() + .createCollaboration( + new CreateCollaborationRequestBody( + new CreateCollaborationRequestBodyItemField.Builder() + .type(CreateCollaborationRequestBodyItemTypeField.FOLDER) + .id(folder.getId()) + .build(), + new CreateCollaborationRequestBodyAccessibleByField.Builder( + CreateCollaborationRequestBodyAccessibleByTypeField.USER) + .id(user.getId()) + .build(), + CreateCollaborationRequestBodyRoleField.EDITOR)); + assert convertToString(collaboration.getRole()).equals("editor"); + String collaborationId = collaboration.getId(); + Collaboration collaborationFromApi = + client.getUserCollaborations().getCollaborationById(collaborationId); + assert collaborationId.equals(collaborationFromApi.getId()); + assert convertToString(collaborationFromApi.getStatus()).equals("accepted"); + assert convertToString(collaborationFromApi.getType()).equals("collaboration"); + assert collaborationFromApi.getInviteEmail() == null; + Collaboration updatedCollaboration = + client + .getUserCollaborations() + .updateCollaborationById( + collaborationId, + new UpdateCollaborationByIdRequestBody( + UpdateCollaborationByIdRequestBodyRoleField.VIEWER)); + assert convertToString(updatedCollaboration.getRole()).equals("viewer"); + client.getUserCollaborations().deleteCollaborationById(collaborationId); + assertThrows( + RuntimeException.class, + () -> client.getUserCollaborations().getCollaborationById(collaborationId)); + client.getFolders().deleteFolderById(folder.getId()); + client.getUsers().deleteUserById(user.getId()); + } + + @Test + public void testConvertingUserCollaborationToOwnership() { + String userName = getUuid(); + String userLogin = String.join("", getUuid(), "@gmail.com"); + UserFull user = + client + .getUsers() + .createUser( + new CreateUserRequestBody.Builder(userName) + .login(userLogin) + .isPlatformAccessOnly(true) + .build()); + FolderFull folder = createNewFolder(); + Collaboration collaboration = + client + .getUserCollaborations() + .createCollaboration( + new CreateCollaborationRequestBody( + new CreateCollaborationRequestBodyItemField.Builder() + .type(CreateCollaborationRequestBodyItemTypeField.FOLDER) + .id(folder.getId()) + .build(), + new CreateCollaborationRequestBodyAccessibleByField.Builder( + CreateCollaborationRequestBodyAccessibleByTypeField.USER) + .id(user.getId()) + .build(), + CreateCollaborationRequestBodyRoleField.EDITOR)); + assert convertToString(collaboration.getRole()).equals("editor"); + Collaboration ownerCollaboration = + client + .getUserCollaborations() + .updateCollaborationById( + collaboration.getId(), + new UpdateCollaborationByIdRequestBody( + UpdateCollaborationByIdRequestBodyRoleField.OWNER)); + assert ownerCollaboration == null; + Collaborations folderCollaborations = + client.getListCollaborations().getFolderCollaborations(folder.getId()); + Collaboration folderCollaboration = folderCollaborations.getEntries().get(0); + client.getUserCollaborations().deleteCollaborationById(folderCollaboration.getId()); + BoxClient userClient = client.withAsUserHeader(user.getId()); + userClient.getFolders().deleteFolderById(folder.getId()); + userClient.getTrashedFolders().deleteTrashedFolderById(folder.getId()); + client.getUsers().deleteUserById(user.getId()); + } + + @Test + public void testExternalUserCollaborations() { + String userName = getUuid(); + String userLogin = String.join("", getUuid(), "@boxdemo.com"); + FolderFull folder = createNewFolder(); + Collaboration collaboration = + client + .getUserCollaborations() + .createCollaboration( + new CreateCollaborationRequestBody( + new CreateCollaborationRequestBodyItemField.Builder() + .type(CreateCollaborationRequestBodyItemTypeField.FOLDER) + .id(folder.getId()) + .build(), + new CreateCollaborationRequestBodyAccessibleByField.Builder( + CreateCollaborationRequestBodyAccessibleByTypeField.USER) + .login(userLogin) + .build(), + CreateCollaborationRequestBodyRoleField.EDITOR)); + assert convertToString(collaboration.getRole()).equals("editor"); + String collaborationId = collaboration.getId(); + Collaboration collaborationFromApi = + client.getUserCollaborations().getCollaborationById(collaborationId); + assert collaborationId.equals(collaborationFromApi.getId()); + assert convertToString(collaborationFromApi.getStatus()).equals("pending"); + assert convertToString(collaborationFromApi.getType()).equals("collaboration"); + assert collaborationFromApi.getInviteEmail().equals(userLogin); + Collaboration updatedCollaboration = + client + .getUserCollaborations() + .updateCollaborationById( + collaborationId, + new UpdateCollaborationByIdRequestBody( + UpdateCollaborationByIdRequestBodyRoleField.VIEWER)); + assert convertToString(updatedCollaboration.getRole()).equals("viewer"); + client.getUserCollaborations().deleteCollaborationById(collaborationId); + assertThrows( + RuntimeException.class, + () -> client.getUserCollaborations().getCollaborationById(collaborationId)); + client.getFolders().deleteFolderById(folder.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/users/UsersITest.java b/src/intTest/java/com/box/sdkgen/users/UsersITest.java new file mode 100644 index 000000000..2757f423b --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/users/UsersITest.java @@ -0,0 +1,55 @@ +package com.box.sdkgen.users; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.users.CreateUserRequestBody; +import com.box.sdkgen.managers.users.UpdateUserByIdRequestBody; +import com.box.sdkgen.schemas.userfull.UserFull; +import com.box.sdkgen.schemas.users.Users; +import org.junit.jupiter.api.Test; + +public class UsersITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testGetUsers() { + Users users = client.getUsers().getUsers(); + assert users.getTotalCount() >= 0; + } + + @Test + public void testGetUserMe() { + UserFull currentUser = client.getUsers().getUserMe(); + assert convertToString(currentUser.getType()).equals("user"); + } + + @Test + public void testCreateUpdateGetDeleteUser() { + String userName = getUuid(); + String userLogin = String.join("", getUuid(), "@gmail.com"); + UserFull user = + client + .getUsers() + .createUser( + new CreateUserRequestBody.Builder(userName) + .login(userLogin) + .isPlatformAccessOnly(true) + .build()); + assert user.getName().equals(userName); + UserFull userById = client.getUsers().getUserById(user.getId()); + assert userById.getId().equals(user.getId()); + String updatedUserName = getUuid(); + UserFull updatedUser = + client + .getUsers() + .updateUserById( + user.getId(), + new UpdateUserByIdRequestBody.Builder().name(updatedUserName).build()); + assert updatedUser.getName().equals(updatedUserName); + client.getUsers().deleteUserById(user.getId()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/webhooks/WebhooksITest.java b/src/intTest/java/com/box/sdkgen/webhooks/WebhooksITest.java new file mode 100644 index 000000000..6afa1a972 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/webhooks/WebhooksITest.java @@ -0,0 +1,273 @@ +package com.box.sdkgen.webhooks; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.internal.utils.UtilsManager.compareSignatures; +import static com.box.sdkgen.internal.utils.UtilsManager.computeWebhookSignature; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.dateTimeToString; +import static com.box.sdkgen.internal.utils.UtilsManager.entryOf; +import static com.box.sdkgen.internal.utils.UtilsManager.epochSecondsToDateTime; +import static com.box.sdkgen.internal.utils.UtilsManager.getEpochTimeInSeconds; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; +import static com.box.sdkgen.internal.utils.UtilsManager.mapOf; +import static com.box.sdkgen.internal.utils.UtilsManager.mergeMaps; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.folders.CreateFolderRequestBody; +import com.box.sdkgen.managers.folders.CreateFolderRequestBodyParentField; +import com.box.sdkgen.managers.webhooks.CreateWebhookRequestBody; +import com.box.sdkgen.managers.webhooks.CreateWebhookRequestBodyTargetField; +import com.box.sdkgen.managers.webhooks.CreateWebhookRequestBodyTargetTypeField; +import com.box.sdkgen.managers.webhooks.CreateWebhookRequestBodyTriggersField; +import com.box.sdkgen.managers.webhooks.UpdateWebhookByIdRequestBody; +import com.box.sdkgen.managers.webhooks.WebhooksManager; +import com.box.sdkgen.schemas.folderfull.FolderFull; +import com.box.sdkgen.schemas.webhook.Webhook; +import com.box.sdkgen.schemas.webhooks.Webhooks; +import java.util.Arrays; +import java.util.Map; +import org.junit.jupiter.api.Test; + +public class WebhooksITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testWebhooksCrud() { + FolderFull folder = + client + .getFolders() + .createFolder( + new CreateFolderRequestBody( + getUuid(), new CreateFolderRequestBodyParentField("0"))); + Webhook webhook = + client + .getWebhooks() + .createWebhook( + new CreateWebhookRequestBody( + new CreateWebhookRequestBodyTargetField.Builder() + .id(folder.getId()) + .type(CreateWebhookRequestBodyTargetTypeField.FOLDER) + .build(), + "https://example.com/new-webhook", + Arrays.asList(CreateWebhookRequestBodyTriggersField.FILE_UPLOADED))); + assert webhook.getTarget().getId().equals(folder.getId()); + assert convertToString(webhook.getTarget().getType()).equals("folder"); + assert webhook.getTriggers().size() == Arrays.asList("FILE.UPLOADED").size(); + assert webhook.getAddress().equals("https://example.com/new-webhook"); + Webhooks webhooks = client.getWebhooks().getWebhooks(); + assert webhooks.getEntries().size() > 0; + Webhook webhookFromApi = client.getWebhooks().getWebhookById(webhook.getId()); + assert webhook.getId().equals(webhookFromApi.getId()); + assert webhook.getTarget().getId().equals(webhookFromApi.getTarget().getId()); + assert webhook.getAddress().equals(webhookFromApi.getAddress()); + Webhook updatedWebhook = + client + .getWebhooks() + .updateWebhookById( + webhook.getId(), + new UpdateWebhookByIdRequestBody.Builder() + .address("https://example.com/updated-webhook") + .build()); + assert updatedWebhook.getId().equals(webhook.getId()); + assert updatedWebhook.getAddress().equals("https://example.com/updated-webhook"); + client.getWebhooks().deleteWebhookById(webhook.getId()); + assertThrows( + RuntimeException.class, () -> client.getWebhooks().deleteWebhookById(webhook.getId())); + client.getFolders().deleteFolderById(folder.getId()); + } + + @Test + public void testWebhookValidation() { + String primaryKey = "SamplePrimaryKey"; + String secondaryKey = "SampleSecondaryKey"; + String incorrectKey = "IncorrectKey"; + String body = + "{\"type\":\"webhook_event\",\"webhook\":{\"id\":\"1234567890\"},\"trigger\":\"FILE.UPLOADED\",\"source\":{\"id\":\"1234567890\",\"type\":\"file\",\"name\":\"Test.txt\"}}"; + String bodyWithJapanese = + "{\"webhook\":{\"id\":\"1234567890\"},\"trigger\":\"FILE.UPLOADED\",\"source\":{\"id\":\"1234567890\",\"type\":\"file\",\"name\":\"スクリーンショット 2020-08-05.txt\"}}"; + String bodyWithEmoji = + "{\"webhook\":{\"id\":\"1234567890\"},\"trigger\":\"FILE.UPLOADED\",\"source\":{\"id\":\"1234567890\",\"type\":\"file\",\"name\":\"😀 2020-08-05.txt\"}}"; + String bodyWithCarriageReturn = + "{\"webhook\":{\"id\":\"1234567890\"},\"trigger\":\"FILE.UPLOADED\",\"source\":{\"id\":\"1234567890\",\"type\":\"file\",\"name\":\"test \r\"}}"; + String bodyWithForwardSlash = + "{\"webhook\":{\"id\":\"1234567890\"},\"trigger\":\"FILE.UPLOADED\",\"source\":{\"id\":\"1234567890\",\"type\":\"file\",\"name\":\"/\"}}"; + String bodyWithBackSlash = + "{\"webhook\":{\"id\":\"1234567890\"},\"trigger\":\"FILE.UPLOADED\",\"source\":{\"id\":\"1234567890\",\"type\":\"file\",\"name\":\"\\\"}}"; + Map headers = + mapOf( + entryOf("box-delivery-id", "f96bb54b-ee16-4fc5-aa65-8c2d9e5b546f"), + entryOf("box-delivery-timestamp", "2020-01-01T00:00:00-07:00"), + entryOf("box-signature-algorithm", "HmacSHA256"), + entryOf("box-signature-primary", "6TfeAW3A1PASkgboxxA5yqHNKOwFyMWuEXny/FPD5hI="), + entryOf("box-signature-secondary", "v+1CD1Jdo3muIcbpv5lxxgPglOqMfsNHPV899xWYydo="), + entryOf("box-signature-version", "1")); + Map headersWithJapanese = + mergeMaps( + headers, + mapOf( + entryOf("box-signature-primary", "LV2uCu+5NJtIHrCXDYgZ0v/PP5THGRuegw3RtdnEyuE="))); + Map headersWithEmoji = + mergeMaps( + headers, + mapOf( + entryOf("box-signature-primary", "xF/SDZosX4le+v4A0Qn59sZhuD1RqY5KRUKzVMSbh0E="))); + Map headersWithCarriageReturn = + mergeMaps( + headers, + mapOf( + entryOf("box-signature-primary", "SVkbKgy3dEEf2PbbzpNu2lDZS7zZ/aboU7HOZgBGrJk="))); + Map headersWithForwardSlash = + mergeMaps( + headers, + mapOf( + entryOf("box-signature-primary", "t41PWT5ZB6OcysnD6SDy9Ud+p9hdXxIdXqcdweyZv/Q="))); + Map headersWithBackSlash = + mergeMaps( + headers, + mapOf( + entryOf("box-signature-primary", "ERpMZwUQsGDTfj82ehdX6VvDZfvOhK5ULNfVmwVAGe0="))); + String currentDatetime = dateTimeToString(epochSecondsToDateTime(getEpochTimeInSeconds())); + String futureDatetime = + dateTimeToString(epochSecondsToDateTime(getEpochTimeInSeconds() + 1200)); + String pastDatetime = dateTimeToString(epochSecondsToDateTime(getEpochTimeInSeconds() - 1200)); + Map headersWithCorrectDatetime = + mergeMaps( + headers, + mapOf( + entryOf("box-delivery-timestamp", currentDatetime), + entryOf( + "box-signature-primary", + computeWebhookSignature( + body, + mergeMaps( + headers, mapOf(entryOf("box-delivery-timestamp", currentDatetime))), + primaryKey, + true)), + entryOf( + "box-signature-secondary", + computeWebhookSignature( + body, + mergeMaps( + headers, mapOf(entryOf("box-delivery-timestamp", currentDatetime))), + secondaryKey, + true)))); + Map headersWithJapaneseWithCorrectDatetime = + mergeMaps( + headersWithJapanese, + mapOf( + entryOf("box-delivery-timestamp", currentDatetime), + entryOf( + "box-signature-primary", + computeWebhookSignature( + bodyWithJapanese, + mergeMaps( + headersWithJapanese, + mapOf(entryOf("box-delivery-timestamp", currentDatetime))), + primaryKey, + true)), + entryOf( + "box-signature-secondary", + computeWebhookSignature( + bodyWithJapanese, + mergeMaps( + headersWithJapanese, + mapOf(entryOf("box-delivery-timestamp", currentDatetime))), + secondaryKey, + true)))); + Map headersWithFutureDatetime = + mergeMaps( + headers, + mapOf( + entryOf("box-delivery-timestamp", futureDatetime), + entryOf( + "box-signature-primary", + computeWebhookSignature( + body, + mergeMaps( + headers, mapOf(entryOf("box-delivery-timestamp", futureDatetime))), + primaryKey, + true)), + entryOf( + "box-signature-secondary", + computeWebhookSignature( + body, + mergeMaps( + headers, mapOf(entryOf("box-delivery-timestamp", futureDatetime))), + secondaryKey, + true)))); + Map headersWithPastDatetime = + mergeMaps( + headers, + mapOf( + entryOf("box-delivery-timestamp", pastDatetime), + entryOf( + "box-signature-primary", + computeWebhookSignature( + body, + mergeMaps(headers, mapOf(entryOf("box-delivery-timestamp", pastDatetime))), + primaryKey, + true)), + entryOf( + "box-signature-secondary", + computeWebhookSignature( + body, + mergeMaps(headers, mapOf(entryOf("box-delivery-timestamp", pastDatetime))), + secondaryKey, + true)))); + Map headersWithWrongSignatureVersion = + mergeMaps(headers, mapOf(entryOf("box-signature-version", "2"))); + Map headersWithWrongSignatureAlgorithm = + mergeMaps(headers, mapOf(entryOf("box-signature-algorithm", "HmacSHA1"))); + assert compareSignatures( + computeWebhookSignature(body, headers, primaryKey, true), + headers.get("box-signature-primary")); + assert compareSignatures( + computeWebhookSignature(body, headers, secondaryKey, true), + headers.get("box-signature-secondary")); + assert !(compareSignatures( + computeWebhookSignature(body, headers, incorrectKey, true), + headers.get("box-signature-primary"))); + assert compareSignatures( + computeWebhookSignature(bodyWithJapanese, headersWithJapanese, primaryKey, true), + headersWithJapanese.get("box-signature-primary")); + assert compareSignatures( + computeWebhookSignature(bodyWithEmoji, headersWithEmoji, primaryKey, true), + headersWithEmoji.get("box-signature-primary")); + assert compareSignatures( + computeWebhookSignature( + bodyWithCarriageReturn, headersWithCarriageReturn, primaryKey, true), + headersWithCarriageReturn.get("box-signature-primary")); + assert compareSignatures( + computeWebhookSignature(bodyWithForwardSlash, headersWithForwardSlash, primaryKey, true), + headersWithForwardSlash.get("box-signature-primary")); + assert compareSignatures( + computeWebhookSignature(bodyWithBackSlash, headersWithBackSlash, primaryKey, true), + headersWithBackSlash.get("box-signature-primary")); + assert WebhooksManager.validateMessage( + body, headersWithCorrectDatetime, primaryKey, secondaryKey); + assert WebhooksManager.validateMessage( + body, headersWithCorrectDatetime, primaryKey, incorrectKey); + assert WebhooksManager.validateMessage( + body, headersWithCorrectDatetime, incorrectKey, secondaryKey); + assert !(WebhooksManager.validateMessage( + body, headersWithCorrectDatetime, incorrectKey, incorrectKey)); + assert !(WebhooksManager.validateMessage( + body, headersWithFutureDatetime, primaryKey, secondaryKey)); + assert !(WebhooksManager.validateMessage( + body, headersWithPastDatetime, primaryKey, secondaryKey)); + assert !(WebhooksManager.validateMessage( + body, headersWithWrongSignatureVersion, primaryKey, secondaryKey)); + assert !(WebhooksManager.validateMessage( + body, headersWithWrongSignatureAlgorithm, primaryKey, secondaryKey)); + assert WebhooksManager.validateMessage( + bodyWithJapanese, headersWithJapaneseWithCorrectDatetime, primaryKey, secondaryKey); + assert WebhooksManager.validateMessage( + bodyWithJapanese, headersWithJapaneseWithCorrectDatetime, primaryKey, incorrectKey); + assert WebhooksManager.validateMessage( + bodyWithJapanese, headersWithJapaneseWithCorrectDatetime, incorrectKey, secondaryKey); + assert !(WebhooksManager.validateMessage( + bodyWithJapanese, headersWithJapanese, primaryKey, secondaryKey)); + } +} diff --git a/src/intTest/java/com/box/sdkgen/weblinks/WeblinksITest.java b/src/intTest/java/com/box/sdkgen/weblinks/WeblinksITest.java new file mode 100644 index 000000000..0df411a61 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/weblinks/WeblinksITest.java @@ -0,0 +1,64 @@ +package com.box.sdkgen.weblinks; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.weblinks.CreateWebLinkRequestBody; +import com.box.sdkgen.managers.weblinks.CreateWebLinkRequestBodyParentField; +import com.box.sdkgen.managers.weblinks.UpdateWebLinkByIdRequestBody; +import com.box.sdkgen.managers.weblinks.UpdateWebLinkByIdRequestBodySharedLinkAccessField; +import com.box.sdkgen.managers.weblinks.UpdateWebLinkByIdRequestBodySharedLinkField; +import com.box.sdkgen.schemas.folderfull.FolderFull; +import com.box.sdkgen.schemas.weblink.WebLink; +import org.junit.jupiter.api.Test; + +public class WeblinksITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testCreateGetDeleteWeblink() { + String url = "https://www.box.com"; + FolderFull parent = client.getFolders().getFolderById("0"); + String name = getUuid(); + String description = "Weblink description"; + String password = "super-secret-password"; + WebLink weblink = + client + .getWebLinks() + .createWebLink( + new CreateWebLinkRequestBody.Builder( + url, new CreateWebLinkRequestBodyParentField(parent.getId())) + .name(name) + .description(description) + .build()); + assert weblink.getUrl().equals(url); + assert weblink.getParent().getId().equals(parent.getId()); + assert weblink.getName().equals(name); + assert weblink.getDescription().equals(description); + WebLink weblinkById = client.getWebLinks().getWebLinkById(weblink.getId()); + assert weblinkById.getId().equals(weblink.getId()); + assert weblinkById.getUrl().equals(url); + String updatedName = getUuid(); + WebLink updatedWeblink = + client + .getWebLinks() + .updateWebLinkById( + weblink.getId(), + new UpdateWebLinkByIdRequestBody.Builder() + .name(updatedName) + .sharedLink( + new UpdateWebLinkByIdRequestBodySharedLinkField.Builder() + .access(UpdateWebLinkByIdRequestBodySharedLinkAccessField.OPEN) + .password(password) + .build()) + .build()); + assert updatedWeblink.getName().equals(updatedName); + assert convertToString(updatedWeblink.getSharedLink().getAccess()).equals("open"); + client.getWebLinks().deleteWebLinkById(weblink.getId()); + WebLink deletedWeblink = client.getWebLinks().getWebLinkById(weblink.getId()); + assert convertToString(deletedWeblink.getItemStatus()).equals("trashed"); + } +} diff --git a/src/intTest/java/com/box/sdkgen/workflows/WorkflowsITest.java b/src/intTest/java/com/box/sdkgen/workflows/WorkflowsITest.java new file mode 100644 index 000000000..31c4912a3 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/workflows/WorkflowsITest.java @@ -0,0 +1,84 @@ +package com.box.sdkgen.workflows; + +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.commons.CommonsManager.getDefaultClientWithUserSubject; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.generateByteStream; +import static com.box.sdkgen.internal.utils.UtilsManager.getEnvVar; +import static com.box.sdkgen.internal.utils.UtilsManager.getUuid; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.managers.uploads.UploadFileRequestBody; +import com.box.sdkgen.managers.uploads.UploadFileRequestBodyAttributesField; +import com.box.sdkgen.managers.uploads.UploadFileRequestBodyAttributesParentField; +import com.box.sdkgen.managers.workflows.GetWorkflowsQueryParams; +import com.box.sdkgen.managers.workflows.StartWorkflowRequestBody; +import com.box.sdkgen.managers.workflows.StartWorkflowRequestBodyFilesField; +import com.box.sdkgen.managers.workflows.StartWorkflowRequestBodyFilesTypeField; +import com.box.sdkgen.managers.workflows.StartWorkflowRequestBodyFlowField; +import com.box.sdkgen.managers.workflows.StartWorkflowRequestBodyFolderField; +import com.box.sdkgen.managers.workflows.StartWorkflowRequestBodyFolderTypeField; +import com.box.sdkgen.managers.workflows.StartWorkflowRequestBodyTypeField; +import com.box.sdkgen.schemas.filefull.FileFull; +import com.box.sdkgen.schemas.files.Files; +import com.box.sdkgen.schemas.workflow.Workflow; +import com.box.sdkgen.schemas.workflows.Workflows; +import java.util.Arrays; +import org.junit.jupiter.api.Test; + +public class WorkflowsITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testWorkflows() { + BoxClient adminClient = getDefaultClientWithUserSubject(getEnvVar("USER_ID")); + String workflowFolderId = getEnvVar("WORKFLOW_FOLDER_ID"); + Files uploadedFiles = + adminClient + .getUploads() + .uploadFile( + new UploadFileRequestBody( + new UploadFileRequestBodyAttributesField( + getUuid(), + new UploadFileRequestBodyAttributesParentField(workflowFolderId)), + generateByteStream(1024 * 1024))); + FileFull file = uploadedFiles.getEntries().get(0); + String workflowFileId = file.getId(); + Workflows workflows = + adminClient.getWorkflows().getWorkflows(new GetWorkflowsQueryParams(workflowFolderId)); + assert workflows.getEntries().size() == 1; + Workflow workflowToRun = workflows.getEntries().get(0); + assert convertToString(workflowToRun.getType()).equals("workflow"); + assert workflowToRun.getIsEnabled() == true; + assert convertToString(workflowToRun.getFlows().get(0).getType()).equals("flow"); + assert convertToString(workflowToRun.getFlows().get(0).getTrigger().getType()) + .equals("trigger"); + assert convertToString(workflowToRun.getFlows().get(0).getTrigger().getTriggerType()) + .equals("WORKFLOW_MANUAL_START"); + assert convertToString(workflowToRun.getFlows().get(0).getOutcomes().get(0).getActionType()) + .equals("delete_file"); + assert convertToString(workflowToRun.getFlows().get(0).getOutcomes().get(0).getType()) + .equals("outcome"); + adminClient + .getWorkflows() + .startWorkflow( + workflowToRun.getId(), + new StartWorkflowRequestBody.Builder( + new StartWorkflowRequestBodyFlowField.Builder() + .type("flow") + .id(workflowToRun.getFlows().get(0).getId()) + .build(), + Arrays.asList( + new StartWorkflowRequestBodyFilesField.Builder() + .type(StartWorkflowRequestBodyFilesTypeField.FILE) + .id(workflowFileId) + .build()), + new StartWorkflowRequestBodyFolderField.Builder() + .type(StartWorkflowRequestBodyFolderTypeField.FOLDER) + .id(workflowFolderId) + .build()) + .type(StartWorkflowRequestBodyTypeField.WORKFLOW_PARAMETERS) + .build()); + } +} diff --git a/src/intTest/java/com/box/sdkgen/zipdownloads/ZipDownloadsITest.java b/src/intTest/java/com/box/sdkgen/zipdownloads/ZipDownloadsITest.java new file mode 100644 index 000000000..e24a4b0d7 --- /dev/null +++ b/src/intTest/java/com/box/sdkgen/zipdownloads/ZipDownloadsITest.java @@ -0,0 +1,89 @@ +package com.box.sdkgen.zipdownloads; + +import static com.box.sdkgen.commons.CommonsManager.createNewFolder; +import static com.box.sdkgen.commons.CommonsManager.getDefaultClient; +import static com.box.sdkgen.commons.CommonsManager.uploadNewFile; +import static com.box.sdkgen.internal.utils.UtilsManager.bufferEquals; +import static com.box.sdkgen.internal.utils.UtilsManager.convertToString; +import static com.box.sdkgen.internal.utils.UtilsManager.dateTimeToString; +import static com.box.sdkgen.internal.utils.UtilsManager.generateByteBuffer; +import static com.box.sdkgen.internal.utils.UtilsManager.readByteStream; + +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.schemas.filefull.FileFull; +import com.box.sdkgen.schemas.folderfull.FolderFull; +import com.box.sdkgen.schemas.zipdownload.ZipDownload; +import com.box.sdkgen.schemas.zipdownloadrequest.ZipDownloadRequest; +import com.box.sdkgen.schemas.zipdownloadrequest.ZipDownloadRequestItemsField; +import com.box.sdkgen.schemas.zipdownloadrequest.ZipDownloadRequestItemsTypeField; +import com.box.sdkgen.schemas.zipdownloadstatus.ZipDownloadStatus; +import java.io.InputStream; +import java.util.Arrays; +import org.junit.jupiter.api.Test; + +public class ZipDownloadsITest { + + private static final BoxClient client = getDefaultClient(); + + @Test + public void testZipDownload() { + FileFull file1 = uploadNewFile(); + FileFull file2 = uploadNewFile(); + FolderFull folder1 = createNewFolder(); + InputStream zipStream = + client + .getZipDownloads() + .downloadZip( + new ZipDownloadRequest.Builder( + Arrays.asList( + new ZipDownloadRequestItemsField( + ZipDownloadRequestItemsTypeField.FILE, file1.getId()), + new ZipDownloadRequestItemsField( + ZipDownloadRequestItemsTypeField.FILE, file2.getId()), + new ZipDownloadRequestItemsField( + ZipDownloadRequestItemsTypeField.FOLDER, folder1.getId()))) + .downloadFileName("zip") + .build()); + assert bufferEquals(readByteStream(zipStream), generateByteBuffer(10)) == false; + client.getFiles().deleteFileById(file1.getId()); + client.getFiles().deleteFileById(file2.getId()); + client.getFolders().deleteFolderById(folder1.getId()); + } + + @Test + public void testManualZipDownloadAndCheckStatus() { + FileFull file1 = uploadNewFile(); + FileFull file2 = uploadNewFile(); + FolderFull folder1 = createNewFolder(); + ZipDownload zipDownload = + client + .getZipDownloads() + .createZipDownload( + new ZipDownloadRequest.Builder( + Arrays.asList( + new ZipDownloadRequestItemsField( + ZipDownloadRequestItemsTypeField.FILE, file1.getId()), + new ZipDownloadRequestItemsField( + ZipDownloadRequestItemsTypeField.FILE, file2.getId()), + new ZipDownloadRequestItemsField( + ZipDownloadRequestItemsTypeField.FOLDER, folder1.getId()))) + .downloadFileName("zip") + .build()); + assert !(zipDownload.getDownloadUrl().equals("")); + assert !(zipDownload.getStatusUrl().equals("")); + assert !(dateTimeToString(zipDownload.getExpiresAt()).equals("")); + InputStream zipStream = + client.getZipDownloads().getZipDownloadContent(zipDownload.getDownloadUrl()); + assert bufferEquals(readByteStream(zipStream), generateByteBuffer(10)) == false; + ZipDownloadStatus zipDownloadStatus = + client.getZipDownloads().getZipDownloadStatus(zipDownload.getStatusUrl()); + assert zipDownloadStatus.getTotalFileCount() == 2; + assert zipDownloadStatus.getDownloadedFileCount() == 2; + assert zipDownloadStatus.getSkippedFileCount() == 0; + assert zipDownloadStatus.getSkippedFolderCount() == 0; + assert !(convertToString(zipDownloadStatus.getState()).equals("failed")); + client.getFiles().deleteFileById(file1.getId()); + client.getFiles().deleteFileById(file2.getId()); + client.getFolders().deleteFolderById(folder1.getId()); + } +} diff --git a/src/main/java/com/box/sdk/AbstractBoxMultipartRequest.java b/src/main/java/com/box/sdk/AbstractBoxMultipartRequest.java index 0419c5bd3..2103c1303 100644 --- a/src/main/java/com/box/sdk/AbstractBoxMultipartRequest.java +++ b/src/main/java/com/box/sdk/AbstractBoxMultipartRequest.java @@ -12,154 +12,150 @@ import okhttp3.RequestBody; /** - *

Base class for multipart uploads

- *

This class partially implements the HTTP multipart standard in order to upload files to Box. The body of this - * * request type cannot be set directly. Instead, it can be modified by adding multipart fields and setting file - * * contents. The body of multipart requests will not be logged since they are likely to contain binary data.

+ * Base class for multipart uploads + * + *

This class partially implements the HTTP multipart standard in order to upload files to Box. + * The body of this * request type cannot be set directly. Instead, it can be modified by adding + * multipart fields and setting file * contents. The body of multipart requests will not be logged + * since they are likely to contain binary data. */ abstract class AbstractBoxMultipartRequest extends BoxAPIRequest { - protected static final String BOUNDARY = "da39a3ee5e6b4b0d3255bfef95601890afd80709"; - static final int BUFFER_SIZE = 8192; - private final StringBuilder loggedRequest = new StringBuilder(); - private final Map fields = new HashMap<>(); - private InputStream inputStream; - private String filename; - private long fileSize = -1; - private UploadFileCallback callback; - - AbstractBoxMultipartRequest(BoxAPIConnection api, URL url) { - super(api, url, "POST"); - this.addHeader("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); + protected static final String BOUNDARY = "da39a3ee5e6b4b0d3255bfef95601890afd80709"; + static final int BUFFER_SIZE = 8192; + private final StringBuilder loggedRequest = new StringBuilder(); + private final Map fields = new HashMap<>(); + private InputStream inputStream; + private String filename; + private long fileSize = -1; + private UploadFileCallback callback; + + AbstractBoxMultipartRequest(BoxAPIConnection api, URL url) { + super(api, url, "POST"); + this.addHeader("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); + } + + /** + * Sets the file contents of this request. + * + * @param inputStream a stream containing the file contents. + * @param filename the name of the file. + */ + public void setFile(InputStream inputStream, String filename) { + this.inputStream = inputStream; + this.filename = filename; + } + + /** + * Sets the file contents of this request. + * + * @param inputStream a stream containing the file contents. + * @param filename the name of the file. + * @param fileSize the size of the file. If the file content is coming from the dynamic stream, + * and it's full size cannot be determined on starting upload use fizeSize=-1 or use {@link + * AbstractBoxMultipartRequest#setFile(InputStream, String)} + */ + public void setFile(InputStream inputStream, String filename, long fileSize) { + this.setFile(inputStream, filename); + this.fileSize = fileSize; + } + + /** + * Adds or updates a multipart field in this request. + * + * @param key the field's key. + * @param value the field's value. + */ + public void putField(String key, String value) { + this.fields.put(key, value); + } + + /** + * Adds or updates a multipart field in this request. + * + * @param key the field's key. + * @param value the field's value. + */ + public void putField(String key, Date value) { + this.fields.put(key, BoxDateFormat.format(value)); + } + + /** + * Sets the callback which allows file content to be written on output stream. + * + * @param callback the callback which allows file content to be written on output stream. + * @param filename the size of the file. + */ + public void setUploadFileCallback(UploadFileCallback callback, String filename) { + this.callback = callback; + this.filename = filename; + } + + /** + * Sets the SHA1 hash of the file contents of this request. If set, it will ensure that the file + * is not corrupted in transit. + * + * @param sha1 a string containing the SHA1 hash of the file contents. + */ + public void setContentSHA1(String sha1) { + this.addHeader("Content-MD5", sha1); + } + + /** + * This method is unsupported in BoxMultipartRequest. Instead, the body should be modified via the + * {@code putField} and {@code setFile} methods. + * + * @param stream N/A + * @throws UnsupportedOperationException this method is unsupported. + */ + @Override + public void setBody(InputStream stream) { + throw new UnsupportedOperationException(); + } + + /** + * This method is unsupported in BoxMultipartRequest. Instead, the body should be modified via the + * {@code putField} and {@code setFile} methods. + * + * @param body N/A + * @throws UnsupportedOperationException this method is unsupported. + */ + @Override + public void setBody(String body) { + throw new UnsupportedOperationException(); + } + + protected abstract String getPartName(); + + protected abstract MediaType getPartContentType(String filename); + + @Override + protected void resetBody() throws IOException { + this.inputStream.reset(); + this.loggedRequest.setLength(0); + } + + @Override + protected String bodyToString() { + return this.loggedRequest.toString(); + } + + @Override + protected void writeMethodWithBody( + Request.Builder requestBuilder, ProgressListener progressListener) { + MultipartBody.Builder bodyBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM); + // Attributes should go first + this.fields.forEach(bodyBuilder::addFormDataPart); + // File should go second + bodyBuilder.addFormDataPart(getPartName(), filename, getBody(progressListener)); + requestBuilder.post(bodyBuilder.build()); + } + + private RequestBody getBody(ProgressListener progressListener) { + if (this.callback == null) { + return new RequestBodyFromStream( + this.inputStream, getPartContentType(filename), progressListener, fileSize); + } else { + return new RequestBodyFromCallback(this.callback, getPartContentType(filename)); } - - /** - * Sets the file contents of this request. - * - * @param inputStream a stream containing the file contents. - * @param filename the name of the file. - */ - public void setFile(InputStream inputStream, String filename) { - this.inputStream = inputStream; - this.filename = filename; - } - - /** - * Sets the file contents of this request. - * - * @param inputStream a stream containing the file contents. - * @param filename the name of the file. - * @param fileSize the size of the file. If the file content is coming from the dynamic stream, - * and it's full size cannot be determined on starting upload use fizeSize=-1 - * or use {@link AbstractBoxMultipartRequest#setFile(InputStream, String)} - */ - public void setFile(InputStream inputStream, String filename, long fileSize) { - this.setFile(inputStream, filename); - this.fileSize = fileSize; - } - - /** - * Adds or updates a multipart field in this request. - * - * @param key the field's key. - * @param value the field's value. - */ - public void putField(String key, String value) { - this.fields.put(key, value); - } - - /** - * Adds or updates a multipart field in this request. - * - * @param key the field's key. - * @param value the field's value. - */ - public void putField(String key, Date value) { - this.fields.put(key, BoxDateFormat.format(value)); - } - - /** - * Sets the callback which allows file content to be written on output stream. - * - * @param callback the callback which allows file content to be written on output stream. - * @param filename the size of the file. - */ - public void setUploadFileCallback(UploadFileCallback callback, String filename) { - this.callback = callback; - this.filename = filename; - } - - /** - * Sets the SHA1 hash of the file contents of this request. - * If set, it will ensure that the file is not corrupted in transit. - * - * @param sha1 a string containing the SHA1 hash of the file contents. - */ - public void setContentSHA1(String sha1) { - this.addHeader("Content-MD5", sha1); - } - - /** - * This method is unsupported in BoxMultipartRequest. Instead, the body should be modified via the {@code putField} - * and {@code setFile} methods. - * - * @param stream N/A - * @throws UnsupportedOperationException this method is unsupported. - */ - @Override - public void setBody(InputStream stream) { - throw new UnsupportedOperationException(); - } - - /** - * This method is unsupported in BoxMultipartRequest. Instead, the body should be modified via the {@code putField} - * and {@code setFile} methods. - * - * @param body N/A - * @throws UnsupportedOperationException this method is unsupported. - */ - @Override - public void setBody(String body) { - throw new UnsupportedOperationException(); - } - - protected abstract String getPartName(); - - protected abstract MediaType getPartContentType(String filename); - - @Override - protected void resetBody() throws IOException { - this.inputStream.reset(); - this.loggedRequest.setLength(0); - } - - @Override - protected String bodyToString() { - return this.loggedRequest.toString(); - } - - @Override - protected void writeMethodWithBody(Request.Builder requestBuilder, ProgressListener progressListener) { - MultipartBody.Builder bodyBuilder = - new MultipartBody.Builder() - .setType(MultipartBody.FORM); - // Attributes should go first - this.fields.forEach(bodyBuilder::addFormDataPart); - // File should go second - bodyBuilder.addFormDataPart( - getPartName(), - filename, - getBody(progressListener)); - requestBuilder.post(bodyBuilder.build()); - } - - private RequestBody getBody(ProgressListener progressListener) { - if (this.callback == null) { - return new RequestBodyFromStream( - this.inputStream, getPartContentType(filename), progressListener, fileSize - ); - } else { - return new RequestBodyFromCallback(this.callback, getPartContentType(filename)); - } - } - + } } diff --git a/src/main/java/com/box/sdk/AvatarUploadResponse.java b/src/main/java/com/box/sdk/AvatarUploadResponse.java index c155ee1a6..c6c34ffd1 100644 --- a/src/main/java/com/box/sdk/AvatarUploadResponse.java +++ b/src/main/java/com/box/sdk/AvatarUploadResponse.java @@ -1,43 +1,41 @@ package com.box.sdk; -/** - * Upload avatar response - */ +/** Upload avatar response */ public class AvatarUploadResponse { - private final String small; - private final String large; - private final String preview; + private final String small; + private final String large; + private final String preview; - AvatarUploadResponse(String small, String large, String preview) { - this.small = small; - this.large = large; - this.preview = preview; - } + AvatarUploadResponse(String small, String large, String preview) { + this.small = small; + this.large = large; + this.preview = preview; + } - /** - * URL with the small representation of Avatar. - * - * @return URL with the small representation of Avatar - */ - public String getSmall() { - return small; - } + /** + * URL with the small representation of Avatar. + * + * @return URL with the small representation of Avatar + */ + public String getSmall() { + return small; + } - /** - * URL with the large representation of Avatar. - * - * @return URL with the large representation of Avatar - */ - public String getLarge() { - return large; - } + /** + * URL with the large representation of Avatar. + * + * @return URL with the large representation of Avatar + */ + public String getLarge() { + return large; + } - /** - * URL with the preview representation of Avatar. - * - * @return URL with the preview representation of Avatar - */ - public String getPreview() { - return preview; - } + /** + * URL with the preview representation of Avatar. + * + * @return URL with the preview representation of Avatar + */ + public String getPreview() { + return preview; + } } diff --git a/src/main/java/com/box/sdk/BCPrivateKeyDecryptor.java b/src/main/java/com/box/sdk/BCPrivateKeyDecryptor.java index 536b8c434..3eea943f6 100644 --- a/src/main/java/com/box/sdk/BCPrivateKeyDecryptor.java +++ b/src/main/java/com/box/sdk/BCPrivateKeyDecryptor.java @@ -19,52 +19,55 @@ import org.bouncycastle.pkcs.PKCSException; /** - * The default implementation of `IPrivateKeyDecryptor`, which uses Bouncy Castle library to decrypt the private key. + * The default implementation of `IPrivateKeyDecryptor`, which uses Bouncy Castle library to decrypt + * the private key. */ public class BCPrivateKeyDecryptor implements IPrivateKeyDecryptor { - /** - * Decrypts private key with provided passphrase using Bouncy Castle library - * - * @param encryptedPrivateKey Encoded private key string. - * @param passphrase Private key passphrase. - * @return java.security.PrivateKey instance representing decrypted private key. - */ - @Override - public PrivateKey decryptPrivateKey(String encryptedPrivateKey, String passphrase) { - Security.addProvider(new BouncyCastleProvider()); - PrivateKey decryptedPrivateKey; - try { - PEMParser keyReader = new PEMParser(new StringReader(encryptedPrivateKey)); - Object keyPair = keyReader.readObject(); - keyReader.close(); + /** + * Decrypts private key with provided passphrase using Bouncy Castle library + * + * @param encryptedPrivateKey Encoded private key string. + * @param passphrase Private key passphrase. + * @return java.security.PrivateKey instance representing decrypted private key. + */ + @Override + public PrivateKey decryptPrivateKey(String encryptedPrivateKey, String passphrase) { + Security.addProvider(new BouncyCastleProvider()); + PrivateKey decryptedPrivateKey; + try { + PEMParser keyReader = new PEMParser(new StringReader(encryptedPrivateKey)); + Object keyPair = keyReader.readObject(); + keyReader.close(); - if (keyPair instanceof PrivateKeyInfo) { - PrivateKeyInfo keyInfo = (PrivateKeyInfo) keyPair; - decryptedPrivateKey = (new JcaPEMKeyConverter()).getPrivateKey(keyInfo); - } else if (keyPair instanceof PEMEncryptedKeyPair) { - JcePEMDecryptorProviderBuilder builder = new JcePEMDecryptorProviderBuilder(); - PEMDecryptorProvider decryptionProvider = builder.build(passphrase.toCharArray()); - keyPair = ((PEMEncryptedKeyPair) keyPair).decryptKeyPair(decryptionProvider); - PrivateKeyInfo keyInfo = ((PEMKeyPair) keyPair).getPrivateKeyInfo(); - decryptedPrivateKey = (new JcaPEMKeyConverter()).getPrivateKey(keyInfo); - } else if (keyPair instanceof PKCS8EncryptedPrivateKeyInfo) { - InputDecryptorProvider pkcs8Prov = new JceOpenSSLPKCS8DecryptorProviderBuilder() - .setProvider("BC") - .build(passphrase.toCharArray()); - PrivateKeyInfo keyInfo = ((PKCS8EncryptedPrivateKeyInfo) keyPair).decryptPrivateKeyInfo(pkcs8Prov); - decryptedPrivateKey = (new JcaPEMKeyConverter()).getPrivateKey(keyInfo); - } else { - PrivateKeyInfo keyInfo = ((PEMKeyPair) keyPair).getPrivateKeyInfo(); - decryptedPrivateKey = (new JcaPEMKeyConverter()).getPrivateKey(keyInfo); - } - } catch (IOException e) { - throw new BoxAPIException("Error parsing private key for Box Developer Edition.", e); - } catch (OperatorCreationException e) { - throw new BoxAPIException("Error parsing PKCS#8 private key for Box Developer Edition.", e); - } catch (PKCSException e) { - throw new BoxAPIException("Error parsing PKCS private key for Box Developer Edition.", e); - } - return decryptedPrivateKey; + if (keyPair instanceof PrivateKeyInfo) { + PrivateKeyInfo keyInfo = (PrivateKeyInfo) keyPair; + decryptedPrivateKey = (new JcaPEMKeyConverter()).getPrivateKey(keyInfo); + } else if (keyPair instanceof PEMEncryptedKeyPair) { + JcePEMDecryptorProviderBuilder builder = new JcePEMDecryptorProviderBuilder(); + PEMDecryptorProvider decryptionProvider = builder.build(passphrase.toCharArray()); + keyPair = ((PEMEncryptedKeyPair) keyPair).decryptKeyPair(decryptionProvider); + PrivateKeyInfo keyInfo = ((PEMKeyPair) keyPair).getPrivateKeyInfo(); + decryptedPrivateKey = (new JcaPEMKeyConverter()).getPrivateKey(keyInfo); + } else if (keyPair instanceof PKCS8EncryptedPrivateKeyInfo) { + InputDecryptorProvider pkcs8Prov = + new JceOpenSSLPKCS8DecryptorProviderBuilder() + .setProvider("BC") + .build(passphrase.toCharArray()); + PrivateKeyInfo keyInfo = + ((PKCS8EncryptedPrivateKeyInfo) keyPair).decryptPrivateKeyInfo(pkcs8Prov); + decryptedPrivateKey = (new JcaPEMKeyConverter()).getPrivateKey(keyInfo); + } else { + PrivateKeyInfo keyInfo = ((PEMKeyPair) keyPair).getPrivateKeyInfo(); + decryptedPrivateKey = (new JcaPEMKeyConverter()).getPrivateKey(keyInfo); + } + } catch (IOException e) { + throw new BoxAPIException("Error parsing private key for Box Developer Edition.", e); + } catch (OperatorCreationException e) { + throw new BoxAPIException("Error parsing PKCS#8 private key for Box Developer Edition.", e); + } catch (PKCSException e) { + throw new BoxAPIException("Error parsing PKCS private key for Box Developer Edition.", e); } + return decryptedPrivateKey; + } } diff --git a/src/main/java/com/box/sdk/BackoffCounter.java b/src/main/java/com/box/sdk/BackoffCounter.java index 6926688c6..515c733c2 100644 --- a/src/main/java/com/box/sdk/BackoffCounter.java +++ b/src/main/java/com/box/sdk/BackoffCounter.java @@ -1,74 +1,73 @@ package com.box.sdk; class BackoffCounter { - private static final BoxLogger LOGGER = BoxLogger.defaultLogger(); - private static final int BASE_TIMEOUT = 1000; - private static final double RANDOM_FACTOR = 0.5; + private static final BoxLogger LOGGER = BoxLogger.defaultLogger(); + private static final int BASE_TIMEOUT = 1000; + private static final double RANDOM_FACTOR = 0.5; - private final Time time; + private final Time time; - private int maxAttempts; - private int attemptsRemaining; + private int maxAttempts; + private int attemptsRemaining; - BackoffCounter() { - this(Time.getInstance()); - } - - BackoffCounter(Time time) { - this.time = time; - } + BackoffCounter() { + this(Time.getInstance()); + } - public int getAttemptsRemaining() { - return this.attemptsRemaining; - } + BackoffCounter(Time time) { + this.time = time; + } - /** - * Waits for some random amount of time {@link BackoffCounter#calculateDelay()} - * @throws InterruptedException - */ - public void waitBackoff() throws InterruptedException { - int delay = this.calculateDelay(); - this.waitBackoff(delay); - } + public int getAttemptsRemaining() { + return this.attemptsRemaining; + } - /** - * Waits for specified amount of miliseconds. - * @param delay Time to wait for in miliseconds. - * @throws InterruptedException - */ - public void waitBackoff(int delay) throws InterruptedException { - if (LOGGER.isWarnEnabled()) { - LOGGER.warn(String.format( - "Backing off for %d seconds before retrying %d more time%s.", - (delay / 1000), - this.attemptsRemaining, - this.attemptsRemaining > 1 ? "s" : "" - )); + /** + * Waits for some random amount of time {@link BackoffCounter#calculateDelay()} + * + * @throws InterruptedException + */ + public void waitBackoff() throws InterruptedException { + int delay = this.calculateDelay(); + this.waitBackoff(delay); + } - } - this.time.waitDuration(delay); + /** + * Waits for specified amount of miliseconds. + * + * @param delay Time to wait for in miliseconds. + * @throws InterruptedException + */ + public void waitBackoff(int delay) throws InterruptedException { + if (LOGGER.isWarnEnabled()) { + LOGGER.warn( + String.format( + "Backing off for %d seconds before retrying %d more time%s.", + (delay / 1000), this.attemptsRemaining, this.attemptsRemaining > 1 ? "s" : "")); } + this.time.waitDuration(delay); + } - public boolean decrement() { - this.attemptsRemaining--; - return (this.attemptsRemaining > 0); - } + public boolean decrement() { + this.attemptsRemaining--; + return (this.attemptsRemaining > 0); + } - public void reset(int maxAttempts) { - this.maxAttempts = maxAttempts; - this.attemptsRemaining = maxAttempts; - } + public void reset(int maxAttempts) { + this.maxAttempts = maxAttempts; + this.attemptsRemaining = maxAttempts; + } - /** - * Generates some random amount of time to backoff. - * Time is within <16000, 48000) ms - * @return Time in miliseconds. - */ - private int calculateDelay() { - int exponent = this.maxAttempts - this.attemptsRemaining; - double minWindow = 1 - RANDOM_FACTOR; - double maxWindow = 1 + RANDOM_FACTOR; - double jitter = (Math.random() * (maxWindow - minWindow)) + minWindow; - return (int) (Math.pow(2, exponent) * BASE_TIMEOUT * jitter); - } + /** + * Generates some random amount of time to backoff. Time is within <16000, 48000) ms + * + * @return Time in miliseconds. + */ + private int calculateDelay() { + int exponent = this.maxAttempts - this.attemptsRemaining; + double minWindow = 1 - RANDOM_FACTOR; + double maxWindow = 1 + RANDOM_FACTOR; + double jitter = (Math.random() * (maxWindow - minWindow)) + minWindow; + return (int) (Math.pow(2, exponent) * BASE_TIMEOUT * jitter); + } } diff --git a/src/main/java/com/box/sdk/Base64.java b/src/main/java/com/box/sdk/Base64.java index 77b806416..eb136fa27 100644 --- a/src/main/java/com/box/sdk/Base64.java +++ b/src/main/java/com/box/sdk/Base64.java @@ -5,101 +5,104 @@ /** * Contains a method for performing base64 encoding. * - *

This class is included so that we don't need to add a dependency on Apache Commons for base64 encoding.

+ *

This class is included so that we don't need to add a dependency on Apache Commons for base64 + * encoding. * - *

The code in this class was mostly taken from https://gist.github.com/EmilHernvall/953733#file-base64-java

+ *

The code in this class was mostly taken from + * https://gist.github.com/EmilHernvall/953733#file-base64-java */ final class Base64 { - private Base64() { - } - - static String encode(byte[] data) { - char[] tbl = { - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', - 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', - 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', - 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}; + private Base64() {} - StringBuilder buffer = new StringBuilder(); - int pad = 0; - for (int i = 0; i < data.length; i += 3) { + static String encode(byte[] data) { + char[] tbl = { + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', + 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', + 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', + 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' + }; - int b = ((data[i] & 0xFF) << 16) & 0xFFFFFF; - if (i + 1 < data.length) { - b |= (data[i + 1] & 0xFF) << 8; - } else { - pad++; - } - if (i + 2 < data.length) { - b |= (data[i + 2] & 0xFF); - } else { - pad++; - } + StringBuilder buffer = new StringBuilder(); + int pad = 0; + for (int i = 0; i < data.length; i += 3) { - for (int j = 0; j < 4 - pad; j++) { - int c = (b & 0xFC0000) >> 18; - buffer.append(tbl[c]); - b <<= 6; - } - } - for (int j = 0; j < pad; j++) { - buffer.append("="); - } + int b = ((data[i] & 0xFF) << 16) & 0xFFFFFF; + if (i + 1 < data.length) { + b |= (data[i + 1] & 0xFF) << 8; + } else { + pad++; + } + if (i + 2 < data.length) { + b |= (data[i + 2] & 0xFF); + } else { + pad++; + } - return buffer.toString(); + for (int j = 0; j < 4 - pad; j++) { + int c = (b & 0xFC0000) >> 18; + buffer.append(tbl[c]); + b <<= 6; + } } + for (int j = 0; j < pad; j++) { + buffer.append("="); + } + + return buffer.toString(); + } - public static byte[] decode(String data) { - int[] tbl = { - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, - 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, - 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, - 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, - 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, - 48, 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; - byte[] bytes = data.getBytes(); - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - for (int i = 0; i < bytes.length; ) { - int b = 0; - if (tbl[bytes[i]] != -1) { - b = (tbl[bytes[i]] & 0xFF) << 18; - } else { - i++; - continue; - } + public static byte[] decode(String data) { + int[] tbl = { + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, + 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, + 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, + 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, + 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + }; + byte[] bytes = data.getBytes(); + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + for (int i = 0; i < bytes.length; ) { + int b = 0; + if (tbl[bytes[i]] != -1) { + b = (tbl[bytes[i]] & 0xFF) << 18; + } else { + i++; + continue; + } - int num = 0; - if (i + 1 < bytes.length && tbl[bytes[i + 1]] != -1) { - b = b | ((tbl[bytes[i + 1]] & 0xFF) << 12); - num++; - } - if (i + 2 < bytes.length && tbl[bytes[i + 2]] != -1) { - b = b | ((tbl[bytes[i + 2]] & 0xFF) << 6); - num++; - } - if (i + 3 < bytes.length && tbl[bytes[i + 3]] != -1) { - b = b | (tbl[bytes[i + 3]] & 0xFF); - num++; - } + int num = 0; + if (i + 1 < bytes.length && tbl[bytes[i + 1]] != -1) { + b = b | ((tbl[bytes[i + 1]] & 0xFF) << 12); + num++; + } + if (i + 2 < bytes.length && tbl[bytes[i + 2]] != -1) { + b = b | ((tbl[bytes[i + 2]] & 0xFF) << 6); + num++; + } + if (i + 3 < bytes.length && tbl[bytes[i + 3]] != -1) { + b = b | (tbl[bytes[i + 3]] & 0xFF); + num++; + } - while (num > 0) { - int c = (b & 0xFF0000) >> 16; - buffer.write((char) c); - b <<= 8; - num--; - } - i += 4; - } - return buffer.toByteArray(); + while (num > 0) { + int c = (b & 0xFF0000) >> 16; + buffer.write((char) c); + b <<= 8; + num--; + } + i += 4; } + return buffer.toByteArray(); + } } diff --git a/src/main/java/com/box/sdk/BinaryBodyUtils.java b/src/main/java/com/box/sdk/BinaryBodyUtils.java index 2873d8c00..733305d0b 100644 --- a/src/main/java/com/box/sdk/BinaryBodyUtils.java +++ b/src/main/java/com/box/sdk/BinaryBodyUtils.java @@ -5,173 +5,178 @@ import java.io.InputStream; import java.io.OutputStream; -/** - * Utility class to help writing binary data to output stream. - */ +/** Utility class to help writing binary data to output stream. */ final class BinaryBodyUtils { - private static final int BUFFER_SIZE = 8192; - - private BinaryBodyUtils() { - // utility class has no public constructor + private static final int BUFFER_SIZE = 8192; + + private BinaryBodyUtils() { + // utility class has no public constructor + } + + /** + * Writes response body bytes to output stream. After all closes the input stream. + * + * @param response Response that is going to be written. + * @param output Output stream. + */ + static void writeStream(BoxAPIResponse response, OutputStream output) { + writeStream(response, output, null); + } + + /** + * Writes response body bytes to output stream. After all closes the input stream. + * + * @param response Response that is going to be written. + * @param output Output stream. + * @param listener Listener that will be notified on writing response. Can be null. + */ + static void writeStream(BoxAPIResponse response, OutputStream output, ProgressListener listener) { + try { + InputStream input; + if (listener != null) { + input = response.getBody(listener); + } else { + input = response.getBody(); + } + writeStreamTo(input, output); + } finally { + response.close(); } - - /** - * Writes response body bytes to output stream. After all closes the input stream. - * - * @param response Response that is going to be written. - * @param output Output stream. - */ - static void writeStream(BoxAPIResponse response, OutputStream output) { - writeStream(response, output, null); + } + + /** + * Writes response body bytes to output stream. After all closes the input stream. + * + * @param response Response that is going to be written. + * @param output Output stream. + */ + static void writeStreamWithContentLength(BoxAPIResponse response, OutputStream output) { + writeStreamWithContentLength(response, output, null); + } + + /** + * Writes response body bytes to output stream. After all closes the input stream. + * + * @param response Response that is going to be written. + * @param output Output stream. + * @param listener Listener that will be notified on writing response. Can be null. + */ + static void writeStreamWithContentLength( + BoxAPIResponse response, OutputStream output, ProgressListener listener) { + try { + InputStream input; + if (listener != null) { + input = response.getBody(listener); + } else { + input = response.getBody(); + } + writeStreamTo(input, output, getContentLengthFromAPIResponse(response)); + } finally { + response.close(); } - - /** - * Writes response body bytes to output stream. After all closes the input stream. - * - * @param response Response that is going to be written. - * @param output Output stream. - * @param listener Listener that will be notified on writing response. Can be null. - */ - - static void writeStream(BoxAPIResponse response, OutputStream output, ProgressListener listener) { + } + + /** + * Get the content length from the API response. In some cases, the Content-Length is not provided + * in the response headers. This could happen when getting the content representation for a + * compressed data. In that case the API will switch to chunk mode and provide the length in the + * "X-Original-Content-Length" header. + * + * @param response API response. + * @return Content length. + */ + private static long getContentLengthFromAPIResponse(BoxAPIResponse response) { + long length = response.getContentLength(); + if (length == -1) { + String headerValue = null; + if (response.getHeaders().containsKey(HttpHeaders.CONTENT_LENGTH)) { + headerValue = response.getHeaders().get(HttpHeaders.CONTENT_LENGTH).get(0); + } else if (response.getHeaders().containsKey(HttpHeaders.X_ORIGINAL_CONTENT_LENGTH)) { + headerValue = response.getHeaders().get(HttpHeaders.X_ORIGINAL_CONTENT_LENGTH).get(0); + } + + if (headerValue != null) { + String trimmedHeaderValue = headerValue.trim(); try { - InputStream input; - if (listener != null) { - input = response.getBody(listener); - } else { - input = response.getBody(); - } - writeStreamTo(input, output); - } finally { - response.close(); + length = Long.parseLong(trimmedHeaderValue); + } catch (NumberFormatException e) { + throw new RuntimeException( + "Invalid content length: " + + trimmedHeaderValue + + " with: " + + trimmedHeaderValue.length() + + " number of characters."); } + } } - /** - * Writes response body bytes to output stream. After all closes the input stream. - * - * @param response Response that is going to be written. - * @param output Output stream. - */ - - static void writeStreamWithContentLength(BoxAPIResponse response, OutputStream output) { - writeStreamWithContentLength(response, output, null); + return length; + } + + /** + * Writes content of input stream to provided output. + * + * @param input Input that will be read. + * @param output Output stream. + */ + static void writeStreamTo(InputStream input, OutputStream output) { + try { + byte[] buffer = new byte[BUFFER_SIZE]; + int n = input.read(buffer); + while (n != -1) { + output.write(buffer, 0, n); + n = input.read(buffer); + } + } catch (IOException e) { + throw new RuntimeException(e); + } finally { + try { + input.close(); + output.close(); + } catch (IOException e) { + throw new RuntimeException(e); + } } - - /** - * Writes response body bytes to output stream. After all closes the input stream. - * - * @param response Response that is going to be written. - * @param output Output stream. - * @param listener Listener that will be notified on writing response. Can be null. - */ - - static void writeStreamWithContentLength(BoxAPIResponse response, OutputStream output, ProgressListener listener) { - try { - InputStream input; - if (listener != null) { - input = response.getBody(listener); - } else { - input = response.getBody(); - } - writeStreamTo(input, output, getContentLengthFromAPIResponse(response)); - } finally { - response.close(); - } + } + + /** + * Writes the content of the input stream to the provided output stream, ensuring the exact number + * of bytes specified by the expected length is written. If the stream ends prematurely an + * exception is thrown. + * + * @param input The input stream to be read. + * @param output The output stream where data will be written. + * @param expectedLength The expected number of bytes to be transferred. + */ + static void writeStreamTo(InputStream input, OutputStream output, long expectedLength) { + long totalBytesRead = 0; + if (expectedLength < 0) { + throw new RuntimeException( + "Expected content length should not be negative: " + expectedLength); } - - /** - * Get the content length from the API response. - * In some cases, the Content-Length is not provided in the response headers. - * This could happen when getting the content representation for a compressed data. - * In that case the API will switch to chunk mode and provide the length in the "X-Original-Content-Length" header. - * - * @param response API response. - * @return Content length. - */ - private static long getContentLengthFromAPIResponse(BoxAPIResponse response) { - long length = response.getContentLength(); - if (length == -1) { - String headerValue = null; - if (response.getHeaders().containsKey(HttpHeaders.CONTENT_LENGTH)) { - headerValue = response.getHeaders().get(HttpHeaders.CONTENT_LENGTH).get(0); - } else if (response.getHeaders().containsKey(HttpHeaders.X_ORIGINAL_CONTENT_LENGTH)) { - headerValue = response.getHeaders().get(HttpHeaders.X_ORIGINAL_CONTENT_LENGTH).get(0); - } - - if (headerValue != null) { - String trimmedHeaderValue = headerValue.trim(); - try { - length = Long.parseLong(trimmedHeaderValue); - } catch (NumberFormatException e) { - throw new RuntimeException("Invalid content length: " + trimmedHeaderValue + " with: " - + trimmedHeaderValue.length() + " number of characters."); - } - } - } - - return length; - } - - /** - * Writes content of input stream to provided output. - * - * @param input Input that will be read. - * @param output Output stream. - */ - static void writeStreamTo(InputStream input, OutputStream output) { - try { - byte[] buffer = new byte[BUFFER_SIZE]; - int n = input.read(buffer); - while (n != -1) { - output.write(buffer, 0, n); - n = input.read(buffer); - } - } catch (IOException e) { - throw new RuntimeException(e); - } finally { - try { - input.close(); - output.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - } - - /** - * Writes the content of the input stream to the provided output stream, ensuring the exact number of bytes specified - * by the expected length is written. If the stream ends prematurely an exception is thrown. - * - * @param input The input stream to be read. - * @param output The output stream where data will be written. - * @param expectedLength The expected number of bytes to be transferred. - */ - - static void writeStreamTo(InputStream input, OutputStream output, long expectedLength) { - long totalBytesRead = 0; - if (expectedLength < 0) { - throw new RuntimeException("Expected content length should not be negative: " + expectedLength); - } - try { - byte[] buffer = new byte[BUFFER_SIZE]; - for (int n = input.read(buffer); n != -1; n = input.read(buffer)) { - output.write(buffer, 0, n); - totalBytesRead += n; // Track the total bytes read - } - if (totalBytesRead != expectedLength) { - throw new IOException("Stream ended prematurely. Expected " - + expectedLength + " bytes, but read " + totalBytesRead + " bytes."); - } - } catch (IOException e) { - throw new RuntimeException("Error during streaming: " + e.getMessage(), e); - } finally { - try { - input.close(); - output.close(); - } catch (IOException closeException) { - throw new RuntimeException("IOException during stream close", closeException); - } - } + try { + byte[] buffer = new byte[BUFFER_SIZE]; + for (int n = input.read(buffer); n != -1; n = input.read(buffer)) { + output.write(buffer, 0, n); + totalBytesRead += n; // Track the total bytes read + } + if (totalBytesRead != expectedLength) { + throw new IOException( + "Stream ended prematurely. Expected " + + expectedLength + + " bytes, but read " + + totalBytesRead + + " bytes."); + } + } catch (IOException e) { + throw new RuntimeException("Error during streaming: " + e.getMessage(), e); + } finally { + try { + input.close(); + output.close(); + } catch (IOException closeException) { + throw new RuntimeException("IOException during stream close", closeException); + } } + } } diff --git a/src/main/java/com/box/sdk/BoxAI.java b/src/main/java/com/box/sdk/BoxAI.java index a38eb6316..69a1014b7 100644 --- a/src/main/java/com/box/sdk/BoxAI.java +++ b/src/main/java/com/box/sdk/BoxAI.java @@ -7,408 +7,412 @@ import java.net.URL; import java.util.List; - public final class BoxAI { - /** - * Ask AI url. - */ - public static final URLTemplate SEND_AI_REQUEST_URL = new URLTemplate("ai/ask"); - /** - * Text gen AI url. - */ - public static final URLTemplate SEND_AI_TEXT_GEN_REQUEST_URL = new URLTemplate("ai/text_gen"); - /** - * AI agent default config url. - */ - public static final URLTemplate AI_AGENT_DEFAULT_CONFIG_URL = new URLTemplate("ai_agent_default"); - /** - * AI extract metadata freeform url. - */ - public static final URLTemplate EXTRACT_METADATA_FREEFORM_URL = new URLTemplate("ai/extract"); - /** - * AI extract metadata structured url. - */ - public static final URLTemplate EXTRACT_METADATA_STRUCTURED_URL = new URLTemplate("ai/extract_structured"); - - private BoxAI() { + /** Ask AI url. */ + public static final URLTemplate SEND_AI_REQUEST_URL = new URLTemplate("ai/ask"); + /** Text gen AI url. */ + public static final URLTemplate SEND_AI_TEXT_GEN_REQUEST_URL = new URLTemplate("ai/text_gen"); + /** AI agent default config url. */ + public static final URLTemplate AI_AGENT_DEFAULT_CONFIG_URL = new URLTemplate("ai_agent_default"); + /** AI extract metadata freeform url. */ + public static final URLTemplate EXTRACT_METADATA_FREEFORM_URL = new URLTemplate("ai/extract"); + /** AI extract metadata structured url. */ + public static final URLTemplate EXTRACT_METADATA_STRUCTURED_URL = + new URLTemplate("ai/extract_structured"); + + private BoxAI() {} + + /** + * Sends an AI request to supported LLMs and returns an answer specifically focused on the user's + * question given the provided items. + * + * @param api the API connection to be used by the created user. + * @param prompt The prompt provided by the client to be answered by the LLM. + * @param items The items to be processed by the LLM, currently only files are supported. + * @param mode The mode specifies if this request is for a single or multiple items. + * @return The response from the AI. + */ + public static BoxAIResponse sendAIRequest( + BoxAPIConnection api, String prompt, List items, Mode mode) { + return sendAIRequest(api, prompt, items, mode, null, null, null); + } + + /** + * Sends an AI request to supported LLMs and returns an answer specifically focused on the user's + * question given the provided items. + * + * @param api the API connection to be used by the created user. + * @param prompt The prompt provided by the client to be answered by the LLM. + * @param items The items to be processed by the LLM, currently only files are supported. + * @param mode The mode specifies if this request is for a single or multiple items. + * @param dialogueHistory The history of prompts and answers previously passed to the LLM. This + * provides additional context to the LLM in generating the response. + * @param agent The AI agent configuration to be used for the request. + * @param includeCitations Whether to include citations in the response. + * @return The response from the AI. + */ + public static BoxAIResponse sendAIRequest( + BoxAPIConnection api, + String prompt, + List items, + Mode mode, + List dialogueHistory, + BoxAIAgentAsk agent, + Boolean includeCitations) { + URL url = SEND_AI_REQUEST_URL.build(api.getBaseURL()); + JsonObject requestJSON = new JsonObject(); + requestJSON.add("mode", mode.toString()); + requestJSON.add("prompt", prompt); + + JsonArray itemsJSON = new JsonArray(); + for (BoxAIItem item : items) { + itemsJSON.add(item.getJSONObject()); } - - /** - * Sends an AI request to supported LLMs and returns an answer specifically focused - * on the user's question given the provided items. - * - * @param api the API connection to be used by the created user. - * @param prompt The prompt provided by the client to be answered by the LLM. - * @param items The items to be processed by the LLM, currently only files are supported. - * @param mode The mode specifies if this request is for a single or multiple items. - * @return The response from the AI. - */ - public static BoxAIResponse sendAIRequest(BoxAPIConnection api, String prompt, List items, Mode mode) { - return sendAIRequest(api, prompt, items, mode, null, null, null); + requestJSON.add("items", itemsJSON); + + if (dialogueHistory != null) { + JsonArray dialogueHistoryJSON = new JsonArray(); + for (BoxAIDialogueEntry dialogueEntry : dialogueHistory) { + dialogueHistoryJSON.add(dialogueEntry.getJSONObject()); + } + requestJSON.add("dialogue_history", dialogueHistoryJSON); } - - /** - * Sends an AI request to supported LLMs and returns an answer specifically focused - * on the user's question given the provided items. - * - * @param api the API connection to be used by the created user. - * @param prompt The prompt provided by the client to be answered by the LLM. - * @param items The items to be processed by the LLM, currently only files are supported. - * @param mode The mode specifies if this request is for a single or multiple items. - * @param dialogueHistory The history of prompts and answers previously passed to the LLM. - * This provides additional context to the LLM in generating the response. - * @param agent The AI agent configuration to be used for the request. - * @param includeCitations Whether to include citations in the response. - * @return The response from the AI. - */ - public static BoxAIResponse sendAIRequest(BoxAPIConnection api, String prompt, List items, Mode mode, - List dialogueHistory, BoxAIAgentAsk agent, - Boolean includeCitations) { - URL url = SEND_AI_REQUEST_URL.build(api.getBaseURL()); - JsonObject requestJSON = new JsonObject(); - requestJSON.add("mode", mode.toString()); - requestJSON.add("prompt", prompt); - - JsonArray itemsJSON = new JsonArray(); - for (BoxAIItem item : items) { - itemsJSON.add(item.getJSONObject()); - } - requestJSON.add("items", itemsJSON); - - if (dialogueHistory != null) { - JsonArray dialogueHistoryJSON = new JsonArray(); - for (BoxAIDialogueEntry dialogueEntry : dialogueHistory) { - dialogueHistoryJSON.add(dialogueEntry.getJSONObject()); - } - requestJSON.add("dialogue_history", dialogueHistoryJSON); - } - if (agent != null) { - requestJSON.add("ai_agent", agent.getJSONObject()); - } - if (includeCitations != null) { - requestJSON.add("include_citations", includeCitations); - } - - BoxJSONRequest req = new BoxJSONRequest(api, url, HttpMethod.POST); - req.setBody(requestJSON.toString()); - - try (BoxJSONResponse response = req.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - return new BoxAIResponse(responseJSON); - } + if (agent != null) { + requestJSON.add("ai_agent", agent.getJSONObject()); } - - /** - * Sends an AI request to supported LLMs and returns an answer specifically focused on the creation of new text. - * - * @param api the API connection to be used by the created user. - * @param prompt The prompt provided by the client to be answered by the LLM. - * @param items The items to be processed by the LLM, currently only files are supported. - * @return The response from the AI. - */ - public static BoxAIResponse sendAITextGenRequest(BoxAPIConnection api, String prompt, List items) { - return sendAITextGenRequest(api, prompt, items, null); + if (includeCitations != null) { + requestJSON.add("include_citations", includeCitations); } - /** - * Sends an AI request to supported LLMs and returns an answer specifically focused on the creation of new text. - * - * @param api the API connection to be used by the created user. - * @param prompt The prompt provided by the client to be answered by the LLM. - * @param items The items to be processed by the LLM, currently only files are supported. - * @param dialogueHistory The history of prompts and answers previously passed to the LLM. - * This provides additional context to the LLM in generating the response. - * @return The response from the AI. - */ - public static BoxAIResponse sendAITextGenRequest(BoxAPIConnection api, String prompt, List items, - List dialogueHistory) { - return sendAITextGenRequest(api, prompt, items, dialogueHistory, null); + BoxJSONRequest req = new BoxJSONRequest(api, url, HttpMethod.POST); + req.setBody(requestJSON.toString()); + + try (BoxJSONResponse response = req.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + return new BoxAIResponse(responseJSON); + } + } + + /** + * Sends an AI request to supported LLMs and returns an answer specifically focused on the + * creation of new text. + * + * @param api the API connection to be used by the created user. + * @param prompt The prompt provided by the client to be answered by the LLM. + * @param items The items to be processed by the LLM, currently only files are supported. + * @return The response from the AI. + */ + public static BoxAIResponse sendAITextGenRequest( + BoxAPIConnection api, String prompt, List items) { + return sendAITextGenRequest(api, prompt, items, null); + } + + /** + * Sends an AI request to supported LLMs and returns an answer specifically focused on the + * creation of new text. + * + * @param api the API connection to be used by the created user. + * @param prompt The prompt provided by the client to be answered by the LLM. + * @param items The items to be processed by the LLM, currently only files are supported. + * @param dialogueHistory The history of prompts and answers previously passed to the LLM. This + * provides additional context to the LLM in generating the response. + * @return The response from the AI. + */ + public static BoxAIResponse sendAITextGenRequest( + BoxAPIConnection api, + String prompt, + List items, + List dialogueHistory) { + return sendAITextGenRequest(api, prompt, items, dialogueHistory, null); + } + + /** + * Sends an AI request to supported LLMs and returns an answer specifically focused on the + * creation of new text. + * + * @param api the API connection to be used by the created user. + * @param prompt The prompt provided by the client to be answered by the LLM. + * @param items The items to be processed by the LLM, currently only files are supported. + * @param dialogueHistory The history of prompts and answers previously passed to the LLM. This + * provides additional context to the LLM in generating the response. + * @param agent The AI agent configuration to be used for the request. + * @return The response from the AI. + */ + public static BoxAIResponse sendAITextGenRequest( + BoxAPIConnection api, + String prompt, + List items, + List dialogueHistory, + BoxAIAgentTextGen agent) { + URL url = SEND_AI_TEXT_GEN_REQUEST_URL.build(api.getBaseURL()); + JsonObject requestJSON = new JsonObject(); + requestJSON.add("prompt", prompt); + + JsonArray itemsJSON = new JsonArray(); + for (BoxAIItem item : items) { + itemsJSON.add(item.getJSONObject()); + } + requestJSON.add("items", itemsJSON); + + if (dialogueHistory != null) { + JsonArray dialogueHistoryJSON = new JsonArray(); + for (BoxAIDialogueEntry dialogueEntry : dialogueHistory) { + dialogueHistoryJSON.add(dialogueEntry.getJSONObject()); + } + requestJSON.add("dialogue_history", dialogueHistoryJSON); } - /** - * Sends an AI request to supported LLMs and returns an answer specifically focused on the creation of new text. - * - * @param api the API connection to be used by the created user. - * @param prompt The prompt provided by the client to be answered by the LLM. - * @param items The items to be processed by the LLM, currently only files are supported. - * @param dialogueHistory The history of prompts and answers previously passed to the LLM. - * This provides additional context to the LLM in generating the response. - * @param agent The AI agent configuration to be used for the request. - * @return The response from the AI. - */ - public static BoxAIResponse sendAITextGenRequest(BoxAPIConnection api, String prompt, List items, - List dialogueHistory, - BoxAIAgentTextGen agent) { - URL url = SEND_AI_TEXT_GEN_REQUEST_URL.build(api.getBaseURL()); - JsonObject requestJSON = new JsonObject(); - requestJSON.add("prompt", prompt); - - JsonArray itemsJSON = new JsonArray(); - for (BoxAIItem item : items) { - itemsJSON.add(item.getJSONObject()); - } - requestJSON.add("items", itemsJSON); - - if (dialogueHistory != null) { - JsonArray dialogueHistoryJSON = new JsonArray(); - for (BoxAIDialogueEntry dialogueEntry : dialogueHistory) { - dialogueHistoryJSON.add(dialogueEntry.getJSONObject()); - } - requestJSON.add("dialogue_history", dialogueHistoryJSON); - } - - if (agent != null) { - requestJSON.add("ai_agent", agent.getJSONObject()); - } - - BoxJSONRequest req = new BoxJSONRequest(api, url, HttpMethod.POST); - req.setBody(requestJSON.toString()); - - try (BoxJSONResponse response = req.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - return new BoxAIResponse(responseJSON); - } + if (agent != null) { + requestJSON.add("ai_agent", agent.getJSONObject()); } - /** - * Get the default AI Agent use for the given mode. - * - * @param api The API connection to be used by the created user. - * @param mode The mode to filter the agent config to return. - * @return A successful response including the default agent configuration. - */ - public static BoxAIAgent getAiAgentDefaultConfig(BoxAPIConnection api, BoxAIAgent.Mode mode) { - return getAiAgentDefaultConfig(api, mode, null, null); + BoxJSONRequest req = new BoxJSONRequest(api, url, HttpMethod.POST); + req.setBody(requestJSON.toString()); + + try (BoxJSONResponse response = req.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + return new BoxAIResponse(responseJSON); + } + } + + /** + * Get the default AI Agent use for the given mode. + * + * @param api The API connection to be used by the created user. + * @param mode The mode to filter the agent config to return. + * @return A successful response including the default agent configuration. + */ + public static BoxAIAgent getAiAgentDefaultConfig(BoxAPIConnection api, BoxAIAgent.Mode mode) { + return getAiAgentDefaultConfig(api, mode, null, null); + } + + /** + * Get the default AI Agent use for the given mode. + * + * @param api The API connection to be used by the created user. + * @param mode The mode to filter the agent config to return. + * @param language The language to filter the agent config to return. + * @param model The model to filter the agent config to return. + * @return A successful response including the default agent configuration. + */ + public static BoxAIAgent getAiAgentDefaultConfig( + BoxAPIConnection api, BoxAIAgent.Mode mode, String language, String model) { + QueryStringBuilder builder = new QueryStringBuilder(); + builder.appendParam("mode", mode.toString()); + if (language != null) { + builder.appendParam("language", language); + } + if (model != null) { + builder.appendParam("model", model); } + URL url = AI_AGENT_DEFAULT_CONFIG_URL.buildWithQuery(api.getBaseURL(), builder.toString()); + BoxAPIRequest req = new BoxAPIRequest(api, url, HttpMethod.GET); + try (BoxJSONResponse response = (BoxJSONResponse) req.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + return BoxAIAgent.parse(responseJSON); + } + } + + public enum Mode { + /** Multiple items */ + MULTIPLE_ITEM_QA("multiple_item_qa"), + + /** Single item */ + SINGLE_ITEM_QA("single_item_qa"); - /** - * Get the default AI Agent use for the given mode. - * - * @param api The API connection to be used by the created user. - * @param mode The mode to filter the agent config to return. - * @param language The language to filter the agent config to return. - * @param model The model to filter the agent config to return. - * @return A successful response including the default agent configuration. - */ - public static BoxAIAgent getAiAgentDefaultConfig(BoxAPIConnection api, - BoxAIAgent.Mode mode, - String language, - String model) { - QueryStringBuilder builder = new QueryStringBuilder(); - builder.appendParam("mode", mode.toString()); - if (language != null) { - builder.appendParam("language", language); - } - if (model != null) { - builder.appendParam("model", model); - } - URL url = AI_AGENT_DEFAULT_CONFIG_URL.buildWithQuery(api.getBaseURL(), builder.toString()); - BoxAPIRequest req = new BoxAPIRequest(api, url, HttpMethod.GET); - try (BoxJSONResponse response = (BoxJSONResponse) req.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - return BoxAIAgent.parse(responseJSON); - } + private final String mode; + + Mode(String mode) { + this.mode = mode; } - public enum Mode { - /** - * Multiple items - */ - MULTIPLE_ITEM_QA("multiple_item_qa"), - - /** - * Single item - */ - SINGLE_ITEM_QA("single_item_qa"); - - private final String mode; - - Mode(String mode) { - this.mode = mode; - } - - static BoxAI.Mode fromJSONValue(String jsonValue) { - if (jsonValue.equals("multiple_item_qa")) { - return BoxAI.Mode.MULTIPLE_ITEM_QA; - } else if (jsonValue.equals("single_item_qa")) { - return BoxAI.Mode.SINGLE_ITEM_QA; - } else { - System.out.print("Invalid AI mode."); - return null; - } - } - - String toJSONValue() { - return this.mode; - } - - public String toString() { - return this.mode; - } + static BoxAI.Mode fromJSONValue(String jsonValue) { + if (jsonValue.equals("multiple_item_qa")) { + return BoxAI.Mode.MULTIPLE_ITEM_QA; + } else if (jsonValue.equals("single_item_qa")) { + return BoxAI.Mode.SINGLE_ITEM_QA; + } else { + System.out.print("Invalid AI mode."); + return null; + } } - /** - * Sends an AI request to supported Large Language Models (LLMs) and extracts metadata in form of key-value pairs. - * Freeform metadata extraction does not require any metadata template setup before sending the request. - * - * @param api the API connection to be used by the created user. - * @param prompt The prompt provided by the client to be answered by the LLM. - * @param items The items to be processed by the LLM, currently only files are supported. - * @return The response from the AI. - */ - public static BoxAIResponse extractMetadataFreeform(BoxAPIConnection api, - String prompt, - List items) { - return extractMetadataFreeform(api, prompt, items, null); + String toJSONValue() { + return this.mode; } - /** - * Sends an AI request to supported Large Language Models (LLMs) and extracts metadata in form of key-value pairs. - * Freeform metadata extraction does not require any metadata template setup before sending the request. - * - * @param api the API connection to be used by the created user. - * @param prompt The prompt provided by the client to be answered by the LLM. - * @param items The items to be processed by the LLM, currently only files are supported. - * @param agent The AI agent configuration to be used for the request. - * @return The response from the AI. - */ - public static BoxAIResponse extractMetadataFreeform(BoxAPIConnection api, - String prompt, - List items, - BoxAIAgentExtract agent) { - URL url = EXTRACT_METADATA_FREEFORM_URL.build(api.getBaseURL()); - - JsonObject requestJSON = new JsonObject(); - JsonArray itemsJSON = new JsonArray(); - for (BoxAIItem item : items) { - itemsJSON.add(item.getJSONObject()); - } - requestJSON.add("items", itemsJSON); - requestJSON.add("prompt", prompt); - if (agent != null) { - requestJSON.add("ai_agent", agent.getJSONObject()); - } - - BoxJSONRequest req = new BoxJSONRequest(api, url, HttpMethod.POST); - req.setBody(requestJSON.toString()); - - try (BoxJSONResponse response = req.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - return new BoxAIResponse(responseJSON); - } + public String toString() { + return this.mode; + } + } + + /** + * Sends an AI request to supported Large Language Models (LLMs) and extracts metadata in form of + * key-value pairs. Freeform metadata extraction does not require any metadata template setup + * before sending the request. + * + * @param api the API connection to be used by the created user. + * @param prompt The prompt provided by the client to be answered by the LLM. + * @param items The items to be processed by the LLM, currently only files are supported. + * @return The response from the AI. + */ + public static BoxAIResponse extractMetadataFreeform( + BoxAPIConnection api, String prompt, List items) { + return extractMetadataFreeform(api, prompt, items, null); + } + + /** + * Sends an AI request to supported Large Language Models (LLMs) and extracts metadata in form of + * key-value pairs. Freeform metadata extraction does not require any metadata template setup + * before sending the request. + * + * @param api the API connection to be used by the created user. + * @param prompt The prompt provided by the client to be answered by the LLM. + * @param items The items to be processed by the LLM, currently only files are supported. + * @param agent The AI agent configuration to be used for the request. + * @return The response from the AI. + */ + public static BoxAIResponse extractMetadataFreeform( + BoxAPIConnection api, String prompt, List items, BoxAIAgentExtract agent) { + URL url = EXTRACT_METADATA_FREEFORM_URL.build(api.getBaseURL()); + + JsonObject requestJSON = new JsonObject(); + JsonArray itemsJSON = new JsonArray(); + for (BoxAIItem item : items) { + itemsJSON.add(item.getJSONObject()); } + requestJSON.add("items", itemsJSON); + requestJSON.add("prompt", prompt); + if (agent != null) { + requestJSON.add("ai_agent", agent.getJSONObject()); + } + + BoxJSONRequest req = new BoxJSONRequest(api, url, HttpMethod.POST); + req.setBody(requestJSON.toString()); - /** - * Sends an AI request to supported Large Language Models (LLMs) and returns extracted metadata as a set of - * key-value pairs. For this request, you need to use an already defined metadata template or a define a - * schema yourself. - * - * @param api The API connection to be used by the created user. - * @param items The items to be processed by the LLM, currently only files are supported. - * @param template The metadata template to be used for the request. - * @return The response from the AI. - */ - public static BoxAIExtractStructuredResponse extractMetadataStructured(BoxAPIConnection api, List items, - BoxAIExtractMetadataTemplate template) { - return extractMetadataStructured(api, items, template, null, null); + try (BoxJSONResponse response = req.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + return new BoxAIResponse(responseJSON); } + } + + /** + * Sends an AI request to supported Large Language Models (LLMs) and returns extracted metadata as + * a set of key-value pairs. For this request, you need to use an already defined metadata + * template or a define a schema yourself. + * + * @param api The API connection to be used by the created user. + * @param items The items to be processed by the LLM, currently only files are supported. + * @param template The metadata template to be used for the request. + * @return The response from the AI. + */ + public static BoxAIExtractStructuredResponse extractMetadataStructured( + BoxAPIConnection api, List items, BoxAIExtractMetadataTemplate template) { + return extractMetadataStructured(api, items, template, null, null); + } + + /** + * Sends an AI request to supported Large Language Models (LLMs) and returns extracted metadata as + * a set of key-value pairs. For this request, you need to use an already defined metadata + * template or a define a schema yourself. + * + * @param api The API connection to be used by the created user. + * @param items The items to be processed by the LLM, currently only files are supported. + * @param template The metadata template to be used for the request. + * @param agent The AI agent configuration to be used for the request. + * @return The response from the AI. + */ + public static BoxAIExtractStructuredResponse extractMetadataStructured( + BoxAPIConnection api, + List items, + BoxAIExtractMetadataTemplate template, + BoxAIAgentExtractStructured agent) { + return extractMetadataStructured(api, items, template, null, agent); + } + + /** + * Sends an AI request to supported Large Language Models (LLMs) and returns extracted metadata as + * a set of key-value pairs. For this request, you need to use an already defined metadata + * template or a define a schema yourself. + * + * @param api The API connection to be used by the created user. + * @param items The items to be processed by the LLM, currently only files are supported. + * @param fields The fields to be extracted from the items. + * @return The response from the AI. + */ + public static BoxAIExtractStructuredResponse extractMetadataStructured( + BoxAPIConnection api, List items, List fields) { + return extractMetadataStructured(api, items, null, fields, null); + } + + /** + * Sends an AI request to supported Large Language Models (LLMs) and returns extracted metadata as + * a set of key-value pairs. For this request, you need to use an already defined metadata + * template or a define a schema yourself. + * + * @param api The API connection to be used by the created user. + * @param items The items to be processed by the LLM, currently only files are supported. + * @param fields The fields to be extracted from the items. + * @param agent The AI agent configuration to be used for the request. + * @return The response from the AI. + */ + public static BoxAIExtractStructuredResponse extractMetadataStructured( + BoxAPIConnection api, + List items, + List fields, + BoxAIAgentExtractStructured agent) { + return extractMetadataStructured(api, items, null, fields, agent); + } + + /** + * Sends an AI request to supported Large Language Models (LLMs) and returns extracted metadata as + * a set of key-value pairs. For this request, you need to use an already defined metadata + * template or a define a schema yourself. + * + * @param api The API connection to be used by the created user. + * @param items The items to be processed by the LLM, currently only files are supported. + * @param template The metadata template to be used for the request. + * @param fields The fields to be extracted from the items. + * @param agent The AI agent configuration to be used for the request. + * @return The response from the AI. + */ + private static BoxAIExtractStructuredResponse extractMetadataStructured( + BoxAPIConnection api, + List items, + BoxAIExtractMetadataTemplate template, + List fields, + BoxAIAgentExtractStructured agent) { + URL url = EXTRACT_METADATA_STRUCTURED_URL.build(api.getBaseURL()); + + JsonObject requestJSON = new JsonObject(); + JsonArray itemsJSON = new JsonArray(); + for (BoxAIItem item : items) { + itemsJSON.add(item.getJSONObject()); + } + requestJSON.add("items", itemsJSON); - /** - * Sends an AI request to supported Large Language Models (LLMs) and returns extracted metadata as a set of - * key-value pairs. For this request, you need to use an already defined metadata template or a define a - * schema yourself. - * - * @param api The API connection to be used by the created user. - * @param items The items to be processed by the LLM, currently only files are supported. - * @param template The metadata template to be used for the request. - * @param agent The AI agent configuration to be used for the request. - * @return The response from the AI. - */ - public static BoxAIExtractStructuredResponse extractMetadataStructured(BoxAPIConnection api, List items, - BoxAIExtractMetadataTemplate template, - BoxAIAgentExtractStructured agent) { - return extractMetadataStructured(api, items, template, null, agent); + if (template != null) { + requestJSON.add("metadata_template", template.getJSONObject()); } - /** - * Sends an AI request to supported Large Language Models (LLMs) and returns extracted metadata as a set of - * key-value pairs. For this request, you need to use an already defined metadata template or a define a - * schema yourself. - * - * @param api The API connection to be used by the created user. - * @param items The items to be processed by the LLM, currently only files are supported. - * @param fields The fields to be extracted from the items. - * @return The response from the AI. - */ - public static BoxAIExtractStructuredResponse extractMetadataStructured(BoxAPIConnection api, List items, - List fields) { - return extractMetadataStructured(api, items, null, fields, null); + if (fields != null) { + JsonArray fieldsJSON = new JsonArray(); + for (BoxAIExtractField field : fields) { + fieldsJSON.add(field.getJSONObject()); + } + requestJSON.add("fields", fieldsJSON); } - /** - * Sends an AI request to supported Large Language Models (LLMs) and returns extracted metadata as a set of - * key-value pairs. For this request, you need to use an already defined metadata template or a define a - * schema yourself. - * - * @param api The API connection to be used by the created user. - * @param items The items to be processed by the LLM, currently only files are supported. - * @param fields The fields to be extracted from the items. - * @param agent The AI agent configuration to be used for the request. - * @return The response from the AI. - */ - public static BoxAIExtractStructuredResponse extractMetadataStructured(BoxAPIConnection api, List items, - List fields, - BoxAIAgentExtractStructured agent) { - return extractMetadataStructured(api, items, null, fields, agent); + if (agent != null) { + requestJSON.add("ai_agent", agent.getJSONObject()); } - /** - * Sends an AI request to supported Large Language Models (LLMs) and returns extracted metadata as a set of - * key-value pairs. For this request, you need to use an already defined metadata template or a define a - * schema yourself. - * - * @param api The API connection to be used by the created user. - * @param items The items to be processed by the LLM, currently only files are supported. - * @param template The metadata template to be used for the request. - * @param fields The fields to be extracted from the items. - * @param agent The AI agent configuration to be used for the request. - * @return The response from the AI. - */ - private static BoxAIExtractStructuredResponse extractMetadataStructured(BoxAPIConnection api, List items, - BoxAIExtractMetadataTemplate template, - List fields, - BoxAIAgentExtractStructured agent) { - URL url = EXTRACT_METADATA_STRUCTURED_URL.build(api.getBaseURL()); - - JsonObject requestJSON = new JsonObject(); - JsonArray itemsJSON = new JsonArray(); - for (BoxAIItem item : items) { - itemsJSON.add(item.getJSONObject()); - } - requestJSON.add("items", itemsJSON); - - if (template != null) { - requestJSON.add("metadata_template", template.getJSONObject()); - } - - if (fields != null) { - JsonArray fieldsJSON = new JsonArray(); - for (BoxAIExtractField field : fields) { - fieldsJSON.add(field.getJSONObject()); - } - requestJSON.add("fields", fieldsJSON); - } - - if (agent != null) { - requestJSON.add("ai_agent", agent.getJSONObject()); - } - - BoxJSONRequest req = new BoxJSONRequest(api, url, HttpMethod.POST); - req.setBody(requestJSON.toString()); - - try (BoxJSONResponse response = req.send()) { - return new BoxAIExtractStructuredResponse(response.getJSON()); - } + BoxJSONRequest req = new BoxJSONRequest(api, url, HttpMethod.POST); + req.setBody(requestJSON.toString()); + + try (BoxJSONResponse response = req.send()) { + return new BoxAIExtractStructuredResponse(response.getJSON()); } + } } diff --git a/src/main/java/com/box/sdk/BoxAIAgent.java b/src/main/java/com/box/sdk/BoxAIAgent.java index 4d0c13ee4..ab14aaaf2 100644 --- a/src/main/java/com/box/sdk/BoxAIAgent.java +++ b/src/main/java/com/box/sdk/BoxAIAgent.java @@ -4,130 +4,124 @@ import com.eclipsesource.json.JsonValue; public abstract class BoxAIAgent extends BoxJSONObject { - /** - * The type of the AI agent. - * Value can be "ai_agent_ask" or "ai_agent_text_gen", "ai_agent_extract", "ai_agent_extract_structured". - */ - private String type; - - /** - * Constructs an AI agent with default settings. - * @param type The type of the AI agent. - * Value can be "ai_agent_ask", "ai_agent_text_gen", "ai_agent_extract", "ai_agent_extract_structured". - */ - public BoxAIAgent(String type) { - super(); - this.type = type; + /** + * The type of the AI agent. Value can be "ai_agent_ask" or "ai_agent_text_gen", + * "ai_agent_extract", "ai_agent_extract_structured". + */ + private String type; + + /** + * Constructs an AI agent with default settings. + * + * @param type The type of the AI agent. Value can be "ai_agent_ask", "ai_agent_text_gen", + * "ai_agent_extract", "ai_agent_extract_structured". + */ + public BoxAIAgent(String type) { + super(); + this.type = type; + } + + /** + * Constructs an AI agent with default settings. + * + * @param jsonObject JSON object representing the AI agent. + */ + public BoxAIAgent(JsonObject jsonObject) { + super(jsonObject); + } + + /** + * Constructs an AI agent with default settings. + * + * @param jsonObject JSON object representing the AI agent. + */ + public static BoxAIAgent parse(JsonObject jsonObject) { + String type = jsonObject.get("type").asString(); + if (type.equals(BoxAIAgentAsk.TYPE)) { + return new BoxAIAgentAsk(jsonObject); + } else if (type.equals(BoxAIAgentTextGen.TYPE)) { + return new BoxAIAgentTextGen(jsonObject); + } else if (type.equals(BoxAIAgentExtract.TYPE)) { + return new BoxAIAgentExtract(jsonObject); + } else if (type.equals(BoxAIAgentExtractStructured.TYPE)) { + return new BoxAIAgentExtractStructured(jsonObject); + } else { + throw new IllegalArgumentException("Invalid AI agent type: " + type); } - - /** - * Constructs an AI agent with default settings. - * @param jsonObject JSON object representing the AI agent. - */ - public BoxAIAgent(JsonObject jsonObject) { - super(jsonObject); + } + + /** + * Gets the type of the AI agent. + * + * @return The type of the AI agent. + */ + public String getType() { + return type; + } + + /** + * Sets the type of the AI agent. + * + * @param type The type of the AI agent. + */ + public void setType(String type) { + this.type = type; + } + + @Override + void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + String memberName = member.getName(); + JsonValue value = member.getValue(); + if (memberName.equals("type")) { + this.type = value.asString(); } - - /** - * Constructs an AI agent with default settings. - * @param jsonObject JSON object representing the AI agent. - */ - public static BoxAIAgent parse(JsonObject jsonObject) { - String type = jsonObject.get("type").asString(); - if (type.equals(BoxAIAgentAsk.TYPE)) { - return new BoxAIAgentAsk(jsonObject); - } else if (type.equals(BoxAIAgentTextGen.TYPE)) { - return new BoxAIAgentTextGen(jsonObject); - } else if (type.equals(BoxAIAgentExtract.TYPE)) { - return new BoxAIAgentExtract(jsonObject); - } else if (type.equals(BoxAIAgentExtractStructured.TYPE)) { - return new BoxAIAgentExtractStructured(jsonObject); - } else { - throw new IllegalArgumentException("Invalid AI agent type: " + type); - } + } + + public JsonObject getJSONObject() { + JsonObject jsonObject = new JsonObject(); + jsonObject.add("type", this.type); + return jsonObject; + } + + /** The type of the AI agent for asking questions. */ + public enum Mode { + /** The type of AI agent used to handle queries. */ + ASK("ask"), + /** The type of AI agent used for generating text. */ + TEXT_GEN("text_gen"), + /** The type of AI agent used for extracting metadata freeform. */ + EXTRACT("extract"), + /** The type of AI agent used for extracting metadata structured. */ + EXTRACT_STRUCTURED("extract_structured"); + + private final String value; + + Mode(String value) { + this.value = value; } - /** - * Gets the type of the AI agent. - * @return The type of the AI agent. - */ - public String getType() { - return type; + static BoxAIAgent.Mode fromJSONValue(String value) { + if (value.equals("ask")) { + return ASK; + } else if (value.equals("text_gen")) { + return TEXT_GEN; + } else if (value.equals("extract")) { + return EXTRACT; + } else if (value.equals("extract_structured")) { + return EXTRACT_STRUCTURED; + } else { + throw new IllegalArgumentException("Invalid AI agent mode: " + value); + } } - /** - * Sets the type of the AI agent. - * @param type The type of the AI agent. - */ - public void setType(String type) { - this.type = type; + String toJSONValue() { + return this.value; } @Override - void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - String memberName = member.getName(); - JsonValue value = member.getValue(); - if (memberName.equals("type")) { - this.type = value.asString(); - } - } - - public JsonObject getJSONObject() { - JsonObject jsonObject = new JsonObject(); - jsonObject.add("type", this.type); - return jsonObject; - } - - /** - * The type of the AI agent for asking questions. - */ - public enum Mode { - /** - * The type of AI agent used to handle queries. - */ - ASK("ask"), - /** - * The type of AI agent used for generating text. - */ - TEXT_GEN("text_gen"), - /** - * The type of AI agent used for extracting metadata freeform. - */ - EXTRACT("extract"), - /** - * The type of AI agent used for extracting metadata structured. - */ - EXTRACT_STRUCTURED("extract_structured"); - - - private final String value; - - Mode(String value) { - this.value = value; - } - - static BoxAIAgent.Mode fromJSONValue(String value) { - if (value.equals("ask")) { - return ASK; - } else if (value.equals("text_gen")) { - return TEXT_GEN; - } else if (value.equals("extract")) { - return EXTRACT; - } else if (value.equals("extract_structured")) { - return EXTRACT_STRUCTURED; - } else { - throw new IllegalArgumentException("Invalid AI agent mode: " + value); - } - } - - String toJSONValue() { - return this.value; - } - - @Override - public String toString() { - return this.value; - } + public String toString() { + return this.value; } + } } diff --git a/src/main/java/com/box/sdk/BoxAIAgentAsk.java b/src/main/java/com/box/sdk/BoxAIAgentAsk.java index c5c02c15b..57f822cb8 100644 --- a/src/main/java/com/box/sdk/BoxAIAgentAsk.java +++ b/src/main/java/com/box/sdk/BoxAIAgentAsk.java @@ -4,166 +4,166 @@ import com.eclipsesource.json.JsonObject; import com.eclipsesource.json.JsonValue; -/** - * Represents an AI Agent used to handle queries. - */ +/** Represents an AI Agent used to handle queries. */ @BoxResourceType("ai_agent_ask") public class BoxAIAgentAsk extends BoxAIAgent { - /** - * The type of the AI Ask agent. - */ - public static final String TYPE = "ai_agent_ask"; - - /** - * AI agent tool used to handle basic text. - */ - private BoxAIAgentAskBasicText basicText; - /** - * AI agent tool used to handle basic text. - */ - private BoxAIAgentAskBasicText basicTextMulti; - /** - * AI agent tool used to handle longer text. - */ - private BoxAIAgentAskLongText longText; - /** - * AI agent tool used to handle longer text. - */ - private BoxAIAgentAskLongText longTextMulti; - - /** - * Constructs an AI agent with default settings. - * @param basicText AI agent tool used to handle basic text. - * @param basicTextMulti AI agent tool used to handle basic text. - * @param longText AI agent tool used to handle longer text. - * @param longTextMulti AI agent tool used to handle longer text. - */ - public BoxAIAgentAsk(BoxAIAgentAskBasicText basicText, BoxAIAgentAskBasicText basicTextMulti, - BoxAIAgentAskLongText longText, BoxAIAgentAskLongText longTextMulti) { - super(TYPE); - this.basicText = basicText; - this.basicTextMulti = basicTextMulti; - this.longText = longText; - this.longTextMulti = longTextMulti; + /** The type of the AI Ask agent. */ + public static final String TYPE = "ai_agent_ask"; + + /** AI agent tool used to handle basic text. */ + private BoxAIAgentAskBasicText basicText; + /** AI agent tool used to handle basic text. */ + private BoxAIAgentAskBasicText basicTextMulti; + /** AI agent tool used to handle longer text. */ + private BoxAIAgentAskLongText longText; + /** AI agent tool used to handle longer text. */ + private BoxAIAgentAskLongText longTextMulti; + + /** + * Constructs an AI agent with default settings. + * + * @param basicText AI agent tool used to handle basic text. + * @param basicTextMulti AI agent tool used to handle basic text. + * @param longText AI agent tool used to handle longer text. + * @param longTextMulti AI agent tool used to handle longer text. + */ + public BoxAIAgentAsk( + BoxAIAgentAskBasicText basicText, + BoxAIAgentAskBasicText basicTextMulti, + BoxAIAgentAskLongText longText, + BoxAIAgentAskLongText longTextMulti) { + super(TYPE); + this.basicText = basicText; + this.basicTextMulti = basicTextMulti; + this.longText = longText; + this.longTextMulti = longTextMulti; + } + + /** + * Constructs an AI agent with default settings. + * + * @param jsonObject JSON object representing the AI agent. + */ + public BoxAIAgentAsk(JsonObject jsonObject) { + super(jsonObject); + } + + /** + * Gets the AI agent tool used to handle basic text. + * + * @return The AI agent tool used to handle basic text. + */ + public BoxAIAgentAskBasicText getBasicText() { + return basicText; + } + + /** + * Sets the AI agent tool used to handle basic text. + * + * @param basicText The AI agent tool used to handle basic text. + */ + public void setBasicText(BoxAIAgentAskBasicText basicText) { + this.basicText = basicText; + } + + /** + * Gets the AI agent tool used to handle basic text. + * + * @return The AI agent tool used to handle basic text. + */ + public BoxAIAgentAskBasicText getBasicTextMulti() { + return basicTextMulti; + } + + /** + * Sets the AI agent tool used to handle basic text. + * + * @param basicTextMulti The AI agent tool used to handle basic text. + */ + public void setBasicTextMulti(BoxAIAgentAskBasicText basicTextMulti) { + this.basicTextMulti = basicTextMulti; + } + + /** + * Gets the AI agent tool used to handle longer text. + * + * @return The AI agent tool used to handle longer text. + */ + public BoxAIAgentAskLongText getLongText() { + return longText; + } + + /** + * Sets the AI agent tool used to handle longer text. + * + * @param longText The AI agent tool used to handle longer text. + */ + public void setLongText(BoxAIAgentAskLongText longText) { + this.longText = longText; + } + + /** + * Gets the AI agent tool used to handle longer text. + * + * @return The AI agent tool used to handle longer text. + */ + public BoxAIAgentAskLongText getLongTextMulti() { + return longTextMulti; + } + + /** + * Sets the AI agent tool used to handle longer text. + * + * @param longTextMulti The AI agent tool used to handle longer text. + */ + public void setLongTextMulti(BoxAIAgentAskLongText longTextMulti) { + this.longTextMulti = longTextMulti; + } + + @Override + void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + String memberName = member.getName(); + JsonValue memberValue = member.getValue(); + try { + switch (memberName) { + case "basic_text": + this.basicText = new BoxAIAgentAskBasicText(memberValue.asObject()); + break; + case "basic_text_multi": + this.basicTextMulti = new BoxAIAgentAskBasicText(memberValue.asObject()); + break; + case "long_text": + this.longText = new BoxAIAgentAskLongText(memberValue.asObject()); + break; + case "long_text_multi": + this.longTextMulti = new BoxAIAgentAskLongText(memberValue.asObject()); + break; + default: + break; + } + } catch (Exception e) { + throw new BoxAPIException("Could not parse JSON response.", e); } - - /** - * Constructs an AI agent with default settings. - * @param jsonObject JSON object representing the AI agent. - */ - public BoxAIAgentAsk(JsonObject jsonObject) { - super(jsonObject); - } - - /** - * Gets the AI agent tool used to handle basic text. - * @return The AI agent tool used to handle basic text. - */ - public BoxAIAgentAskBasicText getBasicText() { - return basicText; - } - - /** - * Sets the AI agent tool used to handle basic text. - * @param basicText The AI agent tool used to handle basic text. - */ - public void setBasicText(BoxAIAgentAskBasicText basicText) { - this.basicText = basicText; + } + + @Override + public JsonObject getJSONObject() { + JsonObject jsonObject = new JsonObject(); + JsonUtils.addIfNotNull(jsonObject, "type", this.getType()); + if (this.basicText != null) { + jsonObject.add("basic_text", this.basicText.getJSONObject()); } - - /** - * Gets the AI agent tool used to handle basic text. - * @return The AI agent tool used to handle basic text. - */ - public BoxAIAgentAskBasicText getBasicTextMulti() { - return basicTextMulti; + if (this.basicTextMulti != null) { + jsonObject.add("basic_text_multi", this.basicTextMulti.getJSONObject()); } - - /** - * Sets the AI agent tool used to handle basic text. - * @param basicTextMulti The AI agent tool used to handle basic text. - */ - public void setBasicTextMulti(BoxAIAgentAskBasicText basicTextMulti) { - this.basicTextMulti = basicTextMulti; + if (this.longText != null) { + jsonObject.add("long_text", this.longText.getJSONObject()); } - - /** - * Gets the AI agent tool used to handle longer text. - * @return The AI agent tool used to handle longer text. - */ - public BoxAIAgentAskLongText getLongText() { - return longText; - } - - /** - * Sets the AI agent tool used to handle longer text. - * @param longText The AI agent tool used to handle longer text. - */ - public void setLongText(BoxAIAgentAskLongText longText) { - this.longText = longText; - } - - /** - * Gets the AI agent tool used to handle longer text. - * @return The AI agent tool used to handle longer text. - */ - public BoxAIAgentAskLongText getLongTextMulti() { - return longTextMulti; - } - - /** - * Sets the AI agent tool used to handle longer text. - * @param longTextMulti The AI agent tool used to handle longer text. - */ - public void setLongTextMulti(BoxAIAgentAskLongText longTextMulti) { - this.longTextMulti = longTextMulti; - } - - @Override - void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - String memberName = member.getName(); - JsonValue memberValue = member.getValue(); - try { - switch (memberName) { - case "basic_text": - this.basicText = new BoxAIAgentAskBasicText(memberValue.asObject()); - break; - case "basic_text_multi": - this.basicTextMulti = new BoxAIAgentAskBasicText(memberValue.asObject()); - break; - case "long_text": - this.longText = new BoxAIAgentAskLongText(memberValue.asObject()); - break; - case "long_text_multi": - this.longTextMulti = new BoxAIAgentAskLongText(memberValue.asObject()); - break; - default: - break; - } - } catch (Exception e) { - throw new BoxAPIException("Could not parse JSON response.", e); - } - } - - @Override - public JsonObject getJSONObject() { - JsonObject jsonObject = new JsonObject(); - JsonUtils.addIfNotNull(jsonObject, "type", this.getType()); - if (this.basicText != null) { - jsonObject.add("basic_text", this.basicText.getJSONObject()); - } - if (this.basicTextMulti != null) { - jsonObject.add("basic_text_multi", this.basicTextMulti.getJSONObject()); - } - if (this.longText != null) { - jsonObject.add("long_text", this.longText.getJSONObject()); - } - if (this.longTextMulti != null) { - jsonObject.add("long_text_multi", this.longTextMulti.getJSONObject()); - } - return jsonObject; + if (this.longTextMulti != null) { + jsonObject.add("long_text_multi", this.longTextMulti.getJSONObject()); } + return jsonObject; + } } - diff --git a/src/main/java/com/box/sdk/BoxAIAgentAskBasicText.java b/src/main/java/com/box/sdk/BoxAIAgentAskBasicText.java index a0287956f..d39a1745c 100644 --- a/src/main/java/com/box/sdk/BoxAIAgentAskBasicText.java +++ b/src/main/java/com/box/sdk/BoxAIAgentAskBasicText.java @@ -4,184 +4,198 @@ import com.eclipsesource.json.JsonObject; import com.eclipsesource.json.JsonValue; -/** - * AI agent tool used to handle basic text. - */ +/** AI agent tool used to handle basic text. */ public class BoxAIAgentAskBasicText extends BoxJSONObject { - /** - * The parameters for the LLM endpoint specific to OpenAI / Google models. - */ - private BoxAIAgentLLMEndpointParams llmEndpointParams; - /** - * The model used for the AI Agent for basic text. - */ - private String model; - /** - * The number of tokens for completion. - */ - private int numTokensForCompletion; - /** - * The prompt template contains contextual information of the request and the user prompt. - * When passing prompt_template parameters, you must include inputs for {user_question} and {content}. - * Input for {current_date} is optional, depending on the use. - */ - private String promptTemplate; - /** - * System messages try to help the LLM "understand" its role and what it is supposed to do. - */ - private String systemMessage; - - /** - * Constructs an AI agent with default settings. - * @param llmEndpointParams The parameters for the LLM endpoint specific to OpenAI / Google models. - * @param model The model used for the AI Agent for basic text. - * @param numTokensForCompletion The number of tokens for completion. - * @param promptTemplate The prompt template contains contextual information of the request and the user prompt. - * When passing prompt_template parameters, you must include inputs for {user_question} and {content}. - * Input for {current_date} is optional, depending on the use. - * @param systemMessage System messages try to help the LLM "understand" its role and what it is supposed to do. - */ - public BoxAIAgentAskBasicText(BoxAIAgentLLMEndpointParams llmEndpointParams, String model, - int numTokensForCompletion, String promptTemplate, String systemMessage) { - super(); - this.llmEndpointParams = llmEndpointParams; - this.model = model; - this.numTokensForCompletion = numTokensForCompletion; - this.promptTemplate = promptTemplate; - this.systemMessage = systemMessage; + /** The parameters for the LLM endpoint specific to OpenAI / Google models. */ + private BoxAIAgentLLMEndpointParams llmEndpointParams; + /** The model used for the AI Agent for basic text. */ + private String model; + /** The number of tokens for completion. */ + private int numTokensForCompletion; + /** + * The prompt template contains contextual information of the request and the user prompt. When + * passing prompt_template parameters, you must include inputs for {user_question} and {content}. + * Input for {current_date} is optional, depending on the use. + */ + private String promptTemplate; + /** System messages try to help the LLM "understand" its role and what it is supposed to do. */ + private String systemMessage; + + /** + * Constructs an AI agent with default settings. + * + * @param llmEndpointParams The parameters for the LLM endpoint specific to OpenAI / Google + * models. + * @param model The model used for the AI Agent for basic text. + * @param numTokensForCompletion The number of tokens for completion. + * @param promptTemplate The prompt template contains contextual information of the request and + * the user prompt. When passing prompt_template parameters, you must include inputs for + * {user_question} and {content}. Input for {current_date} is optional, depending on the use. + * @param systemMessage System messages try to help the LLM "understand" its role and what it is + * supposed to do. + */ + public BoxAIAgentAskBasicText( + BoxAIAgentLLMEndpointParams llmEndpointParams, + String model, + int numTokensForCompletion, + String promptTemplate, + String systemMessage) { + super(); + this.llmEndpointParams = llmEndpointParams; + this.model = model; + this.numTokensForCompletion = numTokensForCompletion; + this.promptTemplate = promptTemplate; + this.systemMessage = systemMessage; + } + + /** + * Constructs an AI agent with default settings. + * + * @param jsonObject JSON object representing the AI agent. + */ + public BoxAIAgentAskBasicText(JsonObject jsonObject) { + super(jsonObject); + } + + /** + * Gets the parameters for the LLM endpoint specific to OpenAI / Google models. + * + * @return The parameters for the LLM endpoint specific to OpenAI / Google models. + */ + public BoxAIAgentLLMEndpointParams getLlmEndpointParams() { + return llmEndpointParams; + } + + /** + * Sets the parameters for the LLM endpoint specific to OpenAI / Google models. + * + * @param llmEndpointParams The parameters for the LLM endpoint specific to OpenAI / Google + * models. + */ + public void setLlmEndpointParams(BoxAIAgentLLMEndpointParams llmEndpointParams) { + this.llmEndpointParams = llmEndpointParams; + } + + /** + * Gets the model used for the AI Agent for basic text. + * + * @return The model used for the AI Agent for basic text. + */ + public String getModel() { + return model; + } + + /** + * Sets the model used for the AI Agent for basic text. + * + * @param model The model used for the AI Agent for basic text. + */ + public void setModel(String model) { + this.model = model; + } + + /** + * Gets the number of tokens for completion. + * + * @return The number of tokens for completion. + */ + public int getNumTokensForCompletion() { + return numTokensForCompletion; + } + + /** + * Sets the number of tokens for completion. + * + * @param numTokensForCompletion The number of tokens for completion. + */ + public void setNumTokensForCompletion(int numTokensForCompletion) { + this.numTokensForCompletion = numTokensForCompletion; + } + + /** + * Gets the prompt template contains contextual information of the request and the user prompt. + * When passing prompt_template parameters, you must include inputs for {user_question} and + * {content}. Input for {current_date} is optional, depending on the use. + * + * @return The prompt template contains contextual information of the request and the user prompt. + */ + public String getPromptTemplate() { + return promptTemplate; + } + + /** + * Sets the prompt template contains contextual information of the request and the user prompt. + * When passing prompt_template parameters, you must include inputs for {user_question} and + * {content}. Input for {current_date} is optional, depending on the use. + * + * @param promptTemplate The prompt template contains contextual information of the request and + * the user prompt. + */ + public void setPromptTemplate(String promptTemplate) { + this.promptTemplate = promptTemplate; + } + + /** + * Gets the system messages try to help the LLM "understand" its role and what it is supposed to + * do. + * + * @return The system messages try to help the LLM "understand" its role and what it is supposed + * to do. + */ + public String getSystemMessage() { + return systemMessage; + } + + /** + * Sets the system messages try to help the LLM "understand" its role and what it is supposed to + * do. + * + * @param systemMessage The system messages try to help the LLM "understand" its role and what it + * is supposed to do. + */ + public void setSystemMessage(String systemMessage) { + this.systemMessage = systemMessage; + } + + @Override + void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + String memberName = member.getName(); + JsonValue memberValue = member.getValue(); + try { + switch (memberName) { + case "llm_endpoint_params": + this.llmEndpointParams = BoxAIAgentLLMEndpointParams.parse(memberValue.asObject()); + break; + case "model": + this.model = memberValue.asString(); + break; + case "num_tokens_for_completion": + this.numTokensForCompletion = memberValue.asInt(); + break; + case "prompt_template": + this.promptTemplate = memberValue.asString(); + break; + case "system_message": + this.systemMessage = memberValue.asString(); + break; + default: + break; + } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, memberValue.toString(), e); } + } - /** - * Constructs an AI agent with default settings. - * @param jsonObject JSON object representing the AI agent. - */ - public BoxAIAgentAskBasicText(JsonObject jsonObject) { - super(jsonObject); - } - - /** - * Gets the parameters for the LLM endpoint specific to OpenAI / Google models. - * @return The parameters for the LLM endpoint specific to OpenAI / Google models. - */ - public BoxAIAgentLLMEndpointParams getLlmEndpointParams() { - return llmEndpointParams; - } - - /** - * Sets the parameters for the LLM endpoint specific to OpenAI / Google models. - * @param llmEndpointParams The parameters for the LLM endpoint specific to OpenAI / Google models. - */ - public void setLlmEndpointParams(BoxAIAgentLLMEndpointParams llmEndpointParams) { - this.llmEndpointParams = llmEndpointParams; - } - - /** - * Gets the model used for the AI Agent for basic text. - * @return The model used for the AI Agent for basic text. - */ - public String getModel() { - return model; - } - - /** - * Sets the model used for the AI Agent for basic text. - * @param model The model used for the AI Agent for basic text. - */ - public void setModel(String model) { - this.model = model; - } - - /** - * Gets the number of tokens for completion. - * @return The number of tokens for completion. - */ - public int getNumTokensForCompletion() { - return numTokensForCompletion; - } - - /** - * Sets the number of tokens for completion. - * @param numTokensForCompletion The number of tokens for completion. - */ - public void setNumTokensForCompletion(int numTokensForCompletion) { - this.numTokensForCompletion = numTokensForCompletion; - } - - /** - * Gets the prompt template contains contextual information of the request and the user prompt. - * When passing prompt_template parameters, you must include inputs for {user_question} and {content}. - * Input for {current_date} is optional, depending on the use. - * @return The prompt template contains contextual information of the request and the user prompt. - */ - public String getPromptTemplate() { - return promptTemplate; - } - - /** - * Sets the prompt template contains contextual information of the request and the user prompt. - * When passing prompt_template parameters, you must include inputs for {user_question} and {content}. - * Input for {current_date} is optional, depending on the use. - * @param promptTemplate The prompt template contains contextual information of the request and the user prompt. - */ - public void setPromptTemplate(String promptTemplate) { - this.promptTemplate = promptTemplate; - } - - /** - * Gets the system messages try to help the LLM "understand" its role and what it is supposed to do. - * @return The system messages try to help the LLM "understand" its role and what it is supposed to do. - */ - public String getSystemMessage() { - return systemMessage; - } - - /** - * Sets the system messages try to help the LLM "understand" its role and what it is supposed to do. - * @param systemMessage The system messages try to help the LLM "understand" its role and what it is supposed to do. - */ - public void setSystemMessage(String systemMessage) { - this.systemMessage = systemMessage; - } - - @Override - void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - String memberName = member.getName(); - JsonValue memberValue = member.getValue(); - try { - switch (memberName) { - case "llm_endpoint_params": - this.llmEndpointParams = BoxAIAgentLLMEndpointParams.parse(memberValue.asObject()); - break; - case "model": - this.model = memberValue.asString(); - break; - case "num_tokens_for_completion": - this.numTokensForCompletion = memberValue.asInt(); - break; - case "prompt_template": - this.promptTemplate = memberValue.asString(); - break; - case "system_message": - this.systemMessage = memberValue.asString(); - break; - default: - break; - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, memberValue.toString(), e); - } - } - - public JsonObject getJSONObject() { - JsonObject jsonObject = new JsonObject(); - if (this.llmEndpointParams != null) { - jsonObject.add("llm_endpoint_params", this.llmEndpointParams.getJSONObject()); - } - JsonUtils.addIfNotNull(jsonObject, "model", this.model); - JsonUtils.addIfNotNull(jsonObject, "num_tokens_for_completion", this.numTokensForCompletion); - JsonUtils.addIfNotNull(jsonObject, "prompt_template", this.promptTemplate); - JsonUtils.addIfNotNull(jsonObject, "system_message", this.systemMessage); - return jsonObject; + public JsonObject getJSONObject() { + JsonObject jsonObject = new JsonObject(); + if (this.llmEndpointParams != null) { + jsonObject.add("llm_endpoint_params", this.llmEndpointParams.getJSONObject()); } + JsonUtils.addIfNotNull(jsonObject, "model", this.model); + JsonUtils.addIfNotNull(jsonObject, "num_tokens_for_completion", this.numTokensForCompletion); + JsonUtils.addIfNotNull(jsonObject, "prompt_template", this.promptTemplate); + JsonUtils.addIfNotNull(jsonObject, "system_message", this.systemMessage); + return jsonObject; + } } diff --git a/src/main/java/com/box/sdk/BoxAIAgentAskLongText.java b/src/main/java/com/box/sdk/BoxAIAgentAskLongText.java index 2193ed103..71b5abef2 100644 --- a/src/main/java/com/box/sdk/BoxAIAgentAskLongText.java +++ b/src/main/java/com/box/sdk/BoxAIAgentAskLongText.java @@ -3,214 +3,225 @@ import com.box.sdk.internal.utils.JsonUtils; import com.eclipsesource.json.JsonObject; -/** - * Represents an AI agent tool used to handle longer text. - */ +/** Represents an AI agent tool used to handle longer text. */ public class BoxAIAgentAskLongText extends BoxJSONObject { - /** - * Embeddings used by the AI agent. - */ - private BoxAIAgentEmbeddings embeddings; - /** - * The parameters for the LLM endpoint specific to OpenAI / Google models. - */ - private BoxAIAgentLLMEndpointParams llmEndpointParams; - /** - * The model used for the AI Agent for basic text. - */ - private String model; - /** - * The number of tokens for completion. - */ - private int numTokensForCompletion; - /** - * The prompt template contains contextual information of the request and the user prompt. - * When passing prompt_template parameters, you must include inputs for {user_question} and {content}. - * Input for {current_date} is optional, depending on the use. - */ - private String promptTemplate; - /** - * System messages try to help the LLM "understand" its role and what it is supposed to do. - */ - private String systemMessage; - - /** - * Constructs an AI agent with default settings. - * @param embeddings Embeddings used by the AI agent. - * @param llmEndpointParams The parameters for the LLM endpoint specific to OpenAI / Google models. - * Value can be "google_params" or "openai_params". - * @param model The model used for the AI Agent for basic text. - * @param numTokensForCompletion The number of tokens for completion. - * @param promptTemplate The prompt template contains contextual information of the request and the user prompt. - * When passing prompt_template parameters, you must include inputs for {user_question} and {content}. - * Input for {current_date} is optional, depending on the use. - * @param systemMessage System messages try to help the LLM "understand" its role and what it is supposed to do. - */ - public BoxAIAgentAskLongText(BoxAIAgentEmbeddings embeddings, - BoxAIAgentLLMEndpointParams llmEndpointParams, - String model, int numTokensForCompletion, - String promptTemplate, - String systemMessage) { - this.embeddings = embeddings; - this.llmEndpointParams = llmEndpointParams; - this.model = model; - this.numTokensForCompletion = numTokensForCompletion; - this.promptTemplate = promptTemplate; - this.systemMessage = systemMessage; - } - - /** - * Constructs an AI agent with default settings. - * @param jsonObject JSON object representing the AI agent. - */ - public BoxAIAgentAskLongText(JsonObject jsonObject) { - super(jsonObject); - } - - /** - * Gets the embeddings used by the AI agent. - * @return The embeddings used by the AI agent. - */ - public BoxAIAgentEmbeddings getEmbeddings() { - return embeddings; - } - - /** - * Sets the embeddings used by the AI agent. - * @param embeddings The embeddings used by the AI agent. - */ - public void setEmbeddings(BoxAIAgentEmbeddings embeddings) { - this.embeddings = embeddings; - } - - /** - * Gets the parameters for the LLM endpoint specific to OpenAI / Google models. - * @return The parameters for the LLM endpoint specific to OpenAI / Google models. - */ - public BoxAIAgentLLMEndpointParams getLlmEndpointParams() { - return llmEndpointParams; - } - - /** - * Sets the parameters for the LLM endpoint specific to OpenAI / Google models. - * @param llmEndpointParams The parameters for the LLM endpoint specific to OpenAI / Google models. - */ - public void setLlmEndpointParams(BoxAIAgentLLMEndpointParams llmEndpointParams) { - this.llmEndpointParams = llmEndpointParams; - } - - /** - * Gets the model used for the AI Agent for basic text. - * @return The model used for the AI Agent for basic text. - */ - public String getModel() { - return model; - } - - /** - * Sets the model used for the AI Agent for basic text. - * @param model The model used for the AI Agent for basic text. - */ - public void setModel(String model) { - this.model = model; - } - - /** - * Gets the number of tokens for completion. - * @return The number of tokens for completion. - */ - public int getNumTokensForCompletion() { - return numTokensForCompletion; - } - - /** - * Sets the number of tokens for completion. - * @param numTokensForCompletion The number of tokens for completion. - */ - public void setNumTokensForCompletion(int numTokensForCompletion) { - this.numTokensForCompletion = numTokensForCompletion; - } - - /** - * Gets the prompt template contains contextual information of the request and the user prompt. - * When passing prompt_template parameters, you must include inputs for {user_question} and {content}. - * Input for {current_date} is optional, depending on the use. - * @return The prompt template contains contextual information of the request and the user prompt. - */ - public String getPromptTemplate() { - return promptTemplate; - } - - /** - * Sets the prompt template contains contextual information of the request and the user prompt. - * When passing prompt_template parameters, you must include inputs for {user_question} and {content}. - * Input for {current_date} is optional, depending on the use. - * @param promptTemplate The prompt template contains contextual information of the request and the user prompt. - */ - public void setPromptTemplate(String promptTemplate) { - this.promptTemplate = promptTemplate; - } - - /** - * Gets the system messages try to help the LLM "understand" its role and what it is supposed to do. - * @return The system messages try to help the LLM "understand" its role and what it is supposed to do. - */ - public String getSystemMessage() { - return systemMessage; - } - - /** - * Sets the system messages try to help the LLM "understand" its role and what it is supposed to do. - * @param systemMessage The system messages try to help the LLM "understand" its role and what it is supposed to do. - */ - public void setSystemMessage(String systemMessage) { - this.systemMessage = systemMessage; - } - - @Override - void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - String memberName = member.getName(); - try { - switch (memberName) { - case "embeddings": - this.embeddings = new BoxAIAgentEmbeddings(member.getValue().asObject()); - break; - case "llm_endpoint_params": - this.llmEndpointParams = BoxAIAgentLLMEndpointParams.parse(member.getValue().asObject()); - break; - case "model": - this.model = member.getValue().asString(); - break; - case "num_tokens_for_completion": - this.numTokensForCompletion = member.getValue().asInt(); - break; - case "prompt_template": - this.promptTemplate = member.getValue().asString(); - break; - case "system_message": - this.systemMessage = member.getValue().asString(); - break; - default: - break; - } - } catch (Exception e) { - throw new BoxAPIException("Could not parse JSON response.", e); - } - } - - public JsonObject getJSONObject() { - JsonObject jsonObject = new JsonObject(); - if (this.embeddings != null) { - jsonObject.add("embeddings", this.embeddings.getJSONObject()); - } - if (this.llmEndpointParams != null) { - jsonObject.add("llm_endpoint_params", this.llmEndpointParams.getJSONObject()); - } - JsonUtils.addIfNotNull(jsonObject, "model", this.model); - JsonUtils.addIfNotNull(jsonObject, "num_tokens_for_completion", this.numTokensForCompletion); - JsonUtils.addIfNotNull(jsonObject, "prompt_template", this.promptTemplate); - JsonUtils.addIfNotNull(jsonObject, "system_message", this.systemMessage); - return jsonObject; - } + /** Embeddings used by the AI agent. */ + private BoxAIAgentEmbeddings embeddings; + /** The parameters for the LLM endpoint specific to OpenAI / Google models. */ + private BoxAIAgentLLMEndpointParams llmEndpointParams; + /** The model used for the AI Agent for basic text. */ + private String model; + /** The number of tokens for completion. */ + private int numTokensForCompletion; + /** + * The prompt template contains contextual information of the request and the user prompt. When + * passing prompt_template parameters, you must include inputs for {user_question} and {content}. + * Input for {current_date} is optional, depending on the use. + */ + private String promptTemplate; + /** System messages try to help the LLM "understand" its role and what it is supposed to do. */ + private String systemMessage; + + /** + * Constructs an AI agent with default settings. + * + * @param embeddings Embeddings used by the AI agent. + * @param llmEndpointParams The parameters for the LLM endpoint specific to OpenAI / Google + * models. Value can be "google_params" or "openai_params". + * @param model The model used for the AI Agent for basic text. + * @param numTokensForCompletion The number of tokens for completion. + * @param promptTemplate The prompt template contains contextual information of the request and + * the user prompt. When passing prompt_template parameters, you must include inputs for + * {user_question} and {content}. Input for {current_date} is optional, depending on the use. + * @param systemMessage System messages try to help the LLM "understand" its role and what it is + * supposed to do. + */ + public BoxAIAgentAskLongText( + BoxAIAgentEmbeddings embeddings, + BoxAIAgentLLMEndpointParams llmEndpointParams, + String model, + int numTokensForCompletion, + String promptTemplate, + String systemMessage) { + this.embeddings = embeddings; + this.llmEndpointParams = llmEndpointParams; + this.model = model; + this.numTokensForCompletion = numTokensForCompletion; + this.promptTemplate = promptTemplate; + this.systemMessage = systemMessage; + } + + /** + * Constructs an AI agent with default settings. + * + * @param jsonObject JSON object representing the AI agent. + */ + public BoxAIAgentAskLongText(JsonObject jsonObject) { + super(jsonObject); + } + + /** + * Gets the embeddings used by the AI agent. + * + * @return The embeddings used by the AI agent. + */ + public BoxAIAgentEmbeddings getEmbeddings() { + return embeddings; + } + + /** + * Sets the embeddings used by the AI agent. + * + * @param embeddings The embeddings used by the AI agent. + */ + public void setEmbeddings(BoxAIAgentEmbeddings embeddings) { + this.embeddings = embeddings; + } + + /** + * Gets the parameters for the LLM endpoint specific to OpenAI / Google models. + * + * @return The parameters for the LLM endpoint specific to OpenAI / Google models. + */ + public BoxAIAgentLLMEndpointParams getLlmEndpointParams() { + return llmEndpointParams; + } + + /** + * Sets the parameters for the LLM endpoint specific to OpenAI / Google models. + * + * @param llmEndpointParams The parameters for the LLM endpoint specific to OpenAI / Google + * models. + */ + public void setLlmEndpointParams(BoxAIAgentLLMEndpointParams llmEndpointParams) { + this.llmEndpointParams = llmEndpointParams; + } + + /** + * Gets the model used for the AI Agent for basic text. + * + * @return The model used for the AI Agent for basic text. + */ + public String getModel() { + return model; + } + + /** + * Sets the model used for the AI Agent for basic text. + * + * @param model The model used for the AI Agent for basic text. + */ + public void setModel(String model) { + this.model = model; + } + + /** + * Gets the number of tokens for completion. + * + * @return The number of tokens for completion. + */ + public int getNumTokensForCompletion() { + return numTokensForCompletion; + } + + /** + * Sets the number of tokens for completion. + * + * @param numTokensForCompletion The number of tokens for completion. + */ + public void setNumTokensForCompletion(int numTokensForCompletion) { + this.numTokensForCompletion = numTokensForCompletion; + } + + /** + * Gets the prompt template contains contextual information of the request and the user prompt. + * When passing prompt_template parameters, you must include inputs for {user_question} and + * {content}. Input for {current_date} is optional, depending on the use. + * + * @return The prompt template contains contextual information of the request and the user prompt. + */ + public String getPromptTemplate() { + return promptTemplate; + } + + /** + * Sets the prompt template contains contextual information of the request and the user prompt. + * When passing prompt_template parameters, you must include inputs for {user_question} and + * {content}. Input for {current_date} is optional, depending on the use. + * + * @param promptTemplate The prompt template contains contextual information of the request and + * the user prompt. + */ + public void setPromptTemplate(String promptTemplate) { + this.promptTemplate = promptTemplate; + } + + /** + * Gets the system messages try to help the LLM "understand" its role and what it is supposed to + * do. + * + * @return The system messages try to help the LLM "understand" its role and what it is supposed + * to do. + */ + public String getSystemMessage() { + return systemMessage; + } + + /** + * Sets the system messages try to help the LLM "understand" its role and what it is supposed to + * do. + * + * @param systemMessage The system messages try to help the LLM "understand" its role and what it + * is supposed to do. + */ + public void setSystemMessage(String systemMessage) { + this.systemMessage = systemMessage; + } + + @Override + void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + String memberName = member.getName(); + try { + switch (memberName) { + case "embeddings": + this.embeddings = new BoxAIAgentEmbeddings(member.getValue().asObject()); + break; + case "llm_endpoint_params": + this.llmEndpointParams = BoxAIAgentLLMEndpointParams.parse(member.getValue().asObject()); + break; + case "model": + this.model = member.getValue().asString(); + break; + case "num_tokens_for_completion": + this.numTokensForCompletion = member.getValue().asInt(); + break; + case "prompt_template": + this.promptTemplate = member.getValue().asString(); + break; + case "system_message": + this.systemMessage = member.getValue().asString(); + break; + default: + break; + } + } catch (Exception e) { + throw new BoxAPIException("Could not parse JSON response.", e); + } + } + + public JsonObject getJSONObject() { + JsonObject jsonObject = new JsonObject(); + if (this.embeddings != null) { + jsonObject.add("embeddings", this.embeddings.getJSONObject()); + } + if (this.llmEndpointParams != null) { + jsonObject.add("llm_endpoint_params", this.llmEndpointParams.getJSONObject()); + } + JsonUtils.addIfNotNull(jsonObject, "model", this.model); + JsonUtils.addIfNotNull(jsonObject, "num_tokens_for_completion", this.numTokensForCompletion); + JsonUtils.addIfNotNull(jsonObject, "prompt_template", this.promptTemplate); + JsonUtils.addIfNotNull(jsonObject, "system_message", this.systemMessage); + return jsonObject; + } } diff --git a/src/main/java/com/box/sdk/BoxAIAgentEmbeddings.java b/src/main/java/com/box/sdk/BoxAIAgentEmbeddings.java index 6cb9261b1..26741c8b9 100644 --- a/src/main/java/com/box/sdk/BoxAIAgentEmbeddings.java +++ b/src/main/java/com/box/sdk/BoxAIAgentEmbeddings.java @@ -4,92 +4,92 @@ import com.eclipsesource.json.JsonObject; import com.eclipsesource.json.JsonValue; -/** - * Represents the embeddings used by an AI agent. - */ +/** Represents the embeddings used by an AI agent. */ public class BoxAIAgentEmbeddings extends BoxJSONObject { - /** - * The model used for the AI Agent for calculating embeddings. - */ - private String model; - /** - * The strategy used for the AI Agent for calculating embeddings. - */ - private BoxAIAgentEmbeddingsStrategy strategy; + /** The model used for the AI Agent for calculating embeddings. */ + private String model; + /** The strategy used for the AI Agent for calculating embeddings. */ + private BoxAIAgentEmbeddingsStrategy strategy; - /** - * Constructs an AI agent with default settings. - * @param model The model used for the AI Agent for calculating embeddings. - * @param strategy The strategy used for the AI Agent for calculating embeddings. - */ - public BoxAIAgentEmbeddings(String model, BoxAIAgentEmbeddingsStrategy strategy) { - this.model = model; - this.strategy = strategy; - } + /** + * Constructs an AI agent with default settings. + * + * @param model The model used for the AI Agent for calculating embeddings. + * @param strategy The strategy used for the AI Agent for calculating embeddings. + */ + public BoxAIAgentEmbeddings(String model, BoxAIAgentEmbeddingsStrategy strategy) { + this.model = model; + this.strategy = strategy; + } - /** - * Constructs an AI agent with default settings. - * @param jsonObject JSON object representing the AI agent. - */ - public BoxAIAgentEmbeddings(JsonObject jsonObject) { - super(jsonObject); - } + /** + * Constructs an AI agent with default settings. + * + * @param jsonObject JSON object representing the AI agent. + */ + public BoxAIAgentEmbeddings(JsonObject jsonObject) { + super(jsonObject); + } - /** - * Gets the model used for the AI Agent for calculating embeddings. - * @return The model used for the AI Agent for calculating embeddings. - */ - public String getModel() { - return model; - } + /** + * Gets the model used for the AI Agent for calculating embeddings. + * + * @return The model used for the AI Agent for calculating embeddings. + */ + public String getModel() { + return model; + } - /** - * Sets the model used for the AI Agent for calculating embeddings. - * @param model The model used for the AI Agent for calculating embeddings. - */ - public void setModel(String model) { - this.model = model; - } + /** + * Sets the model used for the AI Agent for calculating embeddings. + * + * @param model The model used for the AI Agent for calculating embeddings. + */ + public void setModel(String model) { + this.model = model; + } - /** - * Gets the strategy used for the AI Agent for calculating embeddings. - * @return The strategy used for the AI Agent for calculating embeddings. - */ - public BoxAIAgentEmbeddingsStrategy getStrategy() { - return strategy; - } + /** + * Gets the strategy used for the AI Agent for calculating embeddings. + * + * @return The strategy used for the AI Agent for calculating embeddings. + */ + public BoxAIAgentEmbeddingsStrategy getStrategy() { + return strategy; + } - /** - * Sets the strategy used for the AI Agent for calculating embeddings. - * @param strategy The strategy used for the AI Agent for calculating embeddings. - */ - public void setStrategy(BoxAIAgentEmbeddingsStrategy strategy) { - this.strategy = strategy; - } + /** + * Sets the strategy used for the AI Agent for calculating embeddings. + * + * @param strategy The strategy used for the AI Agent for calculating embeddings. + */ + public void setStrategy(BoxAIAgentEmbeddingsStrategy strategy) { + this.strategy = strategy; + } - @Override - void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - String memberName = member.getName(); - JsonValue value = member.getValue(); - switch (memberName) { - case "model": - this.model = member.getValue().asString(); - break; - case "strategy": - this.strategy = new BoxAIAgentEmbeddingsStrategy(value.asObject()); - break; - default: - break; - } + @Override + void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + String memberName = member.getName(); + JsonValue value = member.getValue(); + switch (memberName) { + case "model": + this.model = member.getValue().asString(); + break; + case "strategy": + this.strategy = new BoxAIAgentEmbeddingsStrategy(value.asObject()); + break; + default: + break; } + } - public JsonObject getJSONObject() { - JsonObject jsonObject = new JsonObject(); - JsonUtils.addIfNotNull(jsonObject, "model", this.model); - if (this.strategy != null) { - jsonObject.add("strategy", this.strategy.getJSONObject()); - } - return jsonObject; + public JsonObject getJSONObject() { + JsonObject jsonObject = new JsonObject(); + JsonUtils.addIfNotNull(jsonObject, "model", this.model); + if (this.strategy != null) { + jsonObject.add("strategy", this.strategy.getJSONObject()); } + return jsonObject; + } } diff --git a/src/main/java/com/box/sdk/BoxAIAgentEmbeddingsStrategy.java b/src/main/java/com/box/sdk/BoxAIAgentEmbeddingsStrategy.java index 4d2bbecfe..ffd189ffd 100644 --- a/src/main/java/com/box/sdk/BoxAIAgentEmbeddingsStrategy.java +++ b/src/main/java/com/box/sdk/BoxAIAgentEmbeddingsStrategy.java @@ -3,84 +3,86 @@ import com.box.sdk.internal.utils.JsonUtils; import com.eclipsesource.json.JsonObject; -/** - * Represents the strategy used for the AI Agent for calculating embeddings. - */ +/** Represents the strategy used for the AI Agent for calculating embeddings. */ public class BoxAIAgentEmbeddingsStrategy extends BoxJSONObject { - /** - * The ID of the strategy used for the AI Agent for calculating embeddings. - */ - private String id; - /** - * The number of tokens per chunk used for the AI Agent for calculating embeddings. - */ - private int numTokensPerChunk; + /** The ID of the strategy used for the AI Agent for calculating embeddings. */ + private String id; + /** The number of tokens per chunk used for the AI Agent for calculating embeddings. */ + private int numTokensPerChunk; - /** - * Constructs an AI agent with default settings. - * @param id The ID of the strategy used for the AI Agent for calculating embeddings. - * @param numTokensPerChunk The number of tokens per chunk used for the AI Agent for calculating embeddings. - */ - public BoxAIAgentEmbeddingsStrategy(String id, int numTokensPerChunk) { - this.id = id; - this.numTokensPerChunk = numTokensPerChunk; - } + /** + * Constructs an AI agent with default settings. + * + * @param id The ID of the strategy used for the AI Agent for calculating embeddings. + * @param numTokensPerChunk The number of tokens per chunk used for the AI Agent for calculating + * embeddings. + */ + public BoxAIAgentEmbeddingsStrategy(String id, int numTokensPerChunk) { + this.id = id; + this.numTokensPerChunk = numTokensPerChunk; + } - /** - * Constructs an AI agent with default settings. - * @param jsonObject JSON object representing the AI agent. - */ - public BoxAIAgentEmbeddingsStrategy(JsonObject jsonObject) { - super(jsonObject); - } + /** + * Constructs an AI agent with default settings. + * + * @param jsonObject JSON object representing the AI agent. + */ + public BoxAIAgentEmbeddingsStrategy(JsonObject jsonObject) { + super(jsonObject); + } - /** - * Gets the ID of the strategy used for the AI Agent for calculating embeddings. - * @return The ID of the strategy used for the AI Agent for calculating embeddings. - */ - public String getId() { - return id; - } + /** + * Gets the ID of the strategy used for the AI Agent for calculating embeddings. + * + * @return The ID of the strategy used for the AI Agent for calculating embeddings. + */ + public String getId() { + return id; + } - /** - * Sets the ID of the strategy used for the AI Agent for calculating embeddings. - * @param id The ID of the strategy used for the AI Agent for calculating embeddings. - */ - public void setId(String id) { - this.id = id; - } + /** + * Sets the ID of the strategy used for the AI Agent for calculating embeddings. + * + * @param id The ID of the strategy used for the AI Agent for calculating embeddings. + */ + public void setId(String id) { + this.id = id; + } - /** - * Gets the number of tokens per chunk used for the AI Agent for calculating embeddings. - * @return The number of tokens per chunk used for the AI Agent for calculating embeddings. - */ - public int getNumTokensPerChunk() { - return numTokensPerChunk; - } + /** + * Gets the number of tokens per chunk used for the AI Agent for calculating embeddings. + * + * @return The number of tokens per chunk used for the AI Agent for calculating embeddings. + */ + public int getNumTokensPerChunk() { + return numTokensPerChunk; + } - /** - * Sets the number of tokens per chunk used for the AI Agent for calculating embeddings. - * @param numTokensPerChunk The number of tokens per chunk used for the AI Agent for calculating embeddings. - */ - public void setNumTokensPerChunk(int numTokensPerChunk) { - this.numTokensPerChunk = numTokensPerChunk; - } + /** + * Sets the number of tokens per chunk used for the AI Agent for calculating embeddings. + * + * @param numTokensPerChunk The number of tokens per chunk used for the AI Agent for calculating + * embeddings. + */ + public void setNumTokensPerChunk(int numTokensPerChunk) { + this.numTokensPerChunk = numTokensPerChunk; + } - @Override - void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - String memberName = member.getName(); - if (memberName.equals("id")) { - this.id = member.getValue().asString(); - } else if (memberName.equals("num_tokens_per_chunk")) { - this.numTokensPerChunk = member.getValue().asInt(); - } + @Override + void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + String memberName = member.getName(); + if (memberName.equals("id")) { + this.id = member.getValue().asString(); + } else if (memberName.equals("num_tokens_per_chunk")) { + this.numTokensPerChunk = member.getValue().asInt(); } + } - public JsonObject getJSONObject() { - JsonObject jsonObject = new JsonObject(); - JsonUtils.addIfNotNull(jsonObject, "id", this.id); - JsonUtils.addIfNotNull(jsonObject, "num_tokens_per_chunk", this.numTokensPerChunk); - return jsonObject; - } + public JsonObject getJSONObject() { + JsonObject jsonObject = new JsonObject(); + JsonUtils.addIfNotNull(jsonObject, "id", this.id); + JsonUtils.addIfNotNull(jsonObject, "num_tokens_per_chunk", this.numTokensPerChunk); + return jsonObject; + } } diff --git a/src/main/java/com/box/sdk/BoxAIAgentExtract.java b/src/main/java/com/box/sdk/BoxAIAgentExtract.java index ba7ff31ea..1ddefec36 100644 --- a/src/main/java/com/box/sdk/BoxAIAgentExtract.java +++ b/src/main/java/com/box/sdk/BoxAIAgentExtract.java @@ -4,110 +4,106 @@ import com.eclipsesource.json.JsonObject; import com.eclipsesource.json.JsonValue; -/** - * Represents an AI Agent used for extraction. - */ +/** Represents an AI Agent used for extraction. */ @BoxResourceType("ai_agent_extract") public class BoxAIAgentExtract extends BoxAIAgent { - /** - * The type of the AI Ask agent. - */ - public static final String TYPE = "ai_agent_extract"; + /** The type of the AI Ask agent. */ + public static final String TYPE = "ai_agent_extract"; - /** - * AI agent tool used to handle basic text. - */ - private BoxAIAgentAskBasicText basicText; - /** - * AI agent tool used to handle longer text. - */ - private BoxAIAgentAskLongText longText; + /** AI agent tool used to handle basic text. */ + private BoxAIAgentAskBasicText basicText; + /** AI agent tool used to handle longer text. */ + private BoxAIAgentAskLongText longText; - /** - * Constructs an AI agent with default settings. - * @param basicText AI agent tool used to handle basic text. - * @param longText AI agent tool used to handle longer text. - */ - public BoxAIAgentExtract(BoxAIAgentAskBasicText basicText, - BoxAIAgentAskLongText longText) { - super(TYPE); - this.basicText = basicText; - this.longText = longText; - } + /** + * Constructs an AI agent with default settings. + * + * @param basicText AI agent tool used to handle basic text. + * @param longText AI agent tool used to handle longer text. + */ + public BoxAIAgentExtract(BoxAIAgentAskBasicText basicText, BoxAIAgentAskLongText longText) { + super(TYPE); + this.basicText = basicText; + this.longText = longText; + } - /** - * Constructs an AI agent with default settings. - * @param jsonObject JSON object representing the AI agent. - */ - public BoxAIAgentExtract(JsonObject jsonObject) { - super(jsonObject); - } + /** + * Constructs an AI agent with default settings. + * + * @param jsonObject JSON object representing the AI agent. + */ + public BoxAIAgentExtract(JsonObject jsonObject) { + super(jsonObject); + } - /** - * Gets the AI agent tool used to handle basic text. - * @return The AI agent tool used to handle basic text. - */ - public BoxAIAgentAskBasicText getBasicText() { - return basicText; - } + /** + * Gets the AI agent tool used to handle basic text. + * + * @return The AI agent tool used to handle basic text. + */ + public BoxAIAgentAskBasicText getBasicText() { + return basicText; + } - /** - * Sets the AI agent tool used to handle basic text. - * @param basicText The AI agent tool used to handle basic text. - */ - public void setBasicText(BoxAIAgentAskBasicText basicText) { - this.basicText = basicText; - } + /** + * Sets the AI agent tool used to handle basic text. + * + * @param basicText The AI agent tool used to handle basic text. + */ + public void setBasicText(BoxAIAgentAskBasicText basicText) { + this.basicText = basicText; + } - /** - * Gets the AI agent tool used to handle longer text. - * @return The AI agent tool used to handle longer text. - */ - public BoxAIAgentAskLongText getLongText() { - return longText; - } + /** + * Gets the AI agent tool used to handle longer text. + * + * @return The AI agent tool used to handle longer text. + */ + public BoxAIAgentAskLongText getLongText() { + return longText; + } - /** - * Sets the AI agent tool used to handle longer text. - * @param longText The AI agent tool used to handle longer text. - */ - public void setLongText(BoxAIAgentAskLongText longText) { - this.longText = longText; - } + /** + * Sets the AI agent tool used to handle longer text. + * + * @param longText The AI agent tool used to handle longer text. + */ + public void setLongText(BoxAIAgentAskLongText longText) { + this.longText = longText; + } - @Override - void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - String memberName = member.getName(); - JsonValue memberValue = member.getValue(); - try { - switch (memberName) { - case "basic_text": - this.basicText = new BoxAIAgentAskBasicText(memberValue.asObject()); - break; - case "long_text": - this.longText = new BoxAIAgentAskLongText(memberValue.asObject()); - break; - default: - break; - } - } catch (Exception e) { - throw new BoxAPIException("Could not parse JSON response.", e); - } + @Override + void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + String memberName = member.getName(); + JsonValue memberValue = member.getValue(); + try { + switch (memberName) { + case "basic_text": + this.basicText = new BoxAIAgentAskBasicText(memberValue.asObject()); + break; + case "long_text": + this.longText = new BoxAIAgentAskLongText(memberValue.asObject()); + break; + default: + break; + } + } catch (Exception e) { + throw new BoxAPIException("Could not parse JSON response.", e); } + } - @Override - public JsonObject getJSONObject() { - JsonObject jsonObject = new JsonObject(); - JsonUtils.addIfNotNull(jsonObject, "type", this.getType()); - if (this.basicText != null) { - jsonObject.add("basic_text", this.basicText.getJSONObject()); - } - if (this.longText != null) { - jsonObject.add("long_text", this.longText.getJSONObject()); - } - return jsonObject; + @Override + public JsonObject getJSONObject() { + JsonObject jsonObject = new JsonObject(); + JsonUtils.addIfNotNull(jsonObject, "type", this.getType()); + if (this.basicText != null) { + jsonObject.add("basic_text", this.basicText.getJSONObject()); } + if (this.longText != null) { + jsonObject.add("long_text", this.longText.getJSONObject()); + } + return jsonObject; + } } - diff --git a/src/main/java/com/box/sdk/BoxAIAgentExtractStructured.java b/src/main/java/com/box/sdk/BoxAIAgentExtractStructured.java index dc3dee51c..45a448a4a 100644 --- a/src/main/java/com/box/sdk/BoxAIAgentExtractStructured.java +++ b/src/main/java/com/box/sdk/BoxAIAgentExtractStructured.java @@ -4,110 +4,107 @@ import com.eclipsesource.json.JsonObject; import com.eclipsesource.json.JsonValue; -/** - * Represents an AI Agent used for extraction. - */ +/** Represents an AI Agent used for extraction. */ @BoxResourceType("ai_agent_extract_structured") public class BoxAIAgentExtractStructured extends BoxAIAgent { - /** - * The type of the AI Ask agent. - */ - public static final String TYPE = "ai_agent_extract_structured"; + /** The type of the AI Ask agent. */ + public static final String TYPE = "ai_agent_extract_structured"; - /** - * AI agent tool used to handle basic text. - */ - private BoxAIAgentAskBasicText basicText; - /** - * AI agent tool used to handle longer text. - */ - private BoxAIAgentAskLongText longText; + /** AI agent tool used to handle basic text. */ + private BoxAIAgentAskBasicText basicText; + /** AI agent tool used to handle longer text. */ + private BoxAIAgentAskLongText longText; - /** - * Constructs an AI agent with default settings. - * @param basicText AI agent tool used to handle basic text. - * @param longText AI agent tool used to handle longer text. - */ - public BoxAIAgentExtractStructured(BoxAIAgentAskBasicText basicText, - BoxAIAgentAskLongText longText) { - super(TYPE); - this.basicText = basicText; - this.longText = longText; - } + /** + * Constructs an AI agent with default settings. + * + * @param basicText AI agent tool used to handle basic text. + * @param longText AI agent tool used to handle longer text. + */ + public BoxAIAgentExtractStructured( + BoxAIAgentAskBasicText basicText, BoxAIAgentAskLongText longText) { + super(TYPE); + this.basicText = basicText; + this.longText = longText; + } - /** - * Constructs an AI agent with default settings. - * @param jsonObject JSON object representing the AI agent. - */ - public BoxAIAgentExtractStructured(JsonObject jsonObject) { - super(jsonObject); - } + /** + * Constructs an AI agent with default settings. + * + * @param jsonObject JSON object representing the AI agent. + */ + public BoxAIAgentExtractStructured(JsonObject jsonObject) { + super(jsonObject); + } - /** - * Gets the AI agent tool used to handle basic text. - * @return The AI agent tool used to handle basic text. - */ - public BoxAIAgentAskBasicText getBasicText() { - return basicText; - } + /** + * Gets the AI agent tool used to handle basic text. + * + * @return The AI agent tool used to handle basic text. + */ + public BoxAIAgentAskBasicText getBasicText() { + return basicText; + } - /** - * Sets the AI agent tool used to handle basic text. - * @param basicText The AI agent tool used to handle basic text. - */ - public void setBasicText(BoxAIAgentAskBasicText basicText) { - this.basicText = basicText; - } + /** + * Sets the AI agent tool used to handle basic text. + * + * @param basicText The AI agent tool used to handle basic text. + */ + public void setBasicText(BoxAIAgentAskBasicText basicText) { + this.basicText = basicText; + } - /** - * Gets the AI agent tool used to handle longer text. - * @return The AI agent tool used to handle longer text. - */ - public BoxAIAgentAskLongText getLongText() { - return longText; - } + /** + * Gets the AI agent tool used to handle longer text. + * + * @return The AI agent tool used to handle longer text. + */ + public BoxAIAgentAskLongText getLongText() { + return longText; + } - /** - * Sets the AI agent tool used to handle longer text. - * @param longText The AI agent tool used to handle longer text. - */ - public void setLongText(BoxAIAgentAskLongText longText) { - this.longText = longText; - } + /** + * Sets the AI agent tool used to handle longer text. + * + * @param longText The AI agent tool used to handle longer text. + */ + public void setLongText(BoxAIAgentAskLongText longText) { + this.longText = longText; + } - @Override - void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - String memberName = member.getName(); - JsonValue memberValue = member.getValue(); - try { - switch (memberName) { - case "basic_text": - this.basicText = new BoxAIAgentAskBasicText(memberValue.asObject()); - break; - case "long_text": - this.longText = new BoxAIAgentAskLongText(memberValue.asObject()); - break; - default: - break; - } - } catch (Exception e) { - throw new BoxAPIException("Could not parse JSON response.", e); - } + @Override + void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + String memberName = member.getName(); + JsonValue memberValue = member.getValue(); + try { + switch (memberName) { + case "basic_text": + this.basicText = new BoxAIAgentAskBasicText(memberValue.asObject()); + break; + case "long_text": + this.longText = new BoxAIAgentAskLongText(memberValue.asObject()); + break; + default: + break; + } + } catch (Exception e) { + throw new BoxAPIException("Could not parse JSON response.", e); } + } - @Override - public JsonObject getJSONObject() { - JsonObject jsonObject = new JsonObject(); - JsonUtils.addIfNotNull(jsonObject, "type", this.getType()); - if (this.basicText != null) { - jsonObject.add("basic_text", this.basicText.getJSONObject()); - } - if (this.longText != null) { - jsonObject.add("long_text", this.longText.getJSONObject()); - } - return jsonObject; + @Override + public JsonObject getJSONObject() { + JsonObject jsonObject = new JsonObject(); + JsonUtils.addIfNotNull(jsonObject, "type", this.getType()); + if (this.basicText != null) { + jsonObject.add("basic_text", this.basicText.getJSONObject()); } + if (this.longText != null) { + jsonObject.add("long_text", this.longText.getJSONObject()); + } + return jsonObject; + } } - diff --git a/src/main/java/com/box/sdk/BoxAIAgentLLMEndpointParams.java b/src/main/java/com/box/sdk/BoxAIAgentLLMEndpointParams.java index 9d1428e73..5ff963d56 100644 --- a/src/main/java/com/box/sdk/BoxAIAgentLLMEndpointParams.java +++ b/src/main/java/com/box/sdk/BoxAIAgentLLMEndpointParams.java @@ -3,79 +3,74 @@ import com.box.sdk.internal.utils.JsonUtils; import com.eclipsesource.json.JsonObject; -/** - * The parameters for the LLM endpoint specific to OpenAI / Google models. - */ +/** The parameters for the LLM endpoint specific to OpenAI / Google models. */ public class BoxAIAgentLLMEndpointParams extends BoxJSONObject { - /** - * The type of the LLM endpoint parameters. - * Value can be "google_params" or "openai_params". - */ - private String type; + /** The type of the LLM endpoint parameters. Value can be "google_params" or "openai_params". */ + private String type; - /** - * Constructs LLM endpoint parameters with default settings. - */ - public BoxAIAgentLLMEndpointParams(String type) { - super(); - this.type = type; - } + /** Constructs LLM endpoint parameters with default settings. */ + public BoxAIAgentLLMEndpointParams(String type) { + super(); + this.type = type; + } - /** - * Constructs LLM endpoint parameters with default settings. - * @param jsonObject JSON object representing the LLM endpoint parameters. - */ - public BoxAIAgentLLMEndpointParams(JsonObject jsonObject) { - super(jsonObject); - } + /** + * Constructs LLM endpoint parameters with default settings. + * + * @param jsonObject JSON object representing the LLM endpoint parameters. + */ + public BoxAIAgentLLMEndpointParams(JsonObject jsonObject) { + super(jsonObject); + } - /** - * Parses a JSON object representing LLM endpoint parameters. - * @param jsonObject JSON object representing the LLM endpoint parameters. - * @return The LLM endpoint parameters parsed from the JSON object. - */ - public static BoxAIAgentLLMEndpointParams parse(JsonObject jsonObject) { - String type = jsonObject.get("type").asString(); - switch (type) { - case BoxAIAgentLLMEndpointParamsGoogle.TYPE: - return new BoxAIAgentLLMEndpointParamsGoogle(jsonObject); - case BoxAIAgentLLMEndpointParamsOpenAI.TYPE: - return new BoxAIAgentLLMEndpointParamsOpenAI(jsonObject); - default: - throw new IllegalArgumentException("Invalid LLM endpoint params type: " + type); - } + /** + * Parses a JSON object representing LLM endpoint parameters. + * + * @param jsonObject JSON object representing the LLM endpoint parameters. + * @return The LLM endpoint parameters parsed from the JSON object. + */ + public static BoxAIAgentLLMEndpointParams parse(JsonObject jsonObject) { + String type = jsonObject.get("type").asString(); + switch (type) { + case BoxAIAgentLLMEndpointParamsGoogle.TYPE: + return new BoxAIAgentLLMEndpointParamsGoogle(jsonObject); + case BoxAIAgentLLMEndpointParamsOpenAI.TYPE: + return new BoxAIAgentLLMEndpointParamsOpenAI(jsonObject); + default: + throw new IllegalArgumentException("Invalid LLM endpoint params type: " + type); } + } - /** - * Gets the type of the LLM endpoint parameters. - * @return The type of the LLM endpoint parameters. - */ - public String getType() { - return type; - } + /** + * Gets the type of the LLM endpoint parameters. + * + * @return The type of the LLM endpoint parameters. + */ + public String getType() { + return type; + } - /** - * Sets the type of the LLM endpoint parameters. - * @param type The type of the LLM endpoint parameters. - */ - public void setType(String type) { - this.type = type; - } + /** + * Sets the type of the LLM endpoint parameters. + * + * @param type The type of the LLM endpoint parameters. + */ + public void setType(String type) { + this.type = type; + } - @Override - void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - String memberName = member.getName(); - if (memberName.equals("type")) { - this.type = member.getValue().asString(); - } + @Override + void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + String memberName = member.getName(); + if (memberName.equals("type")) { + this.type = member.getValue().asString(); } + } - public JsonObject getJSONObject() { - JsonObject jsonObject = new JsonObject(); - JsonUtils.addIfNotNull(jsonObject, "type", this.type); - return jsonObject; - } + public JsonObject getJSONObject() { + JsonObject jsonObject = new JsonObject(); + JsonUtils.addIfNotNull(jsonObject, "type", this.type); + return jsonObject; + } } - - diff --git a/src/main/java/com/box/sdk/BoxAIAgentLLMEndpointParamsGoogle.java b/src/main/java/com/box/sdk/BoxAIAgentLLMEndpointParamsGoogle.java index 2a5cabe00..e73b174af 100644 --- a/src/main/java/com/box/sdk/BoxAIAgentLLMEndpointParamsGoogle.java +++ b/src/main/java/com/box/sdk/BoxAIAgentLLMEndpointParamsGoogle.java @@ -3,135 +3,143 @@ import com.box.sdk.internal.utils.JsonUtils; import com.eclipsesource.json.JsonObject; -/** - * Represents the AI LLM endpoint params Google object. - */ +/** Represents the AI LLM endpoint params Google object. */ public class BoxAIAgentLLMEndpointParamsGoogle extends BoxAIAgentLLMEndpointParams { - /** - * The type of the LLM endpoint parameters. - */ - public static final String TYPE = "google_params"; + /** The type of the LLM endpoint parameters. */ + public static final String TYPE = "google_params"; - /** - * The temperature is used for sampling during response generation, which occurs when top-P and top-K are applied. - * Temperature controls the degree of randomness in token selection. - */ - private Double temperature; - /** - * Top-K changes how the model selects tokens for output. - * A top-K of 1 means the next selected token is the most probable among all tokens in the model's vocabulary - * (also called greedy decoding), while a top-K of 3 means that the next token is selected from among the three - * most probable tokens by using temperature. - */ - private Integer topK; - /** - * Top-P changes how the model selects tokens for output. - * Tokens are selected from the most (see top-K) to least probable until the sum of their probabilities equals the - * top-P value. - */ - private Double topP; + /** + * The temperature is used for sampling during response generation, which occurs when top-P and + * top-K are applied. Temperature controls the degree of randomness in token selection. + */ + private Double temperature; + /** + * Top-K changes how the model selects tokens for output. A top-K of 1 means the next selected + * token is the most probable among all tokens in the model's vocabulary (also called greedy + * decoding), while a top-K of 3 means that the next token is selected from among the three most + * probable tokens by using temperature. + */ + private Integer topK; + /** + * Top-P changes how the model selects tokens for output. Tokens are selected from the most (see + * top-K) to least probable until the sum of their probabilities equals the top-P value. + */ + private Double topP; - /** - * Constructs an AI agent with default settings. - * @param temperature The temperature is used for sampling during response generation, which occurs when top-P and top-K are applied. - * Temperature controls the degree of randomness in token selection. - * @param topK Top-K changes how the model selects tokens for output. - * A top-K of 1 means the next selected token is the most probable among all tokens in the model's vocabulary - * (also called greedy decoding), while a top-K of 3 means that the next token is selected from among the three - * most probable tokens by using temperature. - * @param topP Top-P changes how the model selects tokens for output. - * Tokens are selected from the most (see top-K) to least probable until the sum of their probabilities equals the - * top-P value. - */ - public BoxAIAgentLLMEndpointParamsGoogle(Double temperature, Integer topK, Double topP) { - super(TYPE); - this.temperature = temperature; - this.topK = topK; - this.topP = topP; - } + /** + * Constructs an AI agent with default settings. + * + * @param temperature The temperature is used for sampling during response generation, which + * occurs when top-P and top-K are applied. Temperature controls the degree of randomness in + * token selection. + * @param topK Top-K changes how the model selects tokens for output. A top-K of 1 means the next + * selected token is the most probable among all tokens in the model's vocabulary (also called + * greedy decoding), while a top-K of 3 means that the next token is selected from among the + * three most probable tokens by using temperature. + * @param topP Top-P changes how the model selects tokens for output. Tokens are selected from the + * most (see top-K) to least probable until the sum of their probabilities equals the top-P + * value. + */ + public BoxAIAgentLLMEndpointParamsGoogle(Double temperature, Integer topK, Double topP) { + super(TYPE); + this.temperature = temperature; + this.topK = topK; + this.topP = topP; + } - /** - * Constructs an AI agent with default settings. - * @param jsonObject JSON object representing the AI agent. - */ - public BoxAIAgentLLMEndpointParamsGoogle(JsonObject jsonObject) { - super(jsonObject); - } + /** + * Constructs an AI agent with default settings. + * + * @param jsonObject JSON object representing the AI agent. + */ + public BoxAIAgentLLMEndpointParamsGoogle(JsonObject jsonObject) { + super(jsonObject); + } - /** - * Gets the temperature used for sampling during response generation, which occurs when top-P and top-K are applied. - * @return The temperature used for sampling during response generation, which occurs when top-P and top-K are applied. - */ - public Double getTemperature() { - return temperature; - } + /** + * Gets the temperature used for sampling during response generation, which occurs when top-P and + * top-K are applied. + * + * @return The temperature used for sampling during response generation, which occurs when top-P + * and top-K are applied. + */ + public Double getTemperature() { + return temperature; + } - /** - * Sets the temperature used for sampling during response generation, which occurs when top-P and top-K are applied. - * @param temperature The temperature used for sampling during response generation, which occurs when top-P and top-K are applied. - */ - public void setTemperature(Double temperature) { - this.temperature = temperature; - } + /** + * Sets the temperature used for sampling during response generation, which occurs when top-P and + * top-K are applied. + * + * @param temperature The temperature used for sampling during response generation, which occurs + * when top-P and top-K are applied. + */ + public void setTemperature(Double temperature) { + this.temperature = temperature; + } - /** - * Gets the top-K value. - * @return The top-K value. - */ - public Integer getTopK() { - return topK; - } + /** + * Gets the top-K value. + * + * @return The top-K value. + */ + public Integer getTopK() { + return topK; + } - /** - * Sets the top-K value. - * @param topK The top-K value. - */ - public void setTopK(Integer topK) { - this.topK = topK; - } + /** + * Sets the top-K value. + * + * @param topK The top-K value. + */ + public void setTopK(Integer topK) { + this.topK = topK; + } - /** - * Gets the top-P value. - * @return The top-P value. - */ - public Double getTopP() { - return topP; - } + /** + * Gets the top-P value. + * + * @return The top-P value. + */ + public Double getTopP() { + return topP; + } - /** - * Sets the top-P value. - * @param topP The top-P value. - */ - public void setTopP(Double topP) { - this.topP = topP; - } + /** + * Sets the top-P value. + * + * @param topP The top-P value. + */ + public void setTopP(Double topP) { + this.topP = topP; + } - @Override - void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - String memberName = member.getName(); - switch (memberName) { - case "temperature": - this.temperature = member.getValue().asDouble(); - break; - case "top_k": - this.topK = member.getValue().asInt(); - break; - case "top_p": - this.topP = member.getValue().asDouble(); - break; - default: - break; - } + @Override + void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + String memberName = member.getName(); + switch (memberName) { + case "temperature": + this.temperature = member.getValue().asDouble(); + break; + case "top_k": + this.topK = member.getValue().asInt(); + break; + case "top_p": + this.topP = member.getValue().asDouble(); + break; + default: + break; } + } - public JsonObject getJSONObject() { - JsonObject jsonObject = new JsonObject(); - JsonUtils.addIfNotNull(jsonObject, "type", this.getType()); - JsonUtils.addIfNotNull(jsonObject, "temperature", this.temperature); - JsonUtils.addIfNotNull(jsonObject, "top_k", this.topK); - JsonUtils.addIfNotNull(jsonObject, "top_p", this.topP); - return jsonObject; - } + public JsonObject getJSONObject() { + JsonObject jsonObject = new JsonObject(); + JsonUtils.addIfNotNull(jsonObject, "type", this.getType()); + JsonUtils.addIfNotNull(jsonObject, "temperature", this.temperature); + JsonUtils.addIfNotNull(jsonObject, "top_k", this.topK); + JsonUtils.addIfNotNull(jsonObject, "top_p", this.topP); + return jsonObject; + } } diff --git a/src/main/java/com/box/sdk/BoxAIAgentLLMEndpointParamsOpenAI.java b/src/main/java/com/box/sdk/BoxAIAgentLLMEndpointParamsOpenAI.java index 00ecad81a..ad427ffd5 100644 --- a/src/main/java/com/box/sdk/BoxAIAgentLLMEndpointParamsOpenAI.java +++ b/src/main/java/com/box/sdk/BoxAIAgentLLMEndpointParamsOpenAI.java @@ -3,191 +3,203 @@ import com.box.sdk.internal.utils.JsonUtils; import com.eclipsesource.json.JsonObject; -/** - * Represents the AI LLM endpoint params OpenAI object. - */ +/** Represents the AI LLM endpoint params OpenAI object. */ public class BoxAIAgentLLMEndpointParamsOpenAI extends BoxAIAgentLLMEndpointParams { - /** - * The type of the LLM endpoint parameters. - */ - public static final String TYPE = "openai_params"; - - /** - * Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text - * so far, decreasing the model's likelihood to repeat the same line verbatim. - */ - private Double frequencyPenalty; - /** - * Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, - * increasing the model's likelihood to talk about new topics. - */ - private Double presencePenalty; - /** - * Up to 4 sequences where the API will stop generating further tokens. - */ - private String stop; - /** - * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, - * while lower values like 0.2 will make it more focused and deterministic. - * We generally recommend altering this or top_p but not both. - */ - private Double temperature; - /** - * An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of - * the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass - * are considered. We generally recommend altering this or temperature but not both. - */ - private Double topP; - - /** - * Constructs an AI agent with default settings. - * @param frequencyPenalty Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text - * so far, decreasing the model's likelihood to repeat the same line verbatim. - * @param presencePenalty Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, - * increasing the model's likelihood to talk about new topics. - * @param stop Up to 4 sequences where the API will stop generating further tokens. - * @param temperature What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, - * while lower values like 0.2 will make it more focused and deterministic. - * We generally recommend altering this or top_p but not both. - * @param topP An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of - * the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass - * are considered. We generally recommend altering this or temperature but not both. - */ - public BoxAIAgentLLMEndpointParamsOpenAI(Double frequencyPenalty, - Double presencePenalty, - String stop, - Double temperature, - Double topP) { - super(TYPE); - this.frequencyPenalty = frequencyPenalty; - this.presencePenalty = presencePenalty; - this.stop = stop; - this.temperature = temperature; - this.topP = topP; - } - - /** - * Constructs an AI agent with default settings. - * @param jsonObject JSON object representing the AI agent. - */ - public BoxAIAgentLLMEndpointParamsOpenAI(JsonObject jsonObject) { - super(jsonObject); - } - - /** - * Gets the frequency penalty. - * @return The frequency penalty. - */ - public Double getFrequencyPenalty() { - return frequencyPenalty; - } - - /** - * Sets the frequency penalty. - * @param frequencyPenalty The frequency penalty. - */ - public void setFrequencyPenalty(Double frequencyPenalty) { - this.frequencyPenalty = frequencyPenalty; - } - - /** - * Gets the presence penalty. - * @return The presence penalty. - */ - public Double getPresencePenalty() { - return presencePenalty; - } - - /** - * Sets the presence penalty. - * @param presencePenalty The presence penalty. - */ - public void setPresencePenalty(Double presencePenalty) { - this.presencePenalty = presencePenalty; - } - - /** - * Gets the stop. - * @return The stop. - */ - public String getStop() { - return stop; - } - - /** - * Sets the stop. - * @param stop The stop. - */ - public void setStop(String stop) { - this.stop = stop; - } - - /** - * Gets the temperature. - * @return The temperature. - */ - public Double getTemperature() { - return temperature; - } - - /** - * Sets the temperature. - * @param temperature The temperature. - */ - public void setTemperature(Double temperature) { - this.temperature = temperature; - } - - /** - * Gets the top-P. - * @return The top-P. - */ - public Double getTopP() { - return topP; - } - - /** - * Sets the top-P. - * @param topP The top-P. - */ - public void setTopP(Double topP) { - this.topP = topP; - } - - @Override - void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - String memberName = member.getName(); - switch (memberName) { - case "frequency_penalty": - this.frequencyPenalty = member.getValue().asDouble(); - break; - case "presence_penalty": - this.presencePenalty = member.getValue().asDouble(); - break; - case "stop": - this.stop = member.getValue().asString(); - break; - case "temperature": - this.temperature = member.getValue().asDouble(); - break; - case "top_p": - this.topP = member.getValue().asDouble(); - break; - default: - break; - } - } - - public JsonObject getJSONObject() { - JsonObject jsonObject = new JsonObject(); - JsonUtils.addIfNotNull(jsonObject, "type", this.getType()); - JsonUtils.addIfNotNull(jsonObject, "frequency_penalty", this.frequencyPenalty); - JsonUtils.addIfNotNull(jsonObject, "presence_penalty", this.presencePenalty); - JsonUtils.addIfNotNull(jsonObject, "stop", this.stop); - JsonUtils.addIfNotNull(jsonObject, "temperature", this.temperature); - JsonUtils.addIfNotNull(jsonObject, "top_p", this.topP); - return jsonObject; + /** The type of the LLM endpoint parameters. */ + public static final String TYPE = "openai_params"; + + /** + * Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing + * frequency in the text so far, decreasing the model's likelihood to repeat the same line + * verbatim. + */ + private Double frequencyPenalty; + /** + * Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear + * in the text so far, increasing the model's likelihood to talk about new topics. + */ + private Double presencePenalty; + /** Up to 4 sequences where the API will stop generating further tokens. */ + private String stop; + /** + * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output + * more random, while lower values like 0.2 will make it more focused and deterministic. We + * generally recommend altering this or top_p but not both. + */ + private Double temperature; + /** + * An alternative to sampling with temperature, called nucleus sampling, where the model considers + * the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising + * the top 10% probability mass are considered. We generally recommend altering this or + * temperature but not both. + */ + private Double topP; + + /** + * Constructs an AI agent with default settings. + * + * @param frequencyPenalty Number between -2.0 and 2.0. Positive values penalize new tokens based + * on their existing frequency in the text so far, decreasing the model's likelihood to repeat + * the same line verbatim. + * @param presencePenalty Number between -2.0 and 2.0. Positive values penalize new tokens based + * on whether they appear in the text so far, increasing the model's likelihood to talk about + * new topics. + * @param stop Up to 4 sequences where the API will stop generating further tokens. + * @param temperature What sampling temperature to use, between 0 and 2. Higher values like 0.8 + * will make the output more random, while lower values like 0.2 will make it more focused and + * deterministic. We generally recommend altering this or top_p but not both. + * @param topP An alternative to sampling with temperature, called nucleus sampling, where the + * model considers the results of the tokens with top_p probability mass. So 0.1 means only + * the tokens comprising the top 10% probability mass are considered. We generally recommend + * altering this or temperature but not both. + */ + public BoxAIAgentLLMEndpointParamsOpenAI( + Double frequencyPenalty, + Double presencePenalty, + String stop, + Double temperature, + Double topP) { + super(TYPE); + this.frequencyPenalty = frequencyPenalty; + this.presencePenalty = presencePenalty; + this.stop = stop; + this.temperature = temperature; + this.topP = topP; + } + + /** + * Constructs an AI agent with default settings. + * + * @param jsonObject JSON object representing the AI agent. + */ + public BoxAIAgentLLMEndpointParamsOpenAI(JsonObject jsonObject) { + super(jsonObject); + } + + /** + * Gets the frequency penalty. + * + * @return The frequency penalty. + */ + public Double getFrequencyPenalty() { + return frequencyPenalty; + } + + /** + * Sets the frequency penalty. + * + * @param frequencyPenalty The frequency penalty. + */ + public void setFrequencyPenalty(Double frequencyPenalty) { + this.frequencyPenalty = frequencyPenalty; + } + + /** + * Gets the presence penalty. + * + * @return The presence penalty. + */ + public Double getPresencePenalty() { + return presencePenalty; + } + + /** + * Sets the presence penalty. + * + * @param presencePenalty The presence penalty. + */ + public void setPresencePenalty(Double presencePenalty) { + this.presencePenalty = presencePenalty; + } + + /** + * Gets the stop. + * + * @return The stop. + */ + public String getStop() { + return stop; + } + + /** + * Sets the stop. + * + * @param stop The stop. + */ + public void setStop(String stop) { + this.stop = stop; + } + + /** + * Gets the temperature. + * + * @return The temperature. + */ + public Double getTemperature() { + return temperature; + } + + /** + * Sets the temperature. + * + * @param temperature The temperature. + */ + public void setTemperature(Double temperature) { + this.temperature = temperature; + } + + /** + * Gets the top-P. + * + * @return The top-P. + */ + public Double getTopP() { + return topP; + } + + /** + * Sets the top-P. + * + * @param topP The top-P. + */ + public void setTopP(Double topP) { + this.topP = topP; + } + + @Override + void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + String memberName = member.getName(); + switch (memberName) { + case "frequency_penalty": + this.frequencyPenalty = member.getValue().asDouble(); + break; + case "presence_penalty": + this.presencePenalty = member.getValue().asDouble(); + break; + case "stop": + this.stop = member.getValue().asString(); + break; + case "temperature": + this.temperature = member.getValue().asDouble(); + break; + case "top_p": + this.topP = member.getValue().asDouble(); + break; + default: + break; } + } + + public JsonObject getJSONObject() { + JsonObject jsonObject = new JsonObject(); + JsonUtils.addIfNotNull(jsonObject, "type", this.getType()); + JsonUtils.addIfNotNull(jsonObject, "frequency_penalty", this.frequencyPenalty); + JsonUtils.addIfNotNull(jsonObject, "presence_penalty", this.presencePenalty); + JsonUtils.addIfNotNull(jsonObject, "stop", this.stop); + JsonUtils.addIfNotNull(jsonObject, "temperature", this.temperature); + JsonUtils.addIfNotNull(jsonObject, "top_p", this.topP); + return jsonObject; + } } diff --git a/src/main/java/com/box/sdk/BoxAIAgentTextGen.java b/src/main/java/com/box/sdk/BoxAIAgentTextGen.java index 47e70dd76..a76a96b38 100644 --- a/src/main/java/com/box/sdk/BoxAIAgentTextGen.java +++ b/src/main/java/com/box/sdk/BoxAIAgentTextGen.java @@ -3,70 +3,68 @@ import com.box.sdk.internal.utils.JsonUtils; import com.eclipsesource.json.JsonObject; -/** - * Represents an AI Agent used for generating text. - */ +/** Represents an AI Agent used for generating text. */ @BoxResourceType("ai_agent_text_gen") public class BoxAIAgentTextGen extends BoxAIAgent { - /** - * The type of the AI Agent for generating text. - */ - public static final String TYPE = "ai_agent_text_gen"; + /** The type of the AI Agent for generating text. */ + public static final String TYPE = "ai_agent_text_gen"; - /** - * The basic generator used for the AI Agent for generating text. - */ - private BoxAIAgentTextGenBasicGen basicGen; + /** The basic generator used for the AI Agent for generating text. */ + private BoxAIAgentTextGenBasicGen basicGen; - /** - * Constructs an AI agent with default settings. - * @param basicGen The basic generator used for the AI Agent for generating text. - */ - public BoxAIAgentTextGen(BoxAIAgentTextGenBasicGen basicGen) { - super(TYPE); - this.basicGen = basicGen; - } + /** + * Constructs an AI agent with default settings. + * + * @param basicGen The basic generator used for the AI Agent for generating text. + */ + public BoxAIAgentTextGen(BoxAIAgentTextGenBasicGen basicGen) { + super(TYPE); + this.basicGen = basicGen; + } - /** - * Constructs an AI agent with default settings. - * @param jsonObject JSON object representing the AI agent. - */ - public BoxAIAgentTextGen(JsonObject jsonObject) { - super(jsonObject); - } + /** + * Constructs an AI agent with default settings. + * + * @param jsonObject JSON object representing the AI agent. + */ + public BoxAIAgentTextGen(JsonObject jsonObject) { + super(jsonObject); + } - /** - * Gets the basic generator used for the AI Agent for generating text. - * @return The basic generator used for the AI Agent for generating text. - */ - public BoxAIAgentTextGenBasicGen getBasicGen() { - return basicGen; - } + /** + * Gets the basic generator used for the AI Agent for generating text. + * + * @return The basic generator used for the AI Agent for generating text. + */ + public BoxAIAgentTextGenBasicGen getBasicGen() { + return basicGen; + } - /** - * Sets the basic generator used for the AI Agent for generating text. - * @param basicGen The basic generator used for the AI Agent for generating text. - */ - public void setBasicGen(BoxAIAgentTextGenBasicGen basicGen) { - this.basicGen = basicGen; - } + /** + * Sets the basic generator used for the AI Agent for generating text. + * + * @param basicGen The basic generator used for the AI Agent for generating text. + */ + public void setBasicGen(BoxAIAgentTextGenBasicGen basicGen) { + this.basicGen = basicGen; + } - @Override - void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - String memberName = member.getName(); - if (memberName.equals("basic_gen")) { - this.basicGen = new BoxAIAgentTextGenBasicGen(member.getValue().asObject()); - } + @Override + void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + String memberName = member.getName(); + if (memberName.equals("basic_gen")) { + this.basicGen = new BoxAIAgentTextGenBasicGen(member.getValue().asObject()); } + } - public JsonObject getJSONObject() { - JsonObject jsonObject = new JsonObject(); - JsonUtils.addIfNotNull(jsonObject, "type", this.getType()); - if (this.basicGen != null) { - jsonObject.add("basic_gen", this.basicGen.getJSONObject()); - } - return jsonObject; + public JsonObject getJSONObject() { + JsonObject jsonObject = new JsonObject(); + JsonUtils.addIfNotNull(jsonObject, "type", this.getType()); + if (this.basicGen != null) { + jsonObject.add("basic_gen", this.basicGen.getJSONObject()); } + return jsonObject; + } } diff --git a/src/main/java/com/box/sdk/BoxAIAgentTextGenBasicGen.java b/src/main/java/com/box/sdk/BoxAIAgentTextGenBasicGen.java index 5bb30f44b..b116c8727 100644 --- a/src/main/java/com/box/sdk/BoxAIAgentTextGenBasicGen.java +++ b/src/main/java/com/box/sdk/BoxAIAgentTextGenBasicGen.java @@ -3,237 +3,256 @@ import com.box.sdk.internal.utils.JsonUtils; import com.eclipsesource.json.JsonObject; -/** - * Represents the AI agent basic tool used to generate text. - */ +/** Represents the AI agent basic tool used to generate text. */ public class BoxAIAgentTextGenBasicGen extends BoxJSONObject { - /** - * How the content should be included in a request to the LLM. Input for {content} is optional, depending on the use. - */ - private String contentTemplate; - /** - * Embeddings used by the AI agent. - */ - private BoxAIAgentEmbeddings embeddings; - /** - * The parameters for the LLM endpoint specific to OpenAI / Google models. - */ - private BoxAIAgentLLMEndpointParams llmEndpointParams; - /** - * The model used for the AI Agent for generating text. - */ - private String model; - /** - * The number of tokens for completion. - */ - private int numTokensForCompletion; - /** - * The prompt template contains contextual information of the request and the user prompt. - * When passing prompt_template parameters, you must include inputs for {user_question} and {content}. - * Input for {current_date} is optional, depending on the use. - */ - private String promptTemplate; - /** - * System messages try to help the LLM "understand" its role and what it is supposed to do. - */ - private String systemMessage; - - /** - * Constructs an AI agent with default settings. - * @param contentTemplate How the content should be included in a request to the LLM. Input for {content} is optional, depending on the use. - * @param embeddings Embeddings used by the AI agent. - * @param llmEndpointParams The parameters for the LLM endpoint specific to OpenAI / Google models. - * @param model The model used for the AI Agent for generating text. - * @param numTokensForCompletion The number of tokens for completion. - * @param promptTemplate The prompt template contains contextual information of the request and the user prompt. - * When passing prompt_template parameters, you must include inputs for {user_question} and {content}. - * Input for {current_date} is optional, depending on the use. - * @param systemMessage System messages try to help the LLM "understand" its role and what it is supposed to do. - */ - public BoxAIAgentTextGenBasicGen(String contentTemplate, BoxAIAgentEmbeddings embeddings, - BoxAIAgentLLMEndpointParamsOpenAI llmEndpointParams, String model, - int numTokensForCompletion, String promptTemplate, String systemMessage) { - this.contentTemplate = contentTemplate; - this.embeddings = embeddings; - this.llmEndpointParams = llmEndpointParams; - this.model = model; - this.numTokensForCompletion = numTokensForCompletion; - this.promptTemplate = promptTemplate; - this.systemMessage = systemMessage; - } + /** + * How the content should be included in a request to the LLM. Input for {content} is optional, + * depending on the use. + */ + private String contentTemplate; + /** Embeddings used by the AI agent. */ + private BoxAIAgentEmbeddings embeddings; + /** The parameters for the LLM endpoint specific to OpenAI / Google models. */ + private BoxAIAgentLLMEndpointParams llmEndpointParams; + /** The model used for the AI Agent for generating text. */ + private String model; + /** The number of tokens for completion. */ + private int numTokensForCompletion; + /** + * The prompt template contains contextual information of the request and the user prompt. When + * passing prompt_template parameters, you must include inputs for {user_question} and {content}. + * Input for {current_date} is optional, depending on the use. + */ + private String promptTemplate; + /** System messages try to help the LLM "understand" its role and what it is supposed to do. */ + private String systemMessage; - /** - * Constructs an AI agent with default settings. - * @param jsonObject JSON object representing the AI agent. - */ - public BoxAIAgentTextGenBasicGen(JsonObject jsonObject) { - super(jsonObject); - } + /** + * Constructs an AI agent with default settings. + * + * @param contentTemplate How the content should be included in a request to the LLM. Input for + * {content} is optional, depending on the use. + * @param embeddings Embeddings used by the AI agent. + * @param llmEndpointParams The parameters for the LLM endpoint specific to OpenAI / Google + * models. + * @param model The model used for the AI Agent for generating text. + * @param numTokensForCompletion The number of tokens for completion. + * @param promptTemplate The prompt template contains contextual information of the request and + * the user prompt. When passing prompt_template parameters, you must include inputs for + * {user_question} and {content}. Input for {current_date} is optional, depending on the use. + * @param systemMessage System messages try to help the LLM "understand" its role and what it is + * supposed to do. + */ + public BoxAIAgentTextGenBasicGen( + String contentTemplate, + BoxAIAgentEmbeddings embeddings, + BoxAIAgentLLMEndpointParamsOpenAI llmEndpointParams, + String model, + int numTokensForCompletion, + String promptTemplate, + String systemMessage) { + this.contentTemplate = contentTemplate; + this.embeddings = embeddings; + this.llmEndpointParams = llmEndpointParams; + this.model = model; + this.numTokensForCompletion = numTokensForCompletion; + this.promptTemplate = promptTemplate; + this.systemMessage = systemMessage; + } - /** - * Gets how the content should be included in a request to the LLM. Input for {content} is optional, - * depending on the use. - * @return How the content should be included in a request to the LLM. - * Input for {content} is optional, depending on the use. - */ - public String getContentTemplate() { - return contentTemplate; - } + /** + * Constructs an AI agent with default settings. + * + * @param jsonObject JSON object representing the AI agent. + */ + public BoxAIAgentTextGenBasicGen(JsonObject jsonObject) { + super(jsonObject); + } - /** - * Sets how the content should be included in a request to the LLM. Input for {content} is optional, - * depending on the use. - * @param contentTemplate How the content should be included in a request to the LLM. - * Input for {content} is optional, depending on the use. - */ - public void setContentTemplate(String contentTemplate) { - this.contentTemplate = contentTemplate; - } + /** + * Gets how the content should be included in a request to the LLM. Input for {content} is + * optional, depending on the use. + * + * @return How the content should be included in a request to the LLM. Input for {content} is + * optional, depending on the use. + */ + public String getContentTemplate() { + return contentTemplate; + } - /** - * Gets the embeddings used by the AI agent. - * @return The embeddings used by the AI agent. - */ - public BoxAIAgentEmbeddings getEmbeddings() { - return embeddings; - } + /** + * Sets how the content should be included in a request to the LLM. Input for {content} is + * optional, depending on the use. + * + * @param contentTemplate How the content should be included in a request to the LLM. Input for + * {content} is optional, depending on the use. + */ + public void setContentTemplate(String contentTemplate) { + this.contentTemplate = contentTemplate; + } - /** - * Sets the embeddings used by the AI agent. - * @param embeddings The embeddings used by the AI agent. - */ - public void setEmbeddings(BoxAIAgentEmbeddings embeddings) { - this.embeddings = embeddings; - } + /** + * Gets the embeddings used by the AI agent. + * + * @return The embeddings used by the AI agent. + */ + public BoxAIAgentEmbeddings getEmbeddings() { + return embeddings; + } - /** - * Gets the parameters for the LLM endpoint specific to OpenAI / Google models. - * @return The parameters for the LLM endpoint specific to OpenAI / Google models. - */ - public BoxAIAgentLLMEndpointParams getLlmEndpointParams() { - return llmEndpointParams; - } + /** + * Sets the embeddings used by the AI agent. + * + * @param embeddings The embeddings used by the AI agent. + */ + public void setEmbeddings(BoxAIAgentEmbeddings embeddings) { + this.embeddings = embeddings; + } - /** - * Sets the parameters for the LLM endpoint specific to OpenAI / Google models. - * @param llmEndpointParams The parameters for the LLM endpoint specific to OpenAI / Google models. - */ - public void setLlmEndpointParams(BoxAIAgentLLMEndpointParamsOpenAI llmEndpointParams) { - this.llmEndpointParams = llmEndpointParams; - } + /** + * Gets the parameters for the LLM endpoint specific to OpenAI / Google models. + * + * @return The parameters for the LLM endpoint specific to OpenAI / Google models. + */ + public BoxAIAgentLLMEndpointParams getLlmEndpointParams() { + return llmEndpointParams; + } - /** - * Gets the model used for the AI Agent for generating text. - * @return The model used for the AI Agent for generating text. - */ - public String getModel() { - return model; - } + /** + * Sets the parameters for the LLM endpoint specific to OpenAI / Google models. + * + * @param llmEndpointParams The parameters for the LLM endpoint specific to OpenAI / Google + * models. + */ + public void setLlmEndpointParams(BoxAIAgentLLMEndpointParamsOpenAI llmEndpointParams) { + this.llmEndpointParams = llmEndpointParams; + } - /** - * Sets the model used for the AI Agent for generating text. - * @param model The model used for the AI Agent for generating text. - */ - public void setModel(String model) { - this.model = model; - } + /** + * Gets the model used for the AI Agent for generating text. + * + * @return The model used for the AI Agent for generating text. + */ + public String getModel() { + return model; + } - /** - * Gets the number of tokens for completion. - * @return The number of tokens for completion. - */ - public int getNumTokensForCompletion() { - return numTokensForCompletion; - } + /** + * Sets the model used for the AI Agent for generating text. + * + * @param model The model used for the AI Agent for generating text. + */ + public void setModel(String model) { + this.model = model; + } - /** - * Sets the number of tokens for completion. - * @param numTokensForCompletion The number of tokens for completion. - */ - public void setNumTokensForCompletion(int numTokensForCompletion) { - this.numTokensForCompletion = numTokensForCompletion; - } + /** + * Gets the number of tokens for completion. + * + * @return The number of tokens for completion. + */ + public int getNumTokensForCompletion() { + return numTokensForCompletion; + } - /** - * Gets the prompt template contains contextual information of the request and the user prompt. - * When passing prompt_template parameters, you must include inputs for {user_question} and {content}. - * Input for {current_date} is optional, depending on the use. - * @return The prompt template contains contextual information of the request and the user prompt. - */ - public String getPromptTemplate() { - return promptTemplate; - } + /** + * Sets the number of tokens for completion. + * + * @param numTokensForCompletion The number of tokens for completion. + */ + public void setNumTokensForCompletion(int numTokensForCompletion) { + this.numTokensForCompletion = numTokensForCompletion; + } - /** - * Sets the prompt template contains contextual information of the request and the user prompt. - * When passing prompt_template parameters, you must include inputs for {user_question} and {content}. - * Input for {current_date} is optional, depending on the use. - * @param promptTemplate The prompt template contains contextual information of the request and the user prompt. - */ - public void setPromptTemplate(String promptTemplate) { - this.promptTemplate = promptTemplate; - } + /** + * Gets the prompt template contains contextual information of the request and the user prompt. + * When passing prompt_template parameters, you must include inputs for {user_question} and + * {content}. Input for {current_date} is optional, depending on the use. + * + * @return The prompt template contains contextual information of the request and the user prompt. + */ + public String getPromptTemplate() { + return promptTemplate; + } - /** - * Gets the system messages try to help the LLM "understand" its role and what it is supposed to do. - * @return The system messages try to help the LLM "understand" its role and what it is supposed to do. - */ - public String getSystemMessage() { - return systemMessage; - } + /** + * Sets the prompt template contains contextual information of the request and the user prompt. + * When passing prompt_template parameters, you must include inputs for {user_question} and + * {content}. Input for {current_date} is optional, depending on the use. + * + * @param promptTemplate The prompt template contains contextual information of the request and + * the user prompt. + */ + public void setPromptTemplate(String promptTemplate) { + this.promptTemplate = promptTemplate; + } - /** - * Sets the system messages try to help the LLM "understand" its role and what it is supposed to do. - * @param systemMessage The system messages try to help the LLM "understand" its role and what it is supposed to do. - */ - public void setSystemMessage(String systemMessage) { - this.systemMessage = systemMessage; - } + /** + * Gets the system messages try to help the LLM "understand" its role and what it is supposed to + * do. + * + * @return The system messages try to help the LLM "understand" its role and what it is supposed + * to do. + */ + public String getSystemMessage() { + return systemMessage; + } - @Override - void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - String memberName = member.getName(); - switch (memberName) { - case "content_template": - this.contentTemplate = member.getValue().asString(); - break; - case "embeddings": - this.embeddings = new BoxAIAgentEmbeddings(member.getValue().asObject()); - break; - case "llm_endpoint_params": - this.llmEndpointParams = BoxAIAgentLLMEndpointParams.parse(member.getValue().asObject()); - break; - case "model": - this.model = member.getValue().asString(); - break; - case "num_tokens_for_completion": - this.numTokensForCompletion = member.getValue().asInt(); - break; - case "prompt_template": - this.promptTemplate = member.getValue().asString(); - break; - case "system_message": - this.systemMessage = member.getValue().asString(); - break; - default: - break; - } + /** + * Sets the system messages try to help the LLM "understand" its role and what it is supposed to + * do. + * + * @param systemMessage The system messages try to help the LLM "understand" its role and what it + * is supposed to do. + */ + public void setSystemMessage(String systemMessage) { + this.systemMessage = systemMessage; + } + + @Override + void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + String memberName = member.getName(); + switch (memberName) { + case "content_template": + this.contentTemplate = member.getValue().asString(); + break; + case "embeddings": + this.embeddings = new BoxAIAgentEmbeddings(member.getValue().asObject()); + break; + case "llm_endpoint_params": + this.llmEndpointParams = BoxAIAgentLLMEndpointParams.parse(member.getValue().asObject()); + break; + case "model": + this.model = member.getValue().asString(); + break; + case "num_tokens_for_completion": + this.numTokensForCompletion = member.getValue().asInt(); + break; + case "prompt_template": + this.promptTemplate = member.getValue().asString(); + break; + case "system_message": + this.systemMessage = member.getValue().asString(); + break; + default: + break; } + } - public JsonObject getJSONObject() { - JsonObject jsonObject = new JsonObject(); - JsonUtils.addIfNotNull(jsonObject, "content_template", this.contentTemplate); - if (this.embeddings != null) { - jsonObject.add("embeddings", this.embeddings.getJSONObject()); - } - if (this.llmEndpointParams != null) { - jsonObject.add("llm_endpoint_params", this.llmEndpointParams.getJSONObject()); - } - JsonUtils.addIfNotNull(jsonObject, "model", this.model); - JsonUtils.addIfNotNull(jsonObject, "num_tokens_for_completion", this.numTokensForCompletion); - JsonUtils.addIfNotNull(jsonObject, "prompt_template", this.promptTemplate); - JsonUtils.addIfNotNull(jsonObject, "system_message", this.systemMessage); - return jsonObject; + public JsonObject getJSONObject() { + JsonObject jsonObject = new JsonObject(); + JsonUtils.addIfNotNull(jsonObject, "content_template", this.contentTemplate); + if (this.embeddings != null) { + jsonObject.add("embeddings", this.embeddings.getJSONObject()); + } + if (this.llmEndpointParams != null) { + jsonObject.add("llm_endpoint_params", this.llmEndpointParams.getJSONObject()); } + JsonUtils.addIfNotNull(jsonObject, "model", this.model); + JsonUtils.addIfNotNull(jsonObject, "num_tokens_for_completion", this.numTokensForCompletion); + JsonUtils.addIfNotNull(jsonObject, "prompt_template", this.promptTemplate); + JsonUtils.addIfNotNull(jsonObject, "system_message", this.systemMessage); + return jsonObject; + } } diff --git a/src/main/java/com/box/sdk/BoxAIDialogueEntry.java b/src/main/java/com/box/sdk/BoxAIDialogueEntry.java index bc48fd0e2..010b633d2 100644 --- a/src/main/java/com/box/sdk/BoxAIDialogueEntry.java +++ b/src/main/java/com/box/sdk/BoxAIDialogueEntry.java @@ -3,104 +3,105 @@ import com.eclipsesource.json.JsonObject; import java.util.Date; - /** - * Represents an entry of the history of prompts and answers previously passed to the LLM. - * This provides additional context to the LLM in generating the response. + * Represents an entry of the history of prompts and answers previously passed to the LLM. This + * provides additional context to the LLM in generating the response. */ public class BoxAIDialogueEntry extends BoxJSONObject { - private String prompt; - private String answer; - private Date createdAt; + private String prompt; + private String answer; + private Date createdAt; - /** - * - * @param prompt The prompt previously provided by the client and answered by the LLM. - * @param answer The answer previously provided by the LLM. - * @param createdAt The ISO date formatted timestamp of when the previous answer to the prompt was created. - */ - public BoxAIDialogueEntry(String prompt, String answer, Date createdAt) { - super(); - this.prompt = prompt; - this.answer = answer; - this.createdAt = createdAt; - } + /** + * @param prompt The prompt previously provided by the client and answered by the LLM. + * @param answer The answer previously provided by the LLM. + * @param createdAt The ISO date formatted timestamp of when the previous answer to the prompt was + * created. + */ + public BoxAIDialogueEntry(String prompt, String answer, Date createdAt) { + super(); + this.prompt = prompt; + this.answer = answer; + this.createdAt = createdAt; + } - /** - * - * @param prompt The prompt previously provided by the client and answered by the LLM. - * @param answer The answer previously provided by the LLM. - */ - public BoxAIDialogueEntry(String prompt, String answer) { - super(); - this.prompt = prompt; - this.answer = answer; - } + /** + * @param prompt The prompt previously provided by the client and answered by the LLM. + * @param answer The answer previously provided by the LLM. + */ + public BoxAIDialogueEntry(String prompt, String answer) { + super(); + this.prompt = prompt; + this.answer = answer; + } - /** - * Get the answer previously provided by the LLM. - * @return the answer previously provided by the LLM. - */ - public String getAnswer() { - return answer; - } + /** + * Get the answer previously provided by the LLM. + * + * @return the answer previously provided by the LLM. + */ + public String getAnswer() { + return answer; + } - /** - * Set the answer previously provided by the LLM. - * @param answer the answer previously provided by the LLM. - */ - public void setAnswer(String answer) { - this.answer = answer; - } + /** + * Set the answer previously provided by the LLM. + * + * @param answer the answer previously provided by the LLM. + */ + public void setAnswer(String answer) { + this.answer = answer; + } - /** - * Get the prompt previously provided by the client and answered by the LLM. - * - * @return the prompt previously provided by the client and answered by the LLM. - */ - public String getPrompt() { - return prompt; - } + /** + * Get the prompt previously provided by the client and answered by the LLM. + * + * @return the prompt previously provided by the client and answered by the LLM. + */ + public String getPrompt() { + return prompt; + } - /** - * Set the prompt previously provided by the client and answered by the LLM. - * - * @param prompt the prompt previously provided by the client and answered by the LLM. - */ - public void setPrompt(String prompt) { - this.prompt = prompt; - } + /** + * Set the prompt previously provided by the client and answered by the LLM. + * + * @param prompt the prompt previously provided by the client and answered by the LLM. + */ + public void setPrompt(String prompt) { + this.prompt = prompt; + } - /** - * Get The ISO date formatted timestamp of when the previous answer to the prompt was created. - * @return The ISO date formatted timestamp of when the previous answer to the prompt was created. - */ - public Date getCreatedAt() { - return createdAt; - } + /** + * Get The ISO date formatted timestamp of when the previous answer to the prompt was created. + * + * @return The ISO date formatted timestamp of when the previous answer to the prompt was created. + */ + public Date getCreatedAt() { + return createdAt; + } - /** - * Set The ISO date formatted timestamp of when the previous answer to the prompt was created. - * @param createdAt The ISO date formatted timestamp of when the previous answer to the prompt was created. - */ - public void setCreatedAt(Date createdAt) { - this.createdAt = createdAt; - } + /** + * Set The ISO date formatted timestamp of when the previous answer to the prompt was created. + * + * @param createdAt The ISO date formatted timestamp of when the previous answer to the prompt was + * created. + */ + public void setCreatedAt(Date createdAt) { + this.createdAt = createdAt; + } - /** - * Gets a JSON object representing this class. - * - * @return the JSON object representing this class. - */ - public JsonObject getJSONObject() { - JsonObject itemJSON = new JsonObject() - .add("prompt", this.prompt) - .add("answer", this.answer); + /** + * Gets a JSON object representing this class. + * + * @return the JSON object representing this class. + */ + public JsonObject getJSONObject() { + JsonObject itemJSON = new JsonObject().add("prompt", this.prompt).add("answer", this.answer); - if (this.createdAt != null) { - itemJSON.add("created_at", BoxDateFormat.format(this.createdAt)); - } - - return itemJSON; + if (this.createdAt != null) { + itemJSON.add("created_at", BoxDateFormat.format(this.createdAt)); } + + return itemJSON; + } } diff --git a/src/main/java/com/box/sdk/BoxAIExtractField.java b/src/main/java/com/box/sdk/BoxAIExtractField.java index 4aba85906..6280106b4 100644 --- a/src/main/java/com/box/sdk/BoxAIExtractField.java +++ b/src/main/java/com/box/sdk/BoxAIExtractField.java @@ -6,76 +6,70 @@ import java.util.List; public class BoxAIExtractField extends BoxJSONObject { - /** - * The type of the field. It include but is not limited to string, float, date, enum, and multiSelect. - */ - private String type; - /** - * The description of the field. - */ - private String description; - /** - * The display name of the field. - */ - private String displayName; - /** - * The key of the field. - */ - private String key; - /** - * A list of options for this field. - * This is most often used in combination with the enum and multiSelect field types. - */ - private List options; - /** - * The prompt of the field. - */ - private String prompt; + /** + * The type of the field. It include but is not limited to string, float, date, enum, and + * multiSelect. + */ + private String type; + /** The description of the field. */ + private String description; + /** The display name of the field. */ + private String displayName; + /** The key of the field. */ + private String key; + /** + * A list of options for this field. This is most often used in combination with the enum and + * multiSelect field types. + */ + private List options; + /** The prompt of the field. */ + private String prompt; - /** - * Constructs a BoxAIExtractField object with a given key. - */ - public BoxAIExtractField(String key) { - this.key = key; - } + /** Constructs a BoxAIExtractField object with a given key. */ + public BoxAIExtractField(String key) { + this.key = key; + } - /** - * Constructs a BoxAIExtractField object with a given type, description, display name, key, options, and prompt. - * - * @param type the type of the field. - * @param description the description of the field. - * @param displayName the display name of the field. - * @param key the key of the field. - * @param options a list of options for this field. - * @param prompt the prompt of the field. - */ - public BoxAIExtractField(String type, - String description, - String displayName, - String key, List options, - String prompt) { - this.type = type; - this.description = description; - this.displayName = displayName; - this.key = key; - this.options = options; - this.prompt = prompt; - } + /** + * Constructs a BoxAIExtractField object with a given type, description, display name, key, + * options, and prompt. + * + * @param type the type of the field. + * @param description the description of the field. + * @param displayName the display name of the field. + * @param key the key of the field. + * @param options a list of options for this field. + * @param prompt the prompt of the field. + */ + public BoxAIExtractField( + String type, + String description, + String displayName, + String key, + List options, + String prompt) { + this.type = type; + this.description = description; + this.displayName = displayName; + this.key = key; + this.options = options; + this.prompt = prompt; + } - public JsonObject getJSONObject() { - JsonObject jsonObject = new JsonObject(); - JsonUtils.addIfNotNull(jsonObject, "type", this.type); - JsonUtils.addIfNotNull(jsonObject, "description", this.description); - JsonUtils.addIfNotNull(jsonObject, "displayName", this.displayName); - JsonUtils.addIfNotNull(jsonObject, "key", this.key); - if (this.options != null) { - JsonArray options = new JsonArray(); - for (BoxAIExtractFieldOption option : this.options) { - options.add(option.getJSONObject()); - } - jsonObject.add("options", options); - } - JsonUtils.addIfNotNull(jsonObject, "prompt", this.prompt); - return jsonObject; + public JsonObject getJSONObject() { + JsonObject jsonObject = new JsonObject(); + JsonUtils.addIfNotNull(jsonObject, "type", this.type); + JsonUtils.addIfNotNull(jsonObject, "description", this.description); + JsonUtils.addIfNotNull(jsonObject, "displayName", this.displayName); + JsonUtils.addIfNotNull(jsonObject, "key", this.key); + if (this.options != null) { + JsonArray options = new JsonArray(); + for (BoxAIExtractFieldOption option : this.options) { + options.add(option.getJSONObject()); + } + jsonObject.add("options", options); } + JsonUtils.addIfNotNull(jsonObject, "prompt", this.prompt); + return jsonObject; + } } diff --git a/src/main/java/com/box/sdk/BoxAIExtractFieldOption.java b/src/main/java/com/box/sdk/BoxAIExtractFieldOption.java index a1cae5ceb..81779d709 100644 --- a/src/main/java/com/box/sdk/BoxAIExtractFieldOption.java +++ b/src/main/java/com/box/sdk/BoxAIExtractFieldOption.java @@ -1,27 +1,24 @@ package com.box.sdk; - import com.box.sdk.internal.utils.JsonUtils; import com.eclipsesource.json.JsonObject; public class BoxAIExtractFieldOption extends BoxJSONObject { - /** - * A unique identifier for the option. - */ - private final String key; + /** A unique identifier for the option. */ + private final String key; - /** - * Constructs a BoxAIExtractFieldOption object with a given key. - * - * @param key the key of the field option. - */ - public BoxAIExtractFieldOption(String key) { - this.key = key; - } + /** + * Constructs a BoxAIExtractFieldOption object with a given key. + * + * @param key the key of the field option. + */ + public BoxAIExtractFieldOption(String key) { + this.key = key; + } - public JsonObject getJSONObject() { - JsonObject jsonObject = new JsonObject(); - JsonUtils.addIfNotNull(jsonObject, "key", this.key); - return jsonObject; - } + public JsonObject getJSONObject() { + JsonObject jsonObject = new JsonObject(); + JsonUtils.addIfNotNull(jsonObject, "key", this.key); + return jsonObject; + } } diff --git a/src/main/java/com/box/sdk/BoxAIExtractMetadataTemplate.java b/src/main/java/com/box/sdk/BoxAIExtractMetadataTemplate.java index c7fb4c3da..3eeb80a60 100644 --- a/src/main/java/com/box/sdk/BoxAIExtractMetadataTemplate.java +++ b/src/main/java/com/box/sdk/BoxAIExtractMetadataTemplate.java @@ -4,53 +4,48 @@ import com.eclipsesource.json.JsonObject; public class BoxAIExtractMetadataTemplate extends BoxJSONObject { - /** - * The type of object this class represents. - */ - public static final String TYPE = "metadata_template"; - /** - * The scope of the metadata template that can either be global or enterprise. - */ - private String scope; - /** - * The template key of the metadata template. - */ - private String templateKey; + /** The type of object this class represents. */ + public static final String TYPE = "metadata_template"; + /** The scope of the metadata template that can either be global or enterprise. */ + private String scope; + /** The template key of the metadata template. */ + private String templateKey; - /** - * Constructs a BoxAIExtractMetadataTemplate object with a given scope and template key. - * @param templateKey the template key of the metadata template. - * @param scope the scope of the metadata template. - */ - public BoxAIExtractMetadataTemplate(String templateKey, String scope) { - this.templateKey = templateKey; - this.scope = scope; - } + /** + * Constructs a BoxAIExtractMetadataTemplate object with a given scope and template key. + * + * @param templateKey the template key of the metadata template. + * @param scope the scope of the metadata template. + */ + public BoxAIExtractMetadataTemplate(String templateKey, String scope) { + this.templateKey = templateKey; + this.scope = scope; + } - @Override - void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - String memberName = member.getName(); - if (memberName.equals("scope")) { - this.scope = member.getValue().asString(); - } else if (memberName.equals("template_key")) { - this.templateKey = member.getValue().asString(); - } + @Override + void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + String memberName = member.getName(); + if (memberName.equals("scope")) { + this.scope = member.getValue().asString(); + } else if (memberName.equals("template_key")) { + this.templateKey = member.getValue().asString(); } + } - public JsonObject getJSONObject() { - JsonObject jsonObject = new JsonObject(); - JsonUtils.addIfNotNull(jsonObject, "type", TYPE); - JsonUtils.addIfNotNull(jsonObject, "scope", this.scope); - JsonUtils.addIfNotNull(jsonObject, "template_key", this.templateKey); - return jsonObject; - } + public JsonObject getJSONObject() { + JsonObject jsonObject = new JsonObject(); + JsonUtils.addIfNotNull(jsonObject, "type", TYPE); + JsonUtils.addIfNotNull(jsonObject, "scope", this.scope); + JsonUtils.addIfNotNull(jsonObject, "template_key", this.templateKey); + return jsonObject; + } - public String getScope() { - return this.scope; - } + public String getScope() { + return this.scope; + } - public String getTemplateKey() { - return this.templateKey; - } + public String getTemplateKey() { + return this.templateKey; + } } diff --git a/src/main/java/com/box/sdk/BoxAIExtractStructuredResponse.java b/src/main/java/com/box/sdk/BoxAIExtractStructuredResponse.java index e92b10af6..f7f0991fa 100644 --- a/src/main/java/com/box/sdk/BoxAIExtractStructuredResponse.java +++ b/src/main/java/com/box/sdk/BoxAIExtractStructuredResponse.java @@ -6,87 +6,80 @@ import java.text.ParseException; import java.util.Date; -/** - * AI response to a user request. - */ +/** AI response to a user request. */ public class BoxAIExtractStructuredResponse extends BoxJSONObject { - private final JsonObject sourceJson; - private JsonObject answer; - private String completionReason; - private Date createdAt; + private final JsonObject sourceJson; + private JsonObject answer; + private String completionReason; + private Date createdAt; - /** - * Constructs a BoxAIResponse object. - */ - public BoxAIExtractStructuredResponse(String json) { - super(json); - this.sourceJson = Json.parse(json).asObject(); - } + /** Constructs a BoxAIResponse object. */ + public BoxAIExtractStructuredResponse(String json) { + super(json); + this.sourceJson = Json.parse(json).asObject(); + } - /** - * Constructs an BoxAIResponse object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - BoxAIExtractStructuredResponse(JsonObject jsonObject) { - super(jsonObject); - this.sourceJson = jsonObject; - } + /** + * Constructs an BoxAIResponse object using an already parsed JSON object. + * + * @param jsonObject the parsed JSON object. + */ + BoxAIExtractStructuredResponse(JsonObject jsonObject) { + super(jsonObject); + this.sourceJson = jsonObject; + } - /** - * Gets the source JSON of the AI response. - * - * @return the source JSON of the AI response. - */ - public JsonObject getSourceJson() { - return sourceJson; - } + /** + * Gets the source JSON of the AI response. + * + * @return the source JSON of the AI response. + */ + public JsonObject getSourceJson() { + return sourceJson; + } - /** - * Gets the answer of the AI. - * - * @return the answer of the AI. - */ - public JsonObject getAnswer() { - return answer; - } + /** + * Gets the answer of the AI. + * + * @return the answer of the AI. + */ + public JsonObject getAnswer() { + return answer; + } - /** - * Gets reason the response finishes. - * - * @return the reason the response finishes. - */ - public String getCompletionReason() { - return completionReason; - } + /** + * Gets reason the response finishes. + * + * @return the reason the response finishes. + */ + public String getCompletionReason() { + return completionReason; + } - /** - * Gets the ISO date formatted timestamp of when the answer to the prompt was created. - * - * @return The ISO date formatted timestamp of when the answer to the prompt was created. - */ - public Date getCreatedAt() { - return createdAt; - } + /** + * Gets the ISO date formatted timestamp of when the answer to the prompt was created. + * + * @return The ISO date formatted timestamp of when the answer to the prompt was created. + */ + public Date getCreatedAt() { + return createdAt; + } - /** - * {@inheritDoc} - */ - @Override - void parseJSONMember(JsonObject.Member member) { - JsonValue value = member.getValue(); - String memberName = member.getName(); - try { - if (memberName.equals("answer")) { - this.answer = value.asObject(); - } else if (memberName.equals("completion_reason")) { - this.completionReason = value.asString(); - } else if (memberName.equals("created_at")) { - this.createdAt = BoxDateFormat.parse(value.asString()); - } - } catch (ParseException e) { - assert false : "A ParseException indicates a bug in the SDK."; - } + /** {@inheritDoc} */ + @Override + void parseJSONMember(JsonObject.Member member) { + JsonValue value = member.getValue(); + String memberName = member.getName(); + try { + if (memberName.equals("answer")) { + this.answer = value.asObject(); + } else if (memberName.equals("completion_reason")) { + this.completionReason = value.asString(); + } else if (memberName.equals("created_at")) { + this.createdAt = BoxDateFormat.parse(value.asString()); + } + } catch (ParseException e) { + assert false : "A ParseException indicates a bug in the SDK."; } - + } } diff --git a/src/main/java/com/box/sdk/BoxAIItem.java b/src/main/java/com/box/sdk/BoxAIItem.java index 49fabb1e6..d89311c7c 100644 --- a/src/main/java/com/box/sdk/BoxAIItem.java +++ b/src/main/java/com/box/sdk/BoxAIItem.java @@ -2,120 +2,121 @@ import com.eclipsesource.json.JsonObject; -/** - * Represents a Box File to be included in a sign request. - */ +/** Represents a Box File to be included in a sign request. */ public class BoxAIItem { - private String id; - private Type type; - private String content; - - /** - * Created a BoxAIItem - the item to be processed by the LLM. - * @param id The id of the item - * @param type The type of the item. Currently, only "file" is supported. - * @param content The content of the item, often the text representation. - */ - public BoxAIItem(String id, Type type, String content) { - this.id = id; - this.type = type; - this.content = content; + private String id; + private Type type; + private String content; + + /** + * Created a BoxAIItem - the item to be processed by the LLM. + * + * @param id The id of the item + * @param type The type of the item. Currently, only "file" is supported. + * @param content The content of the item, often the text representation. + */ + public BoxAIItem(String id, Type type, String content) { + this.id = id; + this.type = type; + this.content = content; + } + + /** + * Created a BoxAIItem - the item to be processed by the LLM. + * + * @param id The id of the item + * @param type The type of the item. Currently, only "file" is supported. + */ + public BoxAIItem(String id, Type type) { + this.id = id; + this.type = type; + } + + /** + * Gets the id of the item. + * + * @return the id of the item. + */ + public String getId() { + return id; + } + + /** + * Sets the id of the item. + * + * @param id the id of the item. + */ + public void setId(String id) { + this.id = id; + } + + /** + * Gets the type of the item. + * + * @return the type of the item. + */ + public Type getType() { + return type; + } + + /** + * Sets the type of the item. + * + * @param type the type of the item. + */ + public void setType(Type type) { + this.type = type; + } + + /** + * Gets the content of the item. + * + * @return the content of the item. + */ + public String getContent() { + return content; + } + + /** + * Sets the content of the item. + * + * @param content the content of the item. + */ + public void setContent(String content) { + this.content = content; + } + + /** + * Gets a JSON object representing this class. + * + * @return the JSON object representing this class. + */ + public JsonObject getJSONObject() { + JsonObject itemJSON = new JsonObject().add("id", this.id).add("type", this.type.toJSONValue()); + + if (this.content != null) { + itemJSON.add("content", this.content); } - /** - * Created a BoxAIItem - the item to be processed by the LLM. - * @param id The id of the item - * @param type The type of the item. Currently, only "file" is supported. - */ - public BoxAIItem(String id, Type type) { - this.id = id; - this.type = type; - } - - /** - * Gets the id of the item. - * @return the id of the item. - */ - public String getId() { - return id; - } - - /** - * Sets the id of the item. - * @param id the id of the item. - */ - public void setId(String id) { - this.id = id; - } - - /** - * Gets the type of the item. - * @return the type of the item. - */ - public Type getType() { - return type; - } + return itemJSON; + } - /** - * Sets the type of the item. - * @param type the type of the item. - */ - public void setType(Type type) { - this.type = type; - } + public enum Type { + /** A file. */ + FILE("file"); - /** - * Gets the content of the item. - * @return the content of the item. - */ - public String getContent() { - return content; - } + private final String jsonValue; - /** - * Sets the content of the item. - * @param content the content of the item. - */ - public void setContent(String content) { - this.content = content; + Type(String jsonValue) { + this.jsonValue = jsonValue; } - /** - * Gets a JSON object representing this class. - * - * @return the JSON object representing this class. - */ - public JsonObject getJSONObject() { - JsonObject itemJSON = new JsonObject() - .add("id", this.id) - .add("type", this.type.toJSONValue()); - - if (this.content != null) { - itemJSON.add("content", this.content); - } - - return itemJSON; + static BoxAIItem.Type fromJSONValue(String jsonValue) { + return BoxAIItem.Type.valueOf(jsonValue.toUpperCase(java.util.Locale.ROOT)); } - public enum Type { - /** - * A file. - */ - FILE("file"); - - - private final String jsonValue; - - Type(String jsonValue) { - this.jsonValue = jsonValue; - } - - static BoxAIItem.Type fromJSONValue(String jsonValue) { - return BoxAIItem.Type.valueOf(jsonValue.toUpperCase(java.util.Locale.ROOT)); - } - - String toJSONValue() { - return this.jsonValue; - } + String toJSONValue() { + return this.jsonValue; } + } } diff --git a/src/main/java/com/box/sdk/BoxAIResponse.java b/src/main/java/com/box/sdk/BoxAIResponse.java index c563bdf53..a6849425d 100644 --- a/src/main/java/com/box/sdk/BoxAIResponse.java +++ b/src/main/java/com/box/sdk/BoxAIResponse.java @@ -5,88 +5,80 @@ import java.text.ParseException; import java.util.Date; - -/** - * AI response to a user request. - */ +/** AI response to a user request. */ public class BoxAIResponse extends BoxJSONObject { - private String answer; - private String completionReason; - private Date createdAt; - - /** - * Constructs a BoxAIResponse object. - */ - public BoxAIResponse(String answer, String completionReason, Date createdAt) { - super(); - this.answer = answer; - this.completionReason = completionReason; - this.createdAt = createdAt; - } + private String answer; + private String completionReason; + private Date createdAt; - /** - * Constructs a BoxAIResponse from a JSON string. - * - * @param json the JSON encoded upload email. - */ - public BoxAIResponse(String json) { - super(json); - } + /** Constructs a BoxAIResponse object. */ + public BoxAIResponse(String answer, String completionReason, Date createdAt) { + super(); + this.answer = answer; + this.completionReason = completionReason; + this.createdAt = createdAt; + } - /** - * Constructs an BoxAIResponse object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - BoxAIResponse(JsonObject jsonObject) { - super(jsonObject); - } + /** + * Constructs a BoxAIResponse from a JSON string. + * + * @param json the JSON encoded upload email. + */ + public BoxAIResponse(String json) { + super(json); + } - /** - * Gets the answer of the AI. - * - * @return the answer of the AI. - */ - public String getAnswer() { - return answer; - } + /** + * Constructs an BoxAIResponse object using an already parsed JSON object. + * + * @param jsonObject the parsed JSON object. + */ + BoxAIResponse(JsonObject jsonObject) { + super(jsonObject); + } - /** - * Gets reason the response finishes. - * - * @return the reason the response finishes. - */ - public String getCompletionReason() { - return completionReason; - } + /** + * Gets the answer of the AI. + * + * @return the answer of the AI. + */ + public String getAnswer() { + return answer; + } - /** - * Gets the ISO date formatted timestamp of when the answer to the prompt was created. - * - * @return The ISO date formatted timestamp of when the answer to the prompt was created. - */ - public Date getCreatedAt() { - return createdAt; - } + /** + * Gets reason the response finishes. + * + * @return the reason the response finishes. + */ + public String getCompletionReason() { + return completionReason; + } + /** + * Gets the ISO date formatted timestamp of when the answer to the prompt was created. + * + * @return The ISO date formatted timestamp of when the answer to the prompt was created. + */ + public Date getCreatedAt() { + return createdAt; + } - /** - * {@inheritDoc} - */ - @Override - void parseJSONMember(JsonObject.Member member) { - JsonValue value = member.getValue(); - String memberName = member.getName(); - try { - if (memberName.equals("answer")) { - this.answer = value.asString(); - } else if (memberName.equals("completion_reason")) { - this.completionReason = value.asString(); - } else if (memberName.equals("created_at")) { - this.createdAt = BoxDateFormat.parse(value.asString()); - } - } catch (ParseException e) { - assert false : "A ParseException indicates a bug in the SDK."; - } + /** {@inheritDoc} */ + @Override + void parseJSONMember(JsonObject.Member member) { + JsonValue value = member.getValue(); + String memberName = member.getName(); + try { + if (memberName.equals("answer")) { + this.answer = value.asString(); + } else if (memberName.equals("completion_reason")) { + this.completionReason = value.asString(); + } else if (memberName.equals("created_at")) { + this.createdAt = BoxDateFormat.parse(value.asString()); + } + } catch (ParseException e) { + assert false : "A ParseException indicates a bug in the SDK."; } + } } diff --git a/src/main/java/com/box/sdk/BoxAPIConnection.java b/src/main/java/com/box/sdk/BoxAPIConnection.java index aca2913a2..fd5d69a61 100644 --- a/src/main/java/com/box/sdk/BoxAPIConnection.java +++ b/src/main/java/com/box/sdk/BoxAPIConnection.java @@ -39,1097 +39,1133 @@ /** * Represents an authenticated connection to the Box API. * - *

This class handles storing authentication information, automatic token refresh, and rate-limiting. It can also be - * used to configure the Box API endpoint URL in order to hit a different version of the API. Multiple instances of - * BoxAPIConnection may be created to support multi-user login.

+ *

This class handles storing authentication information, automatic token refresh, and + * rate-limiting. It can also be used to configure the Box API endpoint URL in order to hit a + * different version of the API. Multiple instances of BoxAPIConnection may be created to support + * multi-user login. */ public class BoxAPIConnection { - /** - * Used as a marker to setup connection to use default HostnameVerifier - * Example:

{@code
-     * BoxApiConnection api = new BoxApiConnection(...);
-     * HostnameVerifier myHostnameVerifier = ...
-     * api.configureSslCertificatesValidation(DEFAULT_TRUST_MANAGER, myHostnameVerifier);
-     * }
- */ - public static final X509TrustManager DEFAULT_TRUST_MANAGER = null; - /** - * Used as a marker to setup connection to use default HostnameVerifier - * Example:
{@code
-     * BoxApiConnection api = new BoxApiConnection(...);
-     * X509TrustManager myTrustManager = ...
-     * api.configureSslCertificatesValidation(myTrustManager, DEFAULT_HOSTNAME_VERIFIER);
-     * }
- */ - public static final HostnameVerifier DEFAULT_HOSTNAME_VERIFIER = null; - - /** - * The default maximum number of times an API request will be retried after an error response - * is received. - */ - public static final int DEFAULT_MAX_RETRIES = 5; - /** - * Default authorization URL - */ - protected static final String DEFAULT_BASE_AUTHORIZATION_URL = "https://account.box.com/api/"; - static final String AS_USER_HEADER = "As-User"; - - private static final String API_VERSION = "2.0"; - private static final String OAUTH_SUFFIX = "oauth2/authorize"; - private static final String TOKEN_URL_SUFFIX = "oauth2/token"; - private static final String REVOKE_URL_SUFFIX = "oauth2/revoke"; - private static final String DEFAULT_BASE_URL = "https://api.box.com/"; - private static final String DEFAULT_BASE_UPLOAD_URL = "https://upload.box.com/api/"; - private static final String DEFAULT_BASE_APP_URL = "https://app.box.com"; - - private static final String BOX_NOTIFICATIONS_HEADER = "Box-Notifications"; - - private static final String JAVA_VERSION = System.getProperty("java.version"); - private static final String SDK_VERSION = "4.16.3"; - - /** - * The amount of buffer time, in milliseconds, to use when determining if an access token should be refreshed. For - * example, if REFRESH_EPSILON = 60000 and the access token expires in less than one minute, it will be refreshed. - */ - private static final long REFRESH_EPSILON = 60000; - - private final String clientID; - private final String clientSecret; - private final ReadWriteLock refreshLock; - private X509TrustManager trustManager; - private HostnameVerifier hostnameVerifier; - - // These volatile fields are used when determining if the access token needs to be refreshed. Since they are used in - // the double-checked lock in getAccessToken(), they must be atomic. - private volatile long lastRefresh; - private volatile long expires; - - private Proxy proxy; - private String proxyUsername; - private String proxyPassword; - - private String userAgent; - private String accessToken; - private String refreshToken; - private String tokenURL; - private String revokeURL; - private String baseURL; - private String baseUploadURL; - private String baseAppURL; - private String baseAuthorizationURL; - private boolean autoRefresh; - private int maxRetryAttempts; - private int connectTimeout; - private int readTimeout; - private boolean useZstdCompression; - private final List listeners; - private RequestInterceptor interceptor; - private final Map customHeaders; - - private OkHttpClient httpClient; - private OkHttpClient noRedirectsHttpClient; - private Authenticator authenticator; - - /** - * Constructs a new BoxAPIConnection that authenticates with a developer or access token. - * - * @param accessToken a developer or access token to use for authenticating with the API. - */ - public BoxAPIConnection(String accessToken) { - this(null, null, accessToken, null); - } - - /** - * Constructs a new BoxAPIConnection with an access token that can be refreshed. - * - * @param clientID the client ID to use when refreshing the access token. - * @param clientSecret the client secret to use when refreshing the access token. - * @param accessToken an initial access token to use for authenticating with the API. - * @param refreshToken an initial refresh token to use when refreshing the access token. - */ - public BoxAPIConnection(String clientID, String clientSecret, String accessToken, String refreshToken) { - this.clientID = clientID; - this.clientSecret = clientSecret; - this.accessToken = accessToken; - this.refreshToken = refreshToken; - this.baseURL = fixBaseUrl(DEFAULT_BASE_URL); - this.baseUploadURL = fixBaseUrl(DEFAULT_BASE_UPLOAD_URL); - this.baseAppURL = DEFAULT_BASE_APP_URL; - this.baseAuthorizationURL = DEFAULT_BASE_AUTHORIZATION_URL; - this.autoRefresh = true; - this.maxRetryAttempts = BoxGlobalSettings.getMaxRetryAttempts(); - this.connectTimeout = BoxGlobalSettings.getConnectTimeout(); - this.readTimeout = BoxGlobalSettings.getReadTimeout(); - this.useZstdCompression = BoxGlobalSettings.getUseZstdCompression(); - this.refreshLock = new ReentrantReadWriteLock(); - this.userAgent = "Box Java SDK v" + SDK_VERSION + " (Java " + JAVA_VERSION + ")"; - this.listeners = new ArrayList<>(); - this.customHeaders = new HashMap<>(); - - buildHttpClients(); - } - - /** - * Constructs a new BoxAPIConnection with an auth code that was obtained from the first half of OAuth. - * - * @param clientID the client ID to use when exchanging the auth code for an access token. - * @param clientSecret the client secret to use when exchanging the auth code for an access token. - * @param authCode an auth code obtained from the first half of the OAuth process. - */ - public BoxAPIConnection(String clientID, String clientSecret, String authCode) { - this(clientID, clientSecret, null, null); - this.authenticate(authCode); - } - - /** - * Constructs a new BoxAPIConnection. - * - * @param clientID the client ID to use when exchanging the auth code for an access token. - * @param clientSecret the client secret to use when exchanging the auth code for an access token. - */ - public BoxAPIConnection(String clientID, String clientSecret) { - this(clientID, clientSecret, null, null); - } - - /** - * Constructs a new BoxAPIConnection levaraging BoxConfig. - * - * @param boxConfig BoxConfig file, which should have clientId and clientSecret - */ - public BoxAPIConnection(BoxConfig boxConfig) { - this(boxConfig.getClientId(), boxConfig.getClientSecret(), null, null); - } - - private void buildHttpClients() { - OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder(); - if (trustManager != null) { - try { - SSLContext sslContext = SSLContext.getInstance("SSL"); - sslContext.init(null, new TrustManager[]{trustManager}, new java.security.SecureRandom()); - httpClientBuilder.sslSocketFactory(sslContext.getSocketFactory(), trustManager); - } catch (NoSuchAlgorithmException | KeyManagementException e) { - throw new RuntimeException(e); - } - } - - OkHttpClient.Builder builder = httpClientBuilder + /** + * Used as a marker to setup connection to use default HostnameVerifier Example: + * + *
{@code
+   * BoxApiConnection api = new BoxApiConnection(...);
+   * HostnameVerifier myHostnameVerifier = ...
+   * api.configureSslCertificatesValidation(DEFAULT_TRUST_MANAGER, myHostnameVerifier);
+   * }
+ */ + public static final X509TrustManager DEFAULT_TRUST_MANAGER = null; + /** + * Used as a marker to setup connection to use default HostnameVerifier Example: + * + *
{@code
+   * BoxApiConnection api = new BoxApiConnection(...);
+   * X509TrustManager myTrustManager = ...
+   * api.configureSslCertificatesValidation(myTrustManager, DEFAULT_HOSTNAME_VERIFIER);
+   * }
+ */ + public static final HostnameVerifier DEFAULT_HOSTNAME_VERIFIER = null; + + /** + * The default maximum number of times an API request will be retried after an error response is + * received. + */ + public static final int DEFAULT_MAX_RETRIES = 5; + /** Default authorization URL */ + protected static final String DEFAULT_BASE_AUTHORIZATION_URL = "https://account.box.com/api/"; + + static final String AS_USER_HEADER = "As-User"; + + private static final String API_VERSION = "2.0"; + private static final String OAUTH_SUFFIX = "oauth2/authorize"; + private static final String TOKEN_URL_SUFFIX = "oauth2/token"; + private static final String REVOKE_URL_SUFFIX = "oauth2/revoke"; + private static final String DEFAULT_BASE_URL = "https://api.box.com/"; + private static final String DEFAULT_BASE_UPLOAD_URL = "https://upload.box.com/api/"; + private static final String DEFAULT_BASE_APP_URL = "https://app.box.com"; + + private static final String BOX_NOTIFICATIONS_HEADER = "Box-Notifications"; + + private static final String JAVA_VERSION = System.getProperty("java.version"); + private static final String SDK_VERSION = "4.16.3"; + + /** + * The amount of buffer time, in milliseconds, to use when determining if an access token should + * be refreshed. For example, if REFRESH_EPSILON = 60000 and the access token expires in less than + * one minute, it will be refreshed. + */ + private static final long REFRESH_EPSILON = 60000; + + private final String clientID; + private final String clientSecret; + private final ReadWriteLock refreshLock; + private X509TrustManager trustManager; + private HostnameVerifier hostnameVerifier; + + // These volatile fields are used when determining if the access token needs to be refreshed. + // Since they are used in + // the double-checked lock in getAccessToken(), they must be atomic. + private volatile long lastRefresh; + private volatile long expires; + + private Proxy proxy; + private String proxyUsername; + private String proxyPassword; + + private String userAgent; + private String accessToken; + private String refreshToken; + private String tokenURL; + private String revokeURL; + private String baseURL; + private String baseUploadURL; + private String baseAppURL; + private String baseAuthorizationURL; + private boolean autoRefresh; + private int maxRetryAttempts; + private int connectTimeout; + private int readTimeout; + private boolean useZstdCompression; + private final List listeners; + private RequestInterceptor interceptor; + private final Map customHeaders; + + private OkHttpClient httpClient; + private OkHttpClient noRedirectsHttpClient; + private Authenticator authenticator; + + /** + * Constructs a new BoxAPIConnection that authenticates with a developer or access token. + * + * @param accessToken a developer or access token to use for authenticating with the API. + */ + public BoxAPIConnection(String accessToken) { + this(null, null, accessToken, null); + } + + /** + * Constructs a new BoxAPIConnection with an access token that can be refreshed. + * + * @param clientID the client ID to use when refreshing the access token. + * @param clientSecret the client secret to use when refreshing the access token. + * @param accessToken an initial access token to use for authenticating with the API. + * @param refreshToken an initial refresh token to use when refreshing the access token. + */ + public BoxAPIConnection( + String clientID, String clientSecret, String accessToken, String refreshToken) { + this.clientID = clientID; + this.clientSecret = clientSecret; + this.accessToken = accessToken; + this.refreshToken = refreshToken; + this.baseURL = fixBaseUrl(DEFAULT_BASE_URL); + this.baseUploadURL = fixBaseUrl(DEFAULT_BASE_UPLOAD_URL); + this.baseAppURL = DEFAULT_BASE_APP_URL; + this.baseAuthorizationURL = DEFAULT_BASE_AUTHORIZATION_URL; + this.autoRefresh = true; + this.maxRetryAttempts = BoxGlobalSettings.getMaxRetryAttempts(); + this.connectTimeout = BoxGlobalSettings.getConnectTimeout(); + this.readTimeout = BoxGlobalSettings.getReadTimeout(); + this.useZstdCompression = BoxGlobalSettings.getUseZstdCompression(); + this.refreshLock = new ReentrantReadWriteLock(); + this.userAgent = "Box Java SDK v" + SDK_VERSION + " (Java " + JAVA_VERSION + ")"; + this.listeners = new ArrayList<>(); + this.customHeaders = new HashMap<>(); + + buildHttpClients(); + } + + /** + * Constructs a new BoxAPIConnection with an auth code that was obtained from the first half of + * OAuth. + * + * @param clientID the client ID to use when exchanging the auth code for an access token. + * @param clientSecret the client secret to use when exchanging the auth code for an access token. + * @param authCode an auth code obtained from the first half of the OAuth process. + */ + public BoxAPIConnection(String clientID, String clientSecret, String authCode) { + this(clientID, clientSecret, null, null); + this.authenticate(authCode); + } + + /** + * Constructs a new BoxAPIConnection. + * + * @param clientID the client ID to use when exchanging the auth code for an access token. + * @param clientSecret the client secret to use when exchanging the auth code for an access token. + */ + public BoxAPIConnection(String clientID, String clientSecret) { + this(clientID, clientSecret, null, null); + } + + /** + * Constructs a new BoxAPIConnection levaraging BoxConfig. + * + * @param boxConfig BoxConfig file, which should have clientId and clientSecret + */ + public BoxAPIConnection(BoxConfig boxConfig) { + this(boxConfig.getClientId(), boxConfig.getClientSecret(), null, null); + } + + private void buildHttpClients() { + OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder(); + if (trustManager != null) { + try { + SSLContext sslContext = SSLContext.getInstance("SSL"); + sslContext.init(null, new TrustManager[] {trustManager}, new java.security.SecureRandom()); + httpClientBuilder.sslSocketFactory(sslContext.getSocketFactory(), trustManager); + } catch (NoSuchAlgorithmException | KeyManagementException e) { + throw new RuntimeException(e); + } + } + + OkHttpClient.Builder builder = + httpClientBuilder .followSslRedirects(true) .followRedirects(true) .connectTimeout(Duration.ofMillis(connectTimeout)) .readTimeout(Duration.ofMillis(readTimeout)) .connectionSpecs(singletonList(MODERN_TLS)); - if (hostnameVerifier != null) { - httpClientBuilder.hostnameVerifier(hostnameVerifier); - } - - if (proxy != null) { - builder.proxy(proxy); - if (proxyUsername != null && proxyPassword != null) { - builder.proxyAuthenticator((route, response) -> { - String credential = Credentials.basic(proxyUsername, proxyPassword); - return response.request().newBuilder() - .header("Proxy-Authorization", credential) - .build(); - }); - } - if (this.authenticator != null) { - builder.proxyAuthenticator(authenticator); - } - } - builder = modifyHttpClientBuilder(builder); - if (this.useZstdCompression) { - builder.addNetworkInterceptor(new ZstdInterceptor()); - } - - this.httpClient = builder.build(); - this.noRedirectsHttpClient = new OkHttpClient.Builder(httpClient) + if (hostnameVerifier != null) { + httpClientBuilder.hostnameVerifier(hostnameVerifier); + } + + if (proxy != null) { + builder.proxy(proxy); + if (proxyUsername != null && proxyPassword != null) { + builder.proxyAuthenticator( + (route, response) -> { + String credential = Credentials.basic(proxyUsername, proxyPassword); + return response + .request() + .newBuilder() + .header("Proxy-Authorization", credential) + .build(); + }); + } + if (this.authenticator != null) { + builder.proxyAuthenticator(authenticator); + } + } + builder = modifyHttpClientBuilder(builder); + if (this.useZstdCompression) { + builder.addNetworkInterceptor(new ZstdInterceptor()); + } + + this.httpClient = builder.build(); + this.noRedirectsHttpClient = + new OkHttpClient.Builder(httpClient) .followSslRedirects(false) .followRedirects(false) .build(); - } - - /** - * Can be used to modify OkHttp.Builder used to create connection. This method is called after all modifications - * were done, thus allowing others to create their own connections and further customize builder. - * @param httpClientBuilder Builder that will be used to create http connection. - * @return Modified builder. - */ - protected OkHttpClient.Builder modifyHttpClientBuilder(OkHttpClient.Builder httpClientBuilder) { - return httpClientBuilder; - } - - /** - * Sets a proxy authenticator that will be used when proxy requires authentication. - * If you use {@link BoxAPIConnection#setProxyBasicAuthentication(String, String)} it adds an authenticator - * that performs Basic authorization. By calling this method you can override this behaviour. - * You do not need to call {@link BoxAPIConnection#setProxyBasicAuthentication(String, String)} - * in order to set custom authenticator. - * - * @param authenticator Custom authenticator that will be called when proxy asks for authorization. - */ - public void setProxyAuthenticator(Authenticator authenticator) { - this.authenticator = authenticator; - buildHttpClients(); - } - - /** - * Restores a BoxAPIConnection from a saved state. - * - * @param clientID the client ID to use with the connection. - * @param clientSecret the client secret to use with the connection. - * @param state the saved state that was created with {@link #save}. - * @return a restored API connection. - * @see #save - */ - public static BoxAPIConnection restore(String clientID, String clientSecret, String state) { - BoxAPIConnection api = new BoxAPIConnection(clientID, clientSecret); - api.restore(state); - return api; - } - - /** - * Returns the default authorization URL which is used to perform the authorization_code based OAuth2 flow. - * If custom Authorization URL is needed use instance method {@link BoxAPIConnection#getAuthorizationURL} - * - * @param clientID the client ID to use with the connection. - * @param redirectUri the URL to which Box redirects the browser when authentication completes. - * @param state the text string that you choose. - * Box sends the same string to your redirect URL when authentication is complete. - * @param scopes this optional parameter identifies the Box scopes available - * to the application once it's authenticated. - * @return the authorization URL - */ - public static URL getAuthorizationURL(String clientID, URI redirectUri, String state, List scopes) { - return createFullAuthorizationUrl(DEFAULT_BASE_AUTHORIZATION_URL, clientID, redirectUri, state, scopes); - } - - private static URL createFullAuthorizationUrl( - String authorizationUrl, String clientID, URI redirectUri, String state, List scopes - ) { - URLTemplate template = new URLTemplate(authorizationUrl + OAUTH_SUFFIX); - QueryStringBuilder queryBuilder = new QueryStringBuilder().appendParam("client_id", clientID) + } + + /** + * Can be used to modify OkHttp.Builder used to create connection. This method is called after all + * modifications were done, thus allowing others to create their own connections and further + * customize builder. + * + * @param httpClientBuilder Builder that will be used to create http connection. + * @return Modified builder. + */ + protected OkHttpClient.Builder modifyHttpClientBuilder(OkHttpClient.Builder httpClientBuilder) { + return httpClientBuilder; + } + + /** + * Sets a proxy authenticator that will be used when proxy requires authentication. If you use + * {@link BoxAPIConnection#setProxyBasicAuthentication(String, String)} it adds an authenticator + * that performs Basic authorization. By calling this method you can override this behaviour. You + * do not need to call {@link BoxAPIConnection#setProxyBasicAuthentication(String, String)} in + * order to set custom authenticator. + * + * @param authenticator Custom authenticator that will be called when proxy asks for + * authorization. + */ + public void setProxyAuthenticator(Authenticator authenticator) { + this.authenticator = authenticator; + buildHttpClients(); + } + + /** + * Restores a BoxAPIConnection from a saved state. + * + * @param clientID the client ID to use with the connection. + * @param clientSecret the client secret to use with the connection. + * @param state the saved state that was created with {@link #save}. + * @return a restored API connection. + * @see #save + */ + public static BoxAPIConnection restore(String clientID, String clientSecret, String state) { + BoxAPIConnection api = new BoxAPIConnection(clientID, clientSecret); + api.restore(state); + return api; + } + + /** + * Returns the default authorization URL which is used to perform the authorization_code based + * OAuth2 flow. If custom Authorization URL is needed use instance method {@link + * BoxAPIConnection#getAuthorizationURL} + * + * @param clientID the client ID to use with the connection. + * @param redirectUri the URL to which Box redirects the browser when authentication completes. + * @param state the text string that you choose. Box sends the same string to your redirect URL + * when authentication is complete. + * @param scopes this optional parameter identifies the Box scopes available to the application + * once it's authenticated. + * @return the authorization URL + */ + public static URL getAuthorizationURL( + String clientID, URI redirectUri, String state, List scopes) { + return createFullAuthorizationUrl( + DEFAULT_BASE_AUTHORIZATION_URL, clientID, redirectUri, state, scopes); + } + + private static URL createFullAuthorizationUrl( + String authorizationUrl, + String clientID, + URI redirectUri, + String state, + List scopes) { + URLTemplate template = new URLTemplate(authorizationUrl + OAUTH_SUFFIX); + QueryStringBuilder queryBuilder = + new QueryStringBuilder() + .appendParam("client_id", clientID) .appendParam("response_type", "code") .appendParam("redirect_uri", redirectUri.toString()) .appendParam("state", state); - if (scopes != null && !scopes.isEmpty()) { - queryBuilder.appendParam("scope", join(" ", scopes)); - } - - return template.buildWithQuery("", queryBuilder.toString()); - } - - /** - * Authenticates the API connection by obtaining access and refresh tokens using the auth code that was obtained - * from the first half of OAuth. - * - * @param authCode the auth code obtained from the first half of the OAuth process. - */ - public void authenticate(String authCode) { - URL url; - try { - url = new URL(this.getTokenURL()); - } catch (MalformedURLException e) { - assert false : "An invalid token URL indicates a bug in the SDK."; - throw new RuntimeException("An invalid token URL indicates a bug in the SDK.", e); - } - - String urlParameters = format("grant_type=authorization_code&code=%s&client_id=%s&client_secret=%s", - authCode, this.clientID, this.clientSecret); - - BoxAPIRequest request = new BoxAPIRequest(this, url, "POST"); - request.shouldAuthenticate(false); - request.setBody(urlParameters); - - // authentication uses form url encoded but response is JSON - try (BoxJSONResponse response = (BoxJSONResponse) request.send()) { - String json = response.getJSON(); - - JsonObject jsonObject = Json.parse(json).asObject(); - this.accessToken = jsonObject.get("access_token").asString(); - this.refreshToken = jsonObject.get("refresh_token").asString(); - this.lastRefresh = System.currentTimeMillis(); - this.expires = jsonObject.get("expires_in").asLong() * 1000; - } - } - - /** - * Gets the client ID. - * - * @return the client ID. - */ - public String getClientID() { - return this.clientID; - } - - /** - * Gets the client secret. - * - * @return the client secret. - */ - public String getClientSecret() { - return this.clientSecret; - } - - /** - * Gets the amount of time for which this connection's access token is valid. - * - * @return the amount of time in milliseconds. - */ - public long getExpires() { - return this.expires; - } - - /** - * Sets the amount of time for which this connection's access token is valid before it must be refreshed. - * - * @param milliseconds the number of milliseconds for which the access token is valid. - */ - public void setExpires(long milliseconds) { - this.expires = milliseconds; - } - - /** - * Gets the token URL that's used to request access tokens. The default value is - * "https://www.box.com/api/oauth2/token". - * The URL is created from {@link BoxAPIConnection#baseURL} and {@link BoxAPIConnection#TOKEN_URL_SUFFIX}. - * - * @return the token URL. - */ - public String getTokenURL() { - if (this.tokenURL != null) { - return this.tokenURL; - } else { - return this.baseURL + TOKEN_URL_SUFFIX; - } - } - - /** - * Returns the URL used for token revocation. - * The URL is created from {@link BoxAPIConnection#baseURL} and {@link BoxAPIConnection#REVOKE_URL_SUFFIX}. - * - * @return The url used for token revocation. - */ - public String getRevokeURL() { - if (this.revokeURL != null) { - return this.revokeURL; - } else { - return this.baseURL + REVOKE_URL_SUFFIX; - } - } - - /** - * Gets the base URL that's used when sending requests to the Box API. - * The URL is created from {@link BoxAPIConnection#baseURL} and {@link BoxAPIConnection#API_VERSION}. - * The default value is "https://api.box.com/2.0/". - * - * @return the base URL. - */ - public String getBaseURL() { - return this.baseURL + API_VERSION + "/"; - } - - /** - * Sets the base URL to be used when sending requests to the Box API. For example, the default base URL is - * "https://api.box.com/". This method changes how {@link BoxAPIConnection#getRevokeURL()} - * and {@link BoxAPIConnection#getTokenURL()} are constructed. - * - * @param baseURL a base URL - */ - public void setBaseURL(String baseURL) { - this.baseURL = fixBaseUrl(baseURL); - } - - /** - * Gets the base upload URL that's used when performing file uploads to Box. - * The URL is created from {@link BoxAPIConnection#baseUploadURL} and {@link BoxAPIConnection#API_VERSION}. - * - * @return the base upload URL. - */ - public String getBaseUploadURL() { - return this.baseUploadURL + API_VERSION + "/"; - } - - /** - * Sets the base upload URL to be used when performing file uploads to Box. - * - * @param baseUploadURL a base upload URL. - */ - public void setBaseUploadURL(String baseUploadURL) { - this.baseUploadURL = fixBaseUrl(baseUploadURL); - } - - /** - * Returns the authorization URL which is used to perform the authorization_code based OAuth2 flow. - * The URL is created from {@link BoxAPIConnection#baseAuthorizationURL} and {@link BoxAPIConnection#OAUTH_SUFFIX}. - * - * @param redirectUri the URL to which Box redirects the browser when authentication completes. - * @param state the text string that you choose. - * Box sends the same string to your redirect URL when authentication is complete. - * @param scopes this optional parameter identifies the Box scopes available - * to the application once it's authenticated. - * @return the authorization URL - */ - public URL getAuthorizationURL(URI redirectUri, String state, List scopes) { - return createFullAuthorizationUrl(this.baseAuthorizationURL, this.clientID, redirectUri, state, scopes); - } - - /** - * Sets authorization base URL which is used to perform the authorization_code based OAuth2 flow. - * - * @param baseAuthorizationURL Authorization URL. Default value is https://account.box.com/api/. - */ - public void setBaseAuthorizationURL(String baseAuthorizationURL) { - this.baseAuthorizationURL = fixBaseUrl(baseAuthorizationURL); - } - - /** - * Gets the user agent that's used when sending requests to the Box API. - * - * @return the user agent. - */ - public String getUserAgent() { - return this.userAgent; - } - - /** - * Sets the user agent to be used when sending requests to the Box API. - * - * @param userAgent the user agent. - */ - public void setUserAgent(String userAgent) { - this.userAgent = userAgent; - } - - /** - * Gets the base App url. Used for e.g. file requests. - * - * @return the base App Url. - */ - public String getBaseAppUrl() { - return this.baseAppURL; - } - - /** - * Sets the base App url. Used for e.g. file requests. - * - * @param baseAppURL a base App Url. - */ - public void setBaseAppUrl(String baseAppURL) { - this.baseAppURL = baseAppURL; - } - - /** - * Gets an access token that can be used to authenticate an API request. This method will automatically refresh the - * access token if it has expired since the last call to getAccessToken(). - * - * @return a valid access token that can be used to authenticate an API request. - */ - public String getAccessToken() { - if (this.autoRefresh && this.canRefresh() && this.needsRefresh()) { - this.refreshLock.writeLock().lock(); - try { - if (this.needsRefresh()) { - this.refresh(); - } - } finally { - this.refreshLock.writeLock().unlock(); - } - } - - this.refreshLock.readLock().lock(); - try { - return this.accessToken; - } finally { - this.refreshLock.readLock().unlock(); - } - } - - /** - * Sets the access token to use when authenticating API requests. - * - * @param accessToken a valid access token to use when authenticating API requests. - */ - public void setAccessToken(String accessToken) { - this.accessToken = accessToken; - } - - /** - * Gets the refresh lock to be used when refreshing an access token. - * - * @return the refresh lock. - */ - protected ReadWriteLock getRefreshLock() { - return this.refreshLock; - } - - /** - * Gets a refresh token that can be used to refresh an access token. - * - * @return a valid refresh token. - */ - public String getRefreshToken() { - return this.refreshToken; - } - - /** - * Sets the refresh token to use when refreshing an access token. - * - * @param refreshToken a valid refresh token. - */ - public void setRefreshToken(String refreshToken) { - this.refreshToken = refreshToken; - } - - /** - * Gets the last time that the access token was refreshed. - * - * @return the last refresh time in milliseconds. - */ - public long getLastRefresh() { - return this.lastRefresh; - } - - /** - * Sets the last time that the access token was refreshed. - * - *

This value is used when determining if an access token needs to be auto-refreshed. If the amount of time since - * the last refresh exceeds the access token's expiration time, then the access token will be refreshed.

- * - * @param lastRefresh the new last refresh time in milliseconds. - */ - public void setLastRefresh(long lastRefresh) { - this.lastRefresh = lastRefresh; - } - - /** - * Gets whether or not automatic refreshing of this connection's access token is enabled. Defaults to true. - * - * @return true if auto token refresh is enabled; otherwise false. - */ - public boolean getAutoRefresh() { - return this.autoRefresh; - } - - /** - * Enables or disables automatic refreshing of this connection's access token. Defaults to true. - * - * @param autoRefresh true to enable auto token refresh; otherwise false. - */ - public void setAutoRefresh(boolean autoRefresh) { - this.autoRefresh = autoRefresh; - } - - - /** - * Gets the maximum number of times an API request will be retried after an error response - * is received. - * - * @return the maximum number of request attempts. - */ - public int getMaxRetryAttempts() { - return this.maxRetryAttempts; - } - - /** - * Sets the maximum number of times an API request will be retried after an error response - * is received. - * - * @param attempts the maximum number of request attempts. - */ - public void setMaxRetryAttempts(int attempts) { - this.maxRetryAttempts = attempts; - } - - /** - * Gets the connect timeout for this connection in milliseconds. - * - * @return the number of milliseconds to connect before timing out. - */ - public int getConnectTimeout() { - return this.connectTimeout; - } - - /** - * Sets the connect timeout for this connection. - * - * @param connectTimeout The number of milliseconds to wait for the connection to be established. - */ - public void setConnectTimeout(int connectTimeout) { - this.connectTimeout = connectTimeout; - buildHttpClients(); - } - - /* - * Gets if request use zstd encoding when possible - * @return true if request use zstd encoding when possible - */ - public boolean getUseZstdCompression() { - return this.useZstdCompression; - } - - /* - * Sets if request use zstd encoding when possible - * @param useZstdCompression true if request use zstd encoding when possible - */ - public void setUseZstdCompression(boolean useZstdCompression) { - this.useZstdCompression = useZstdCompression; - buildHttpClients(); - } - - /** - * Gets the read timeout for this connection in milliseconds. - * - * @return the number of milliseconds to wait for bytes to be read before timing out. - */ - public int getReadTimeout() { - return this.readTimeout; - } - - /** - * Sets the read timeout for this connection. - * - * @param readTimeout The number of milliseconds to wait for bytes to be read. - */ - public void setReadTimeout(int readTimeout) { - this.readTimeout = readTimeout; - buildHttpClients(); - } - - /** - * Gets the proxy value to use for API calls to Box. - * - * @return the current proxy. - */ - public Proxy getProxy() { - return this.proxy; - } - - /** - * Sets the proxy to use for API calls to Box. - * - * @param proxy the proxy to use for API calls to Box. - */ - public void setProxy(Proxy proxy) { - this.proxy = proxy; - buildHttpClients(); - } - - /** - * Gets the username to use for a proxy that requires basic auth. - * - * @return the username to use for a proxy that requires basic auth. - */ - public String getProxyUsername() { - return this.proxyUsername; - } - - /** - * Sets the username to use for a proxy that requires basic auth. - * - * @param proxyUsername the username to use for a proxy that requires basic auth. - * @deprecated Use {@link BoxAPIConnection#setProxyBasicAuthentication(String, String)} - */ - public void setProxyUsername(String proxyUsername) { - this.proxyUsername = proxyUsername; - buildHttpClients(); - } - - /** - * Gets the password to use for a proxy that requires basic auth. - * - * @return the password to use for a proxy that requires basic auth. - */ - public String getProxyPassword() { - return this.proxyPassword; - } - - /** - * Sets the proxy user and password used in basic authentication - * - * @param proxyUsername Username to use for a proxy that requires basic auth. - * @param proxyPassword Password to use for a proxy that requires basic auth. - */ - public void setProxyBasicAuthentication(String proxyUsername, String proxyPassword) { - this.proxyUsername = proxyUsername; - this.proxyPassword = proxyPassword; - buildHttpClients(); - } - - /** - * Sets the password to use for a proxy that requires basic auth. - * - * @param proxyPassword the password to use for a proxy that requires basic auth. - * @deprecated Use {@link BoxAPIConnection#setProxyBasicAuthentication(String, String)} - */ - public void setProxyPassword(String proxyPassword) { - this.proxyPassword = proxyPassword; - buildHttpClients(); - } - - /** - * Determines if this connection's access token can be refreshed. An access token cannot be refreshed if a refresh - * token was never set. - * - * @return true if the access token can be refreshed; otherwise false. - */ - public boolean canRefresh() { - return this.refreshToken != null; - } - - /** - * Determines if this connection's access token has expired and needs to be refreshed. - * - * @return true if the access token needs to be refreshed; otherwise false. - */ - public boolean needsRefresh() { - boolean needsRefresh; - - this.refreshLock.readLock().lock(); - try { - long now = System.currentTimeMillis(); - long tokenDuration = (now - this.lastRefresh); - needsRefresh = (tokenDuration >= this.expires - REFRESH_EPSILON); - } finally { - this.refreshLock.readLock().unlock(); - } - - return needsRefresh; - } - - /** - * Refresh's this connection's access token using its refresh token. - * - * @throws IllegalStateException if this connection's access token cannot be refreshed. - */ - public void refresh() { - this.refreshLock.writeLock().lock(); - try { - if (!this.canRefresh()) { - throw new IllegalStateException("The BoxAPIConnection cannot be refreshed because it doesn't have a " - + "refresh token."); - } - - URL url; - try { - url = new URL(getTokenURL()); - } catch (MalformedURLException e) { - assert false : "An invalid refresh URL indicates a bug in the SDK."; - throw new RuntimeException("An invalid refresh URL indicates a bug in the SDK.", e); - } - - BoxAPIRequest request = createTokenRequest(url); - - String json; - try (BoxAPIResponse boxAPIResponse = request.send()) { - BoxJSONResponse response = (BoxJSONResponse) boxAPIResponse; - json = response.getJSON(); - } catch (BoxAPIException e) { - this.notifyError(e); - throw e; - } - - extractTokens(Json.parse(json).asObject()); - this.notifyRefresh(); - } finally { - this.refreshLock.writeLock().unlock(); - } - } - - /** - * Restores a saved connection state into this BoxAPIConnection. - * - * @param state the saved state that was created with {@link #save}. - * @see #save - */ - public void restore(String state) { - JsonObject json = Json.parse(state).asObject(); - String accessToken = json.get("accessToken").asString(); - String refreshToken = getKeyValueOrDefault(json, "refreshToken", null); - long lastRefresh = json.get("lastRefresh").asLong(); - long expires = json.get("expires").asLong(); - String userAgent = json.get("userAgent").asString(); - String tokenURL = getKeyValueOrDefault(json, "tokenURL", null); - String revokeURL = getKeyValueOrDefault(json, "revokeURL", null); - String baseURL = adoptBaseUrlWhenLoadingFromOldVersion( - getKeyValueOrDefault(json, "baseURL", DEFAULT_BASE_URL) - ); - String baseUploadURL = adoptUploadBaseUrlWhenLoadingFromOldVersion( - getKeyValueOrDefault(json, "baseUploadURL", DEFAULT_BASE_UPLOAD_URL) - ); - String authorizationURL = - getKeyValueOrDefault(json, "authorizationURL", DEFAULT_BASE_AUTHORIZATION_URL); - boolean autoRefresh = json.get("autoRefresh").asBoolean(); - - // Try to read deprecated value - int maxRequestAttempts = -1; - if (json.names().contains("maxRequestAttempts")) { - maxRequestAttempts = json.get("maxRequestAttempts").asInt(); - } - - int maxRetryAttempts = -1; - if (json.names().contains("maxRetryAttempts")) { - maxRetryAttempts = json.get("maxRetryAttempts").asInt(); - } - - this.accessToken = accessToken; - this.refreshToken = refreshToken; - this.lastRefresh = lastRefresh; - this.expires = expires; - this.userAgent = userAgent; - this.tokenURL = tokenURL; - this.revokeURL = revokeURL; - this.setBaseURL(baseURL); - this.setBaseUploadURL(baseUploadURL); - this.setBaseAuthorizationURL(authorizationURL); - this.autoRefresh = autoRefresh; - - // Try to use deprecated value "maxRequestAttempts", else use newer value "maxRetryAttempts" - if (maxRequestAttempts > -1) { - this.maxRetryAttempts = maxRequestAttempts - 1; - } - if (maxRetryAttempts > -1) { - this.maxRetryAttempts = maxRetryAttempts; - } - - } - - private String adoptBaseUrlWhenLoadingFromOldVersion(String url) { - if (url == null) { - return null; - } - String urlEndingWithSlash = fixBaseUrl(url); - return urlEndingWithSlash.equals("https://api.box.com/2.0/") - ? DEFAULT_BASE_URL - : urlEndingWithSlash; - } - - private String adoptUploadBaseUrlWhenLoadingFromOldVersion(String url) { - if (url == null) { - return null; - } - String urlEndingWithSlash = fixBaseUrl(url); - return urlEndingWithSlash.equals("https://upload.box.com/api/2.0/") - ? DEFAULT_BASE_UPLOAD_URL - : urlEndingWithSlash; - } - - protected String getKeyValueOrDefault(JsonObject json, String key, String defaultValue) { - return Optional.ofNullable(json.get(key)) - .filter(js -> !js.isNull()) - .map(JsonValue::asString) - .orElse(defaultValue); - } - - /** - * Notifies a refresh event to all the listeners. - */ - protected void notifyRefresh() { - for (BoxAPIConnectionListener listener : this.listeners) { - listener.onRefresh(this); - } - } - - /** - * Notifies an error event to all the listeners. - * - * @param error A BoxAPIException instance. - */ - protected void notifyError(BoxAPIException error) { - for (BoxAPIConnectionListener listener : this.listeners) { - listener.onError(this, error); - } - } - - /** - * Add a listener to listen to Box API connection events. - * - * @param listener a listener to listen to Box API connection. - */ - public void addListener(BoxAPIConnectionListener listener) { - this.listeners.add(listener); + if (scopes != null && !scopes.isEmpty()) { + queryBuilder.appendParam("scope", join(" ", scopes)); } - /** - * Remove a listener listening to Box API connection events. - * - * @param listener the listener to remove. - */ - public void removeListener(BoxAPIConnectionListener listener) { - this.listeners.remove(listener); - } + return template.buildWithQuery("", queryBuilder.toString()); + } - /** - * Gets the RequestInterceptor associated with this API connection. - * - * @return the RequestInterceptor associated with this API connection. - */ - public RequestInterceptor getRequestInterceptor() { - return this.interceptor; + /** + * Authenticates the API connection by obtaining access and refresh tokens using the auth code + * that was obtained from the first half of OAuth. + * + * @param authCode the auth code obtained from the first half of the OAuth process. + */ + public void authenticate(String authCode) { + URL url; + try { + url = new URL(this.getTokenURL()); + } catch (MalformedURLException e) { + assert false : "An invalid token URL indicates a bug in the SDK."; + throw new RuntimeException("An invalid token URL indicates a bug in the SDK.", e); } - /** - * Sets a RequestInterceptor that can intercept requests and manipulate them before they're sent to the Box API. - * - * @param interceptor the RequestInterceptor. - */ - public void setRequestInterceptor(RequestInterceptor interceptor) { - this.interceptor = interceptor; - } + String urlParameters = + format( + "grant_type=authorization_code&code=%s&client_id=%s&client_secret=%s", + authCode, this.clientID, this.clientSecret); - /** - * Get a lower-scoped token restricted to a resource for the list of scopes that are passed. - * - * @param scopes the list of scopes to which the new token should be restricted for - * @param resource the resource for which the new token has to be obtained - * @return scopedToken which has access token and other details - * @throws BoxAPIException if resource is not a valid Box API endpoint or shared link - */ - public ScopedToken getLowerScopedToken(List scopes, String resource) { - assert (scopes != null); - assert (scopes.size() > 0); - URL url; - try { - url = new URL(this.getTokenURL()); - } catch (MalformedURLException e) { - assert false : "An invalid refresh URL indicates a bug in the SDK."; - throw new BoxAPIException("An invalid refresh URL indicates a bug in the SDK.", e); + BoxAPIRequest request = new BoxAPIRequest(this, url, "POST"); + request.shouldAuthenticate(false); + request.setBody(urlParameters); + + // authentication uses form url encoded but response is JSON + try (BoxJSONResponse response = (BoxJSONResponse) request.send()) { + String json = response.getJSON(); + + JsonObject jsonObject = Json.parse(json).asObject(); + this.accessToken = jsonObject.get("access_token").asString(); + this.refreshToken = jsonObject.get("refresh_token").asString(); + this.lastRefresh = System.currentTimeMillis(); + this.expires = jsonObject.get("expires_in").asLong() * 1000; + } + } + + /** + * Gets the client ID. + * + * @return the client ID. + */ + public String getClientID() { + return this.clientID; + } + + /** + * Gets the client secret. + * + * @return the client secret. + */ + public String getClientSecret() { + return this.clientSecret; + } + + /** + * Gets the amount of time for which this connection's access token is valid. + * + * @return the amount of time in milliseconds. + */ + public long getExpires() { + return this.expires; + } + + /** + * Sets the amount of time for which this connection's access token is valid before it must be + * refreshed. + * + * @param milliseconds the number of milliseconds for which the access token is valid. + */ + public void setExpires(long milliseconds) { + this.expires = milliseconds; + } + + /** + * Gets the token URL that's used to request access tokens. The default value is + * "https://www.box.com/api/oauth2/token". The URL is created from {@link + * BoxAPIConnection#baseURL} and {@link BoxAPIConnection#TOKEN_URL_SUFFIX}. + * + * @return the token URL. + */ + public String getTokenURL() { + if (this.tokenURL != null) { + return this.tokenURL; + } else { + return this.baseURL + TOKEN_URL_SUFFIX; + } + } + + /** + * Returns the URL used for token revocation. The URL is created from {@link + * BoxAPIConnection#baseURL} and {@link BoxAPIConnection#REVOKE_URL_SUFFIX}. + * + * @return The url used for token revocation. + */ + public String getRevokeURL() { + if (this.revokeURL != null) { + return this.revokeURL; + } else { + return this.baseURL + REVOKE_URL_SUFFIX; + } + } + + /** + * Gets the base URL that's used when sending requests to the Box API. The URL is created from + * {@link BoxAPIConnection#baseURL} and {@link BoxAPIConnection#API_VERSION}. The default value is + * "https://api.box.com/2.0/". + * + * @return the base URL. + */ + public String getBaseURL() { + return this.baseURL + API_VERSION + "/"; + } + + /** + * Sets the base URL to be used when sending requests to the Box API. For example, the default + * base URL is "https://api.box.com/". This method changes how {@link + * BoxAPIConnection#getRevokeURL()} and {@link BoxAPIConnection#getTokenURL()} are constructed. + * + * @param baseURL a base URL + */ + public void setBaseURL(String baseURL) { + this.baseURL = fixBaseUrl(baseURL); + } + + /** + * Gets the base upload URL that's used when performing file uploads to Box. The URL is created + * from {@link BoxAPIConnection#baseUploadURL} and {@link BoxAPIConnection#API_VERSION}. + * + * @return the base upload URL. + */ + public String getBaseUploadURL() { + return this.baseUploadURL + API_VERSION + "/"; + } + + /** + * Sets the base upload URL to be used when performing file uploads to Box. + * + * @param baseUploadURL a base upload URL. + */ + public void setBaseUploadURL(String baseUploadURL) { + this.baseUploadURL = fixBaseUrl(baseUploadURL); + } + + /** + * Returns the authorization URL which is used to perform the authorization_code based OAuth2 + * flow. The URL is created from {@link BoxAPIConnection#baseAuthorizationURL} and {@link + * BoxAPIConnection#OAUTH_SUFFIX}. + * + * @param redirectUri the URL to which Box redirects the browser when authentication completes. + * @param state the text string that you choose. Box sends the same string to your redirect URL + * when authentication is complete. + * @param scopes this optional parameter identifies the Box scopes available to the application + * once it's authenticated. + * @return the authorization URL + */ + public URL getAuthorizationURL(URI redirectUri, String state, List scopes) { + return createFullAuthorizationUrl( + this.baseAuthorizationURL, this.clientID, redirectUri, state, scopes); + } + + /** + * Sets authorization base URL which is used to perform the authorization_code based OAuth2 flow. + * + * @param baseAuthorizationURL Authorization URL. Default value is https://account.box.com/api/. + */ + public void setBaseAuthorizationURL(String baseAuthorizationURL) { + this.baseAuthorizationURL = fixBaseUrl(baseAuthorizationURL); + } + + /** + * Gets the user agent that's used when sending requests to the Box API. + * + * @return the user agent. + */ + public String getUserAgent() { + return this.userAgent; + } + + /** + * Sets the user agent to be used when sending requests to the Box API. + * + * @param userAgent the user agent. + */ + public void setUserAgent(String userAgent) { + this.userAgent = userAgent; + } + + /** + * Gets the base App url. Used for e.g. file requests. + * + * @return the base App Url. + */ + public String getBaseAppUrl() { + return this.baseAppURL; + } + + /** + * Sets the base App url. Used for e.g. file requests. + * + * @param baseAppURL a base App Url. + */ + public void setBaseAppUrl(String baseAppURL) { + this.baseAppURL = baseAppURL; + } + + /** + * Gets an access token that can be used to authenticate an API request. This method will + * automatically refresh the access token if it has expired since the last call to + * getAccessToken(). + * + * @return a valid access token that can be used to authenticate an API request. + */ + public String getAccessToken() { + if (this.autoRefresh && this.canRefresh() && this.needsRefresh()) { + this.refreshLock.writeLock().lock(); + try { + if (this.needsRefresh()) { + this.refresh(); } - - StringBuilder spaceSeparatedScopes = this.buildScopesForTokenDownscoping(scopes); - - String urlParameters = format("grant_type=urn:ietf:params:oauth:grant-type:token-exchange" + } finally { + this.refreshLock.writeLock().unlock(); + } + } + + this.refreshLock.readLock().lock(); + try { + return this.accessToken; + } finally { + this.refreshLock.readLock().unlock(); + } + } + + /** + * Sets the access token to use when authenticating API requests. + * + * @param accessToken a valid access token to use when authenticating API requests. + */ + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + /** + * Gets the refresh lock to be used when refreshing an access token. + * + * @return the refresh lock. + */ + protected ReadWriteLock getRefreshLock() { + return this.refreshLock; + } + + /** + * Gets a refresh token that can be used to refresh an access token. + * + * @return a valid refresh token. + */ + public String getRefreshToken() { + return this.refreshToken; + } + + /** + * Sets the refresh token to use when refreshing an access token. + * + * @param refreshToken a valid refresh token. + */ + public void setRefreshToken(String refreshToken) { + this.refreshToken = refreshToken; + } + + /** + * Gets the last time that the access token was refreshed. + * + * @return the last refresh time in milliseconds. + */ + public long getLastRefresh() { + return this.lastRefresh; + } + + /** + * Sets the last time that the access token was refreshed. + * + *

This value is used when determining if an access token needs to be auto-refreshed. If the + * amount of time since the last refresh exceeds the access token's expiration time, then the + * access token will be refreshed. + * + * @param lastRefresh the new last refresh time in milliseconds. + */ + public void setLastRefresh(long lastRefresh) { + this.lastRefresh = lastRefresh; + } + + /** + * Gets whether or not automatic refreshing of this connection's access token is enabled. Defaults + * to true. + * + * @return true if auto token refresh is enabled; otherwise false. + */ + public boolean getAutoRefresh() { + return this.autoRefresh; + } + + /** + * Enables or disables automatic refreshing of this connection's access token. Defaults to true. + * + * @param autoRefresh true to enable auto token refresh; otherwise false. + */ + public void setAutoRefresh(boolean autoRefresh) { + this.autoRefresh = autoRefresh; + } + + /** + * Gets the maximum number of times an API request will be retried after an error response is + * received. + * + * @return the maximum number of request attempts. + */ + public int getMaxRetryAttempts() { + return this.maxRetryAttempts; + } + + /** + * Sets the maximum number of times an API request will be retried after an error response is + * received. + * + * @param attempts the maximum number of request attempts. + */ + public void setMaxRetryAttempts(int attempts) { + this.maxRetryAttempts = attempts; + } + + /** + * Gets the connect timeout for this connection in milliseconds. + * + * @return the number of milliseconds to connect before timing out. + */ + public int getConnectTimeout() { + return this.connectTimeout; + } + + /** + * Sets the connect timeout for this connection. + * + * @param connectTimeout The number of milliseconds to wait for the connection to be established. + */ + public void setConnectTimeout(int connectTimeout) { + this.connectTimeout = connectTimeout; + buildHttpClients(); + } + + /* + * Gets if request use zstd encoding when possible + * @return true if request use zstd encoding when possible + */ + public boolean getUseZstdCompression() { + return this.useZstdCompression; + } + + /* + * Sets if request use zstd encoding when possible + * @param useZstdCompression true if request use zstd encoding when possible + */ + public void setUseZstdCompression(boolean useZstdCompression) { + this.useZstdCompression = useZstdCompression; + buildHttpClients(); + } + + /** + * Gets the read timeout for this connection in milliseconds. + * + * @return the number of milliseconds to wait for bytes to be read before timing out. + */ + public int getReadTimeout() { + return this.readTimeout; + } + + /** + * Sets the read timeout for this connection. + * + * @param readTimeout The number of milliseconds to wait for bytes to be read. + */ + public void setReadTimeout(int readTimeout) { + this.readTimeout = readTimeout; + buildHttpClients(); + } + + /** + * Gets the proxy value to use for API calls to Box. + * + * @return the current proxy. + */ + public Proxy getProxy() { + return this.proxy; + } + + /** + * Sets the proxy to use for API calls to Box. + * + * @param proxy the proxy to use for API calls to Box. + */ + public void setProxy(Proxy proxy) { + this.proxy = proxy; + buildHttpClients(); + } + + /** + * Gets the username to use for a proxy that requires basic auth. + * + * @return the username to use for a proxy that requires basic auth. + */ + public String getProxyUsername() { + return this.proxyUsername; + } + + /** + * Sets the username to use for a proxy that requires basic auth. + * + * @param proxyUsername the username to use for a proxy that requires basic auth. + * @deprecated Use {@link BoxAPIConnection#setProxyBasicAuthentication(String, String)} + */ + public void setProxyUsername(String proxyUsername) { + this.proxyUsername = proxyUsername; + buildHttpClients(); + } + + /** + * Gets the password to use for a proxy that requires basic auth. + * + * @return the password to use for a proxy that requires basic auth. + */ + public String getProxyPassword() { + return this.proxyPassword; + } + + /** + * Sets the proxy user and password used in basic authentication + * + * @param proxyUsername Username to use for a proxy that requires basic auth. + * @param proxyPassword Password to use for a proxy that requires basic auth. + */ + public void setProxyBasicAuthentication(String proxyUsername, String proxyPassword) { + this.proxyUsername = proxyUsername; + this.proxyPassword = proxyPassword; + buildHttpClients(); + } + + /** + * Sets the password to use for a proxy that requires basic auth. + * + * @param proxyPassword the password to use for a proxy that requires basic auth. + * @deprecated Use {@link BoxAPIConnection#setProxyBasicAuthentication(String, String)} + */ + public void setProxyPassword(String proxyPassword) { + this.proxyPassword = proxyPassword; + buildHttpClients(); + } + + /** + * Determines if this connection's access token can be refreshed. An access token cannot be + * refreshed if a refresh token was never set. + * + * @return true if the access token can be refreshed; otherwise false. + */ + public boolean canRefresh() { + return this.refreshToken != null; + } + + /** + * Determines if this connection's access token has expired and needs to be refreshed. + * + * @return true if the access token needs to be refreshed; otherwise false. + */ + public boolean needsRefresh() { + boolean needsRefresh; + + this.refreshLock.readLock().lock(); + try { + long now = System.currentTimeMillis(); + long tokenDuration = (now - this.lastRefresh); + needsRefresh = (tokenDuration >= this.expires - REFRESH_EPSILON); + } finally { + this.refreshLock.readLock().unlock(); + } + + return needsRefresh; + } + + /** + * Refresh's this connection's access token using its refresh token. + * + * @throws IllegalStateException if this connection's access token cannot be refreshed. + */ + public void refresh() { + this.refreshLock.writeLock().lock(); + try { + if (!this.canRefresh()) { + throw new IllegalStateException( + "The BoxAPIConnection cannot be refreshed because it doesn't have a " + + "refresh token."); + } + + URL url; + try { + url = new URL(getTokenURL()); + } catch (MalformedURLException e) { + assert false : "An invalid refresh URL indicates a bug in the SDK."; + throw new RuntimeException("An invalid refresh URL indicates a bug in the SDK.", e); + } + + BoxAPIRequest request = createTokenRequest(url); + + String json; + try (BoxAPIResponse boxAPIResponse = request.send()) { + BoxJSONResponse response = (BoxJSONResponse) boxAPIResponse; + json = response.getJSON(); + } catch (BoxAPIException e) { + this.notifyError(e); + throw e; + } + + extractTokens(Json.parse(json).asObject()); + this.notifyRefresh(); + } finally { + this.refreshLock.writeLock().unlock(); + } + } + + /** + * Restores a saved connection state into this BoxAPIConnection. + * + * @param state the saved state that was created with {@link #save}. + * @see #save + */ + public void restore(String state) { + JsonObject json = Json.parse(state).asObject(); + String accessToken = json.get("accessToken").asString(); + String refreshToken = getKeyValueOrDefault(json, "refreshToken", null); + long lastRefresh = json.get("lastRefresh").asLong(); + long expires = json.get("expires").asLong(); + String userAgent = json.get("userAgent").asString(); + String tokenURL = getKeyValueOrDefault(json, "tokenURL", null); + String revokeURL = getKeyValueOrDefault(json, "revokeURL", null); + String baseURL = + adoptBaseUrlWhenLoadingFromOldVersion( + getKeyValueOrDefault(json, "baseURL", DEFAULT_BASE_URL)); + String baseUploadURL = + adoptUploadBaseUrlWhenLoadingFromOldVersion( + getKeyValueOrDefault(json, "baseUploadURL", DEFAULT_BASE_UPLOAD_URL)); + String authorizationURL = + getKeyValueOrDefault(json, "authorizationURL", DEFAULT_BASE_AUTHORIZATION_URL); + boolean autoRefresh = json.get("autoRefresh").asBoolean(); + + // Try to read deprecated value + int maxRequestAttempts = -1; + if (json.names().contains("maxRequestAttempts")) { + maxRequestAttempts = json.get("maxRequestAttempts").asInt(); + } + + int maxRetryAttempts = -1; + if (json.names().contains("maxRetryAttempts")) { + maxRetryAttempts = json.get("maxRetryAttempts").asInt(); + } + + this.accessToken = accessToken; + this.refreshToken = refreshToken; + this.lastRefresh = lastRefresh; + this.expires = expires; + this.userAgent = userAgent; + this.tokenURL = tokenURL; + this.revokeURL = revokeURL; + this.setBaseURL(baseURL); + this.setBaseUploadURL(baseUploadURL); + this.setBaseAuthorizationURL(authorizationURL); + this.autoRefresh = autoRefresh; + + // Try to use deprecated value "maxRequestAttempts", else use newer value "maxRetryAttempts" + if (maxRequestAttempts > -1) { + this.maxRetryAttempts = maxRequestAttempts - 1; + } + if (maxRetryAttempts > -1) { + this.maxRetryAttempts = maxRetryAttempts; + } + } + + private String adoptBaseUrlWhenLoadingFromOldVersion(String url) { + if (url == null) { + return null; + } + String urlEndingWithSlash = fixBaseUrl(url); + return urlEndingWithSlash.equals("https://api.box.com/2.0/") + ? DEFAULT_BASE_URL + : urlEndingWithSlash; + } + + private String adoptUploadBaseUrlWhenLoadingFromOldVersion(String url) { + if (url == null) { + return null; + } + String urlEndingWithSlash = fixBaseUrl(url); + return urlEndingWithSlash.equals("https://upload.box.com/api/2.0/") + ? DEFAULT_BASE_UPLOAD_URL + : urlEndingWithSlash; + } + + protected String getKeyValueOrDefault(JsonObject json, String key, String defaultValue) { + return Optional.ofNullable(json.get(key)) + .filter(js -> !js.isNull()) + .map(JsonValue::asString) + .orElse(defaultValue); + } + + /** Notifies a refresh event to all the listeners. */ + protected void notifyRefresh() { + for (BoxAPIConnectionListener listener : this.listeners) { + listener.onRefresh(this); + } + } + + /** + * Notifies an error event to all the listeners. + * + * @param error A BoxAPIException instance. + */ + protected void notifyError(BoxAPIException error) { + for (BoxAPIConnectionListener listener : this.listeners) { + listener.onError(this, error); + } + } + + /** + * Add a listener to listen to Box API connection events. + * + * @param listener a listener to listen to Box API connection. + */ + public void addListener(BoxAPIConnectionListener listener) { + this.listeners.add(listener); + } + + /** + * Remove a listener listening to Box API connection events. + * + * @param listener the listener to remove. + */ + public void removeListener(BoxAPIConnectionListener listener) { + this.listeners.remove(listener); + } + + /** + * Gets the RequestInterceptor associated with this API connection. + * + * @return the RequestInterceptor associated with this API connection. + */ + public RequestInterceptor getRequestInterceptor() { + return this.interceptor; + } + + /** + * Sets a RequestInterceptor that can intercept requests and manipulate them before they're sent + * to the Box API. + * + * @param interceptor the RequestInterceptor. + */ + public void setRequestInterceptor(RequestInterceptor interceptor) { + this.interceptor = interceptor; + } + + /** + * Get a lower-scoped token restricted to a resource for the list of scopes that are passed. + * + * @param scopes the list of scopes to which the new token should be restricted for + * @param resource the resource for which the new token has to be obtained + * @return scopedToken which has access token and other details + * @throws BoxAPIException if resource is not a valid Box API endpoint or shared link + */ + public ScopedToken getLowerScopedToken(List scopes, String resource) { + assert (scopes != null); + assert (scopes.size() > 0); + URL url; + try { + url = new URL(this.getTokenURL()); + } catch (MalformedURLException e) { + assert false : "An invalid refresh URL indicates a bug in the SDK."; + throw new BoxAPIException("An invalid refresh URL indicates a bug in the SDK.", e); + } + + StringBuilder spaceSeparatedScopes = this.buildScopesForTokenDownscoping(scopes); + + String urlParameters = + format( + "grant_type=urn:ietf:params:oauth:grant-type:token-exchange" + "&subject_token_type=urn:ietf:params:oauth:token-type:access_token&subject_token=%s" + "&scope=%s", this.getAccessToken(), spaceSeparatedScopes); - if (resource != null) { - - ResourceLinkType resourceType = this.determineResourceLinkType(resource); - - if (resourceType == ResourceLinkType.APIEndpoint) { - urlParameters = format(urlParameters + "&resource=%s", resource); - } else if (resourceType == ResourceLinkType.SharedLink) { - urlParameters = format(urlParameters + "&box_shared_link=%s", resource); - } else if (resourceType == ResourceLinkType.Unknown) { - String argExceptionMessage = format("Unable to determine resource type: %s", resource); - BoxAPIException e = new BoxAPIException(argExceptionMessage); - this.notifyError(e); - throw e; - } else { - String argExceptionMessage = format("Unhandled resource type: %s", resource); - BoxAPIException e = new BoxAPIException(argExceptionMessage); - this.notifyError(e); - throw e; - } - } - - BoxAPIRequest request = new BoxAPIRequest(this, url, "POST"); - request.shouldAuthenticate(false); - request.setBody(urlParameters); - - String jsonResponse; - try (BoxJSONResponse response = (BoxJSONResponse) request.send()) { - jsonResponse = response.getJSON(); - } catch (BoxAPIException e) { - this.notifyError(e); - throw e; - } - - JsonObject jsonObject = Json.parse(jsonResponse).asObject(); - ScopedToken token = new ScopedToken(jsonObject); - token.setObtainedAt(System.currentTimeMillis()); - token.setExpiresIn(jsonObject.get("expires_in").asLong() * 1000); - return token; - } - - /** - * Convert List to space-delimited String. - * Needed for versions prior to Java 8, which don't have String.join(delimiter, list) - * - * @param scopes the list of scopes to read from - * @return space-delimited String of scopes - */ - private StringBuilder buildScopesForTokenDownscoping(List scopes) { - StringBuilder spaceSeparatedScopes = new StringBuilder(); - for (int i = 0; i < scopes.size(); i++) { - spaceSeparatedScopes.append(scopes.get(i)); - if (i < scopes.size() - 1) { - spaceSeparatedScopes.append(" "); - } - } - - return spaceSeparatedScopes; - } - - /** - * Determines the type of resource, given a link to a Box resource. - * - * @param resourceLink the resource URL to check - * @return ResourceLinkType that categorizes the provided resourceLink - */ - protected ResourceLinkType determineResourceLinkType(String resourceLink) { - - ResourceLinkType resourceType = ResourceLinkType.Unknown; - - try { - URL validUrl = new URL(resourceLink); - String validURLStr = validUrl.toString(); - final String apiFilesEndpointPattern = ".*box.com/2.0/files/\\d+"; - final String apiFoldersEndpointPattern = ".*box.com/2.0/folders/\\d+"; - final String sharedLinkPattern = "(.*box.com/s/.*|.*box.com.*s=.*)"; - - if (Pattern.matches(apiFilesEndpointPattern, validURLStr) - || Pattern.matches(apiFoldersEndpointPattern, validURLStr)) { - resourceType = ResourceLinkType.APIEndpoint; - } else if (Pattern.matches(sharedLinkPattern, validURLStr)) { - resourceType = ResourceLinkType.SharedLink; - } - } catch (MalformedURLException e) { - //Swallow exception and return default ResourceLinkType set at top of function - } - - return resourceType; - } - - /** - * Revokes the tokens associated with this API connection. This results in the connection no - * longer being able to make API calls until a fresh authorization is made by calling authenticate() - */ - public void revokeToken() { - - URL url; - try { - url = new URL(getRevokeURL()); - } catch (MalformedURLException e) { - assert false : "An invalid refresh URL indicates a bug in the SDK."; - throw new RuntimeException("An invalid refresh URL indicates a bug in the SDK.", e); - } - - String urlParameters = format("token=%s&client_id=%s&client_secret=%s", + if (resource != null) { + + ResourceLinkType resourceType = this.determineResourceLinkType(resource); + + if (resourceType == ResourceLinkType.APIEndpoint) { + urlParameters = format(urlParameters + "&resource=%s", resource); + } else if (resourceType == ResourceLinkType.SharedLink) { + urlParameters = format(urlParameters + "&box_shared_link=%s", resource); + } else if (resourceType == ResourceLinkType.Unknown) { + String argExceptionMessage = format("Unable to determine resource type: %s", resource); + BoxAPIException e = new BoxAPIException(argExceptionMessage); + this.notifyError(e); + throw e; + } else { + String argExceptionMessage = format("Unhandled resource type: %s", resource); + BoxAPIException e = new BoxAPIException(argExceptionMessage); + this.notifyError(e); + throw e; + } + } + + BoxAPIRequest request = new BoxAPIRequest(this, url, "POST"); + request.shouldAuthenticate(false); + request.setBody(urlParameters); + + String jsonResponse; + try (BoxJSONResponse response = (BoxJSONResponse) request.send()) { + jsonResponse = response.getJSON(); + } catch (BoxAPIException e) { + this.notifyError(e); + throw e; + } + + JsonObject jsonObject = Json.parse(jsonResponse).asObject(); + ScopedToken token = new ScopedToken(jsonObject); + token.setObtainedAt(System.currentTimeMillis()); + token.setExpiresIn(jsonObject.get("expires_in").asLong() * 1000); + return token; + } + + /** + * Convert List to space-delimited String. Needed for versions prior to Java 8, which + * don't have String.join(delimiter, list) + * + * @param scopes the list of scopes to read from + * @return space-delimited String of scopes + */ + private StringBuilder buildScopesForTokenDownscoping(List scopes) { + StringBuilder spaceSeparatedScopes = new StringBuilder(); + for (int i = 0; i < scopes.size(); i++) { + spaceSeparatedScopes.append(scopes.get(i)); + if (i < scopes.size() - 1) { + spaceSeparatedScopes.append(" "); + } + } + + return spaceSeparatedScopes; + } + + /** + * Determines the type of resource, given a link to a Box resource. + * + * @param resourceLink the resource URL to check + * @return ResourceLinkType that categorizes the provided resourceLink + */ + protected ResourceLinkType determineResourceLinkType(String resourceLink) { + + ResourceLinkType resourceType = ResourceLinkType.Unknown; + + try { + URL validUrl = new URL(resourceLink); + String validURLStr = validUrl.toString(); + final String apiFilesEndpointPattern = ".*box.com/2.0/files/\\d+"; + final String apiFoldersEndpointPattern = ".*box.com/2.0/folders/\\d+"; + final String sharedLinkPattern = "(.*box.com/s/.*|.*box.com.*s=.*)"; + + if (Pattern.matches(apiFilesEndpointPattern, validURLStr) + || Pattern.matches(apiFoldersEndpointPattern, validURLStr)) { + resourceType = ResourceLinkType.APIEndpoint; + } else if (Pattern.matches(sharedLinkPattern, validURLStr)) { + resourceType = ResourceLinkType.SharedLink; + } + } catch (MalformedURLException e) { + // Swallow exception and return default ResourceLinkType set at top of function + } + + return resourceType; + } + + /** + * Revokes the tokens associated with this API connection. This results in the connection no + * longer being able to make API calls until a fresh authorization is made by calling + * authenticate() + */ + public void revokeToken() { + + URL url; + try { + url = new URL(getRevokeURL()); + } catch (MalformedURLException e) { + assert false : "An invalid refresh URL indicates a bug in the SDK."; + throw new RuntimeException("An invalid refresh URL indicates a bug in the SDK.", e); + } + + String urlParameters = + format( + "token=%s&client_id=%s&client_secret=%s", this.accessToken, this.clientID, this.clientSecret); - BoxAPIRequest request = new BoxAPIRequest(this, url, "POST"); - request.shouldAuthenticate(false); - request.setBody(urlParameters); - - request.send().close(); - } - - /** - * Saves the state of this connection to a string so that it can be persisted and restored at a later time. - * - *

Note that proxy settings aren't automatically saved or restored. This is mainly due to security concerns - * around persisting proxy authentication details to the state string. If your connection uses a proxy, you will - * have to manually configure it again after restoring the connection.

- * - * @return the state of this connection. - * @see #restore - */ - public String save() { - JsonObject state = new JsonObject() + BoxAPIRequest request = new BoxAPIRequest(this, url, "POST"); + request.shouldAuthenticate(false); + request.setBody(urlParameters); + + request.send().close(); + } + + /** + * Saves the state of this connection to a string so that it can be persisted and restored at a + * later time. + * + *

Note that proxy settings aren't automatically saved or restored. This is mainly due to + * security concerns around persisting proxy authentication details to the state string. If your + * connection uses a proxy, you will have to manually configure it again after restoring the + * connection. + * + * @return the state of this connection. + * @see #restore + */ + public String save() { + JsonObject state = + new JsonObject() .add("accessToken", this.accessToken) .add("refreshToken", this.refreshToken) .add("lastRefresh", this.lastRefresh) @@ -1142,192 +1178,191 @@ public String save() { .add("authorizationURL", this.baseAuthorizationURL) .add("autoRefresh", this.autoRefresh) .add("maxRetryAttempts", this.maxRetryAttempts); - return state.toString(); - } - - String lockAccessToken() { - if (this.autoRefresh && this.canRefresh() && this.needsRefresh()) { - this.refreshLock.writeLock().lock(); - try { - if (this.needsRefresh()) { - this.refresh(); - } - this.refreshLock.readLock().lock(); - } finally { - this.refreshLock.writeLock().unlock(); - } - } else { - this.refreshLock.readLock().lock(); + return state.toString(); + } + + String lockAccessToken() { + if (this.autoRefresh && this.canRefresh() && this.needsRefresh()) { + this.refreshLock.writeLock().lock(); + try { + if (this.needsRefresh()) { + this.refresh(); } + this.refreshLock.readLock().lock(); + } finally { + this.refreshLock.writeLock().unlock(); + } + } else { + this.refreshLock.readLock().lock(); + } + + return this.accessToken; + } + + void unlockAccessToken() { + this.refreshLock.readLock().unlock(); + } + + /** + * Get the value for the X-Box-UA header. + * + * @return the header value. + */ + String getBoxUAHeader() { + + return "agent=box-java-sdk/" + SDK_VERSION + "; env=Java/" + JAVA_VERSION; + } + + /** + * Sets a custom header to be sent on all requests through this API connection. + * + * @param header the header name. + * @param value the header value. + */ + public void setCustomHeader(String header, String value) { + this.customHeaders.put(header, value); + } + + /** + * Removes a custom header, so it will no longer be sent on requests through this API connection. + * + * @param header the header name. + */ + public void removeCustomHeader(String header) { + this.customHeaders.remove(header); + } + + /** + * Suppresses email notifications from API actions. This is typically used by security or admin + * applications to prevent spamming end users when doing automated processing on their content. + */ + public void suppressNotifications() { + this.setCustomHeader(BOX_NOTIFICATIONS_HEADER, "off"); + } + + /** + * Re-enable email notifications from API actions if they have been suppressed. + * + * @see #suppressNotifications + */ + public void enableNotifications() { + this.removeCustomHeader(BOX_NOTIFICATIONS_HEADER); + } + + /** + * Set this API connection to make API calls on behalf of another users, impersonating them. This + * functionality can only be used by admins and service accounts. + * + * @param userID the ID of the user to act as. + */ + public void asUser(String userID) { + this.setCustomHeader(AS_USER_HEADER, userID); + } + + /** + * Sets this API connection to make API calls on behalf of the user with whom the access token is + * associated. This undoes any previous calls to asUser(). + * + * @see #asUser + */ + public void asSelf() { + this.removeCustomHeader(AS_USER_HEADER); + } + + /** + * Used to override default SSL certification handling. For example, you can provide your own + * trust manager or hostname verifier to allow self-signed certificates. You can check examples here. + * + * @param trustManager TrustManager that verifies certificates are valid. + * @param hostnameVerifier HostnameVerifier that allows you to specify what hostnames are allowed. + */ + public void configureSslCertificatesValidation( + X509TrustManager trustManager, HostnameVerifier hostnameVerifier) { + this.trustManager = trustManager; + this.hostnameVerifier = hostnameVerifier; + buildHttpClients(); + } + + Map getHeaders() { + return this.customHeaders; + } + + protected void extractTokens(JsonObject jsonObject) { + this.accessToken = jsonObject.get("access_token").asString(); + this.refreshToken = jsonObject.get("refresh_token").asString(); + this.lastRefresh = System.currentTimeMillis(); + this.expires = jsonObject.get("expires_in").asLong() * 1000; + } + + protected BoxAPIRequest createTokenRequest(URL url) { + String urlParameters = + format( + "grant_type=refresh_token&refresh_token=%s&client_id=%s&client_secret=%s", + this.refreshToken, this.clientID, this.clientSecret); - return this.accessToken; - } - - void unlockAccessToken() { - this.refreshLock.readLock().unlock(); - } + BoxAPIRequest request = new BoxAPIRequest(this, url, "POST"); + request.shouldAuthenticate(false); + request.setBody(urlParameters); + return request; + } - /** - * Get the value for the X-Box-UA header. - * - * @return the header value. - */ - String getBoxUAHeader() { + private String fixBaseUrl(String baseUrl) { + return baseUrl.endsWith("/") ? baseUrl : baseUrl + "/"; + } - return "agent=box-java-sdk/" + SDK_VERSION + "; env=Java/" + JAVA_VERSION; - } + Response execute(Request request) { + return executeOnClient(httpClient, request); + } - /** - * Sets a custom header to be sent on all requests through this API connection. - * - * @param header the header name. - * @param value the header value. - */ - public void setCustomHeader(String header, String value) { - this.customHeaders.put(header, value); - } + Response executeWithoutRedirect(Request request) { + return executeOnClient(noRedirectsHttpClient, request); + } - /** - * Removes a custom header, so it will no longer be sent on requests through this API connection. - * - * @param header the header name. - */ - public void removeCustomHeader(String header) { - this.customHeaders.remove(header); - } + protected Call createNewCall(OkHttpClient httpClient, Request request) { + return httpClient.newCall(request); + } - /** - * Suppresses email notifications from API actions. This is typically used by security or admin applications - * to prevent spamming end users when doing automated processing on their content. - */ - public void suppressNotifications() { - this.setCustomHeader(BOX_NOTIFICATIONS_HEADER, "off"); + private Response executeOnClient(OkHttpClient httpClient, Request request) { + try { + return createNewCall(httpClient, request).execute(); + } catch (IOException e) { + throw new BoxAPIException( + "Couldn't connect to the Box API due to a network error. Request\n" + + toSanitizedRequest(request), + e); } + } - /** - * Re-enable email notifications from API actions if they have been suppressed. - * - * @see #suppressNotifications - */ - public void enableNotifications() { - this.removeCustomHeader(BOX_NOTIFICATIONS_HEADER); - } + protected X509TrustManager getTrustManager() { + return trustManager; + } - /** - * Set this API connection to make API calls on behalf of another users, impersonating them. This - * functionality can only be used by admins and service accounts. - * - * @param userID the ID of the user to act as. - */ - public void asUser(String userID) { - this.setCustomHeader(AS_USER_HEADER, userID); - } + protected HostnameVerifier getHostnameVerifier() { + return hostnameVerifier; + } - /** - * Sets this API connection to make API calls on behalf of the user with whom the access token is associated. - * This undoes any previous calls to asUser(). - * - * @see #asUser - */ - public void asSelf() { - this.removeCustomHeader(AS_USER_HEADER); - } + /** Used to categorize the types of resource links. */ + protected enum ResourceLinkType { + /** Catch-all default for resource links that are unknown. */ + Unknown, /** - * Used to override default SSL certification handling. For example, you can provide your own - * trust manager or hostname verifier to allow self-signed certificates. - * You can check examples here. - * - * @param trustManager TrustManager that verifies certificates are valid. - * @param hostnameVerifier HostnameVerifier that allows you to specify what hostnames are allowed. + * Resource URLs that point to an API endipoint such as https://api.box.com/2.0/files/:file_id. */ - public void configureSslCertificatesValidation(X509TrustManager trustManager, HostnameVerifier hostnameVerifier) { - this.trustManager = trustManager; - this.hostnameVerifier = hostnameVerifier; - buildHttpClients(); - } - - Map getHeaders() { - return this.customHeaders; - } - - protected void extractTokens(JsonObject jsonObject) { - this.accessToken = jsonObject.get("access_token").asString(); - this.refreshToken = jsonObject.get("refresh_token").asString(); - this.lastRefresh = System.currentTimeMillis(); - this.expires = jsonObject.get("expires_in").asLong() * 1000; - } - - protected BoxAPIRequest createTokenRequest(URL url) { - String urlParameters = format("grant_type=refresh_token&refresh_token=%s&client_id=%s&client_secret=%s", - this.refreshToken, this.clientID, this.clientSecret); - - BoxAPIRequest request = new BoxAPIRequest(this, url, "POST"); - request.shouldAuthenticate(false); - request.setBody(urlParameters); - return request; - } - - private String fixBaseUrl(String baseUrl) { - return baseUrl.endsWith("/") ? baseUrl : baseUrl + "/"; - } - - Response execute(Request request) { - return executeOnClient(httpClient, request); - } - - Response executeWithoutRedirect(Request request) { - return executeOnClient(noRedirectsHttpClient, request); - } - - protected Call createNewCall(OkHttpClient httpClient, Request request) { - return httpClient.newCall(request); - } - - private Response executeOnClient(OkHttpClient httpClient, Request request) { - try { - return createNewCall(httpClient, request).execute(); - } catch (IOException e) { - throw new BoxAPIException("Couldn't connect to the Box API due to a network error. Request\n" - + toSanitizedRequest(request), e); - } - } - - protected X509TrustManager getTrustManager() { - return trustManager; - } - - protected HostnameVerifier getHostnameVerifier() { - return hostnameVerifier; - } + APIEndpoint, /** - * Used to categorize the types of resource links. + * Resource URLs that point to a resource that has been shared such as + * https://example.box.com/s/qwertyuiop1234567890asdfghjk or + * https://example.app.box.com/notes/0987654321?s=zxcvbnm1234567890asdfghjk. */ - protected enum ResourceLinkType { - /** - * Catch-all default for resource links that are unknown. - */ - Unknown, - - /** - * Resource URLs that point to an API endipoint such as https://api.box.com/2.0/files/:file_id. - */ - APIEndpoint, - - /** - * Resource URLs that point to a resource that has been shared - * such as https://example.box.com/s/qwertyuiop1234567890asdfghjk - * or https://example.app.box.com/notes/0987654321?s=zxcvbnm1234567890asdfghjk. - */ - SharedLink - } + SharedLink + } - private Request toSanitizedRequest(Request originalRequest) { - Headers sanitizedHeaders = BoxSensitiveDataSanitizer.sanitizeHeaders(originalRequest.headers()); + private Request toSanitizedRequest(Request originalRequest) { + Headers sanitizedHeaders = BoxSensitiveDataSanitizer.sanitizeHeaders(originalRequest.headers()); - return originalRequest.newBuilder() - .headers(sanitizedHeaders) - .build(); - } + return originalRequest.newBuilder().headers(sanitizedHeaders).build(); + } } diff --git a/src/main/java/com/box/sdk/BoxAPIConnectionListener.java b/src/main/java/com/box/sdk/BoxAPIConnectionListener.java index a30395815..9c89a5ad9 100644 --- a/src/main/java/com/box/sdk/BoxAPIConnectionListener.java +++ b/src/main/java/com/box/sdk/BoxAPIConnectionListener.java @@ -1,28 +1,26 @@ package com.box.sdk; -/** - * Listener to listen to Box API connection events. - */ +/** Listener to listen to Box API connection events. */ public interface BoxAPIConnectionListener { - /** - * Called when the Box API connection refreshes its tokens. - * - *

The provided connection is guaranteed to not be auto-refreshed or modified by another listener until this - * method returns.

- * - * @param api the API connection that was refreshed. - */ - void onRefresh(BoxAPIConnection api); + /** + * Called when the Box API connection refreshes its tokens. + * + *

The provided connection is guaranteed to not be auto-refreshed or modified by another + * listener until this method returns. + * + * @param api the API connection that was refreshed. + */ + void onRefresh(BoxAPIConnection api); - /** - * Called when an error occurs while attempting to refresh the Box API connection's tokens. - * - *

The provided connection is guaranteed to not be auto-refreshed or modified by another listener until this - * method returns.

- * - * @param api the API connection that encountered an error. - * @param error the error that occurred. - */ - void onError(BoxAPIConnection api, BoxAPIException error); + /** + * Called when an error occurs while attempting to refresh the Box API connection's tokens. + * + *

The provided connection is guaranteed to not be auto-refreshed or modified by another + * listener until this method returns. + * + * @param api the API connection that encountered an error. + * @param error the error that occurred. + */ + void onError(BoxAPIConnection api, BoxAPIException error); } diff --git a/src/main/java/com/box/sdk/BoxAPIException.java b/src/main/java/com/box/sdk/BoxAPIException.java index a6f10db1a..399a32e0a 100644 --- a/src/main/java/com/box/sdk/BoxAPIException.java +++ b/src/main/java/com/box/sdk/BoxAPIException.java @@ -4,167 +4,174 @@ import java.util.List; import java.util.Map; -/** - * Thrown to indicate that an error occurred while communicating with the Box API. - */ +/** Thrown to indicate that an error occurred while communicating with the Box API. */ public class BoxAPIException extends RuntimeException { - private static final long serialVersionUID = 1L; - - private int responseCode; - private String response; - private Map> headers; - - /** - * Constructs a BoxAPIException with a specified message. - * - * @param message a message explaining why the exception occurred. - */ - public BoxAPIException(String message) { - super(message); - - this.responseCode = 0; - this.response = null; - this.headers = null; - } - - /** - * Constructs a BoxAPIException with details about the server's response. - * - * @param message a message explaining why the exception occurred. - * @param responseCode the response code returned by the Box server. - * @param response the response body returned by the Box server. - */ - public BoxAPIException(String message, int responseCode, String response) { - //People are missing the getResponse method we have. So adding it to message - super(message + "\n" + response); - - this.responseCode = responseCode; - this.response = response; - this.headers = null; - } - - /** - * Constructs a BoxAPIException with details about the server's response, including response headers. - * - * @param message a message explaining why the exception occurred. - * @param responseCode the response code returned by the Box server. - * @param responseBody the response body returned by the Box server. - * @param responseHeaders the response headers returned by the Box server. - */ - public BoxAPIException(String message, int responseCode, String responseBody, - Map> responseHeaders) { - //People are missing the getResponse method we have. So adding it to message - super(message + "\n" + responseBody); - - this.responseCode = responseCode; - this.response = responseBody; - this.headers = responseHeaders; - } - - /** - * Constructs a BoxAPIException that wraps another underlying exception. - * - * @param message a message explaining why the exception occurred. - * @param cause an underlying exception. - */ - public BoxAPIException(String message, Throwable cause) { - super(message, cause); - - this.responseCode = 0; - this.response = null; - this.headers = null; - } - - /** - * Constructs a BoxAPIException that wraps another underlying exception with details about the server's response. - * - * @param message a message explaining why the exception occurred. - * @param responseCode the response code returned by the Box server. - * @param response the response body returned by the Box server. - * @param cause an underlying exception. - */ - public BoxAPIException(String message, int responseCode, String response, Throwable cause) { - super(message, cause); - - this.responseCode = responseCode; - this.response = response; - this.headers = null; - } - - /** - * Constructs a BoxAPIException that includes the response headers. - * - * @param message a message explaining why the exception occurred. - * @param responseCode the response code returned by the Box server. - * @param responseBody the response body returned by the Box server. - * @param responseHeaders the response headers returned by the Box server. - * @param cause an underlying exception. - */ - public BoxAPIException(String message, int responseCode, String responseBody, - Map> responseHeaders, Throwable cause) { - - super(message, cause); - - this.responseCode = responseCode; - this.response = responseBody; - this.headers = responseHeaders; - } - - /** - * Gets the response code returned by the server when this exception was thrown. - * - * @return the response code returned by the server. - */ - public int getResponseCode() { - return this.responseCode; - } - - /** - * Sets the response code returned by the server. - * - * @param responseCode the response code returned by the server. - */ - protected void setResponseCode(int responseCode) { - this.responseCode = responseCode; - } - - /** - * Gets the body of the response returned by the server when this exception was thrown. - * - * @return the body of the response returned by the server. - */ - public String getResponse() { - return this.response; - } - - /** - * Sets the response returned by ther server. - * - * @param response the response returned by the server. - */ - protected void setResponse(String response) { - this.response = response; - } - - /** - * Gets the response headers, if available. - * - * @return the response headers, or empty map if not available. - */ - public Map> getHeaders() { - if (this.headers != null) { - return this.headers; - } else { - return Collections.emptyMap(); - } - } - - /** - * Sets the response headers. - * - * @param headers headers to set. - */ - protected void setHeaders(Map> headers) { - this.headers = headers; + private static final long serialVersionUID = 1L; + + private int responseCode; + private String response; + private Map> headers; + + /** + * Constructs a BoxAPIException with a specified message. + * + * @param message a message explaining why the exception occurred. + */ + public BoxAPIException(String message) { + super(message); + + this.responseCode = 0; + this.response = null; + this.headers = null; + } + + /** + * Constructs a BoxAPIException with details about the server's response. + * + * @param message a message explaining why the exception occurred. + * @param responseCode the response code returned by the Box server. + * @param response the response body returned by the Box server. + */ + public BoxAPIException(String message, int responseCode, String response) { + // People are missing the getResponse method we have. So adding it to message + super(message + "\n" + response); + + this.responseCode = responseCode; + this.response = response; + this.headers = null; + } + + /** + * Constructs a BoxAPIException with details about the server's response, including response + * headers. + * + * @param message a message explaining why the exception occurred. + * @param responseCode the response code returned by the Box server. + * @param responseBody the response body returned by the Box server. + * @param responseHeaders the response headers returned by the Box server. + */ + public BoxAPIException( + String message, + int responseCode, + String responseBody, + Map> responseHeaders) { + // People are missing the getResponse method we have. So adding it to message + super(message + "\n" + responseBody); + + this.responseCode = responseCode; + this.response = responseBody; + this.headers = responseHeaders; + } + + /** + * Constructs a BoxAPIException that wraps another underlying exception. + * + * @param message a message explaining why the exception occurred. + * @param cause an underlying exception. + */ + public BoxAPIException(String message, Throwable cause) { + super(message, cause); + + this.responseCode = 0; + this.response = null; + this.headers = null; + } + + /** + * Constructs a BoxAPIException that wraps another underlying exception with details about the + * server's response. + * + * @param message a message explaining why the exception occurred. + * @param responseCode the response code returned by the Box server. + * @param response the response body returned by the Box server. + * @param cause an underlying exception. + */ + public BoxAPIException(String message, int responseCode, String response, Throwable cause) { + super(message, cause); + + this.responseCode = responseCode; + this.response = response; + this.headers = null; + } + + /** + * Constructs a BoxAPIException that includes the response headers. + * + * @param message a message explaining why the exception occurred. + * @param responseCode the response code returned by the Box server. + * @param responseBody the response body returned by the Box server. + * @param responseHeaders the response headers returned by the Box server. + * @param cause an underlying exception. + */ + public BoxAPIException( + String message, + int responseCode, + String responseBody, + Map> responseHeaders, + Throwable cause) { + + super(message, cause); + + this.responseCode = responseCode; + this.response = responseBody; + this.headers = responseHeaders; + } + + /** + * Gets the response code returned by the server when this exception was thrown. + * + * @return the response code returned by the server. + */ + public int getResponseCode() { + return this.responseCode; + } + + /** + * Sets the response code returned by the server. + * + * @param responseCode the response code returned by the server. + */ + protected void setResponseCode(int responseCode) { + this.responseCode = responseCode; + } + + /** + * Gets the body of the response returned by the server when this exception was thrown. + * + * @return the body of the response returned by the server. + */ + public String getResponse() { + return this.response; + } + + /** + * Sets the response returned by ther server. + * + * @param response the response returned by the server. + */ + protected void setResponse(String response) { + this.response = response; + } + + /** + * Gets the response headers, if available. + * + * @return the response headers, or empty map if not available. + */ + public Map> getHeaders() { + if (this.headers != null) { + return this.headers; + } else { + return Collections.emptyMap(); } + } + + /** + * Sets the response headers. + * + * @param headers headers to set. + */ + protected void setHeaders(Map> headers) { + this.headers = headers; + } } diff --git a/src/main/java/com/box/sdk/BoxAPIRequest.java b/src/main/java/com/box/sdk/BoxAPIRequest.java index e7c36e619..5cf156cfe 100644 --- a/src/main/java/com/box/sdk/BoxAPIRequest.java +++ b/src/main/java/com/box/sdk/BoxAPIRequest.java @@ -27,702 +27,705 @@ import okhttp3.RequestBody; import okhttp3.Response; - /** * Used to make HTTP requests to the Box API. * - *

All requests to the REST API are sent using this class or one of its subclasses. This class wraps {@link - * HttpURLConnection} in order to provide a simpler interface that can automatically handle various conditions specific - * to Box's API. Requests will be authenticated using a {@link BoxAPIConnection} (if one is provided), so it isn't - * necessary to add authorization headers. Requests can also be sent more than once, unlike with HttpURLConnection. If - * an error occurs while sending a request, it will be automatically retried (with a back off delay) up to the maximum - * number of times set in the BoxAPIConnection.

+ *

All requests to the REST API are sent using this class or one of its subclasses. This class + * wraps {@link HttpURLConnection} in order to provide a simpler interface that can automatically + * handle various conditions specific to Box's API. Requests will be authenticated using a {@link + * BoxAPIConnection} (if one is provided), so it isn't necessary to add authorization headers. + * Requests can also be sent more than once, unlike with HttpURLConnection. If an error occurs while + * sending a request, it will be automatically retried (with a back off delay) up to the maximum + * number of times set in the BoxAPIConnection. * - *

Specifying a body for a BoxAPIRequest is done differently than it is with HttpURLConnection. Instead of writing to - * an OutputStream, the request is provided an {@link InputStream} which will be read when the {@link #send} method is - * called. This makes it easy to retry requests since the stream can automatically reset and reread with each attempt. - * If the stream cannot be reset, then a new stream will need to be provided before each call to send. There is also a - * convenience method for specifying the body as a String, which simply wraps the String with an InputStream.

+ *

Specifying a body for a BoxAPIRequest is done differently than it is with HttpURLConnection. + * Instead of writing to an OutputStream, the request is provided an {@link InputStream} which will + * be read when the {@link #send} method is called. This makes it easy to retry requests since the + * stream can automatically reset and reread with each attempt. If the stream cannot be reset, then + * a new stream will need to be provided before each call to send. There is also a convenience + * method for specifying the body as a String, which simply wraps the String with an InputStream. */ public class BoxAPIRequest { - private static final BoxLogger LOGGER = BoxLogger.defaultLogger(); - private static final String ERROR_CREATING_REQUEST_BODY = "Error creating request body"; - private static final int BUFFER_SIZE = 8192; - private final BoxAPIConnection api; - private final List headers; - private final String method; - private URL url; - private BackoffCounter backoffCounter; - private int connectTimeout; - private int readTimeout; - private InputStream body; - private long bodyLength; - private boolean shouldAuthenticate; - private boolean followRedirects = true; - private final String mediaType; - - /** - * Constructs an authenticated BoxAPIRequest using a provided BoxAPIConnection. - * - * @param api an API connection for authenticating the request. - * @param url the URL of the request. - * @param method the HTTP method of the request. - */ - public BoxAPIRequest(BoxAPIConnection api, URL url, String method) { - this(api, url, method, ContentType.APPLICATION_FORM_URLENCODED); - } - - protected BoxAPIRequest(BoxAPIConnection api, URL url, String method, String mediaType) { - this.api = api; - this.url = url; - this.method = method; - this.mediaType = mediaType; - this.headers = new ArrayList<>(); - if (api != null) { - Map customHeaders = api.getHeaders(); - if (customHeaders != null) { - for (String header : customHeaders.keySet()) { - this.addHeader(header, customHeaders.get(header)); - } - } - this.headers.add(new RequestHeader("X-Box-UA", api.getBoxUAHeader())); + private static final BoxLogger LOGGER = BoxLogger.defaultLogger(); + private static final String ERROR_CREATING_REQUEST_BODY = "Error creating request body"; + private static final int BUFFER_SIZE = 8192; + private final BoxAPIConnection api; + private final List headers; + private final String method; + private URL url; + private BackoffCounter backoffCounter; + private int connectTimeout; + private int readTimeout; + private InputStream body; + private long bodyLength; + private boolean shouldAuthenticate; + private boolean followRedirects = true; + private final String mediaType; + + /** + * Constructs an authenticated BoxAPIRequest using a provided BoxAPIConnection. + * + * @param api an API connection for authenticating the request. + * @param url the URL of the request. + * @param method the HTTP method of the request. + */ + public BoxAPIRequest(BoxAPIConnection api, URL url, String method) { + this(api, url, method, ContentType.APPLICATION_FORM_URLENCODED); + } + + protected BoxAPIRequest(BoxAPIConnection api, URL url, String method, String mediaType) { + this.api = api; + this.url = url; + this.method = method; + this.mediaType = mediaType; + this.headers = new ArrayList<>(); + if (api != null) { + Map customHeaders = api.getHeaders(); + if (customHeaders != null) { + for (String header : customHeaders.keySet()) { + this.addHeader(header, customHeaders.get(header)); } - this.backoffCounter = new BackoffCounter(new Time()); - this.shouldAuthenticate = true; - if (api != null) { - this.connectTimeout = api.getConnectTimeout(); - this.readTimeout = api.getReadTimeout(); - } else { - this.connectTimeout = BoxGlobalSettings.getConnectTimeout(); - this.readTimeout = BoxGlobalSettings.getReadTimeout(); + } + this.headers.add(new RequestHeader("X-Box-UA", api.getBoxUAHeader())); + } + this.backoffCounter = new BackoffCounter(new Time()); + this.shouldAuthenticate = true; + if (api != null) { + this.connectTimeout = api.getConnectTimeout(); + this.readTimeout = api.getReadTimeout(); + } else { + this.connectTimeout = BoxGlobalSettings.getConnectTimeout(); + this.readTimeout = BoxGlobalSettings.getReadTimeout(); + } + + this.addHeader("Accept-Charset", "utf-8"); + } + + /** + * Constructs an authenticated BoxAPIRequest using a provided BoxAPIConnection. + * + * @param api an API connection for authenticating the request. + * @param url the URL of the request. + * @param method the HTTP method of the request. + */ + public BoxAPIRequest(BoxAPIConnection api, URL url, HttpMethod method) { + this(api, url, method.name()); + } + + /** + * Constructs an request, using URL and HttpMethod. + * + * @param url the URL of the request. + * @param method the HTTP method of the request. + */ + public BoxAPIRequest(URL url, HttpMethod method) { + this(null, url, method.name()); + } + + /** + * @param apiException BoxAPIException thrown + * @return true if the request is one that should be retried, otherwise false + */ + public static boolean isRequestRetryable(BoxAPIException apiException) { + // Only requests that failed to send should be retried + return (Objects.equals(apiException.getMessage(), ERROR_CREATING_REQUEST_BODY)); + } + + /** + * @param responseCode HTTP error code of the response + * @param apiException BoxAPIException thrown + * @return true if the response is one that should be retried, otherwise false + */ + public static boolean isResponseRetryable(int responseCode, BoxAPIException apiException) { + if (responseCode >= 500 || responseCode == 429) { + return true; + } + return isClockSkewError(responseCode, apiException); + } + + private static boolean isClockSkewError(int responseCode, BoxAPIException apiException) { + String response = apiException.getResponse(); + if (response == null || response.length() == 0) { + return false; + } + String message = apiException.getMessage(); + String errorCode = ""; + + try { + JsonObject responseBody = Json.parse(response).asObject(); + if (responseBody.get("code") != null) { + errorCode = responseBody.get("code").toString(); + } else if (responseBody.get("error") != null) { + errorCode = responseBody.get("error").toString(); + } + + return responseCode == 400 && errorCode.contains("invalid_grant") && message.contains("exp"); + } catch (ParseException e) { + // 400 error which is not a JSON will not trigger a retry + throw new BoxAPIException("API returned an error", responseCode, response); + } + } + + /** + * Adds an HTTP header to this request. + * + * @param key the header key. + * @param value the header value. + */ + public void addHeader(String key, String value) { + if (key.equals("As-User")) { + for (int i = 0; i < this.headers.size(); i++) { + if (this.headers.get(i).getKey().equals("As-User")) { + this.headers.remove(i); } - - this.addHeader("Accept-Charset", "utf-8"); - } - - /** - * Constructs an authenticated BoxAPIRequest using a provided BoxAPIConnection. - * - * @param api an API connection for authenticating the request. - * @param url the URL of the request. - * @param method the HTTP method of the request. - */ - public BoxAPIRequest(BoxAPIConnection api, URL url, HttpMethod method) { - this(api, url, method.name()); - } - - /** - * Constructs an request, using URL and HttpMethod. - * - * @param url the URL of the request. - * @param method the HTTP method of the request. - */ - public BoxAPIRequest(URL url, HttpMethod method) { - this(null, url, method.name()); - } - - /** - * @param apiException BoxAPIException thrown - * @return true if the request is one that should be retried, otherwise false - */ - public static boolean isRequestRetryable(BoxAPIException apiException) { - // Only requests that failed to send should be retried - return (Objects.equals(apiException.getMessage(), ERROR_CREATING_REQUEST_BODY)); - } - - /** - * @param responseCode HTTP error code of the response - * @param apiException BoxAPIException thrown - * @return true if the response is one that should be retried, otherwise false - */ - public static boolean isResponseRetryable(int responseCode, BoxAPIException apiException) { - if (responseCode >= 500 || responseCode == 429) { - return true; + } + } + if (key.equals("X-Box-UA")) { + throw new IllegalArgumentException("Altering the X-Box-UA header is not permitted"); + } + this.headers.add(new RequestHeader(key, value)); + } + + /** + * Gets the connect timeout for the request. + * + * @return the request connection timeout. + */ + public int getConnectTimeout() { + return this.connectTimeout; + } + + /** + * Sets a Connect timeout for this request in milliseconds. + * + * @param timeout the timeout in milliseconds. + */ + public void setConnectTimeout(int timeout) { + this.connectTimeout = timeout; + } + + /** + * Gets the read timeout for the request. + * + * @return the request's read timeout. + */ + public int getReadTimeout() { + return this.readTimeout; + } + + /** + * Sets a read timeout for this request in milliseconds. + * + * @param timeout the timeout in milliseconds. + */ + public void setReadTimeout(int timeout) { + this.readTimeout = timeout; + } + + /** + * Sets whether or not to follow redirects (i.e. Location header) + * + * @param followRedirects true to follow, false to not follow + */ + public void setFollowRedirects(boolean followRedirects) { + this.followRedirects = followRedirects; + } + + /** + * Gets the stream containing contents of this request's body. + * + *

Note that any bytes that read from the returned stream won't be sent unless the stream is + * reset back to its initial position. + * + * @return an InputStream containing the contents of this request's body. + */ + public InputStream getBody() { + return this.body; + } + + /** + * Sets the request body to the contents of an InputStream. + * + *

The stream must support the {@link InputStream#reset} method if auto-retry is used or if the + * request needs to be resent. Otherwise, the body must be manually set before each call to {@link + * #send}. + * + * @param stream an InputStream containing the contents of the body. + */ + public void setBody(InputStream stream) { + this.body = stream; + } + + /** + * Sets the request body to the contents of a String. + * + *

If the contents of the body are large, then it may be more efficient to use an {@link + * InputStream} instead of a String. Using a String requires that the entire body be in memory + * before sending the request. + * + * @param body a String containing the contents of the body. + */ + public void setBody(String body) { + byte[] bytes = body.getBytes(StandardCharsets.UTF_8); + this.bodyLength = bytes.length; + this.body = new ByteArrayInputStream(bytes); + } + + /** + * Sets the request body to the contents of an InputStream. + * + *

Providing the length of the InputStream allows for the progress of the request to be + * monitored when calling {@link #send(ProgressListener)}. + * + *

See {@link #setBody(InputStream)} for more information on setting the body of the request. + * + * @param stream an InputStream containing the contents of the body. + * @param length the expected length of the stream. + */ + public void setBody(InputStream stream, long length) { + this.bodyLength = length; + this.body = stream; + } + + /** + * Gets the URL from the request. + * + * @return a URL containing the URL of the request. + */ + public URL getUrl() { + return this.url; + } + + /** Sets the URL to the request. */ + public void setUrl(URL url) { + this.url = url; + } + + /** + * Gets the http method from the request. + * + * @return http method + */ + public String getMethod() { + return this.method; + } + + /** + * Get headers as list of RequestHeader objects. + * + * @return headers as list of RequestHeader objects + */ + List getHeaders() { + return this.headers; + } + + /** + * Sends this request and returns a BoxAPIResponse containing the server's response. + * + *

The type of the returned BoxAPIResponse will be based on the content type returned by the + * server, allowing it to be cast to a more specific type. For example, if it's known that the API + * call will return a JSON response, then it can be cast to a {@link BoxJSONResponse} like so: + * + *

BoxJSONResponse response = (BoxJSONResponse) request.sendWithoutRetry();
+ * + * @return a {@link BoxAPIResponse} containing the server's response. + * @throws BoxAPIException if the server returns an error code or if a network error occurs. + */ + public BoxAPIResponse sendWithoutRetry() { + return this.trySend(null); + } + + /** + * Sends this request and returns a BoxAPIResponse containing the server's response. + * + *

The type of the returned BoxAPIResponse will be based on the content type returned by the + * server, allowing it to be cast to a more specific type. For example, if it's known that the API + * call will return a JSON response, then it can be cast to a {@link BoxJSONResponse} like so: + * + *

BoxJSONResponse response = (BoxJSONResponse) request.send();
+ * + *

If the server returns an error code or if a network error occurs, then the request will be + * automatically retried. If the maximum number of retries is reached and an error still occurs, + * then a {@link BoxAPIException} will be thrown. + * + *

See {@link #send} for more information on sending requests. + * + * @return a {@link BoxAPIResponse} containing the server's response. + * @throws BoxAPIException if the server returns an error code or if a network error occurs. + */ + public BoxAPIResponse send() { + return this.send(null); + } + + /** + * Sends this request while monitoring its progress and returns a BoxAPIResponse containing the + * server's response. + * + *

The type of the returned BoxAPIResponse will be based on the content type returned by the + * server, allowing it to be cast to a more specific type. For example, if it's known that the API + * call will return a JSON response, then it can be cast to a {@link BoxJSONResponse} like so: + * + *

If the server returns an error code or if a network error occurs, then the request will be + * automatically retried. If the maximum number of retries is reached and an error still occurs, + * then a {@link BoxAPIException} will be thrown. + * + *

A ProgressListener is generally only useful when the size of the request is known + * beforehand. If the size is unknown, then the ProgressListener will be updated for each byte + * sent, but the total number of bytes will be reported as 0. + * + *

See {@link #send} for more information on sending requests. + * + * @param listener a listener for monitoring the progress of the request. + * @return a {@link BoxAPIResponse} containing the server's response. + * @throws BoxAPIException if the server returns an error code or if a network error occurs. + */ + public BoxAPIResponse send(ProgressListener listener) { + if (this.api == null) { + this.backoffCounter.reset(BoxGlobalSettings.getMaxRetryAttempts() + 1); + } else { + this.backoffCounter.reset(this.api.getMaxRetryAttempts() + 1); + } + + while (this.backoffCounter.getAttemptsRemaining() > 0) { + try { + return this.trySend(listener); + } catch (BoxAPIException apiException) { + if (!this.backoffCounter.decrement() + || (!isRequestRetryable(apiException) + && !isResponseRetryable(apiException.getResponseCode(), apiException))) { + throw apiException; } - return isClockSkewError(responseCode, apiException); - } - private static boolean isClockSkewError(int responseCode, BoxAPIException apiException) { - String response = apiException.getResponse(); - if (response == null || response.length() == 0) { - return false; - } - String message = apiException.getMessage(); - String errorCode = ""; + LOGGER.warn( + format( + "Retrying request due to transient error status=%d body=%s headers=%s", + apiException.getResponseCode(), + apiException.getResponse(), + mapToString(apiException.getHeaders()))); try { - JsonObject responseBody = Json.parse(response).asObject(); - if (responseBody.get("code") != null) { - errorCode = responseBody.get("code").toString(); - } else if (responseBody.get("error") != null) { - errorCode = responseBody.get("error").toString(); - } - - return responseCode == 400 && errorCode.contains("invalid_grant") && message.contains("exp"); - } catch (ParseException e) { - // 400 error which is not a JSON will not trigger a retry - throw new BoxAPIException("API returned an error", responseCode, response); + this.resetBody(); + } catch (IOException ioException) { + throw apiException; } - } - /** - * Adds an HTTP header to this request. - * - * @param key the header key. - * @param value the header value. - */ - public void addHeader(String key, String value) { - if (key.equals("As-User")) { - for (int i = 0; i < this.headers.size(); i++) { - if (this.headers.get(i).getKey().equals("As-User")) { - this.headers.remove(i); - } - } - } - if (key.equals("X-Box-UA")) { - throw new IllegalArgumentException("Altering the X-Box-UA header is not permitted"); + try { + List retryAfterHeader = apiException.getHeaders().get("Retry-After"); + if (retryAfterHeader == null) { + this.backoffCounter.waitBackoff(); + } else { + int retryAfterDelay = Integer.parseInt(retryAfterHeader.get(0)) * 1000; + this.backoffCounter.waitBackoff(retryAfterDelay); + } + } catch (InterruptedException interruptedException) { + Thread.currentThread().interrupt(); + throw apiException; } - this.headers.add(new RequestHeader(key, value)); - } - - /** - * Gets the connect timeout for the request. - * - * @return the request connection timeout. - */ - public int getConnectTimeout() { - return this.connectTimeout; - } - - /** - * Sets a Connect timeout for this request in milliseconds. - * - * @param timeout the timeout in milliseconds. - */ - public void setConnectTimeout(int timeout) { - this.connectTimeout = timeout; - } - - /** - * Gets the read timeout for the request. - * - * @return the request's read timeout. - */ - public int getReadTimeout() { - return this.readTimeout; - } - - /** - * Sets a read timeout for this request in milliseconds. - * - * @param timeout the timeout in milliseconds. - */ - public void setReadTimeout(int timeout) { - this.readTimeout = timeout; - } - - /** - * Sets whether or not to follow redirects (i.e. Location header) - * - * @param followRedirects true to follow, false to not follow - */ - public void setFollowRedirects(boolean followRedirects) { - this.followRedirects = followRedirects; - } - - /** - * Gets the stream containing contents of this request's body. - * - *

Note that any bytes that read from the returned stream won't be sent unless the stream is reset back to its - * initial position.

- * - * @return an InputStream containing the contents of this request's body. - */ - public InputStream getBody() { - return this.body; - } - - /** - * Sets the request body to the contents of an InputStream. - * - *

The stream must support the {@link InputStream#reset} method if auto-retry is used or if the request needs to - * be resent. Otherwise, the body must be manually set before each call to {@link #send}.

- * - * @param stream an InputStream containing the contents of the body. - */ - public void setBody(InputStream stream) { - this.body = stream; - } - - /** - * Sets the request body to the contents of a String. - * - *

If the contents of the body are large, then it may be more efficient to use an {@link InputStream} instead of - * a String. Using a String requires that the entire body be in memory before sending the request.

- * - * @param body a String containing the contents of the body. - */ - public void setBody(String body) { - byte[] bytes = body.getBytes(StandardCharsets.UTF_8); - this.bodyLength = bytes.length; - this.body = new ByteArrayInputStream(bytes); - } - - /** - * Sets the request body to the contents of an InputStream. - * - *

Providing the length of the InputStream allows for the progress of the request to be monitored when calling - * {@link #send(ProgressListener)}.

- * - *

See {@link #setBody(InputStream)} for more information on setting the body of the request.

- * - * @param stream an InputStream containing the contents of the body. - * @param length the expected length of the stream. - */ - public void setBody(InputStream stream, long length) { - this.bodyLength = length; - this.body = stream; - } - - /** - * Gets the URL from the request. - * - * @return a URL containing the URL of the request. - */ - public URL getUrl() { - return this.url; - } - - /** - * Sets the URL to the request. - * - */ - public void setUrl(URL url) { - this.url = url; - } - - /** - * Gets the http method from the request. - * - * @return http method - */ - public String getMethod() { - return this.method; - } - - /** - * Get headers as list of RequestHeader objects. - * - * @return headers as list of RequestHeader objects - */ - List getHeaders() { - return this.headers; - } - - /** - * Sends this request and returns a BoxAPIResponse containing the server's response. - * - *

The type of the returned BoxAPIResponse will be based on the content type returned by the server, allowing it - * to be cast to a more specific type. For example, if it's known that the API call will return a JSON response, - * then it can be cast to a {@link BoxJSONResponse} like so:

- * - *
BoxJSONResponse response = (BoxJSONResponse) request.sendWithoutRetry();
- * - * @return a {@link BoxAPIResponse} containing the server's response. - * @throws BoxAPIException if the server returns an error code or if a network error occurs. - */ - public BoxAPIResponse sendWithoutRetry() { - return this.trySend(null); - } - - /** - * Sends this request and returns a BoxAPIResponse containing the server's response. - * - *

The type of the returned BoxAPIResponse will be based on the content type returned by the server, allowing it - * to be cast to a more specific type. For example, if it's known that the API call will return a JSON response, - * then it can be cast to a {@link BoxJSONResponse} like so:

- * - *
BoxJSONResponse response = (BoxJSONResponse) request.send();
- * - *

If the server returns an error code or if a network error occurs, then the request will be automatically - * retried. If the maximum number of retries is reached and an error still occurs, then a {@link BoxAPIException} - * will be thrown.

- * - *

See {@link #send} for more information on sending requests.

- * - * @return a {@link BoxAPIResponse} containing the server's response. - * @throws BoxAPIException if the server returns an error code or if a network error occurs. - */ - public BoxAPIResponse send() { - return this.send(null); - } - - /** - * Sends this request while monitoring its progress and returns a BoxAPIResponse containing the server's response. - * - *

The type of the returned BoxAPIResponse will be based on the content type returned by the server, allowing it - * to be cast to a more specific type. For example, if it's known that the API call will return a JSON response, - * then it can be cast to a {@link BoxJSONResponse} like so:

- * - *

If the server returns an error code or if a network error occurs, then the request will be automatically - * retried. If the maximum number of retries is reached and an error still occurs, then a {@link BoxAPIException} - * will be thrown.

- * - *

A ProgressListener is generally only useful when the size of the request is known beforehand. If the size is - * unknown, then the ProgressListener will be updated for each byte sent, but the total number of bytes will be - * reported as 0.

- * - *

See {@link #send} for more information on sending requests.

- * - * @param listener a listener for monitoring the progress of the request. - * @return a {@link BoxAPIResponse} containing the server's response. - * @throws BoxAPIException if the server returns an error code or if a network error occurs. - */ - public BoxAPIResponse send(ProgressListener listener) { - if (this.api == null) { - this.backoffCounter.reset(BoxGlobalSettings.getMaxRetryAttempts() + 1); - } else { - this.backoffCounter.reset(this.api.getMaxRetryAttempts() + 1); + } + } + + throw new RuntimeException(); + } + + /** + * Disables adding authentication header to request. Useful when you want to add your own + * authentication method. Default value is `true` and SKD will add authenticaton header to + * request. + * + * @param shouldAuthenticate use `false` to disable authentication. + */ + public void shouldAuthenticate(boolean shouldAuthenticate) { + this.shouldAuthenticate = shouldAuthenticate; + } + + /** + * Sends a request to upload a file part and returns a BoxFileUploadSessionPart containing + * information about the upload part. This method is separate from send() because it has custom + * retry logic. + * + *

If the server returns an error code or if a network error occurs, then the request will be + * automatically retried. If the maximum number of retries is reached and an error still occurs, + * then a {@link BoxAPIException} will be thrown. + * + * @param session The BoxFileUploadSession uploading the part + * @param offset Offset of the part being uploaded + * @return A {@link BoxFileUploadSessionPart} part that has been uploaded. + * @throws BoxAPIException if the server returns an error code or if a network error occurs. + */ + BoxFileUploadSessionPart sendForUploadPart(BoxFileUploadSession session, long offset) { + if (this.api == null) { + this.backoffCounter.reset(BoxGlobalSettings.getMaxRetryAttempts() + 1); + } else { + this.backoffCounter.reset(this.api.getMaxRetryAttempts() + 1); + } + + while (this.backoffCounter.getAttemptsRemaining() > 0) { + try (BoxJSONResponse response = (BoxJSONResponse) this.trySend(null)) { + // upload sends binary data but response is JSON + JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); + return new BoxFileUploadSessionPart((JsonObject) jsonObject.get("part")); + } catch (BoxAPIException apiException) { + if (!this.backoffCounter.decrement() + || (!isRequestRetryable(apiException) + && !isResponseRetryable(apiException.getResponseCode(), apiException))) { + throw apiException; } - - while (this.backoffCounter.getAttemptsRemaining() > 0) { - try { - return this.trySend(listener); - } catch (BoxAPIException apiException) { - if (!this.backoffCounter.decrement() - || (!isRequestRetryable(apiException) - && !isResponseRetryable(apiException.getResponseCode(), apiException))) { - throw apiException; - } - - LOGGER.warn( - format("Retrying request due to transient error status=%d body=%s headers=%s", - apiException.getResponseCode(), - apiException.getResponse(), - mapToString(apiException.getHeaders())) - ); - - try { - this.resetBody(); - } catch (IOException ioException) { - throw apiException; - } - - try { - List retryAfterHeader = apiException.getHeaders().get("Retry-After"); - if (retryAfterHeader == null) { - this.backoffCounter.waitBackoff(); - } else { - int retryAfterDelay = Integer.parseInt(retryAfterHeader.get(0)) * 1000; - this.backoffCounter.waitBackoff(retryAfterDelay); - } - } catch (InterruptedException interruptedException) { - Thread.currentThread().interrupt(); - throw apiException; - } + if (apiException.getResponseCode() == 500) { + try { + Iterable parts = session.listParts(); + for (BoxFileUploadSessionPart part : parts) { + if (part.getOffset() == offset) { + return part; + } } + } catch (BoxAPIException e) { + // ignoring exception as we are retrying + } } + LOGGER.warn( + format( + "Retrying request due to transient error status=%d body=%s", + apiException.getResponseCode(), apiException.getResponse())); - throw new RuntimeException(); - } - - /** - * Disables adding authentication header to request. - * Useful when you want to add your own authentication method. - * Default value is `true` and SKD will add authenticaton header to request. - * - * @param shouldAuthenticate use `false` to disable authentication. - */ - public void shouldAuthenticate(boolean shouldAuthenticate) { - this.shouldAuthenticate = shouldAuthenticate; - } - - /** - * Sends a request to upload a file part and returns a BoxFileUploadSessionPart containing information - * about the upload part. This method is separate from send() because it has custom retry logic. - * - *

If the server returns an error code or if a network error occurs, then the request will be automatically - * retried. If the maximum number of retries is reached and an error still occurs, then a {@link BoxAPIException} - * will be thrown.

- * - * @param session The BoxFileUploadSession uploading the part - * @param offset Offset of the part being uploaded - * @return A {@link BoxFileUploadSessionPart} part that has been uploaded. - * @throws BoxAPIException if the server returns an error code or if a network error occurs. - */ - BoxFileUploadSessionPart sendForUploadPart(BoxFileUploadSession session, long offset) { - if (this.api == null) { - this.backoffCounter.reset(BoxGlobalSettings.getMaxRetryAttempts() + 1); - } else { - this.backoffCounter.reset(this.api.getMaxRetryAttempts() + 1); - } - - while (this.backoffCounter.getAttemptsRemaining() > 0) { - try (BoxJSONResponse response = (BoxJSONResponse) this.trySend(null)) { - // upload sends binary data but response is JSON - JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - return new BoxFileUploadSessionPart((JsonObject) jsonObject.get("part")); - } catch (BoxAPIException apiException) { - if (!this.backoffCounter.decrement() - || (!isRequestRetryable(apiException) - && !isResponseRetryable(apiException.getResponseCode(), apiException))) { - throw apiException; - } - if (apiException.getResponseCode() == 500) { - try { - Iterable parts = session.listParts(); - for (BoxFileUploadSessionPart part : parts) { - if (part.getOffset() == offset) { - return part; - } - } - } catch (BoxAPIException e) { - // ignoring exception as we are retrying - } - } - LOGGER.warn(format( - "Retrying request due to transient error status=%d body=%s", - apiException.getResponseCode(), - apiException.getResponse() - )); - - try { - this.resetBody(); - } catch (IOException ioException) { - throw apiException; - } - - try { - this.backoffCounter.waitBackoff(); - } catch (InterruptedException interruptedException) { - Thread.currentThread().interrupt(); - throw apiException; - } - } + try { + this.resetBody(); + } catch (IOException ioException) { + throw apiException; } - throw new RuntimeException(); - } - - /** - * Returns a String containing the URL, HTTP method, headers and body of this request. - * - * @return a String containing information about this request. - */ - @Override - public String toString() { - return toStringWithHeaders(null); - } - - private String toStringWithHeaders(Headers headers) { - String lineSeparator = System.getProperty("line.separator"); - StringBuilder builder = new StringBuilder(); - builder.append("Request"); - builder.append(lineSeparator); - builder.append(this.method); - builder.append(' '); - builder.append(this.url.toString()); - builder.append(lineSeparator); - if (headers != null) { - builder.append("Headers:").append(lineSeparator); - sanitizeHeaders(headers) - .forEach(h -> builder.append(format("%s: [%s]%s", h.getFirst(), h.getSecond(), lineSeparator))); + try { + this.backoffCounter.waitBackoff(); + } catch (InterruptedException interruptedException) { + Thread.currentThread().interrupt(); + throw apiException; } - - String bodyString = this.bodyToString(); - if (bodyString != null) { - builder.append(lineSeparator); - builder.append(bodyString); + } + } + + throw new RuntimeException(); + } + + /** + * Returns a String containing the URL, HTTP method, headers and body of this request. + * + * @return a String containing information about this request. + */ + @Override + public String toString() { + return toStringWithHeaders(null); + } + + private String toStringWithHeaders(Headers headers) { + String lineSeparator = System.getProperty("line.separator"); + StringBuilder builder = new StringBuilder(); + builder.append("Request"); + builder.append(lineSeparator); + builder.append(this.method); + builder.append(' '); + builder.append(this.url.toString()); + builder.append(lineSeparator); + if (headers != null) { + builder.append("Headers:").append(lineSeparator); + sanitizeHeaders(headers) + .forEach( + h -> + builder.append(format("%s: [%s]%s", h.getFirst(), h.getSecond(), lineSeparator))); + } + + String bodyString = this.bodyToString(); + if (bodyString != null) { + builder.append(lineSeparator); + builder.append(bodyString); + } + + return builder.toString().trim(); + } + + /** + * Returns a String representation of this request's body used in {@link #toString}. This method + * returns null by default. + * + *

A subclass may want override this method if the body can be converted to a String for + * logging or debugging purposes. + * + * @return a String representation of this request's body. + */ + protected String bodyToString() { + return null; + } + + private void writeWithBuffer(OutputStream output, ProgressListener listener) { + try { + OutputStream finalOutput = output; + if (listener != null) { + finalOutput = new ProgressOutputStream(output, listener, this.bodyLength); + } + byte[] buffer = new byte[BUFFER_SIZE]; + int b = this.body.read(buffer); + while (b != -1) { + finalOutput.write(buffer, 0, b); + b = this.body.read(buffer); + } + } catch (IOException e) { + throw new RuntimeException("Error writting body", e); + } + } + + /** + * Resets the InputStream containing this request's body. + * + *

This method will be called before each attempt to resend the request, giving subclasses an + * opportunity to reset any streams that need to be read when sending the body. + * + * @throws IOException if the stream cannot be reset. + */ + protected void resetBody() throws IOException { + if (this.body != null) { + this.body.reset(); + } + } + + void setBackoffCounter(BackoffCounter counter) { + this.backoffCounter = counter; + } + + private BoxAPIResponse trySend(ProgressListener listener) { + if (this.api != null) { + RequestInterceptor interceptor = this.api.getRequestInterceptor(); + if (interceptor != null) { + BoxAPIResponse response = interceptor.onRequest(this); + if (response != null) { + return response; } - - return builder.toString().trim(); - } + } + } + long start = System.currentTimeMillis(); + Request request = composeRequest(listener); + Response response; + this.logRequest(request.headers()); + if (this.followRedirects) { + response = api.execute(request); + } else { + response = api.executeWithoutRedirect(request); + } + logDebug( + format("[trySend] connection.connect() took %dms%n", (System.currentTimeMillis() - start))); + + BoxAPIResponse result = BoxAPIResponse.toBoxResponse(response); + long getResponseStart = System.currentTimeMillis(); + logDebug( + format( + "[trySend] Get Response (read network) took %dms%n", + System.currentTimeMillis() - getResponseStart)); + return result; + } + + private Request composeRequest(ProgressListener listener) { + Request.Builder requestBuilder = new Request.Builder().url(getUrl()); + if (this.shouldAuthenticate) { + requestBuilder.addHeader(HttpHeaders.AUTHORIZATION, "Bearer " + this.api.lockAccessToken()); + } + try { + requestBuilder.addHeader("User-Agent", this.api.getUserAgent()); + requestBuilder.addHeader("X-Box-UA", this.api.getBoxUAHeader()); + headers.forEach( + h -> { + requestBuilder.removeHeader(h.getKey()); + requestBuilder.addHeader(h.getKey(), h.getValue()); + }); + + if (this.api instanceof SharedLinkAPIConnection) { + SharedLinkAPIConnection sharedItemAPI = (SharedLinkAPIConnection) this.api; + String boxAPIValue = + BoxSharedLink.getSharedLinkHeaderValue( + sharedItemAPI.getSharedLink(), sharedItemAPI.getSharedLinkPassword()); + requestBuilder.addHeader("BoxApi", boxAPIValue); + } + + writeMethodWithBody(requestBuilder, listener); + return requestBuilder.build(); + } finally { + if (this.shouldAuthenticate) { + this.api.unlockAccessToken(); + } + } + } + + protected void writeMethodWithBody(Request.Builder requestBuilder, ProgressListener listener) { + ByteArrayOutputStream bodyBytes = new ByteArrayOutputStream(); + if (body != null) { + long writeStart = System.currentTimeMillis(); + writeWithBuffer(bodyBytes, listener); + logDebug( + format("[trySend] Body write took %dms%n", (System.currentTimeMillis() - writeStart))); + } + if (method.equals("GET")) { + requestBuilder.get(); + } + if (method.equals("DELETE")) { + requestBuilder.delete(); + } + if (method.equals("OPTIONS")) { + if (body == null) { + requestBuilder.method("OPTIONS", null); + } else { + requestBuilder.method("OPTIONS", RequestBody.create(bodyBytes.toByteArray(), mediaType())); + } + } + if (method.equals("POST")) { + requestBuilder.post(RequestBody.create(bodyBytes.toByteArray(), mediaType())); + } + if (method.equals("PUT")) { + requestBuilder.put(RequestBody.create(bodyBytes.toByteArray(), mediaType())); + } + } + + private void logDebug(String message) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(message); + } + } + + private void logRequest(Headers headers) { + logDebug(headers != null ? this.toStringWithHeaders(headers) : this.toString()); + } + + /** Class for mapping a request header and value. */ + public static final class RequestHeader { + private final String key; + private final String value; /** - * Returns a String representation of this request's body used in {@link #toString}. This method returns - * null by default. - * - *

A subclass may want override this method if the body can be converted to a String for logging or debugging - * purposes.

+ * Construct a request header from header key and value. * - * @return a String representation of this request's body. + * @param key header name + * @param value header value */ - protected String bodyToString() { - return null; - } - - private void writeWithBuffer(OutputStream output, ProgressListener listener) { - try { - OutputStream finalOutput = output; - if (listener != null) { - finalOutput = new ProgressOutputStream(output, listener, this.bodyLength); - } - byte[] buffer = new byte[BUFFER_SIZE]; - int b = this.body.read(buffer); - while (b != -1) { - finalOutput.write(buffer, 0, b); - b = this.body.read(buffer); - } - } catch (IOException e) { - throw new RuntimeException("Error writting body", e); - } + public RequestHeader(String key, String value) { + this.key = key; + this.value = value; } /** - * Resets the InputStream containing this request's body. - * - *

This method will be called before each attempt to resend the request, giving subclasses an opportunity to - * reset any streams that need to be read when sending the body.

+ * Get header key. * - * @throws IOException if the stream cannot be reset. + * @return http header name */ - protected void resetBody() throws IOException { - if (this.body != null) { - this.body.reset(); - } - } - - void setBackoffCounter(BackoffCounter counter) { - this.backoffCounter = counter; - } - - private BoxAPIResponse trySend(ProgressListener listener) { - if (this.api != null) { - RequestInterceptor interceptor = this.api.getRequestInterceptor(); - if (interceptor != null) { - BoxAPIResponse response = interceptor.onRequest(this); - if (response != null) { - return response; - } - } - } - long start = System.currentTimeMillis(); - Request request = composeRequest(listener); - Response response; - this.logRequest(request.headers()); - if (this.followRedirects) { - response = api.execute(request); - } else { - response = api.executeWithoutRedirect(request); - } - logDebug(format("[trySend] connection.connect() took %dms%n", (System.currentTimeMillis() - start))); - - BoxAPIResponse result = BoxAPIResponse.toBoxResponse(response); - long getResponseStart = System.currentTimeMillis(); - logDebug(format( - "[trySend] Get Response (read network) took %dms%n", System.currentTimeMillis() - getResponseStart - )); - return result; - } - - private Request composeRequest(ProgressListener listener) { - Request.Builder requestBuilder = new Request.Builder().url(getUrl()); - if (this.shouldAuthenticate) { - requestBuilder.addHeader(HttpHeaders.AUTHORIZATION, "Bearer " + this.api.lockAccessToken()); - } - try { - requestBuilder.addHeader("User-Agent", this.api.getUserAgent()); - requestBuilder.addHeader("X-Box-UA", this.api.getBoxUAHeader()); - headers.forEach(h -> { - requestBuilder.removeHeader(h.getKey()); - requestBuilder.addHeader(h.getKey(), h.getValue()); - }); - - if (this.api instanceof SharedLinkAPIConnection) { - SharedLinkAPIConnection sharedItemAPI = (SharedLinkAPIConnection) this.api; - String boxAPIValue = BoxSharedLink.getSharedLinkHeaderValue( - sharedItemAPI.getSharedLink(), - sharedItemAPI.getSharedLinkPassword() - ); - requestBuilder.addHeader("BoxApi", boxAPIValue); - } - - - writeMethodWithBody(requestBuilder, listener); - return requestBuilder.build(); - } finally { - if (this.shouldAuthenticate) { - this.api.unlockAccessToken(); - } - } - } - - protected void writeMethodWithBody(Request.Builder requestBuilder, ProgressListener listener) { - ByteArrayOutputStream bodyBytes = new ByteArrayOutputStream(); - if (body != null) { - long writeStart = System.currentTimeMillis(); - writeWithBuffer(bodyBytes, listener); - logDebug(format("[trySend] Body write took %dms%n", (System.currentTimeMillis() - writeStart))); - } - if (method.equals("GET")) { - requestBuilder.get(); - } - if (method.equals("DELETE")) { - requestBuilder.delete(); - } - if (method.equals("OPTIONS")) { - if (body == null) { - requestBuilder.method("OPTIONS", null); - } else { - requestBuilder.method("OPTIONS", RequestBody.create(bodyBytes.toByteArray(), mediaType())); - } - } - if (method.equals("POST")) { - requestBuilder.post(RequestBody.create(bodyBytes.toByteArray(), mediaType())); - } - if (method.equals("PUT")) { - requestBuilder.put(RequestBody.create(bodyBytes.toByteArray(), mediaType())); - } - } - - private void logDebug(String message) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(message); - } - } - - private void logRequest(Headers headers) { - logDebug(headers != null ? this.toStringWithHeaders(headers) : this.toString()); + public String getKey() { + return this.key; } /** - * Class for mapping a request header and value. + * Get header value. + * + * @return http header value */ - public static final class RequestHeader { - private final String key; - private final String value; - - /** - * Construct a request header from header key and value. - * - * @param key header name - * @param value header value - */ - public RequestHeader(String key, String value) { - this.key = key; - this.value = value; - } - - /** - * Get header key. - * - * @return http header name - */ - public String getKey() { - return this.key; - } - - /** - * Get header value. - * - * @return http header value - */ - public String getValue() { - return this.value; - } + public String getValue() { + return this.value; } + } - protected MediaType mediaType() { - return MediaType.parse(mediaType); - } + protected MediaType mediaType() { + return MediaType.parse(mediaType); + } } diff --git a/src/main/java/com/box/sdk/BoxAPIResponse.java b/src/main/java/com/box/sdk/BoxAPIResponse.java index 59bab8ed7..722a61124 100644 --- a/src/main/java/com/box/sdk/BoxAPIResponse.java +++ b/src/main/java/com/box/sdk/BoxAPIResponse.java @@ -24,350 +24,364 @@ /** * Used to read HTTP responses from the Box API. * - *

- * All responses from the REST API are read using this class or one of its subclasses. This class wraps {@link - * HttpURLConnection} in order to provide a simpler interface that can automatically handle various conditions specific - * to Box's API. When a response is contructed, it will throw a {@link BoxAPIException} if the response from the API - * was an error. Therefore every BoxAPIResponse instance is guaranteed to represent a successful response. - *

+ *

All responses from the REST API are read using this class or one of its subclasses. This class + * wraps {@link HttpURLConnection} in order to provide a simpler interface that can automatically + * handle various conditions specific to Box's API. When a response is contructed, it will throw a + * {@link BoxAPIException} if the response from the API was an error. Therefore every BoxAPIResponse + * instance is guaranteed to represent a successful response. * - *

- * This class usually isn't instantiated directly, but is instead returned after calling {@link BoxAPIRequest#send}. - *

+ *

This class usually isn't instantiated directly, but is instead returned after calling {@link + * BoxAPIRequest#send}. */ public class BoxAPIResponse implements Closeable { - private static final int BUFFER_SIZE = 8192; - private static final BoxLogger LOGGER = BoxLogger.defaultLogger(); - private final Map> headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); - private final long contentLength; - private final String contentType; - private final String requestMethod; - private final String requestUrl; - private int responseCode; - private String bodyString; + private static final int BUFFER_SIZE = 8192; + private static final BoxLogger LOGGER = BoxLogger.defaultLogger(); + private final Map> headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + private final long contentLength; + private final String contentType; + private final String requestMethod; + private final String requestUrl; + private int responseCode; + private String bodyString; - /** - * The raw InputStream is the stream returned directly from HttpURLConnection.getInputStream(). We need to keep - * track of this stream in case we need to access it after wrapping it inside another stream. - */ - private InputStream rawInputStream; + /** + * The raw InputStream is the stream returned directly from HttpURLConnection.getInputStream(). We + * need to keep track of this stream in case we need to access it after wrapping it inside another + * stream. + */ + private InputStream rawInputStream; - /** - * The regular InputStream is the stream that will be returned by getBody(). This stream might be a GZIPInputStream - * or a ProgressInputStream (or both) that wrap the raw InputStream. - */ - private InputStream inputStream; + /** + * The regular InputStream is the stream that will be returned by getBody(). This stream might be + * a GZIPInputStream or a ProgressInputStream (or both) that wrap the raw InputStream. + */ + private InputStream inputStream; - /** - * Constructs an empty BoxAPIResponse without an associated HttpURLConnection. - */ - public BoxAPIResponse() { - this.contentLength = 0; - this.contentType = null; - this.requestMethod = null; - this.requestUrl = null; - } + /** Constructs an empty BoxAPIResponse without an associated HttpURLConnection. */ + public BoxAPIResponse() { + this.contentLength = 0; + this.contentType = null; + this.requestMethod = null; + this.requestUrl = null; + } - /** - * Constructs a BoxAPIResponse with a http response code and response headers. - * - * @param responseCode http response code - * @param headers map of headers - */ - public BoxAPIResponse( - int responseCode, String requestMethod, String requestUrl, Map> headers - ) { - this(responseCode, requestMethod, requestUrl, headers, null, null, 0); - } + /** + * Constructs a BoxAPIResponse with a http response code and response headers. + * + * @param responseCode http response code + * @param headers map of headers + */ + public BoxAPIResponse( + int responseCode, + String requestMethod, + String requestUrl, + Map> headers) { + this(responseCode, requestMethod, requestUrl, headers, null, null, 0); + } - public BoxAPIResponse(int responseCode, - String requestMethod, - String requestUrl, - Map> headers, - String bodyString, - String contentType) { - this(responseCode, requestMethod, requestUrl, headers, null, contentType, 0, bodyString); - } + public BoxAPIResponse( + int responseCode, + String requestMethod, + String requestUrl, + Map> headers, + String bodyString, + String contentType) { + this(responseCode, requestMethod, requestUrl, headers, null, contentType, 0, bodyString); + } - public BoxAPIResponse(int code, - String requestMethod, - String requestUrl, - Map> headers, - InputStream body, - String contentType, - long contentLength - ) { - this(code, requestMethod, requestUrl, headers, body, contentType, contentLength, null); - } + public BoxAPIResponse( + int code, + String requestMethod, + String requestUrl, + Map> headers, + InputStream body, + String contentType, + long contentLength) { + this(code, requestMethod, requestUrl, headers, body, contentType, contentLength, null); + } - public BoxAPIResponse(int code, - String requestMethod, - String requestUrl, - Map> headers, - InputStream body, - String contentType, - long contentLength, - String bodyString - ) { - this.responseCode = code; - this.requestMethod = requestMethod; - this.requestUrl = requestUrl; - if (headers != null) { - this.headers.putAll(headers); - } - this.rawInputStream = body; - this.contentType = contentType; - this.contentLength = contentLength; - this.bodyString = bodyString; - if (body != null) { - storeBodyResponse(body); - } - if (isSuccess(responseCode)) { - this.logResponse(); - } else { - this.logErrorResponse(this.responseCode); - throw new BoxAPIResponseException("The API returned an error code", responseCode, null, headers); - } + public BoxAPIResponse( + int code, + String requestMethod, + String requestUrl, + Map> headers, + InputStream body, + String contentType, + long contentLength, + String bodyString) { + this.responseCode = code; + this.requestMethod = requestMethod; + this.requestUrl = requestUrl; + if (headers != null) { + this.headers.putAll(headers); } - - private static boolean isSuccess(int responseCode) { - return responseCode >= 200 && responseCode < 400; + this.rawInputStream = body; + this.contentType = contentType; + this.contentLength = contentLength; + this.bodyString = bodyString; + if (body != null) { + storeBodyResponse(body); } + if (isSuccess(responseCode)) { + this.logResponse(); + } else { + this.logErrorResponse(this.responseCode); + throw new BoxAPIResponseException( + "The API returned an error code", responseCode, null, headers); + } + } + + private static boolean isSuccess(int responseCode) { + return responseCode >= 200 && responseCode < 400; + } - static BoxAPIResponse toBoxResponse(Response response) { - if (!response.isSuccessful() && !response.isRedirect()) { - throw new BoxAPIResponseException( - "The API returned an error code", - response.code(), - Optional.ofNullable(response.body()).map(body -> { + static BoxAPIResponse toBoxResponse(Response response) { + if (!response.isSuccessful() && !response.isRedirect()) { + throw new BoxAPIResponseException( + "The API returned an error code", + response.code(), + Optional.ofNullable(response.body()) + .map( + body -> { try { - return body.string(); + return body.string(); } catch (IOException e) { - throw new RuntimeException(e); + throw new RuntimeException(e); } - }).orElse("Body was null"), - response.headers().toMultimap() - ); - } - ResponseBody responseBody = response.body(); - if (responseBody.contentType() == null) { - try { - return emptyContentResponse(response); - } finally { - responseBody.close(); - } - } - if (responseBody != null && responseBody.contentType() != null) { - if (responseBody.contentType().toString().contains(APPLICATION_JSON)) { - if (responseBody.contentLength() == 0) { - return emptyContentResponse(response); - } - String bodyAsString = ""; - try { - bodyAsString = responseBody.string(); - return new BoxJSONResponse(response.code(), - response.request().method(), - response.request().url().toString(), - response.headers().toMultimap(), - Json.parse(bodyAsString).asObject() - ); - } catch (ParseException e) { - throw new BoxAPIException(format("Error parsing JSON:\n%s", bodyAsString), e); - } catch (IOException e) { - throw new RuntimeException("Error getting response to string", e); - } finally { - responseBody.close(); - } - } - } - return new BoxAPIResponse(response.code(), - response.request().method(), - response.request().url().toString(), - response.headers().toMultimap(), - responseBody.byteStream(), - Optional.ofNullable(responseBody.contentType()).map(MediaType::toString).orElse(null), - responseBody.contentLength() - ); + }) + .orElse("Body was null"), + response.headers().toMultimap()); } - - private static BoxAPIResponse emptyContentResponse(Response response) { - return new BoxAPIResponse(response.code(), - response.request().method(), - response.request().url().toString(), - response.headers().toMultimap() - ); + ResponseBody responseBody = response.body(); + if (responseBody.contentType() == null) { + try { + return emptyContentResponse(response); + } finally { + responseBody.close(); + } } - - private void storeBodyResponse(InputStream body) { + if (responseBody != null && responseBody.contentType() != null) { + if (responseBody.contentType().toString().contains(APPLICATION_JSON)) { + if (responseBody.contentLength() == 0) { + return emptyContentResponse(response); + } + String bodyAsString = ""; try { - if (contentType != null && body != null && contentType.contains(APPLICATION_JSON) && body.available() > 0) { - InputStreamReader reader = new InputStreamReader(this.getBody(), UTF_8); - StringBuilder builder = new StringBuilder(); - char[] buffer = new char[BUFFER_SIZE]; - - int read = reader.read(buffer, 0, BUFFER_SIZE); - while (read != -1) { - builder.append(buffer, 0, read); - read = reader.read(buffer, 0, BUFFER_SIZE); - } - reader.close(); - this.disconnect(); - bodyString = builder.toString(); - rawInputStream = new ByteArrayInputStream(bodyString.getBytes(UTF_8)); - } + bodyAsString = responseBody.string(); + return new BoxJSONResponse( + response.code(), + response.request().method(), + response.request().url().toString(), + response.headers().toMultimap(), + Json.parse(bodyAsString).asObject()); + } catch (ParseException e) { + throw new BoxAPIException(format("Error parsing JSON:\n%s", bodyAsString), e); } catch (IOException e) { - throw new RuntimeException("Cannot read body stream", e); + throw new RuntimeException("Error getting response to string", e); + } finally { + responseBody.close(); } + } } + return new BoxAPIResponse( + response.code(), + response.request().method(), + response.request().url().toString(), + response.headers().toMultimap(), + responseBody.byteStream(), + Optional.ofNullable(responseBody.contentType()).map(MediaType::toString).orElse(null), + responseBody.contentLength()); + } - /** - * Gets the response code returned by the API. - * - * @return the response code returned by the API. - */ - public int getResponseCode() { - return this.responseCode; - } + private static BoxAPIResponse emptyContentResponse(Response response) { + return new BoxAPIResponse( + response.code(), + response.request().method(), + response.request().url().toString(), + response.headers().toMultimap()); + } - /** - * Gets the length of this response's body as indicated by the "Content-Length" header. - * - * @return the length of the response's body. - */ - public long getContentLength() { - return this.contentLength; - } + private void storeBodyResponse(InputStream body) { + try { + if (contentType != null + && body != null + && contentType.contains(APPLICATION_JSON) + && body.available() > 0) { + InputStreamReader reader = new InputStreamReader(this.getBody(), UTF_8); + StringBuilder builder = new StringBuilder(); + char[] buffer = new char[BUFFER_SIZE]; - /** - * Gets the value of the given header field. - * - * @param fieldName name of the header field. - * @return value of the header. - */ - public String getHeaderField(String fieldName) { - return Optional.ofNullable(this.headers.get(fieldName)).map((l) -> l.get(0)).orElse(""); + int read = reader.read(buffer, 0, BUFFER_SIZE); + while (read != -1) { + builder.append(buffer, 0, read); + read = reader.read(buffer, 0, BUFFER_SIZE); + } + reader.close(); + this.disconnect(); + bodyString = builder.toString(); + rawInputStream = new ByteArrayInputStream(bodyString.getBytes(UTF_8)); + } + } catch (IOException e) { + throw new RuntimeException("Cannot read body stream", e); } + } - /** - * Gets an InputStream for reading this response's body. - * - * @return an InputStream for reading the response's body. - */ - public InputStream getBody() { - return this.getBody(null); - } + /** + * Gets the response code returned by the API. + * + * @return the response code returned by the API. + */ + public int getResponseCode() { + return this.responseCode; + } - /** - * Gets an InputStream for reading this response's body which will report its read progress to a ProgressListener. - * - * @param listener a listener for monitoring the read progress of the body. - * @return an InputStream for reading the response's body. - */ - public InputStream getBody(ProgressListener listener) { - if (this.inputStream == null) { - if (listener == null) { - this.inputStream = this.rawInputStream; - } else { - this.inputStream = new ProgressInputStream(this.rawInputStream, listener, this.getContentLength()); - } - } - return this.inputStream; - } + /** + * Gets the length of this response's body as indicated by the "Content-Length" header. + * + * @return the length of the response's body. + */ + public long getContentLength() { + return this.contentLength; + } - /** - * Disconnects this response from the server and frees up any network resources. The body of this response can no - * longer be read after it has been disconnected. - */ - public void disconnect() { - this.close(); - } + /** + * Gets the value of the given header field. + * + * @param fieldName name of the header field. + * @return value of the header. + */ + public String getHeaderField(String fieldName) { + return Optional.ofNullable(this.headers.get(fieldName)).map((l) -> l.get(0)).orElse(""); + } - /** - * @return A Map containg headers on this Box API Response. - */ - public Map> getHeaders() { - return this.headers; + /** + * Gets an InputStream for reading this response's body. + * + * @return an InputStream for reading the response's body. + */ + public InputStream getBody() { + return this.getBody(null); + } + + /** + * Gets an InputStream for reading this response's body which will report its read progress to a + * ProgressListener. + * + * @param listener a listener for monitoring the read progress of the body. + * @return an InputStream for reading the response's body. + */ + public InputStream getBody(ProgressListener listener) { + if (this.inputStream == null) { + if (listener == null) { + this.inputStream = this.rawInputStream; + } else { + this.inputStream = + new ProgressInputStream(this.rawInputStream, listener, this.getContentLength()); + } } + return this.inputStream; + } - @Override - public String toString() { - String lineSeparator = System.getProperty("line.separator"); - StringBuilder builder = new StringBuilder(); - builder.append("Response") - .append(lineSeparator) - .append(this.requestMethod) - .append(' ') - .append(this.requestUrl) - .append(' ') - .append(this.responseCode) - .append(lineSeparator) - .append(contentType != null ? "Content-Type: " + contentType + lineSeparator : "") - .append(headers.isEmpty() ? "" : "Headers:" + lineSeparator); - headers.entrySet() - .stream() - .filter(Objects::nonNull) - .forEach(e -> builder.append(format("%s: [%s]%s", e.getKey().toLowerCase(java.util.Locale.ROOT), - e.getValue(), lineSeparator))); + /** + * Disconnects this response from the server and frees up any network resources. The body of this + * response can no longer be read after it has been disconnected. + */ + public void disconnect() { + this.close(); + } - String bodyString = this.bodyToString(); - if (bodyString != null && !bodyString.equals("")) { - String sanitizedBodyString = contentType.equals(APPLICATION_JSON) - ? BoxSensitiveDataSanitizer.sanitizeJsonBody(Json.parse(bodyString).asObject()).toString() - : bodyString; - builder.append("Body:").append(lineSeparator).append(sanitizedBodyString); - } + /** @return A Map containg headers on this Box API Response. */ + public Map> getHeaders() { + return this.headers; + } - return builder.toString().trim(); - } + @Override + public String toString() { + String lineSeparator = System.getProperty("line.separator"); + StringBuilder builder = new StringBuilder(); + builder + .append("Response") + .append(lineSeparator) + .append(this.requestMethod) + .append(' ') + .append(this.requestUrl) + .append(' ') + .append(this.responseCode) + .append(lineSeparator) + .append(contentType != null ? "Content-Type: " + contentType + lineSeparator : "") + .append(headers.isEmpty() ? "" : "Headers:" + lineSeparator); + headers.entrySet().stream() + .filter(Objects::nonNull) + .forEach( + e -> + builder.append( + format( + "%s: [%s]%s", + e.getKey().toLowerCase(java.util.Locale.ROOT), + e.getValue(), + lineSeparator))); - @Override - public void close() { - try { - if (this.inputStream == null && this.rawInputStream != null) { - this.rawInputStream.close(); - } - if (this.inputStream != null) { - this.inputStream.close(); - } - } catch (IOException e) { - throw new BoxAPIException( - "Couldn't finish closing the connection to the Box API due to a network error or " - + "because the stream was already closed.", e - ); - } + String bodyString = this.bodyToString(); + if (bodyString != null && !bodyString.equals("")) { + String sanitizedBodyString = + contentType.equals(APPLICATION_JSON) + ? BoxSensitiveDataSanitizer.sanitizeJsonBody(Json.parse(bodyString).asObject()) + .toString() + : bodyString; + builder.append("Body:").append(lineSeparator).append(sanitizedBodyString); } - /** - * Returns a string representation of this response's body. This method is used when logging this response's body. - * By default, it returns an empty string (to avoid accidentally logging binary data) unless the response contained - * an error message or content type is application/json. - * - * @return a string representation of this response's body. - */ - protected String bodyToString() { - return this.bodyString; - } + return builder.toString().trim(); + } - private void logResponse() { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(this.toString()); - } + @Override + public void close() { + try { + if (this.inputStream == null && this.rawInputStream != null) { + this.rawInputStream.close(); + } + if (this.inputStream != null) { + this.inputStream.close(); + } + } catch (IOException e) { + throw new BoxAPIException( + "Couldn't finish closing the connection to the Box API due to a network error or " + + "because the stream was already closed.", + e); } + } - private void logErrorResponse(int responseCode) { - if (responseCode < 500 && LOGGER.isWarnEnabled()) { - LOGGER.warn(this.toString()); - } - if (responseCode >= 500 && LOGGER.isErrorEnabled()) { - LOGGER.error(this.toString()); - } - } + /** + * Returns a string representation of this response's body. This method is used when logging this + * response's body. By default, it returns an empty string (to avoid accidentally logging binary + * data) unless the response contained an error message or content type is application/json. + * + * @return a string representation of this response's body. + */ + protected String bodyToString() { + return this.bodyString; + } - protected String getRequestMethod() { - return requestMethod; + private void logResponse() { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(this.toString()); } + } - protected String getRequestUrl() { - return requestUrl; + private void logErrorResponse(int responseCode) { + if (responseCode < 500 && LOGGER.isWarnEnabled()) { + LOGGER.warn(this.toString()); + } + if (responseCode >= 500 && LOGGER.isErrorEnabled()) { + LOGGER.error(this.toString()); } + } + + protected String getRequestMethod() { + return requestMethod; + } + + protected String getRequestUrl() { + return requestUrl; + } } diff --git a/src/main/java/com/box/sdk/BoxAPIResponseException.java b/src/main/java/com/box/sdk/BoxAPIResponseException.java index 2458b440a..9f2297c5f 100644 --- a/src/main/java/com/box/sdk/BoxAPIResponseException.java +++ b/src/main/java/com/box/sdk/BoxAPIResponseException.java @@ -5,80 +5,77 @@ import java.util.List; import java.util.Map; -/** - * Thrown to indicate than an error occured while returning with a response from the Box API. - */ +/** Thrown to indicate than an error occured while returning with a response from the Box API. */ public class BoxAPIResponseException extends BoxAPIException { - static final long serialVersionUID = -7515717760101647173L; - private String message; + static final long serialVersionUID = -7515717760101647173L; + private String message; - /** - * Constructs a BoxAPIException that contains detailed message for underlying exception. - * - * @param message a message explaining why the error occurred. - * @param responseCode a response code. - * @param bodyString a response body. - * @param responseHeaders response headers. - */ - public BoxAPIResponseException( - String message, int responseCode, String bodyString, Map> responseHeaders - ) { - super(message, responseCode, bodyString); - String requestId = ""; - String apiMessage = ""; - JsonObject responseJSON = null; + /** + * Constructs a BoxAPIException that contains detailed message for underlying exception. + * + * @param message a message explaining why the error occurred. + * @param responseCode a response code. + * @param bodyString a response body. + * @param responseHeaders response headers. + */ + public BoxAPIResponseException( + String message, + int responseCode, + String bodyString, + Map> responseHeaders) { + super(message, responseCode, bodyString); + String requestId = ""; + String apiMessage = ""; + JsonObject responseJSON = null; - this.setHeaders(responseHeaders); + this.setHeaders(responseHeaders); - if (this.getHeaders().containsKey("BOX-REQUEST-ID")) { - requestId += "." + this.getHeaders().get("BOX-REQUEST-ID").get(0); - } - - try { - responseJSON = Json.parse(bodyString).asObject(); - } catch (Exception ex) { - // Continue because we will construct the exception message below and return it to user. - } + if (this.getHeaders().containsKey("BOX-REQUEST-ID")) { + requestId += "." + this.getHeaders().get("BOX-REQUEST-ID").get(0); + } - if (responseJSON != null) { - if (responseJSON.get("request_id") != null) { - requestId = responseJSON.get("request_id").asString() + requestId; - } + try { + responseJSON = Json.parse(bodyString).asObject(); + } catch (Exception ex) { + // Continue because we will construct the exception message below and return it to user. + } - if (responseJSON.get("code") != null) { - apiMessage += " " + responseJSON.get("code").asString(); - } else if (responseJSON.get("error") != null) { - apiMessage += " " + responseJSON.get("error").asString(); - } + if (responseJSON != null) { + if (responseJSON.get("request_id") != null) { + requestId = responseJSON.get("request_id").asString() + requestId; + } - if (responseJSON.get("message") != null) { - apiMessage += " - " + responseJSON.get("message").asString(); - } else if (responseJSON.get("error_description") != null) { - apiMessage += " - " + responseJSON.get("error_description").asString(); - } - } + if (responseJSON.get("code") != null) { + apiMessage += " " + responseJSON.get("code").asString(); + } else if (responseJSON.get("error") != null) { + apiMessage += " " + responseJSON.get("error").asString(); + } - if (!requestId.isEmpty()) { - this.setMessage(message + " [" + responseCode + " | " + requestId + "]" - + apiMessage); - } else { - this.setMessage(message + " [" + responseCode + "]" + apiMessage); - } + if (responseJSON.get("message") != null) { + apiMessage += " - " + responseJSON.get("message").asString(); + } else if (responseJSON.get("error_description") != null) { + apiMessage += " - " + responseJSON.get("error_description").asString(); + } } - /** - * @return The constructed message for the API exception. - */ - public String getMessage() { - return this.message; + if (!requestId.isEmpty()) { + this.setMessage(message + " [" + responseCode + " | " + requestId + "]" + apiMessage); + } else { + this.setMessage(message + " [" + responseCode + "]" + apiMessage); } + } - /** - * The message to return for the API exception. - * - * @param message the constructed for the API exception. - */ - protected void setMessage(String message) { - this.message = message; - } + /** @return The constructed message for the API exception. */ + public String getMessage() { + return this.message; + } + + /** + * The message to return for the API exception. + * + * @param message the constructed for the API exception. + */ + protected void setMessage(String message) { + this.message = message; + } } diff --git a/src/main/java/com/box/sdk/BoxCCGAPIConnection.java b/src/main/java/com/box/sdk/BoxCCGAPIConnection.java index 8c0eca9b1..9a73f3dd6 100644 --- a/src/main/java/com/box/sdk/BoxCCGAPIConnection.java +++ b/src/main/java/com/box/sdk/BoxCCGAPIConnection.java @@ -6,130 +6,130 @@ import com.eclipsesource.json.JsonObject; import java.net.URL; -/** - * Creates and manages Client Credentials Grant API connection. - */ +/** Creates and manages Client Credentials Grant API connection. */ public final class BoxCCGAPIConnection extends BoxAPIConnection { - static final String ENTERPRISE_SUBJECT_TYPE = "enterprise"; - static final String USER_SUBJECT_TYPE = "user"; - private String subjectType; - private String subjectId; - - // Hiding constructor - private BoxCCGAPIConnection(String accessToken) { - super(accessToken); - } - - // Hiding constructor - private BoxCCGAPIConnection(String clientID, String clientSecret, String accessToken, String refreshToken) { - super(clientID, clientSecret, accessToken, refreshToken); - } - - // Hiding constructor - private BoxCCGAPIConnection(String clientID, String clientSecret, String authCode) { - super(clientID, clientSecret, authCode); - } - - // Hiding constructor - private BoxCCGAPIConnection(String clientID, String clientSecret) { - super(clientID, clientSecret); - } - - // Hiding constructor - private BoxCCGAPIConnection(BoxConfig boxConfig) { - super(boxConfig); - } - - /** - * Creates connection that authenticates as a Service Account - * - * @param clientId the client ID to use when getting the access token. - * @param clientSecret the client secret to use when getting the access token. - * @param enterpriseId the enterprise ID to use when getting the access token. - * @return Client Credentials Grant API connection. - */ - public static BoxCCGAPIConnection applicationServiceAccountConnection( - String clientId, String clientSecret, String enterpriseId - ) { - BoxCCGAPIConnection api = new BoxCCGAPIConnection(clientId, clientSecret); - api.subjectType = ENTERPRISE_SUBJECT_TYPE; - api.subjectId = enterpriseId; - return api; - } - - /** - * Creates connection that authenticates as a User - * - * @param clientId the client ID to use when getting the access token. - * @param clientSecret the client secret to use when getting the access token. - * @param userId the user ID to use when getting the access token. - * @return Client Credentials Grant API connection. - */ - public static BoxCCGAPIConnection userConnection(String clientId, String clientSecret, String userId) { - BoxCCGAPIConnection api = new BoxCCGAPIConnection(clientId, clientSecret); - api.subjectType = USER_SUBJECT_TYPE; - api.subjectId = userId; - return api; - } - - /** - * Restores a BoxAPIConnection from a saved state. - * - * @param clientID the client ID to use with the connection. - * @param clientSecret the client secret to use with the connection. - * @param state the saved state that was created with {@link #save}. - * @return a restored API connection. - * @see #save - */ - public static BoxCCGAPIConnection restore(String clientID, String clientSecret, String state) { - BoxCCGAPIConnection api = new BoxCCGAPIConnection(clientID, clientSecret); - api.restore(state); - return api; - } - - @Override - protected BoxAPIRequest createTokenRequest(URL url) { - String urlParameters = String.format( + static final String ENTERPRISE_SUBJECT_TYPE = "enterprise"; + static final String USER_SUBJECT_TYPE = "user"; + private String subjectType; + private String subjectId; + + // Hiding constructor + private BoxCCGAPIConnection(String accessToken) { + super(accessToken); + } + + // Hiding constructor + private BoxCCGAPIConnection( + String clientID, String clientSecret, String accessToken, String refreshToken) { + super(clientID, clientSecret, accessToken, refreshToken); + } + + // Hiding constructor + private BoxCCGAPIConnection(String clientID, String clientSecret, String authCode) { + super(clientID, clientSecret, authCode); + } + + // Hiding constructor + private BoxCCGAPIConnection(String clientID, String clientSecret) { + super(clientID, clientSecret); + } + + // Hiding constructor + private BoxCCGAPIConnection(BoxConfig boxConfig) { + super(boxConfig); + } + + /** + * Creates connection that authenticates as a Service Account + * + * @param clientId the client ID to use when getting the access token. + * @param clientSecret the client secret to use when getting the access token. + * @param enterpriseId the enterprise ID to use when getting the access token. + * @return Client Credentials Grant API connection. + */ + public static BoxCCGAPIConnection applicationServiceAccountConnection( + String clientId, String clientSecret, String enterpriseId) { + BoxCCGAPIConnection api = new BoxCCGAPIConnection(clientId, clientSecret); + api.subjectType = ENTERPRISE_SUBJECT_TYPE; + api.subjectId = enterpriseId; + return api; + } + + /** + * Creates connection that authenticates as a User + * + * @param clientId the client ID to use when getting the access token. + * @param clientSecret the client secret to use when getting the access token. + * @param userId the user ID to use when getting the access token. + * @return Client Credentials Grant API connection. + */ + public static BoxCCGAPIConnection userConnection( + String clientId, String clientSecret, String userId) { + BoxCCGAPIConnection api = new BoxCCGAPIConnection(clientId, clientSecret); + api.subjectType = USER_SUBJECT_TYPE; + api.subjectId = userId; + return api; + } + + /** + * Restores a BoxAPIConnection from a saved state. + * + * @param clientID the client ID to use with the connection. + * @param clientSecret the client secret to use with the connection. + * @param state the saved state that was created with {@link #save}. + * @return a restored API connection. + * @see #save + */ + public static BoxCCGAPIConnection restore(String clientID, String clientSecret, String state) { + BoxCCGAPIConnection api = new BoxCCGAPIConnection(clientID, clientSecret); + api.restore(state); + return api; + } + + @Override + protected BoxAPIRequest createTokenRequest(URL url) { + String urlParameters = + String.format( "grant_type=client_credentials&client_id=%s&client_secret=%s&box_subject_type=%s&box_subject_id=%s", this.getClientID(), this.getClientSecret(), this.subjectType, this.subjectId); - BoxAPIRequest request = new BoxAPIRequest(this, url, "POST"); - request.shouldAuthenticate(false); - request.setBody(urlParameters); - request.addHeader("Content-Type", APPLICATION_FORM_URLENCODED); - return request; - } - - @Override - protected void extractTokens(JsonObject jsonObject) { - this.setAccessToken(jsonObject.get("access_token").asString()); - this.setLastRefresh(System.currentTimeMillis()); - this.setExpires(jsonObject.get("expires_in").asLong() * 1000); - } - - @Override - public boolean canRefresh() { - return true; - } - - public boolean isUserConnection() { - return subjectType.equals(USER_SUBJECT_TYPE); - } - - @Override - public String save() { - JsonObject state = Json.parse(super.save()).asObject(); - state.add("subjectType", this.subjectType); - state.add("subjectId", this.subjectId); - return state.toString(); - } - - @Override - public void restore(String state) { - super.restore(state); - - JsonObject json = Json.parse(state).asObject(); - this.subjectType = json.get("subjectType").asString(); - this.subjectId = json.get("subjectId").asString(); - } + BoxAPIRequest request = new BoxAPIRequest(this, url, "POST"); + request.shouldAuthenticate(false); + request.setBody(urlParameters); + request.addHeader("Content-Type", APPLICATION_FORM_URLENCODED); + return request; + } + + @Override + protected void extractTokens(JsonObject jsonObject) { + this.setAccessToken(jsonObject.get("access_token").asString()); + this.setLastRefresh(System.currentTimeMillis()); + this.setExpires(jsonObject.get("expires_in").asLong() * 1000); + } + + @Override + public boolean canRefresh() { + return true; + } + + public boolean isUserConnection() { + return subjectType.equals(USER_SUBJECT_TYPE); + } + + @Override + public String save() { + JsonObject state = Json.parse(super.save()).asObject(); + state.add("subjectType", this.subjectType); + state.add("subjectId", this.subjectId); + return state.toString(); + } + + @Override + public void restore(String state) { + super.restore(state); + + JsonObject json = Json.parse(state).asObject(); + this.subjectType = json.get("subjectType").asString(); + this.subjectId = json.get("subjectId").asString(); + } } diff --git a/src/main/java/com/box/sdk/BoxClassification.java b/src/main/java/com/box/sdk/BoxClassification.java index 099340ffd..6d3b72687 100644 --- a/src/main/java/com/box/sdk/BoxClassification.java +++ b/src/main/java/com/box/sdk/BoxClassification.java @@ -3,67 +3,65 @@ import com.eclipsesource.json.JsonObject; import com.eclipsesource.json.JsonValue; -/** - * Represents the classification information for a File or Folder on Box. - */ +/** Represents the classification information for a File or Folder on Box. */ public class BoxClassification extends BoxJSONObject { - private String color; - private String definition; - private String name; + private String color; + private String definition; + private String name; - /** - * Constructs an BoxClassification object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - BoxClassification(JsonObject jsonObject) { - super(jsonObject); - } + /** + * Constructs an BoxClassification object using an already parsed JSON object. + * + * @param jsonObject the parsed JSON object. + */ + BoxClassification(JsonObject jsonObject) { + super(jsonObject); + } - /** - * Gets the color that is used to display the classification label in a user-interface. - * - * @return the color of this classification. - */ - public String getColor() { - return this.color; - } + /** + * Gets the color that is used to display the classification label in a user-interface. + * + * @return the color of this classification. + */ + public String getColor() { + return this.color; + } - /** - * Gets the meaning of this classification. - * - * @return the meaning of this classification. - */ - public String getDefinition() { - return this.definition; - } + /** + * Gets the meaning of this classification. + * + * @return the meaning of this classification. + */ + public String getDefinition() { + return this.definition; + } - /** - * Gets the name of this classification. - * - * @return the name of this classification. - */ - public String getName() { - return this.name; - } + /** + * Gets the name of this classification. + * + * @return the name of this classification. + */ + public String getName() { + return this.name; + } - @Override - protected void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); + @Override + protected void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); - String memberName = member.getName(); - JsonValue value = member.getValue(); + String memberName = member.getName(); + JsonValue value = member.getValue(); - try { - if (memberName.equals("color")) { - this.color = value.asString(); - } else if (memberName.equals("definition")) { - this.definition = value.asString(); - } else if (memberName.equals("name")) { - this.name = value.asString(); - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); - } + try { + if (memberName.equals("color")) { + this.color = value.asString(); + } else if (memberName.equals("definition")) { + this.definition = value.asString(); + } else if (memberName.equals("name")) { + this.name = value.asString(); + } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); } + } } diff --git a/src/main/java/com/box/sdk/BoxCollaboration.java b/src/main/java/com/box/sdk/BoxCollaboration.java index 6787a6883..43d1a23a2 100644 --- a/src/main/java/com/box/sdk/BoxCollaboration.java +++ b/src/main/java/com/box/sdk/BoxCollaboration.java @@ -10,683 +10,683 @@ import java.util.Date; /** - * Represents a collaboration between a user and another user or group. Collaborations are Box's equivalent of access - * control lists. They can be used to set and apply permissions for users or groups to folders. + * Represents a collaboration between a user and another user or group. Collaborations are Box's + * equivalent of access control lists. They can be used to set and apply permissions for users or + * groups to folders. * - *

Unless otherwise noted, the methods in this class can throw an unchecked {@link BoxAPIException} (unchecked - * meaning that the compiler won't force you to handle it) if an error occurs. If you wish to implement custom error - * handling for errors related to the Box REST API, you should capture this exception explicitly.

+ *

Unless otherwise noted, the methods in this class can throw an unchecked {@link + * BoxAPIException} (unchecked meaning that the compiler won't force you to handle it) if an error + * occurs. If you wish to implement custom error handling for errors related to the Box REST API, + * you should capture this exception explicitly. */ @BoxResourceType("collaboration") public class BoxCollaboration extends BoxResource { + /** All possible fields on a collaboration object. */ + public static final String[] ALL_FIELDS = { + "type", + "id", + "item", + "accessible_by", + "role", + "expires_at", + "can_view_path", + "status", + "acknowledged_at", + "created_by", + "created_at", + "modified_at", + "is_access_only" + }; + + /** Collaborations URL Template. */ + public static final URLTemplate COLLABORATIONS_URL_TEMPLATE = new URLTemplate("collaborations"); + /** Pending Collaborations URL. */ + public static final URLTemplate PENDING_COLLABORATIONS_URL = + new URLTemplate("collaborations?status=pending"); + /** Collaboration URL Template. */ + public static final URLTemplate COLLABORATION_URL_TEMPLATE = new URLTemplate("collaborations/%s"); + /** Get All File Collaboations URL. */ + public static final URLTemplate GET_ALL_FILE_COLLABORATIONS_URL = + new URLTemplate("files/%s/collaborations"); + + /** + * Constructs a BoxCollaboration for a collaboration with a given ID. + * + * @param api the API connection to be used by the collaboration. + * @param id the ID of the collaboration. + */ + public BoxCollaboration(BoxAPIConnection api, String id) { + super(api, id); + } + + /** + * Create a new collaboration object. + * + * @param api the API connection used to make the request. + * @param accessibleBy the JSON object describing who should be collaborated. + * @param item the JSON object describing which item to collaborate. + * @param role the role to give the collaborators. + * @param notify the user/group should receive email notification of the collaboration or not. + * @param canViewPath the view path collaboration feature is enabled or not. + * @return info about the new collaboration. + */ + protected static BoxCollaboration.Info create( + BoxAPIConnection api, + JsonObject accessibleBy, + JsonObject item, + BoxCollaboration.Role role, + Boolean notify, + Boolean canViewPath) { + return create(api, accessibleBy, item, role, notify, canViewPath, null, null); + } + + /** + * Create a new collaboration object. + * + * @param api the API connection used to make the request. + * @param accessibleBy the JSON object describing who should be collaborated. + * @param item the JSON object describing which item to collaborate. + * @param role the role to give the collaborators. + * @param notify the user/group should receive email notification of the collaboration or not. + * @param canViewPath the view path collaboration feature is enabled or not. + * @param expiresAt the date the collaboration expires + * @return info about the new collaboration. + */ + protected static BoxCollaboration.Info create( + BoxAPIConnection api, + JsonObject accessibleBy, + JsonObject item, + BoxCollaboration.Role role, + Boolean notify, + Boolean canViewPath, + Date expiresAt) { + return create(api, accessibleBy, item, role, notify, canViewPath, expiresAt, null); + } + + /** + * Create a new collaboration object. + * + * @param api the API connection used to make the request. + * @param accessibleBy the JSON object describing who should be collaborated. + * @param item the JSON object describing which item to collaborate. + * @param role the role to give the collaborators. + * @param notify the user/group should receive email notification of the collaboration or not. + * @param canViewPath the view path collaboration feature is enabled or not. + * @param expiresAt the date the collaboration expires + * @param isAccessOnly the collaboration is an access only collaboration or not. + * @return info about the new collaboration. + */ + protected static BoxCollaboration.Info create( + BoxAPIConnection api, + JsonObject accessibleBy, + JsonObject item, + BoxCollaboration.Role role, + Boolean notify, + Boolean canViewPath, + Date expiresAt, + Boolean isAccessOnly) { + + String queryString = ""; + if (notify != null) { + queryString = new QueryStringBuilder().appendParam("notify", notify.toString()).toString(); + } + URL url; + if (queryString.length() > 0) { + url = COLLABORATIONS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), queryString); + } else { + url = COLLABORATIONS_URL_TEMPLATE.build(api.getBaseURL()); + } + + JsonObject requestJSON = new JsonObject(); + requestJSON.add("item", item); + requestJSON.add("accessible_by", accessibleBy); + requestJSON.add("role", role.toJSONString()); + if (canViewPath != null) { + requestJSON.add("can_view_path", canViewPath); + } + if (expiresAt != null) { + requestJSON.add("expires_at", BoxDateFormat.format(expiresAt)); + } + if (isAccessOnly != null) { + requestJSON.add("is_access_only", isAccessOnly); + } + + BoxJSONRequest request = new BoxJSONRequest(api, url, "POST"); + + request.setBody(requestJSON.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + BoxCollaboration newCollaboration = + new BoxCollaboration(api, responseJSON.get("id").asString()); + return newCollaboration.new Info(responseJSON); + } + } + + /** + * Gets all pending collaboration invites for the current user. + * + * @param api the API connection to use. + * @return a collection of pending collaboration infos. + */ + public static Collection getPendingCollaborations(BoxAPIConnection api, String... fields) { + QueryStringBuilder queryBuilder = new QueryStringBuilder(); + queryBuilder.appendParam("status", "pending"); + if (fields.length > 0) { + queryBuilder.appendParam("fields", fields); + } + URL url = COLLABORATIONS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), queryBuilder.toString()); + + BoxJSONRequest request = new BoxJSONRequest(api, url, "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + + int entriesCount = responseJSON.get("total_count").asInt(); + Collection collaborations = new ArrayList<>(entriesCount); + JsonArray entries = responseJSON.get("entries").asArray(); + for (JsonValue entry : entries) { + JsonObject entryObject = entry.asObject(); + BoxCollaboration collaboration = + new BoxCollaboration(api, entryObject.get("id").asString()); + BoxCollaboration.Info info = collaboration.new Info(entryObject); + collaborations.add(info); + } + + return collaborations; + } + } + + /** + * Used to retrieve all collaborations associated with the item. + * + * @param api BoxAPIConnection from the associated file. + * @param fileID FileID of the associated file + * @param pageSize page size for server pages of the Iterable + * @param fields the optional fields to retrieve. + * @return An iterable of BoxCollaboration.Info instances associated with the item. + */ + public static BoxResourceIterable getAllFileCollaborations( + final BoxAPIConnection api, String fileID, int pageSize, String... fields) { + QueryStringBuilder builder = new QueryStringBuilder(); + if (fields.length > 0) { + builder.appendParam("fields", fields); + } + return new BoxResourceIterable( + api, + GET_ALL_FILE_COLLABORATIONS_URL.buildWithQuery( + api.getBaseURL(), builder.toString(), fileID), + pageSize) { + + @Override + protected BoxCollaboration.Info factory(JsonObject jsonObject) { + String id = jsonObject.get("id").asString(); + return new BoxCollaboration(api, id).new Info(jsonObject); + } + }; + } + + /** + * Gets information about this collection with a custom set of fields. + * + * @param fields the fields to retrieve. + * @return info about the collaboration. + */ + public Info getInfo(String... fields) { + URL url = COLLABORATION_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + if (fields.length > 0) { + String queryString = new QueryStringBuilder().appendParam("fields", fields).toString(); + url = + COLLABORATION_URL_TEMPLATE.buildWithQuery( + this.getAPI().getBaseURL(), queryString, this.getID()); + } + + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); + try (BoxJSONResponse response = request.send()) { + return new Info(response.getJSON()); + } + } + + /** + * Updates the information about this collaboration with any info fields that have been modified + * locally. + * + * @param info the updated info. + */ + public void updateInfo(Info info) { + BoxAPIConnection api = this.getAPI(); + URL url = COLLABORATION_URL_TEMPLATE.build(api.getBaseURL(), this.getID()); + + BoxJSONRequest request = new BoxJSONRequest(api, url, "PUT"); + request.setBody(info.getPendingChanges()); + try (BoxJSONResponse response = request.send()) { + JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); + info.update(jsonObject); + } + } + + /** Deletes this collaboration. */ + public void delete() { + BoxAPIConnection api = this.getAPI(); + URL url = COLLABORATION_URL_TEMPLATE.build(api.getBaseURL(), this.getID()); + + BoxAPIRequest request = new BoxAPIRequest(api, url, "DELETE"); + request.send().close(); + } + + /** Enumerates the possible statuses that a collaboration can have. */ + public enum Status { + /** The collaboration has been accepted. */ + ACCEPTED, + + /** The collaboration is waiting to be accepted or rejected. */ + PENDING, + + /** The collaboration has been rejected. */ + REJECTED + } + + /** Enumerates the possible access levels that a collaborator can have. */ + public enum Role { /** - * All possible fields on a collaboration object. + * An Editor has full read/write access to a folder. Once invited to a folder, they will be able + * to view, download, upload, edit, delete, copy, move, rename, generate shared links, make + * comments, assign tasks, create tags, and invite/remove collaborators. They will not be able + * to delete or move root level folders. */ - public static final String[] ALL_FIELDS = {"type", "id", "item", "accessible_by", "role", "expires_at", - "can_view_path", "status", "acknowledged_at", "created_by", - "created_at", "modified_at", "is_access_only"}; + EDITOR("editor"), /** - * Collaborations URL Template. + * The viewer role has full read access to a folder. Once invited to a folder, they will be able + * to preview, download, make comments, and generate shared links. They will not be able to add + * tags, invite new collaborators, upload, edit, or delete items in the folder. */ - public static final URLTemplate COLLABORATIONS_URL_TEMPLATE = new URLTemplate("collaborations"); + VIEWER("viewer"), + /** - * Pending Collaborations URL. + * The previewer role has limited read access to a folder. They will only be able to preview the + * items in the folder using the integrated content viewer. They will not be able to share, + * upload, edit, or delete any content. This role is only available to enterprise accounts. */ - public static final URLTemplate PENDING_COLLABORATIONS_URL = new URLTemplate("collaborations?status=pending"); + PREVIEWER("previewer"), + /** - * Collaboration URL Template. + * The uploader has limited write access to a folder. They will only be able to upload and see + * the names of the items in a folder. They will not able to download or view any content. This + * role is only available to enterprise accounts. */ - public static final URLTemplate COLLABORATION_URL_TEMPLATE = new URLTemplate("collaborations/%s"); + UPLOADER("uploader"), + /** - * Get All File Collaboations URL. + * The previewer-uploader role is a combination of previewer and uploader. A user with this + * access level will be able to preview files using the integrated content viewer as well as + * upload items into the folder. They will not be able to download, edit, or share, items in the + * folder. This role is only available to enterprise accounts. */ - public static final URLTemplate GET_ALL_FILE_COLLABORATIONS_URL = new URLTemplate("files/%s/collaborations"); + PREVIEWER_UPLOADER("previewer uploader"), /** - * Constructs a BoxCollaboration for a collaboration with a given ID. - * - * @param api the API connection to be used by the collaboration. - * @param id the ID of the collaboration. + * The viewer-uploader role is a combination of viewer and uploader. A viewer-uploader has full + * read access to a folder and limited write access. They are able to preview, download, add + * comments, generate shared links, and upload content to the folder. They will not be able to + * add tags, invite new collaborators, edit, or delete items in the folder. This role is only + * available to enterprise accounts. + */ + VIEWER_UPLOADER("viewer uploader"), + + /** + * The co-owner role has all of the functional read/write access that an editor does. This + * permission level has the added ability of being able to manage users in the folder. A + * co-owner can add new collaborators, change access levels of existing collaborators, and + * remove collaborators. However, they will not be able to manipulate the owner of the folder or + * transfer ownership to another user. This role is only available to enterprise accounts. */ - public BoxCollaboration(BoxAPIConnection api, String id) { - super(api, id); + CO_OWNER("co-owner"), + + /** + * The owner role has all of the functional capabilities of a co-owner. However, they will be + * able to manipulate the owner of the folder or transfer ownership to another user. This role + * is only available to enterprise accounts. + */ + OWNER("owner"); + + private final String jsonValue; + + Role(String jsonValue) { + this.jsonValue = jsonValue; + } + + static Role fromJSONString(String jsonValue) { + switch (jsonValue) { + case "editor": + return EDITOR; + case "viewer": + return VIEWER; + case "previewer": + return PREVIEWER; + case "uploader": + return UPLOADER; + case "previewer uploader": + return PREVIEWER_UPLOADER; + case "viewer uploader": + return VIEWER_UPLOADER; + case "co-owner": + return CO_OWNER; + case "owner": + return OWNER; + default: + throw new IllegalArgumentException("The provided JSON value isn't a valid Role."); + } + } + + String toJSONString() { + return this.jsonValue; + } + } + + /** Contains information about a BoxCollaboration. */ + public class Info extends BoxResource.Info { + private BoxUser.Info createdBy; + private Date createdAt; + private Date modifiedAt; + private Date expiresAt; + private Status status; + private BoxCollaborator.Info accessibleBy; + private Role role; + private Date acknowledgedAt; + private BoxItem.Info item; + private String inviteEmail; + private boolean canViewPath; + private boolean isAccessOnly; + + /** Constructs an empty Info object. */ + public Info() { + super(); } /** - * Create a new collaboration object. + * Constructs an Info object by parsing information from a JSON string. * - * @param api the API connection used to make the request. - * @param accessibleBy the JSON object describing who should be collaborated. - * @param item the JSON object describing which item to collaborate. - * @param role the role to give the collaborators. - * @param notify the user/group should receive email notification of the collaboration or not. - * @param canViewPath the view path collaboration feature is enabled or not. - * @return info about the new collaboration. + * @param json the JSON string to parse. */ - protected static BoxCollaboration.Info create(BoxAPIConnection api, JsonObject accessibleBy, JsonObject item, - BoxCollaboration.Role role, Boolean notify, Boolean canViewPath) { - return create(api, accessibleBy, item, role, notify, canViewPath, null, null); + public Info(String json) { + super(json); + } + + Info(JsonObject jsonObject) { + super(jsonObject); } /** - * Create a new collaboration object. + * Gets the user who created the collaboration. * - * @param api the API connection used to make the request. - * @param accessibleBy the JSON object describing who should be collaborated. - * @param item the JSON object describing which item to collaborate. - * @param role the role to give the collaborators. - * @param notify the user/group should receive email notification of the collaboration or not. - * @param canViewPath the view path collaboration feature is enabled or not. - * @param expiresAt the date the collaboration expires - * @return info about the new collaboration. + * @return the user who created the collaboration. */ - protected static BoxCollaboration.Info create( - BoxAPIConnection api, - JsonObject accessibleBy, - JsonObject item, - BoxCollaboration.Role role, - Boolean notify, - Boolean canViewPath, - Date expiresAt - ) { - return create(api, accessibleBy, item, role, notify, canViewPath, expiresAt, null); + public BoxUser.Info getCreatedBy() { + return this.createdBy; } /** - * Create a new collaboration object. + * Gets the time the collaboration was created. * - * @param api the API connection used to make the request. - * @param accessibleBy the JSON object describing who should be collaborated. - * @param item the JSON object describing which item to collaborate. - * @param role the role to give the collaborators. - * @param notify the user/group should receive email notification of the collaboration or not. - * @param canViewPath the view path collaboration feature is enabled or not. - * @param expiresAt the date the collaboration expires - * @param isAccessOnly the collaboration is an access only collaboration or not. - * @return info about the new collaboration. + * @return the time the collaboration was created. */ - protected static BoxCollaboration.Info create( - BoxAPIConnection api, - JsonObject accessibleBy, - JsonObject item, - BoxCollaboration.Role role, - Boolean notify, - Boolean canViewPath, - Date expiresAt, - Boolean isAccessOnly - ) { - - String queryString = ""; - if (notify != null) { - queryString = new QueryStringBuilder().appendParam("notify", notify.toString()).toString(); - } - URL url; - if (queryString.length() > 0) { - url = COLLABORATIONS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), queryString); - } else { - url = COLLABORATIONS_URL_TEMPLATE.build(api.getBaseURL()); - } - - JsonObject requestJSON = new JsonObject(); - requestJSON.add("item", item); - requestJSON.add("accessible_by", accessibleBy); - requestJSON.add("role", role.toJSONString()); - if (canViewPath != null) { - requestJSON.add("can_view_path", canViewPath); - } - if (expiresAt != null) { - requestJSON.add("expires_at", BoxDateFormat.format(expiresAt)); - } - if (isAccessOnly != null) { - requestJSON.add("is_access_only", isAccessOnly); - } - - BoxJSONRequest request = new BoxJSONRequest(api, url, "POST"); - - request.setBody(requestJSON.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - BoxCollaboration newCollaboration = new BoxCollaboration(api, responseJSON.get("id").asString()); - return newCollaboration.new Info(responseJSON); - } + public Date getCreatedAt() { + return this.createdAt; } /** - * Gets all pending collaboration invites for the current user. + * Gets the time the collaboration was last modified. * - * @param api the API connection to use. - * @return a collection of pending collaboration infos. + * @return the time the collaboration was last modified. */ - public static Collection getPendingCollaborations(BoxAPIConnection api, String... fields) { - QueryStringBuilder queryBuilder = new QueryStringBuilder(); - queryBuilder.appendParam("status", "pending"); - if (fields.length > 0) { - queryBuilder.appendParam("fields", fields); - } - URL url = COLLABORATIONS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), queryBuilder.toString()); - - - BoxJSONRequest request = new BoxJSONRequest(api, url, "GET"); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - - int entriesCount = responseJSON.get("total_count").asInt(); - Collection collaborations = new ArrayList<>(entriesCount); - JsonArray entries = responseJSON.get("entries").asArray(); - for (JsonValue entry : entries) { - JsonObject entryObject = entry.asObject(); - BoxCollaboration collaboration = new BoxCollaboration(api, entryObject.get("id").asString()); - BoxCollaboration.Info info = collaboration.new Info(entryObject); - collaborations.add(info); - } - - return collaborations; - } + public Date getModifiedAt() { + return this.modifiedAt; } /** - * Used to retrieve all collaborations associated with the item. + * Gets the time the collaboration will expire. * - * @param api BoxAPIConnection from the associated file. - * @param fileID FileID of the associated file - * @param pageSize page size for server pages of the Iterable - * @param fields the optional fields to retrieve. - * @return An iterable of BoxCollaboration.Info instances associated with the item. + * @return the time the collaboration will expire. */ - public static BoxResourceIterable getAllFileCollaborations(final BoxAPIConnection api, String fileID, - int pageSize, String... fields) { - QueryStringBuilder builder = new QueryStringBuilder(); - if (fields.length > 0) { - builder.appendParam("fields", fields); - } - return new BoxResourceIterable( - api, GET_ALL_FILE_COLLABORATIONS_URL.buildWithQuery(api.getBaseURL(), builder.toString(), fileID), - pageSize) { - - @Override - protected BoxCollaboration.Info factory(JsonObject jsonObject) { - String id = jsonObject.get("id").asString(); - return new BoxCollaboration(api, id).new Info(jsonObject); - } - }; + public Date getExpiresAt() { + return this.expiresAt; } /** - * Gets information about this collection with a custom set of fields. + * Set the time the collaboration will expire. * - * @param fields the fields to retrieve. - * @return info about the collaboration. + * @param expiresAt the expiration date of the collaboration. */ - public Info getInfo(String... fields) { - URL url = COLLABORATION_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - if (fields.length > 0) { - String queryString = new QueryStringBuilder().appendParam("fields", fields).toString(); - url = COLLABORATION_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID()); - } - - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); - try (BoxJSONResponse response = request.send()) { - return new Info(response.getJSON()); - } + public void setExpiresAt(Date expiresAt) { + this.expiresAt = expiresAt; + this.addPendingChange("expires_at", BoxDateFormat.format(expiresAt)); } /** - * Updates the information about this collaboration with any info fields that have been modified locally. + * Gets a boolean indicator whether "view path collaboration" feature is enabled or not. When + * set to true this allows the invitee to see the entire parent path to the item. It is + * important to note that this does not grant privileges in any parent folder. * - * @param info the updated info. + * @return the Boolean value indicating if "view path collaboration" is enabled or not */ - public void updateInfo(Info info) { - BoxAPIConnection api = this.getAPI(); - URL url = COLLABORATION_URL_TEMPLATE.build(api.getBaseURL(), this.getID()); - - BoxJSONRequest request = new BoxJSONRequest(api, url, "PUT"); - request.setBody(info.getPendingChanges()); - try (BoxJSONResponse response = request.send()) { - JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - info.update(jsonObject); - } + public boolean getCanViewPath() { + return this.canViewPath; } /** - * Deletes this collaboration. + * Sets the permission for "view path collaboration" feature. When set to true this allows the + * invitee to to see the entire parent path to the item + * + * @param canViewState the boolean value indicating whether the invitee can see the parent + * folder. */ - public void delete() { - BoxAPIConnection api = this.getAPI(); - URL url = COLLABORATION_URL_TEMPLATE.build(api.getBaseURL(), this.getID()); - - BoxAPIRequest request = new BoxAPIRequest(api, url, "DELETE"); - request.send().close(); + public void setCanViewPath(boolean canViewState) { + this.canViewPath = canViewState; + this.addPendingChange("can_view_path", canViewState); } /** - * Enumerates the possible statuses that a collaboration can have. + * Gets a boolean indicator weather "is access only" feature is enabled or not. This field is + * read only. It is used to indicate whether a collaboration is an Access Only Collaboration + * (AOC). When set to true, it separates access from interest by hiding collaborated items from + * the All Files page and the ALF stream. This means that users who have been granted access + * through AOCs will not see these items in their regular file view. */ - public enum Status { - /** - * The collaboration has been accepted. - */ - ACCEPTED, - - /** - * The collaboration is waiting to be accepted or rejected. - */ - PENDING, - - /** - * The collaboration has been rejected. - */ - REJECTED + public boolean getIsAccessOnly() { + return this.isAccessOnly; } /** - * Enumerates the possible access levels that a collaborator can have. + * The email address used to invite an un-registered collaborator, if they are not a registered + * user. + * + * @return the email for the un-registed collaborator. */ - public enum Role { - /** - * An Editor has full read/write access to a folder. Once invited to a folder, they will be able to view, - * download, upload, edit, delete, copy, move, rename, generate shared links, make comments, assign tasks, - * create tags, and invite/remove collaborators. They will not be able to delete or move root level folders. - */ - EDITOR("editor"), - - /** - * The viewer role has full read access to a folder. Once invited to a folder, they will be able to preview, - * download, make comments, and generate shared links. They will not be able to add tags, invite new - * collaborators, upload, edit, or delete items in the folder. - */ - VIEWER("viewer"), - - /** - * The previewer role has limited read access to a folder. They will only be able to preview the items in the - * folder using the integrated content viewer. They will not be able to share, upload, edit, or delete any - * content. This role is only available to enterprise accounts. - */ - PREVIEWER("previewer"), - - /** - * The uploader has limited write access to a folder. They will only be able to upload and see the names of the - * items in a folder. They will not able to download or view any content. This role is only available to - * enterprise accounts. - */ - UPLOADER("uploader"), - - /** - * The previewer-uploader role is a combination of previewer and uploader. A user with this access level will be - * able to preview files using the integrated content viewer as well as upload items into the folder. They will - * not be able to download, edit, or share, items in the folder. This role is only available to enterprise - * accounts. - */ - PREVIEWER_UPLOADER("previewer uploader"), - - /** - * The viewer-uploader role is a combination of viewer and uploader. A viewer-uploader has full read access to a - * folder and limited write access. They are able to preview, download, add comments, generate shared links, and - * upload content to the folder. They will not be able to add tags, invite new collaborators, edit, or delete - * items in the folder. This role is only available to enterprise accounts. - */ - VIEWER_UPLOADER("viewer uploader"), - - /** - * The co-owner role has all of the functional read/write access that an editor does. This permission level has - * the added ability of being able to manage users in the folder. A co-owner can add new collaborators, change - * access levels of existing collaborators, and remove collaborators. However, they will not be able to - * manipulate the owner of the folder or transfer ownership to another user. This role is only available to - * enterprise accounts. - */ - CO_OWNER("co-owner"), - - /** - * The owner role has all of the functional capabilities of a co-owner. However, they will be able to manipulate - * the owner of the folder or transfer ownership to another user. This role is only available to enterprise - * accounts. - */ - OWNER("owner"); - - private final String jsonValue; - - Role(String jsonValue) { - this.jsonValue = jsonValue; - } - - static Role fromJSONString(String jsonValue) { - switch (jsonValue) { - case "editor": - return EDITOR; - case "viewer": - return VIEWER; - case "previewer": - return PREVIEWER; - case "uploader": - return UPLOADER; - case "previewer uploader": - return PREVIEWER_UPLOADER; - case "viewer uploader": - return VIEWER_UPLOADER; - case "co-owner": - return CO_OWNER; - case "owner": - return OWNER; - default: - throw new IllegalArgumentException("The provided JSON value isn't a valid Role."); - } - } - - String toJSONString() { - return this.jsonValue; - } + public String getInviteEmail() { + return this.inviteEmail; } /** - * Contains information about a BoxCollaboration. + * Gets the status of the collaboration. + * + * @return the status of the collaboration. */ - public class Info extends BoxResource.Info { - private BoxUser.Info createdBy; - private Date createdAt; - private Date modifiedAt; - private Date expiresAt; - private Status status; - private BoxCollaborator.Info accessibleBy; - private Role role; - private Date acknowledgedAt; - private BoxItem.Info item; - private String inviteEmail; - private boolean canViewPath; - private boolean isAccessOnly; - - /** - * Constructs an empty Info object. - */ - public Info() { - super(); - } - - /** - * Constructs an Info object by parsing information from a JSON string. - * - * @param json the JSON string to parse. - */ - public Info(String json) { - super(json); - } - - Info(JsonObject jsonObject) { - super(jsonObject); - } - - /** - * Gets the user who created the collaboration. - * - * @return the user who created the collaboration. - */ - public BoxUser.Info getCreatedBy() { - return this.createdBy; - } - - /** - * Gets the time the collaboration was created. - * - * @return the time the collaboration was created. - */ - public Date getCreatedAt() { - return this.createdAt; - } - - /** - * Gets the time the collaboration was last modified. - * - * @return the time the collaboration was last modified. - */ - public Date getModifiedAt() { - return this.modifiedAt; - } - - /** - * Gets the time the collaboration will expire. - * - * @return the time the collaboration will expire. - */ - public Date getExpiresAt() { - return this.expiresAt; - } - - /** - * Set the time the collaboration will expire. - * - * @param expiresAt the expiration date of the collaboration. - */ - public void setExpiresAt(Date expiresAt) { - this.expiresAt = expiresAt; - this.addPendingChange("expires_at", BoxDateFormat.format(expiresAt)); - } - - /** - * Gets a boolean indicator whether "view path collaboration" feature is enabled or not. - * When set to true this allows the invitee to see the entire parent path to the item. - * It is important to note that this does not grant privileges in any parent folder. - * - * @return the Boolean value indicating if "view path collaboration" is enabled or not - */ - public boolean getCanViewPath() { - return this.canViewPath; - } - - /** - * Sets the permission for "view path collaboration" feature. When set to true this allows - * the invitee to to see the entire parent path to the item - * - * @param canViewState the boolean value indicating whether the invitee can see the parent folder. - */ - public void setCanViewPath(boolean canViewState) { - this.canViewPath = canViewState; - this.addPendingChange("can_view_path", canViewState); - } - - /** - * Gets a boolean indicator weather "is access only" feature is enabled or not. This field is read only. - * It is used to indicate whether a collaboration is an Access Only Collaboration (AOC). - * When set to true, it separates access from interest by hiding collaborated items from the All Files page - * and the ALF stream. - * This means that users who have been granted access through AOCs will not see these items in their - * regular file view. - */ - public boolean getIsAccessOnly() { - return this.isAccessOnly; - } - - /** - * The email address used to invite an un-registered collaborator, if they are not a registered user. - * - * @return the email for the un-registed collaborator. - */ - public String getInviteEmail() { - return this.inviteEmail; - } - - /** - * Gets the status of the collaboration. - * - * @return the status of the collaboration. - */ - public Status getStatus() { - return this.status; - } + public Status getStatus() { + return this.status; + } - /** - * Sets the status of the collaboration in order to accept or reject the collaboration if it's pending. - * - * @param status the new status of the collaboration. - */ - public void setStatus(Status status) { - this.status = status; - this.addPendingChange("status", status.name().toLowerCase(java.util.Locale.ROOT)); - } + /** + * Sets the status of the collaboration in order to accept or reject the collaboration if it's + * pending. + * + * @param status the new status of the collaboration. + */ + public void setStatus(Status status) { + this.status = status; + this.addPendingChange("status", status.name().toLowerCase(java.util.Locale.ROOT)); + } - /** - * Gets the collaborator who this collaboration applies to. - * - * @return the collaborator who this collaboration applies to. - */ - public BoxCollaborator.Info getAccessibleBy() { - return this.accessibleBy; - } + /** + * Gets the collaborator who this collaboration applies to. + * + * @return the collaborator who this collaboration applies to. + */ + public BoxCollaborator.Info getAccessibleBy() { + return this.accessibleBy; + } - /** - * Gets the level of access the collaborator has. - * - * @return the level of access the collaborator has. - */ - public Role getRole() { - return this.role; - } + /** + * Gets the level of access the collaborator has. + * + * @return the level of access the collaborator has. + */ + public Role getRole() { + return this.role; + } - /** - * Sets the level of access the collaborator has. - * - * @param role the new level of access to give the collaborator. - */ - public void setRole(Role role) { - this.role = role; - this.addPendingChange("role", role.toJSONString()); - } + /** + * Sets the level of access the collaborator has. + * + * @param role the new level of access to give the collaborator. + */ + public void setRole(Role role) { + this.role = role; + this.addPendingChange("role", role.toJSONString()); + } - /** - * Gets the time the collaboration's status was changed. - * - * @return the time the collaboration's status was changed. - */ - public Date getAcknowledgedAt() { - return this.acknowledgedAt; - } + /** + * Gets the time the collaboration's status was changed. + * + * @return the time the collaboration's status was changed. + */ + public Date getAcknowledgedAt() { + return this.acknowledgedAt; + } - /** - * Gets the folder the collaboration is related to. - * - * @return the folder the collaboration is related to. - */ - public BoxItem.Info getItem() { - return this.item; - } + /** + * Gets the folder the collaboration is related to. + * + * @return the folder the collaboration is related to. + */ + public BoxItem.Info getItem() { + return this.item; + } - @Override - public BoxCollaboration getResource() { - return BoxCollaboration.this; - } + @Override + public BoxCollaboration getResource() { + return BoxCollaboration.this; + } - @SuppressWarnings("checkstyle:MissingSwitchDefault") - @Override - protected void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - - String memberName = member.getName(); - JsonValue value = member.getValue(); - try { - switch (memberName) { - case "created_by": - JsonObject userJSON = value.asObject(); - if (this.createdBy == null) { - String userID = userJSON.get("id").asString(); - BoxUser user = new BoxUser(getAPI(), userID); - this.createdBy = user.new Info(userJSON); - } else { - this.createdBy.update(userJSON); - } - break; - case "created_at": - this.createdAt = BoxDateFormat.parse(value.asString()); - - break; - case "modified_at": - this.modifiedAt = BoxDateFormat.parse(value.asString()); - break; - case "expires_at": - this.expiresAt = BoxDateFormat.parse(value.asString()); - break; - case "status": - String statusString = value.asString().toUpperCase(java.util.Locale.ROOT); - this.status = Status.valueOf(statusString); - - break; - case "accessible_by": - JsonObject accessibleByJSON = value.asObject(); - if (this.accessibleBy == null) { - this.accessibleBy = this.parseAccessibleBy(accessibleByJSON); - } else { - this.updateAccessibleBy(accessibleByJSON); - } - break; - case "role": - this.role = Role.fromJSONString(value.asString()); - break; - case "acknowledged_at": - this.acknowledgedAt = BoxDateFormat.parse(value.asString()); - break; - case "can_view_path": - this.canViewPath = value.asBoolean(); - break; - case "is_access_only": - this.isAccessOnly = value.asBoolean(); - break; - case "invite_email": - this.inviteEmail = value.asString(); - break; - case "item": - JsonObject itemJson = value.asObject(); - if (this.item == null) { - this.item = selectCollaborationItem(itemJson); - } else { - this.item.update(itemJson); - } - break; - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); + @SuppressWarnings("checkstyle:MissingSwitchDefault") + @Override + protected void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + + String memberName = member.getName(); + JsonValue value = member.getValue(); + try { + switch (memberName) { + case "created_by": + JsonObject userJSON = value.asObject(); + if (this.createdBy == null) { + String userID = userJSON.get("id").asString(); + BoxUser user = new BoxUser(getAPI(), userID); + this.createdBy = user.new Info(userJSON); + } else { + this.createdBy.update(userJSON); } - } - - private BoxItem.Info selectCollaborationItem(JsonObject itemJson) { - String itemId = itemJson.get("id").asString(); - String itemType = itemJson.get("type").asString(); - switch (itemType) { - case BoxFile.TYPE: - return new BoxFile(getAPI(), itemId).new Info(itemJson); - case BoxFolder.TYPE: - return new BoxFolder(getAPI(), itemId).new Info(itemJson); - default: - throw new IllegalStateException( - String.format( - "Unsupported collaboration item type '%s': JSON %n%s", - itemType, - itemJson - )); + break; + case "created_at": + this.createdAt = BoxDateFormat.parse(value.asString()); + + break; + case "modified_at": + this.modifiedAt = BoxDateFormat.parse(value.asString()); + break; + case "expires_at": + this.expiresAt = BoxDateFormat.parse(value.asString()); + break; + case "status": + String statusString = value.asString().toUpperCase(java.util.Locale.ROOT); + this.status = Status.valueOf(statusString); + + break; + case "accessible_by": + JsonObject accessibleByJSON = value.asObject(); + if (this.accessibleBy == null) { + this.accessibleBy = this.parseAccessibleBy(accessibleByJSON); + } else { + this.updateAccessibleBy(accessibleByJSON); } - } - - private void updateAccessibleBy(JsonObject json) { - String type = json.get("type").asString(); - if ((type.equals("user") && this.accessibleBy instanceof BoxUser.Info) - || (type.equals("group") && this.accessibleBy instanceof BoxGroup.Info)) { - - this.accessibleBy.update(json); + break; + case "role": + this.role = Role.fromJSONString(value.asString()); + break; + case "acknowledged_at": + this.acknowledgedAt = BoxDateFormat.parse(value.asString()); + break; + case "can_view_path": + this.canViewPath = value.asBoolean(); + break; + case "is_access_only": + this.isAccessOnly = value.asBoolean(); + break; + case "invite_email": + this.inviteEmail = value.asString(); + break; + case "item": + JsonObject itemJson = value.asObject(); + if (this.item == null) { + this.item = selectCollaborationItem(itemJson); } else { - this.accessibleBy = this.parseAccessibleBy(json); + this.item.update(itemJson); } + break; } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); + } + } - private BoxCollaborator.Info parseAccessibleBy(JsonObject json) { - String id = json.get("id").asString(); - String type = json.get("type").asString(); - BoxCollaborator.Info parsedInfo = null; - if (type.equals("user")) { - BoxUser user = new BoxUser(getAPI(), id); - parsedInfo = user.new Info(json); - } else if (type.equals("group")) { - BoxGroup group = new BoxGroup(getAPI(), id); - parsedInfo = group.new Info(json); - } + private BoxItem.Info selectCollaborationItem(JsonObject itemJson) { + String itemId = itemJson.get("id").asString(); + String itemType = itemJson.get("type").asString(); + switch (itemType) { + case BoxFile.TYPE: + return new BoxFile(getAPI(), itemId).new Info(itemJson); + case BoxFolder.TYPE: + return new BoxFolder(getAPI(), itemId).new Info(itemJson); + default: + throw new IllegalStateException( + String.format( + "Unsupported collaboration item type '%s': JSON %n%s", itemType, itemJson)); + } + } - return parsedInfo; - } + private void updateAccessibleBy(JsonObject json) { + String type = json.get("type").asString(); + if ((type.equals("user") && this.accessibleBy instanceof BoxUser.Info) + || (type.equals("group") && this.accessibleBy instanceof BoxGroup.Info)) { + + this.accessibleBy.update(json); + } else { + this.accessibleBy = this.parseAccessibleBy(json); + } + } + + private BoxCollaborator.Info parseAccessibleBy(JsonObject json) { + String id = json.get("id").asString(); + String type = json.get("type").asString(); + BoxCollaborator.Info parsedInfo = null; + if (type.equals("user")) { + BoxUser user = new BoxUser(getAPI(), id); + parsedInfo = user.new Info(json); + } else if (type.equals("group")) { + BoxGroup group = new BoxGroup(getAPI(), id); + parsedInfo = group.new Info(json); + } + + return parsedInfo; } + } } diff --git a/src/main/java/com/box/sdk/BoxCollaborationAllowlist.java b/src/main/java/com/box/sdk/BoxCollaborationAllowlist.java index a0ea9339e..57cc4b62d 100644 --- a/src/main/java/com/box/sdk/BoxCollaborationAllowlist.java +++ b/src/main/java/com/box/sdk/BoxCollaborationAllowlist.java @@ -7,312 +7,293 @@ import java.net.URL; import java.util.Date; - /** - * Represents a collaboration allowlist between a domain and a Box Enterprise. Collaboration Allowlist enables a Box - * Enterprise(only available if you have Box Governance) to manage a set of approved domains that can collaborate - * with an enterprise. + * Represents a collaboration allowlist between a domain and a Box Enterprise. Collaboration + * Allowlist enables a Box Enterprise(only available if you have Box Governance) to manage a set of + * approved domains that can collaborate with an enterprise. * - *

Unless otherwise noted, the methods in this class can throw an unchecked {@link BoxAPIException} (unchecked - * meaning that the compiler won't force you to handle it) if an error occurs. If you wish to implement custom error - * handling for errors related to the Box REST API, you should capture this exception explicitly.

+ *

Unless otherwise noted, the methods in this class can throw an unchecked {@link + * BoxAPIException} (unchecked meaning that the compiler won't force you to handle it) if an error + * occurs. If you wish to implement custom error handling for errors related to the Box REST API, + * you should capture this exception explicitly. */ @BoxResourceType("collaboration_allowlist_entry") public class BoxCollaborationAllowlist extends BoxResource { - /** - * Collaboration Allowlist Entries URL Template. - */ - public static final URLTemplate COLLABORATION_ALLOWLIST_ENTRIES_URL_TEMPLATE = - new URLTemplate("collaboration_whitelist_entries"); + /** Collaboration Allowlist Entries URL Template. */ + public static final URLTemplate COLLABORATION_ALLOWLIST_ENTRIES_URL_TEMPLATE = + new URLTemplate("collaboration_whitelist_entries"); + + /** Collaboration Allowlist Entries URL Template with given ID. */ + public static final URLTemplate COLLABORATION_ALLOWLIST_ENTRY_URL_TEMPLATE = + new URLTemplate("collaboration_whitelist_entries/%s"); + + /** The default limit of entries per response. */ + private static final int DEFAULT_LIMIT = 100; + + /** + * Constructs a BoxCollaborationAllowlist for a collaboration allowlist with a given ID. + * + * @param api the API connection to be used by the collaboration allowlist. + * @param id the ID of the collaboration allowlist. + */ + public BoxCollaborationAllowlist(BoxAPIConnection api, String id) { + super(api, id); + } + + /** + * Creates a new Collaboration Allowlist for a domain. + * + * @param api the API connection to be used by the resource. + * @param domain the domain to be added to a collaboration allowlist for a Box Enterprise. + * @param direction an enum representing the direction of the collaboration allowlist. Can be set + * to inbound, outbound, or both. + * @return information about the collaboration allowlist created. + */ + public static BoxCollaborationAllowlist.Info create( + final BoxAPIConnection api, String domain, AllowlistDirection direction) { + + URL url = COLLABORATION_ALLOWLIST_ENTRIES_URL_TEMPLATE.build(api.getBaseURL()); + BoxJSONRequest request = new BoxJSONRequest(api, url, HttpMethod.POST); + JsonObject requestJSON = + new JsonObject().add("domain", domain).add("direction", direction.toString()); + + request.setBody(requestJSON.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + BoxCollaborationAllowlist domainAllowlist = + new BoxCollaborationAllowlist(api, responseJSON.get("id").asString()); + + return domainAllowlist.new Info(responseJSON); + } + } + + /** + * Returns all the collaboration allowlisting with specified filters. + * + * @param api the API connection to be used by the resource. + * @param fields the fields to retrieve. + * @return an iterable with all the collaboration allowlists met search conditions. + */ + public static Iterable getAll( + final BoxAPIConnection api, String... fields) { + + return getAll(api, DEFAULT_LIMIT, fields); + } + + /** + * Returns all the collaboration allowlisting with specified filters. + * + * @param api the API connection to be used by the resource. + * @param limit the limit of items per single response. The default value is 100. + * @param fields the fields to retrieve. + * @return an iterable with all the collaboration allowlists met search conditions. + */ + public static Iterable getAll( + final BoxAPIConnection api, int limit, String... fields) { + + QueryStringBuilder builder = new QueryStringBuilder(); + if (fields.length > 0) { + builder.appendParam("fields", fields); + } - /** - * Collaboration Allowlist Entries URL Template with given ID. - */ - public static final URLTemplate COLLABORATION_ALLOWLIST_ENTRY_URL_TEMPLATE = - new URLTemplate("collaboration_whitelist_entries/%s"); + URL url = + COLLABORATION_ALLOWLIST_ENTRIES_URL_TEMPLATE.buildWithQuery( + api.getBaseURL(), builder.toString()); + return new BoxResourceIterable(api, url, limit) { + + @Override + protected BoxCollaborationAllowlist.Info factory(JsonObject jsonObject) { + BoxCollaborationAllowlist allowlist = + new BoxCollaborationAllowlist(api, jsonObject.get("id").asString()); + + return allowlist.new Info(jsonObject); + } + }; + } + + /** @return information about this {@link BoxCollaborationAllowlist}. */ + public BoxCollaborationAllowlist.Info getInfo() { + URL url = + COLLABORATION_ALLOWLIST_ENTRY_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, HttpMethod.GET); + try (BoxJSONResponse response = request.send()) { + return new Info(Json.parse(response.getJSON()).asObject()); + } + } - /** - * The default limit of entries per response. - */ - private static final int DEFAULT_LIMIT = 100; + /** Deletes this collaboration allowlist. */ + public void delete() { + BoxAPIConnection api = this.getAPI(); + URL url = COLLABORATION_ALLOWLIST_ENTRY_URL_TEMPLATE.build(api.getBaseURL(), this.getID()); + + BoxAPIRequest request = new BoxAPIRequest(api, url, HttpMethod.DELETE); + request.send().close(); + } + + /** Enumerates the direction of the collaboration allowlist. */ + public enum AllowlistDirection { + /** Allowlist inbound collaboration. */ + INBOUND("inbound"), + + /** Allowlist outbound collaboration. */ + OUTBOUND("outbound"), + + /** Allowlist both inbound and outbound collaboration. */ + BOTH("both"); + + private final String direction; + + AllowlistDirection(String direction) { + + this.direction = direction; + } + + static AllowlistDirection fromDirection(String direction) { + if (direction.equals("inbound")) { + return AllowlistDirection.INBOUND; + } else if (direction.equals("outbound")) { + return AllowlistDirection.OUTBOUND; + } else if (direction.equals("both")) { + return AllowlistDirection.BOTH; + } else { + return null; + } + } /** - * Constructs a BoxCollaborationAllowlist for a collaboration allowlist with a given ID. + * Returns a String containing the current direction of the collaboration allowlisting. * - * @param api the API connection to be used by the collaboration allowlist. - * @param id the ID of the collaboration allowlist. + * @return a String containing information about the direction of the collaboration + * allowlisting. */ - public BoxCollaborationAllowlist(BoxAPIConnection api, String id) { - super(api, id); + public String toString() { + + return this.direction; + } + } + + /** Contains information about a BoxCollaborationAllowlist. */ + public class Info extends BoxResource.Info { + private String type; + private String domain; + private AllowlistDirection direction; + private BoxEnterprise enterprise; + private Date createdAt; + private Date modifiedAt; + + /** Constructs an empty Info object. */ + public Info() { + super(); } /** - * Creates a new Collaboration Allowlist for a domain. + * Constructs an Info object by parsing information from a JSON string. * - * @param api the API connection to be used by the resource. - * @param domain the domain to be added to a collaboration allowlist for a Box Enterprise. - * @param direction an enum representing the direction of the collaboration allowlist. Can be set to - * inbound, outbound, or both. - * @return information about the collaboration allowlist created. + * @param json the JSON string to parse. */ - public static BoxCollaborationAllowlist.Info create(final BoxAPIConnection api, String domain, - AllowlistDirection direction) { - - URL url = COLLABORATION_ALLOWLIST_ENTRIES_URL_TEMPLATE.build(api.getBaseURL()); - BoxJSONRequest request = new BoxJSONRequest(api, url, HttpMethod.POST); - JsonObject requestJSON = new JsonObject() - .add("domain", domain) - .add("direction", direction.toString()); - - request.setBody(requestJSON.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - BoxCollaborationAllowlist domainAllowlist = - new BoxCollaborationAllowlist(api, responseJSON.get("id").asString()); - - return domainAllowlist.new Info(responseJSON); - } + public Info(String json) { + super(json); + } + + Info(JsonObject jsonObject) { + super(jsonObject); } /** - * Returns all the collaboration allowlisting with specified filters. + * Gets the type of the collaboration allowlist. * - * @param api the API connection to be used by the resource. - * @param fields the fields to retrieve. - * @return an iterable with all the collaboration allowlists met search conditions. + * @return the type for the collaboration allowlist. */ - public static Iterable getAll(final BoxAPIConnection api, String... fields) { + public String getType() { - return getAll(api, DEFAULT_LIMIT, fields); + return this.type; } /** - * Returns all the collaboration allowlisting with specified filters. + * Gets the domain added to the collaboration allowlist. * - * @param api the API connection to be used by the resource. - * @param limit the limit of items per single response. The default value is 100. - * @param fields the fields to retrieve. - * @return an iterable with all the collaboration allowlists met search conditions. + * @return the domain in the collaboration allowlist */ - public static Iterable getAll(final BoxAPIConnection api, int limit, - String... fields) { - - QueryStringBuilder builder = new QueryStringBuilder(); - if (fields.length > 0) { - builder.appendParam("fields", fields); - } + public String getDomain() { - URL url = COLLABORATION_ALLOWLIST_ENTRIES_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString()); - return new BoxResourceIterable(api, url, limit) { - - @Override - protected BoxCollaborationAllowlist.Info factory(JsonObject jsonObject) { - BoxCollaborationAllowlist allowlist = new BoxCollaborationAllowlist( - api, jsonObject.get("id").asString()); - - return allowlist.new Info(jsonObject); - } - }; + return this.domain; } /** - * @return information about this {@link BoxCollaborationAllowlist}. + * Get the direction of the collaboration allowlist. Values can be inbound, outbound, or both. + * + * @return the direction set for the collaboration allowlist. Values can be inbound, outbound, + * or both. */ - public BoxCollaborationAllowlist.Info getInfo() { - URL url = COLLABORATION_ALLOWLIST_ENTRY_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, HttpMethod.GET); - try (BoxJSONResponse response = request.send()) { - return new Info(Json.parse(response.getJSON()).asObject()); - } + public AllowlistDirection getDirection() { + + return this.direction; } /** - * Deletes this collaboration allowlist. + * Gets the enterprise that the collaboration allowlist belongs to. + * + * @return the enterprise that the collaboration allowlist belongs to. */ - public void delete() { - BoxAPIConnection api = this.getAPI(); - URL url = COLLABORATION_ALLOWLIST_ENTRY_URL_TEMPLATE.build(api.getBaseURL(), this.getID()); + public BoxEnterprise getEnterprise() { - BoxAPIRequest request = new BoxAPIRequest(api, url, HttpMethod.DELETE); - request.send().close(); + return this.enterprise; } /** - * Enumerates the direction of the collaboration allowlist. + * Gets the time the collaboration allowlist was created. + * + * @return the time the collaboration allowlist was created. */ - public enum AllowlistDirection { - /** - * Allowlist inbound collaboration. - */ - INBOUND("inbound"), - - /** - * Allowlist outbound collaboration. - */ - OUTBOUND("outbound"), - - /** - * Allowlist both inbound and outbound collaboration. - */ - BOTH("both"); + public Date getCreatedAt() { - private final String direction; - - AllowlistDirection(String direction) { - - this.direction = direction; - } - - static AllowlistDirection fromDirection(String direction) { - if (direction.equals("inbound")) { - return AllowlistDirection.INBOUND; - } else if (direction.equals("outbound")) { - return AllowlistDirection.OUTBOUND; - } else if (direction.equals("both")) { - return AllowlistDirection.BOTH; - } else { - return null; - } - } - - /** - * Returns a String containing the current direction of the collaboration allowlisting. - * - * @return a String containing information about the direction of the collaboration allowlisting. - */ - public String toString() { - - return this.direction; - } + return this.createdAt; } /** - * Contains information about a BoxCollaborationAllowlist. + * Gets the time the collaboration allowlist was last modified. + * + * @return the time the collaboration allowlist was last modified. */ - public class Info extends BoxResource.Info { - private String type; - private String domain; - private AllowlistDirection direction; - private BoxEnterprise enterprise; - private Date createdAt; - private Date modifiedAt; - - /** - * Constructs an empty Info object. - */ - public Info() { - super(); - } - - /** - * Constructs an Info object by parsing information from a JSON string. - * - * @param json the JSON string to parse. - */ - public Info(String json) { - super(json); - } - - Info(JsonObject jsonObject) { - super(jsonObject); - } - - /** - * Gets the type of the collaboration allowlist. - * - * @return the type for the collaboration allowlist. - */ - public String getType() { - - return this.type; - } - - /** - * Gets the domain added to the collaboration allowlist. - * - * @return the domain in the collaboration allowlist - */ - public String getDomain() { + public Date getModifiedAt() { - return this.domain; - } - - /** - * Get the direction of the collaboration allowlist. Values can be inbound, outbound, or - * both. - * - * @return the direction set for the collaboration allowlist. Values can be inbound, outbound, or both. - */ - public AllowlistDirection getDirection() { - - return this.direction; - } - - /** - * Gets the enterprise that the collaboration allowlist belongs to. - * - * @return the enterprise that the collaboration allowlist belongs to. - */ - public BoxEnterprise getEnterprise() { - - return this.enterprise; - } - - /** - * Gets the time the collaboration allowlist was created. - * - * @return the time the collaboration allowlist was created. - */ - public Date getCreatedAt() { - - return this.createdAt; - } - - /** - * Gets the time the collaboration allowlist was last modified. - * - * @return the time the collaboration allowlist was last modified. - */ - public Date getModifiedAt() { - - return this.modifiedAt; - } - - @Override - public BoxCollaborationAllowlist getResource() { - return BoxCollaborationAllowlist.this; - } + return this.modifiedAt; + } - @Override - protected void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); + @Override + public BoxCollaborationAllowlist getResource() { + return BoxCollaborationAllowlist.this; + } - String memberName = member.getName(); - JsonValue value = member.getValue(); - try { - if (memberName.equals("domain")) { - this.domain = value.asString(); + @Override + protected void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); - } else if (memberName.equals("type")) { - this.type = value.asString(); + String memberName = member.getName(); + JsonValue value = member.getValue(); + try { + if (memberName.equals("domain")) { + this.domain = value.asString(); - } else if (memberName.equals("direction")) { - this.direction = AllowlistDirection.fromDirection(value.asString()); + } else if (memberName.equals("type")) { + this.type = value.asString(); - } else if (memberName.equals("enterprise")) { - JsonObject jsonObject = value.asObject(); - this.enterprise = new BoxEnterprise(jsonObject); + } else if (memberName.equals("direction")) { + this.direction = AllowlistDirection.fromDirection(value.asString()); - } else if (memberName.equals("created_at")) { - this.createdAt = BoxDateFormat.parse(value.asString()); + } else if (memberName.equals("enterprise")) { + JsonObject jsonObject = value.asObject(); + this.enterprise = new BoxEnterprise(jsonObject); - } else if (memberName.equals("modified_at")) { - this.modifiedAt = BoxDateFormat.parse(value.asString()); + } else if (memberName.equals("created_at")) { + this.createdAt = BoxDateFormat.parse(value.asString()); - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); - } + } else if (memberName.equals("modified_at")) { + this.modifiedAt = BoxDateFormat.parse(value.asString()); } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); + } } + } } diff --git a/src/main/java/com/box/sdk/BoxCollaborationAllowlistExemptTarget.java b/src/main/java/com/box/sdk/BoxCollaborationAllowlistExemptTarget.java index f29ce9204..5e0adb54b 100644 --- a/src/main/java/com/box/sdk/BoxCollaborationAllowlistExemptTarget.java +++ b/src/main/java/com/box/sdk/BoxCollaborationAllowlistExemptTarget.java @@ -8,250 +8,242 @@ import java.util.Date; /** - * Represents a collaboration allowlist between a user and a Box Enterprise. Collaboration Allowlist enables a Box - * Enterprise(only available if you have Box Governance) to manage a set of approved users that can collaborate - * with an enterprise. + * Represents a collaboration allowlist between a user and a Box Enterprise. Collaboration Allowlist + * enables a Box Enterprise(only available if you have Box Governance) to manage a set of approved + * users that can collaborate with an enterprise. * - *

Unless otherwise noted, the methods in this class can throw an unchecked {@link BoxAPIException} (unchecked - * meaning that the compiler won't force you to handle it) if an error occurs. If you wish to implement custom error - * handling for errors related to the Box REST API, you should capture this exception explicitly.

+ *

Unless otherwise noted, the methods in this class can throw an unchecked {@link + * BoxAPIException} (unchecked meaning that the compiler won't force you to handle it) if an error + * occurs. If you wish to implement custom error handling for errors related to the Box REST API, + * you should capture this exception explicitly. */ @BoxResourceType("collaboration_allowlist_exempt_target") public class BoxCollaborationAllowlistExemptTarget extends BoxResource { - /** - * Collaboration Allowlist Exempt Target Entries URL Template. - */ - public static final URLTemplate COLLABORATION_ALLOWLIST_EXEMPT_TARGET_ENTRIES_URL_TEMPLATE = - new URLTemplate("collaboration_whitelist_exempt_targets"); - - /** - * Collaboration Allowlist Exempt Target Entries URL Template with given ID. - */ - public static final URLTemplate COLLABORATION_ALLOWLIST_EXEMPT_TARGET_ENTRY_URL_TEMPLATE = - new URLTemplate("collaboration_whitelist_exempt_targets/%s"); + /** Collaboration Allowlist Exempt Target Entries URL Template. */ + public static final URLTemplate COLLABORATION_ALLOWLIST_EXEMPT_TARGET_ENTRIES_URL_TEMPLATE = + new URLTemplate("collaboration_whitelist_exempt_targets"); + + /** Collaboration Allowlist Exempt Target Entries URL Template with given ID. */ + public static final URLTemplate COLLABORATION_ALLOWLIST_EXEMPT_TARGET_ENTRY_URL_TEMPLATE = + new URLTemplate("collaboration_whitelist_exempt_targets/%s"); + + /** The default limit of entries per response. */ + private static final int DEFAULT_LIMIT = 100; + + /** + * Constructs a BoxCollaborationAllowlistExemptTarget for a collaboration allowlist with a give + * ID. + * + * @param api the API connection to be used by the collaboration allowlist. + * @param id the ID of the collaboration allowlist. + */ + public BoxCollaborationAllowlistExemptTarget(BoxAPIConnection api, String id) { + + super(api, id); + } + + /** + * Creates a collaboration allowlist for a Box User with a given ID. + * + * @param api the API connection to be used by the collaboration allowlist. + * @param userID the ID of the Box User to add to the collaboration allowlist. + * @return information about the collaboration allowlist created for user. + */ + public static BoxCollaborationAllowlistExemptTarget.Info create( + final BoxAPIConnection api, String userID) { + URL url = COLLABORATION_ALLOWLIST_EXEMPT_TARGET_ENTRIES_URL_TEMPLATE.build(api.getBaseURL()); + BoxJSONRequest request = new BoxJSONRequest(api, url, HttpMethod.POST); + JsonObject requestJSON = + new JsonObject().add("user", new JsonObject().add("type", "user").add("id", userID)); + + request.setBody(requestJSON.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + BoxCollaborationAllowlistExemptTarget userAllowlist = + new BoxCollaborationAllowlistExemptTarget(api, responseJSON.get("id").asString()); + + return userAllowlist.new Info(responseJSON); + } + } + + /** + * Returns all the collaboration allowlisting for user with default limit set to 100. + * + * @param api the API connection to be use by the resource. + * @param fields the fields to retrieve. + * @return an iterable with all the collaboration allowlists for users met search conditions. + */ + public static Iterable getAll( + final BoxAPIConnection api, String... fields) { + return getAll(api, DEFAULT_LIMIT, fields); + } + + /** + * Returns all the collaboration allowlisting for user with specified filters. + * + * @param api the API connection to be used by the resource. + * @param limit the number of collaboration allowlists to retrieve. + * @param fields the fields to retrieve. + * @return an iterable with all the collaboration allowlists for users met search conditions. + */ + public static Iterable getAll( + final BoxAPIConnection api, int limit, String... fields) { + QueryStringBuilder builder = new QueryStringBuilder(); + if (fields.length > 0) { + builder.appendParam("fields", fields); + } - /** - * The default limit of entries per response. - */ - private static final int DEFAULT_LIMIT = 100; + URL url = + COLLABORATION_ALLOWLIST_EXEMPT_TARGET_ENTRIES_URL_TEMPLATE.buildWithQuery( + api.getBaseURL(), builder.toString()); + return new BoxResourceIterable(api, url, limit) { + + @Override + protected BoxCollaborationAllowlistExemptTarget.Info factory(JsonObject jsonObject) { + BoxCollaborationAllowlistExemptTarget userAllowlist = + new BoxCollaborationAllowlistExemptTarget(api, jsonObject.get("id").asString()); + + return userAllowlist.new Info(jsonObject); + } + }; + } + + /** + * Retrieves information for a collaboration allowlist for a given allowlist ID. + * + * @return information about this {@link BoxCollaborationAllowlistExemptTarget}. + */ + public BoxCollaborationAllowlistExemptTarget.Info getInfo() { + URL url = + COLLABORATION_ALLOWLIST_EXEMPT_TARGET_ENTRY_URL_TEMPLATE.build( + this.getAPI().getBaseURL(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, HttpMethod.GET); + try (BoxJSONResponse response = request.send()) { + return new Info(Json.parse(response.getJSON()).asObject()); + } + } + + /** Deletes this collaboration allowlist entry for user. */ + public void delete() { + BoxAPIConnection api = this.getAPI(); + URL url = + COLLABORATION_ALLOWLIST_EXEMPT_TARGET_ENTRY_URL_TEMPLATE.build( + api.getBaseURL(), this.getID()); + + BoxAPIRequest request = new BoxAPIRequest(api, url, HttpMethod.DELETE); + request.send().close(); + } + + /** Contains information about a BoxCollaborationAllowlistExemptTarget. */ + public class Info extends BoxResource.Info { + private String type; + private BoxUser.Info user; + private BoxEnterprise enterprise; + private Date createdAt; + private Date modifiedAt; + + /** Constructs an empty Info object. */ + public Info() { + super(); + } /** - * Constructs a BoxCollaborationAllowlistExemptTarget for a collaboration allowlist with a give ID. + * Constructs an Info object by parsing information from a JSON string. * - * @param api the API connection to be used by the collaboration allowlist. - * @param id the ID of the collaboration allowlist. + * @param json the JSON string to parse. */ - public BoxCollaborationAllowlistExemptTarget(BoxAPIConnection api, String id) { - - super(api, id); + public Info(String json) { + super(json); } - /** - * Creates a collaboration allowlist for a Box User with a given ID. - * - * @param api the API connection to be used by the collaboration allowlist. - * @param userID the ID of the Box User to add to the collaboration allowlist. - * @return information about the collaboration allowlist created for user. - */ - public static BoxCollaborationAllowlistExemptTarget.Info create(final BoxAPIConnection api, String userID) { - URL url = COLLABORATION_ALLOWLIST_EXEMPT_TARGET_ENTRIES_URL_TEMPLATE.build(api.getBaseURL()); - BoxJSONRequest request = new BoxJSONRequest(api, url, HttpMethod.POST); - JsonObject requestJSON = new JsonObject() - .add("user", new JsonObject() - .add("type", "user") - .add("id", userID)); - - request.setBody(requestJSON.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - BoxCollaborationAllowlistExemptTarget userAllowlist = new BoxCollaborationAllowlistExemptTarget(api, - responseJSON.get("id").asString()); - - return userAllowlist.new Info(responseJSON); - } + Info(JsonObject jsonObject) { + super(jsonObject); } /** - * Returns all the collaboration allowlisting for user with default limit set to 100. + * Gets the type of the collaboration allowlist for user. * - * @param api the API connection to be use by the resource. - * @param fields the fields to retrieve. - * @return an iterable with all the collaboration allowlists for users met search conditions. + * @return the type of the collaboration allowlist for user. */ - public static Iterable getAll(final BoxAPIConnection api, - String... fields) { - return getAll(api, DEFAULT_LIMIT, fields); + public String getType() { + + return this.type; } /** - * Returns all the collaboration allowlisting for user with specified filters. + * Gets the user added to the collaboration allowlist. * - * @param api the API connection to be used by the resource. - * @param limit the number of collaboration allowlists to retrieve. - * @param fields the fields to retrieve. - * @return an iterable with all the collaboration allowlists for users met search conditions. + * @return the user in the collaboration allowlist. */ - public static Iterable getAll(final BoxAPIConnection api, int limit, - String... fields) { - QueryStringBuilder builder = new QueryStringBuilder(); - if (fields.length > 0) { - builder.appendParam("fields", fields); - } - - URL url = COLLABORATION_ALLOWLIST_EXEMPT_TARGET_ENTRIES_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), - builder.toString()); - return new BoxResourceIterable(api, url, limit) { + public BoxUser.Info getUser() { - @Override - protected BoxCollaborationAllowlistExemptTarget.Info factory(JsonObject jsonObject) { - BoxCollaborationAllowlistExemptTarget userAllowlist = new BoxCollaborationAllowlistExemptTarget( - api, jsonObject.get("id").asString()); - - return userAllowlist.new Info(jsonObject); - } - }; + return this.user; } /** - * Retrieves information for a collaboration allowlist for a given allowlist ID. + * Gets the enterprise that the collaboration allowlist for user belongs to. * - * @return information about this {@link BoxCollaborationAllowlistExemptTarget}. + * @return the enterprise that the collaboration allowlist for user belongs to. */ - public BoxCollaborationAllowlistExemptTarget.Info getInfo() { - URL url = COLLABORATION_ALLOWLIST_EXEMPT_TARGET_ENTRY_URL_TEMPLATE.build(this.getAPI().getBaseURL(), - this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, HttpMethod.GET); - try (BoxJSONResponse response = request.send()) { - return new Info(Json.parse(response.getJSON()).asObject()); - } + public BoxEnterprise getEnterprise() { + + return this.enterprise; } /** - * Deletes this collaboration allowlist entry for user. + * Gets the time the collaboration allowlist was created for user. + * + * @return the time the collaboration allowlist was created for user. */ - public void delete() { - BoxAPIConnection api = this.getAPI(); - URL url = COLLABORATION_ALLOWLIST_EXEMPT_TARGET_ENTRY_URL_TEMPLATE.build(api.getBaseURL(), - this.getID()); + public Date getCreatedAt() { - BoxAPIRequest request = new BoxAPIRequest(api, url, HttpMethod.DELETE); - request.send().close(); + return this.createdAt; } /** - * Contains information about a BoxCollaborationAllowlistExemptTarget. + * Gets the last modified time of the collaboration allowlist for user. + * + * @return the last modified time of the collaboration allowlist for user. */ - public class Info extends BoxResource.Info { - private String type; - private BoxUser.Info user; - private BoxEnterprise enterprise; - private Date createdAt; - private Date modifiedAt; - - /** - * Constructs an empty Info object. - */ - public Info() { - super(); - } - - /** - * Constructs an Info object by parsing information from a JSON string. - * - * @param json the JSON string to parse. - */ - public Info(String json) { - super(json); - } - - Info(JsonObject jsonObject) { - super(jsonObject); - } - - /** - * Gets the type of the collaboration allowlist for user. - * - * @return the type of the collaboration allowlist for user. - */ - public String getType() { - - return this.type; - } - - /** - * Gets the user added to the collaboration allowlist. - * - * @return the user in the collaboration allowlist. - */ - public BoxUser.Info getUser() { + public Date getModifiedAt() { - return this.user; - } - - /** - * Gets the enterprise that the collaboration allowlist for user belongs to. - * - * @return the enterprise that the collaboration allowlist for user belongs to. - */ - public BoxEnterprise getEnterprise() { + return this.modifiedAt; + } - return this.enterprise; - } + @Override + public BoxCollaborationAllowlistExemptTarget getResource() { + return BoxCollaborationAllowlistExemptTarget.this; + } - /** - * Gets the time the collaboration allowlist was created for user. - * - * @return the time the collaboration allowlist was created for user. - */ - public Date getCreatedAt() { + @Override + protected void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); - return this.createdAt; - } + String memberName = member.getName(); + JsonValue value = member.getValue(); + try { + if (memberName.equals("user")) { + JsonObject userJSON = value.asObject(); + String userID = userJSON.get("id").asString(); + BoxUser user = new BoxUser(getAPI(), userID); + this.user = user.new Info(userJSON); - /** - * Gets the last modified time of the collaboration allowlist for user. - * - * @return the last modified time of the collaboration allowlist for user. - */ - public Date getModifiedAt() { + } else if (memberName.equals("type")) { + this.type = value.asString(); - return this.modifiedAt; - } + } else if (memberName.equals("enterprise")) { + JsonObject jsonObject = value.asObject(); + this.enterprise = new BoxEnterprise(jsonObject); - @Override - public BoxCollaborationAllowlistExemptTarget getResource() { - return BoxCollaborationAllowlistExemptTarget.this; - } + } else if (memberName.equals("created_at")) { + this.createdAt = BoxDateFormat.parse(value.asString()); - @Override - protected void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - - String memberName = member.getName(); - JsonValue value = member.getValue(); - try { - if (memberName.equals("user")) { - JsonObject userJSON = value.asObject(); - String userID = userJSON.get("id").asString(); - BoxUser user = new BoxUser(getAPI(), userID); - this.user = user.new Info(userJSON); - - } else if (memberName.equals("type")) { - this.type = value.asString(); - - } else if (memberName.equals("enterprise")) { - JsonObject jsonObject = value.asObject(); - this.enterprise = new BoxEnterprise(jsonObject); - - } else if (memberName.equals("created_at")) { - this.createdAt = BoxDateFormat.parse(value.asString()); - - } else if (memberName.equals("modified_at")) { - this.modifiedAt = BoxDateFormat.parse(value.asString()); - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); - } + } else if (memberName.equals("modified_at")) { + this.modifiedAt = BoxDateFormat.parse(value.asString()); } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); + } } + } } diff --git a/src/main/java/com/box/sdk/BoxCollaborationIterator.java b/src/main/java/com/box/sdk/BoxCollaborationIterator.java index 7c7a297b7..84fd4e96c 100644 --- a/src/main/java/com/box/sdk/BoxCollaborationIterator.java +++ b/src/main/java/com/box/sdk/BoxCollaborationIterator.java @@ -7,30 +7,30 @@ import java.util.Iterator; class BoxCollaborationIterator implements Iterator { - private static final long LIMIT = 100; - private final BoxAPIConnection api; - private final JsonIterator jsonIterator; - - BoxCollaborationIterator(BoxAPIConnection api, URL url) { - this.api = api; - this.jsonIterator = new JsonIterator(api, url, offset(0, LIMIT)); - } - - @Override - public boolean hasNext() { - return this.jsonIterator.hasNext(); - } - - @Override - public BoxCollaboration.Info next() { - JsonObject nextJSONObject = this.jsonIterator.next(); - String id = nextJSONObject.get("id").asString(); - - BoxCollaboration collaboration = new BoxCollaboration(this.api, id); - return collaboration.new Info(nextJSONObject); - } - - public void remove() { - throw new UnsupportedOperationException(); - } + private static final long LIMIT = 100; + private final BoxAPIConnection api; + private final JsonIterator jsonIterator; + + BoxCollaborationIterator(BoxAPIConnection api, URL url) { + this.api = api; + this.jsonIterator = new JsonIterator(api, url, offset(0, LIMIT)); + } + + @Override + public boolean hasNext() { + return this.jsonIterator.hasNext(); + } + + @Override + public BoxCollaboration.Info next() { + JsonObject nextJSONObject = this.jsonIterator.next(); + String id = nextJSONObject.get("id").asString(); + + BoxCollaboration collaboration = new BoxCollaboration(this.api, id); + return collaboration.new Info(nextJSONObject); + } + + public void remove() { + throw new UnsupportedOperationException(); + } } diff --git a/src/main/java/com/box/sdk/BoxCollaborator.java b/src/main/java/com/box/sdk/BoxCollaborator.java index 1a490d4f1..cdca6c1cf 100644 --- a/src/main/java/com/box/sdk/BoxCollaborator.java +++ b/src/main/java/com/box/sdk/BoxCollaborator.java @@ -4,212 +4,194 @@ import com.eclipsesource.json.JsonValue; import java.util.Date; -/** - * The abstract base class for types that can be added to collaborations. - */ +/** The abstract base class for types that can be added to collaborations. */ public abstract class BoxCollaborator extends BoxResource { - /** - * Constructs a BoxCollaborator for a collaborator with a given ID. - * - * @param api the API connection to be used by the collaborator. - * @param id the ID of the collaborator. - */ - public BoxCollaborator(BoxAPIConnection api, String id) { - super(api, id); - } + /** + * Constructs a BoxCollaborator for a collaborator with a given ID. + * + * @param api the API connection to be used by the collaborator. + * @param id the ID of the collaborator. + */ + public BoxCollaborator(BoxAPIConnection api, String id) { + super(api, id); + } - /** - * Enumerates the possible types of collaborations. - */ - public enum CollaboratorType { - /** - * A user. - */ - USER("user"), + /** Enumerates the possible types of collaborations. */ + public enum CollaboratorType { + /** A user. */ + USER("user"), - /** - * A group. - */ - GROUP("group"); + /** A group. */ + GROUP("group"); - private final String jsonValue; + private final String jsonValue; - CollaboratorType(String jsonValue) { - this.jsonValue = jsonValue; - } + CollaboratorType(String jsonValue) { + this.jsonValue = jsonValue; + } - static CollaboratorType fromJSONValue(String jsonValue) { - return CollaboratorType.valueOf(jsonValue.toUpperCase(java.util.Locale.ROOT)); - } + static CollaboratorType fromJSONValue(String jsonValue) { + return CollaboratorType.valueOf(jsonValue.toUpperCase(java.util.Locale.ROOT)); + } - String toJSONValue() { - return this.jsonValue; - } + String toJSONValue() { + return this.jsonValue; } + } - /** - * Enumerates the possible types of groups. - */ - public enum GroupType { - /** - * A users group. - */ - ALL_USERS_GROUP("all_users_group"), + /** Enumerates the possible types of groups. */ + public enum GroupType { + /** A users group. */ + ALL_USERS_GROUP("all_users_group"), - /** - * A managed group. - */ - MANAGED_GROUP("managed_group"); + /** A managed group. */ + MANAGED_GROUP("managed_group"); - private final String jsonValue; + private final String jsonValue; - GroupType(String jsonValue) { - this.jsonValue = jsonValue; - } + GroupType(String jsonValue) { + this.jsonValue = jsonValue; + } - static GroupType fromJSONValue(String jsonValue) { - return GroupType.valueOf(jsonValue.toUpperCase(java.util.Locale.ROOT)); - } + static GroupType fromJSONValue(String jsonValue) { + return GroupType.valueOf(jsonValue.toUpperCase(java.util.Locale.ROOT)); + } - String toJSONValue() { - return this.jsonValue; - } + String toJSONValue() { + return this.jsonValue; + } + } + + /** Contains information about a BoxCollaborator. */ + public abstract class Info extends BoxResource.Info { + private CollaboratorType type; + private String name; + private Date createdAt; + private Date modifiedAt; + private String login; + private GroupType groupType; + + /** Constructs an empty Info object. */ + public Info() { + super(); } /** - * Contains information about a BoxCollaborator. + * Constructs an Info object by parsing information from a JSON string. + * + * @param json the JSON string to parse. */ - public abstract class Info extends BoxResource.Info { - private CollaboratorType type; - private String name; - private Date createdAt; - private Date modifiedAt; - private String login; - private GroupType groupType; - - /** - * Constructs an empty Info object. - */ - public Info() { - super(); - } - - /** - * Constructs an Info object by parsing information from a JSON string. - * - * @param json the JSON string to parse. - */ - public Info(String json) { - super(json); - } + public Info(String json) { + super(json); + } - /** - * Constructs an Info object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - Info(JsonObject jsonObject) { - super(jsonObject); - } + /** + * Constructs an Info object using an already parsed JSON object. + * + * @param jsonObject the parsed JSON object. + */ + Info(JsonObject jsonObject) { + super(jsonObject); + } - /** - * Gets the type of the collaborator. - * - * @return the type of the collaborator. - */ - public CollaboratorType getType() { - return this.type; - } + /** + * Gets the type of the collaborator. + * + * @return the type of the collaborator. + */ + public CollaboratorType getType() { + return this.type; + } - /** - * Gets the name of the collaborator. - * - * @return the name of the collaborator. - */ - public String getName() { - return this.name; - } + /** + * Gets the name of the collaborator. + * + * @return the name of the collaborator. + */ + public String getName() { + return this.name; + } - /** - * Sets the name of the collaborator. - * - * @param name the new name of the collaborator. - */ - public void setName(String name) { - this.name = name; - this.addPendingChange("name", name); - } + /** + * Sets the name of the collaborator. + * + * @param name the new name of the collaborator. + */ + public void setName(String name) { + this.name = name; + this.addPendingChange("name", name); + } - /** - * Gets the date that the collaborator was created. - * - * @return the date that the collaborator was created. - */ - public Date getCreatedAt() { - return this.createdAt; - } + /** + * Gets the date that the collaborator was created. + * + * @return the date that the collaborator was created. + */ + public Date getCreatedAt() { + return this.createdAt; + } - /** - * Gets the date that the collaborator was modified. - * - * @return the date that the collaborator was modified. - */ - public Date getModifiedAt() { - return this.modifiedAt; - } + /** + * Gets the date that the collaborator was modified. + * + * @return the date that the collaborator was modified. + */ + public Date getModifiedAt() { + return this.modifiedAt; + } - /** - * Gets the login for the collaborator if the collaborator is a user. - * - * @return the login of the collaboraor. - */ - public String getLogin() { - return this.login; - } + /** + * Gets the login for the collaborator if the collaborator is a user. + * + * @return the login of the collaboraor. + */ + public String getLogin() { + return this.login; + } - /** - * Gets the group type for the collaborator if the collaborator is a group. - * - * @return the group type of the collaboraor. - */ - public GroupType getGroupType() { - return this.groupType; - } + /** + * Gets the group type for the collaborator if the collaborator is a group. + * + * @return the group type of the collaboraor. + */ + public GroupType getGroupType() { + return this.groupType; + } - @Override - protected void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - JsonValue value = member.getValue(); - String name = member.getName(); - - try { - - switch (name) { - case "type": - this.type = CollaboratorType.fromJSONValue(value.asString()); - break; - case "name": - this.name = value.asString(); - break; - case "created_at": - this.createdAt = BoxDateFormat.parse(value.asString()); - break; - case "modified_at": - this.modifiedAt = BoxDateFormat.parse(value.asString()); - break; - case "login": - this.login = value.asString(); - break; - case "group_type": - this.groupType = GroupType.fromJSONValue(value.asString()); - break; - default: - break; - } - } catch (Exception e) { - throw new BoxDeserializationException(name, value.toString(), e); - } - } + @Override + protected void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + JsonValue value = member.getValue(); + String name = member.getName(); + + try { + + switch (name) { + case "type": + this.type = CollaboratorType.fromJSONValue(value.asString()); + break; + case "name": + this.name = value.asString(); + break; + case "created_at": + this.createdAt = BoxDateFormat.parse(value.asString()); + break; + case "modified_at": + this.modifiedAt = BoxDateFormat.parse(value.asString()); + break; + case "login": + this.login = value.asString(); + break; + case "group_type": + this.groupType = GroupType.fromJSONValue(value.asString()); + break; + default: + break; + } + } catch (Exception e) { + throw new BoxDeserializationException(name, value.toString(), e); + } } + } } diff --git a/src/main/java/com/box/sdk/BoxCollection.java b/src/main/java/com/box/sdk/BoxCollection.java index c5fa549e7..dd3fe9c67 100644 --- a/src/main/java/com/box/sdk/BoxCollection.java +++ b/src/main/java/com/box/sdk/BoxCollection.java @@ -8,186 +8,183 @@ import java.util.Iterator; /** - * Collections contain information about the items contained inside of them, including files and folders. The only - * collection available currently is a “Favorites” collection. + * Collections contain information about the items contained inside of them, including files and + * folders. The only collection available currently is a “Favorites” collection. * - *

Unless otherwise noted, the methods in this class can throw an unchecked {@link BoxAPIException} (unchecked - * meaning that the compiler won't force you to handle it) if an error occurs. If you wish to implement custom error - * handling for errors related to the Box REST API, you should capture this exception explicitly.

+ *

Unless otherwise noted, the methods in this class can throw an unchecked {@link + * BoxAPIException} (unchecked meaning that the compiler won't force you to handle it) if an error + * occurs. If you wish to implement custom error handling for errors related to the Box REST API, + * you should capture this exception explicitly. */ @BoxResourceType("collection") public class BoxCollection extends BoxResource implements Iterable { - /** - * Get Collections URL Template. - */ - public static final URLTemplate GET_COLLECTIONS_URL_TEMPLATE = new URLTemplate("collections/"); - /** - * Get Collection Items URL Template. - */ - public static final URLTemplate GET_COLLECTION_ITEMS_URL = new URLTemplate("collections/%s/items/"); + /** Get Collections URL Template. */ + public static final URLTemplate GET_COLLECTIONS_URL_TEMPLATE = new URLTemplate("collections/"); + /** Get Collection Items URL Template. */ + public static final URLTemplate GET_COLLECTION_ITEMS_URL = + new URLTemplate("collections/%s/items/"); + + /** + * Constructs a BoxCollection for a collection with a given ID. + * + * @param api the API connection to be used by the collection. + * @param id the ID of the collection. + */ + public BoxCollection(BoxAPIConnection api, String id) { + super(api, id); + } + + /** + * Gets an iterable of all the collections for the given user. + * + * @param api the API connection to be used when retrieving the collections. + * @return an iterable containing info about all the collections. + */ + public static Iterable getAllCollections(final BoxAPIConnection api) { + return () -> { + URL url = GET_COLLECTIONS_URL_TEMPLATE.build(api.getBaseURL()); + return new BoxCollectionIterator(api, url); + }; + } + + /** + * Returns an iterable containing the items in this collection. Iterating over the iterable + * returned by this method is equivalent to iterating over this BoxCollection directly. + * + * @return an iterable containing the items in this collection. + */ + public Iterable getItems() { + return this; + } + + /** + * Returns an iterable containing the items in this collection and specifies which attributes to + * include in the response. + * + * @param fields the fields to retrieve. + * @return an iterable containing the items in this collection. + */ + public Iterable getItems(final String... fields) { + return () -> { + String queryString = new QueryStringBuilder().appendParam("fields", fields).toString(); + URL url = + GET_COLLECTION_ITEMS_URL.buildWithQuery(getAPI().getBaseURL(), queryString, getID()); + return new BoxItemIterator(getAPI(), url); + }; + } + + /** + * Retrieves a specific range of items in this collection. + * + * @param offset the index of the first item to retrieve. + * @param limit the maximum number of items to retrieve after the offset. + * @param fields the fields to retrieve. + * @return a partial collection containing the specified range of items. + */ + public PartialCollection getItemsRange(long offset, long limit, String... fields) { + QueryStringBuilder builder = + new QueryStringBuilder().appendParam("offset", offset).appendParam("limit", limit); + + if (fields.length > 0) { + builder.appendParam("fields", fields); + } - /** - * Constructs a BoxCollection for a collection with a given ID. - * - * @param api the API connection to be used by the collection. - * @param id the ID of the collection. - */ - public BoxCollection(BoxAPIConnection api, String id) { - super(api, id); + URL url = + GET_COLLECTION_ITEMS_URL.buildWithQuery(getAPI().getBaseURL(), builder.toString(), getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + + String totalCountString = responseJSON.get("total_count").toString(); + long fullSize = Double.valueOf(totalCountString).longValue(); + PartialCollection items = new PartialCollection<>(offset, limit, fullSize); + JsonArray entries = responseJSON.get("entries").asArray(); + for (JsonValue entry : entries) { + BoxItem.Info entryInfo = + (BoxItem.Info) BoxResource.parseInfo(this.getAPI(), entry.asObject()); + if (entryInfo != null) { + items.add(entryInfo); + } + } + return items; + } + } + + /** + * Returns an iterator over the items in this collection. + * + * @return an iterator over the items in this collection. + */ + @Override + public Iterator iterator() { + URL url = + GET_COLLECTION_ITEMS_URL.build(this.getAPI().getBaseURL(), BoxCollection.this.getID()); + return new BoxItemIterator(BoxCollection.this.getAPI(), url); + } + + /** Contains information about a BoxCollection. */ + public class Info extends BoxResource.Info { + private String collectionType; + private String name; + + /** Constructs an empty Info object. */ + public Info() { + super(); } /** - * Gets an iterable of all the collections for the given user. + * Constructs an Info object by parsing information from a JSON string. * - * @param api the API connection to be used when retrieving the collections. - * @return an iterable containing info about all the collections. + * @param json the JSON string to parse. */ - public static Iterable getAllCollections(final BoxAPIConnection api) { - return () -> { - URL url = GET_COLLECTIONS_URL_TEMPLATE.build(api.getBaseURL()); - return new BoxCollectionIterator(api, url); - }; + public Info(String json) { + super(json); } /** - * Returns an iterable containing the items in this collection. Iterating over the iterable returned by this method - * is equivalent to iterating over this BoxCollection directly. + * Constructs an Info object using an already parsed JSON object. * - * @return an iterable containing the items in this collection. + * @param jsonObject the parsed JSON object. */ - public Iterable getItems() { - return this; + Info(JsonObject jsonObject) { + super(jsonObject); } /** - * Returns an iterable containing the items in this collection and specifies which attributes to include in the - * response. + * Gets the type of the collection. * - * @param fields the fields to retrieve. - * @return an iterable containing the items in this collection. + * @return the type of the collection. */ - public Iterable getItems(final String... fields) { - return () -> { - String queryString = new QueryStringBuilder().appendParam("fields", fields).toString(); - URL url = GET_COLLECTION_ITEMS_URL.buildWithQuery(getAPI().getBaseURL(), queryString, getID()); - return new BoxItemIterator(getAPI(), url); - }; + public String getCollectionType() { + return this.collectionType; } /** - * Retrieves a specific range of items in this collection. + * Gets the name of the collection. * - * @param offset the index of the first item to retrieve. - * @param limit the maximum number of items to retrieve after the offset. - * @param fields the fields to retrieve. - * @return a partial collection containing the specified range of items. + * @return the name of the collection. */ - public PartialCollection getItemsRange(long offset, long limit, String... fields) { - QueryStringBuilder builder = new QueryStringBuilder() - .appendParam("offset", offset) - .appendParam("limit", limit); - - if (fields.length > 0) { - builder.appendParam("fields", fields); - } - - URL url = GET_COLLECTION_ITEMS_URL.buildWithQuery(getAPI().getBaseURL(), builder.toString(), getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - - String totalCountString = responseJSON.get("total_count").toString(); - long fullSize = Double.valueOf(totalCountString).longValue(); - PartialCollection items = new PartialCollection<>(offset, limit, fullSize); - JsonArray entries = responseJSON.get("entries").asArray(); - for (JsonValue entry : entries) { - BoxItem.Info entryInfo = (BoxItem.Info) BoxResource.parseInfo(this.getAPI(), entry.asObject()); - if (entryInfo != null) { - items.add(entryInfo); - } - } - return items; - } + public String getName() { + return this.name; } - /** - * Returns an iterator over the items in this collection. - * - * @return an iterator over the items in this collection. - */ @Override - public Iterator iterator() { - URL url = GET_COLLECTION_ITEMS_URL.build(this.getAPI().getBaseURL(), BoxCollection.this.getID()); - return new BoxItemIterator(BoxCollection.this.getAPI(), url); + public BoxCollection getResource() { + return BoxCollection.this; } - /** - * Contains information about a BoxCollection. - */ - public class Info extends BoxResource.Info { - private String collectionType; - private String name; - - /** - * Constructs an empty Info object. - */ - public Info() { - super(); - } - - /** - * Constructs an Info object by parsing information from a JSON string. - * - * @param json the JSON string to parse. - */ - public Info(String json) { - super(json); - } - - /** - * Constructs an Info object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - Info(JsonObject jsonObject) { - super(jsonObject); - } - - /** - * Gets the type of the collection. - * - * @return the type of the collection. - */ - public String getCollectionType() { - return this.collectionType; - } - - /** - * Gets the name of the collection. - * - * @return the name of the collection. - */ - public String getName() { - return this.name; - } - - @Override - public BoxCollection getResource() { - return BoxCollection.this; - } - - @Override - protected void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - - String memberName = member.getName(); - JsonValue value = member.getValue(); - if (memberName.equals("collection_type")) { - this.collectionType = value.asString(); - } else if (memberName.equals("name")) { - this.name = value.asString(); - } - } + @Override + protected void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + + String memberName = member.getName(); + JsonValue value = member.getValue(); + if (memberName.equals("collection_type")) { + this.collectionType = value.asString(); + } else if (memberName.equals("name")) { + this.name = value.asString(); + } } + } } diff --git a/src/main/java/com/box/sdk/BoxCollectionIterator.java b/src/main/java/com/box/sdk/BoxCollectionIterator.java index 33e7854c3..17c0b8741 100644 --- a/src/main/java/com/box/sdk/BoxCollectionIterator.java +++ b/src/main/java/com/box/sdk/BoxCollectionIterator.java @@ -7,30 +7,30 @@ import java.util.Iterator; class BoxCollectionIterator implements Iterator { - private static final long LIMIT = 100; - private final BoxAPIConnection api; - private final JsonIterator jsonIterator; - - BoxCollectionIterator(BoxAPIConnection api, URL url) { - this.api = api; - this.jsonIterator = new JsonIterator(api, url, offset(0, LIMIT)); - } - - @Override - public boolean hasNext() { - return this.jsonIterator.hasNext(); - } - - @Override - public BoxCollection.Info next() { - JsonObject nextJSONObject = this.jsonIterator.next(); - String id = nextJSONObject.get("id").asString(); - - BoxCollection collection = new BoxCollection(this.api, id); - return collection.new Info(nextJSONObject); - } - - public void remove() { - throw new UnsupportedOperationException(); - } + private static final long LIMIT = 100; + private final BoxAPIConnection api; + private final JsonIterator jsonIterator; + + BoxCollectionIterator(BoxAPIConnection api, URL url) { + this.api = api; + this.jsonIterator = new JsonIterator(api, url, offset(0, LIMIT)); + } + + @Override + public boolean hasNext() { + return this.jsonIterator.hasNext(); + } + + @Override + public BoxCollection.Info next() { + JsonObject nextJSONObject = this.jsonIterator.next(); + String id = nextJSONObject.get("id").asString(); + + BoxCollection collection = new BoxCollection(this.api, id); + return collection.new Info(nextJSONObject); + } + + public void remove() { + throw new UnsupportedOperationException(); + } } diff --git a/src/main/java/com/box/sdk/BoxComment.java b/src/main/java/com/box/sdk/BoxComment.java index 4edcff00e..404c9ea57 100644 --- a/src/main/java/com/box/sdk/BoxComment.java +++ b/src/main/java/com/box/sdk/BoxComment.java @@ -8,328 +8,324 @@ import java.util.regex.Pattern; /** - * Represents a comment on a file. Comments can be added directly to a file or they can be created as replies to other - * comments. + * Represents a comment on a file. Comments can be added directly to a file or they can be created + * as replies to other comments. * - *

Unless otherwise noted, the methods in this class can throw an unchecked {@link BoxAPIException} (unchecked - * meaning that the compiler won't force you to handle it) if an error occurs. If you wish to implement custom error - * handling for errors related to the Box REST API, you should capture this exception explicitly.

+ *

Unless otherwise noted, the methods in this class can throw an unchecked {@link + * BoxAPIException} (unchecked meaning that the compiler won't force you to handle it) if an error + * occurs. If you wish to implement custom error handling for errors related to the Box REST API, + * you should capture this exception explicitly. */ @BoxResourceType("comment") public class BoxComment extends BoxResource { - /** - * Add Comment URL Template. - */ - public static final URLTemplate ADD_COMMENT_URL_TEMPLATE = new URLTemplate("comments"); - /** - * Comment URL Template. - */ - public static final URLTemplate COMMENT_URL_TEMPLATE = new URLTemplate("comments/%s"); + /** Add Comment URL Template. */ + public static final URLTemplate ADD_COMMENT_URL_TEMPLATE = new URLTemplate("comments"); + /** Comment URL Template. */ + public static final URLTemplate COMMENT_URL_TEMPLATE = new URLTemplate("comments/%s"); + + private static final Pattern MENTION_REGEX = Pattern.compile("@\\[.+:.+\\]"); + + /** + * Constructs a BoxComment for a comment with a given ID. + * + * @param api the API connection to be used with the comment. + * @param id the ID of the comment. + */ + public BoxComment(BoxAPIConnection api, String id) { + super(api, id); + } + + /** + * Determines if a comment message contains an @mention. + * + * @param message the comment message. + * @return true if the message contains an @mention; otherwise false. + */ + static boolean messageContainsMention(String message) { + return MENTION_REGEX.matcher(message).find(); + } + + /** + * Gets information about this comment. + * + * @return info about this comment. + */ + public Info getInfo() { + URL url = COMMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject jsonResponse = Json.parse(response.getJSON()).asObject(); + + return new Info(jsonResponse); + } + } + + /** + * Changes the message of this comment. + * + * @param newMessage the new message for this comment. + * @return updated info about this comment. + */ + public Info changeMessage(String newMessage) { + Info newInfo = new Info(); + newInfo.setMessage(newMessage); + + URL url = COMMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); + request.setBody(newInfo.getPendingChanges()); + try (BoxJSONResponse response = request.send()) { + JsonObject jsonResponse = Json.parse(response.getJSON()).asObject(); + + return new Info(jsonResponse); + } + } + + /** + * Replies to this comment with another message. + * + * @param message the message for the reply. + * @return info about the newly created reply comment. + */ + public BoxComment.Info reply(String message) { + JsonObject itemJSON = new JsonObject(); + itemJSON.add("type", "comment"); + itemJSON.add("id", this.getID()); + + JsonObject requestJSON = new JsonObject(); + requestJSON.add("item", itemJSON); + if (BoxComment.messageContainsMention(message)) { + requestJSON.add("tagged_message", message); + } else { + requestJSON.add("message", message); + } - private static final Pattern MENTION_REGEX = Pattern.compile("@\\[.+:.+\\]"); + URL url = ADD_COMMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); + request.setBody(requestJSON.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + + BoxComment addedComment = new BoxComment(this.getAPI(), responseJSON.get("id").asString()); + return addedComment.new Info(responseJSON); + } + } + + /** Deletes this comment. */ + public void delete() { + URL url = COMMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); + request.send().close(); + } + + /** Contains information about a BoxComment. */ + public class Info extends BoxResource.Info { + private boolean isReplyComment; + private String message; + private String taggedMessage; + private BoxUser.Info createdBy; + private Date createdAt; + private BoxResource.Info item; + private BoxUser.Info modifiedBy; + private Date modifiedAt; + + /** Constructs an empty Info object. */ + public Info() { + super(); + } /** - * Constructs a BoxComment for a comment with a given ID. + * Constructs an Info object by parsing information from a JSON string. * - * @param api the API connection to be used with the comment. - * @param id the ID of the comment. + * @param json the JSON string to parse. */ - public BoxComment(BoxAPIConnection api, String id) { - super(api, id); + public Info(String json) { + super(json); } /** - * Determines if a comment message contains an @mention. + * Constructs an Info object using an already parsed JSON object. * - * @param message the comment message. - * @return true if the message contains an @mention; otherwise false. + * @param jsonObject the parsed JSON object. */ - static boolean messageContainsMention(String message) { - return MENTION_REGEX.matcher(message).find(); + Info(JsonObject jsonObject) { + super(jsonObject); } /** - * Gets information about this comment. + * Gets whether or not the comment is a reply to another comment. * - * @return info about this comment. + * @return true if this comment is a reply to another comment; otherwise false. */ - public Info getInfo() { - URL url = COMMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); - try (BoxJSONResponse response = request.send()) { - JsonObject jsonResponse = Json.parse(response.getJSON()).asObject(); - - return new Info(jsonResponse); - } + public boolean getIsReplyComment() { + return this.isReplyComment; } /** - * Changes the message of this comment. + * Gets the comment's message. * - * @param newMessage the new message for this comment. - * @return updated info about this comment. + * @return the comment's message. */ - public Info changeMessage(String newMessage) { - Info newInfo = new Info(); - newInfo.setMessage(newMessage); + public String getMessage() { + if (this.taggedMessage != null) { + return this.taggedMessage; + } - URL url = COMMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); - request.setBody(newInfo.getPendingChanges()); - try (BoxJSONResponse response = request.send()) { - JsonObject jsonResponse = Json.parse(response.getJSON()).asObject(); - - return new Info(jsonResponse); - } + return this.message; } /** - * Replies to this comment with another message. + * Sets the comment's message. The message can contain @mentions by using the + * string @[userid:username] anywhere within the message, where userid and username are the ID + * and username of the person being mentioned. * - * @param message the message for the reply. - * @return info about the newly created reply comment. + * @param message the comment's new message. */ - public BoxComment.Info reply(String message) { - JsonObject itemJSON = new JsonObject(); - itemJSON.add("type", "comment"); - itemJSON.add("id", this.getID()); - - JsonObject requestJSON = new JsonObject(); - requestJSON.add("item", itemJSON); - if (BoxComment.messageContainsMention(message)) { - requestJSON.add("tagged_message", message); - } else { - requestJSON.add("message", message); - } - - URL url = ADD_COMMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); - request.setBody(requestJSON.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - - BoxComment addedComment = new BoxComment(this.getAPI(), responseJSON.get("id").asString()); - return addedComment.new Info(responseJSON); - } + public void setMessage(String message) { + if (messageContainsMention(message)) { + this.taggedMessage = message; + this.addPendingChange("tagged_message", message); + this.removePendingChange("message"); + } else { + this.message = message; + this.addPendingChange("message", message); + this.removePendingChange("tagged_message"); + } } /** - * Deletes this comment. + * Gets info about the user who created the comment. + * + * @return info about the user who created the comment. */ - public void delete() { - URL url = COMMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); - request.send().close(); + public BoxUser.Info getCreatedBy() { + return this.createdBy; } /** - * Contains information about a BoxComment. + * Gets the time the comment was created. + * + * @return the time the comment was created. */ - public class Info extends BoxResource.Info { - private boolean isReplyComment; - private String message; - private String taggedMessage; - private BoxUser.Info createdBy; - private Date createdAt; - private BoxResource.Info item; - private BoxUser.Info modifiedBy; - private Date modifiedAt; - - /** - * Constructs an empty Info object. - */ - public Info() { - super(); - } - - /** - * Constructs an Info object by parsing information from a JSON string. - * - * @param json the JSON string to parse. - */ - public Info(String json) { - super(json); - } - - /** - * Constructs an Info object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - Info(JsonObject jsonObject) { - super(jsonObject); - } - - /** - * Gets whether or not the comment is a reply to another comment. - * - * @return true if this comment is a reply to another comment; otherwise false. - */ - public boolean getIsReplyComment() { - return this.isReplyComment; - } - - /** - * Gets the comment's message. - * - * @return the comment's message. - */ - public String getMessage() { - if (this.taggedMessage != null) { - return this.taggedMessage; - } - - return this.message; - } - - /** - * Sets the comment's message. The message can contain @mentions by using the string @[userid:username] anywhere - * within the message, where userid and username are the ID and username of the person being mentioned. - * - * @param message the comment's new message. - */ - public void setMessage(String message) { - if (messageContainsMention(message)) { - this.taggedMessage = message; - this.addPendingChange("tagged_message", message); - this.removePendingChange("message"); - } else { - this.message = message; - this.addPendingChange("message", message); - this.removePendingChange("tagged_message"); - } - } - - /** - * Gets info about the user who created the comment. - * - * @return info about the user who created the comment. - */ - public BoxUser.Info getCreatedBy() { - return this.createdBy; - } - - /** - * Gets the time the comment was created. - * - * @return the time the comment was created. - */ - public Date getCreatedAt() { - return this.createdAt; - } + public Date getCreatedAt() { + return this.createdAt; + } - /** - * Gets info about the item this comment is attached to. If the comment is a reply, then the item will be - * another BoxComment. Otherwise, the item will be a {@link BoxFile}. - * - * @return the item this comment is attached to. - */ - public BoxResource.Info getItem() { - return this.item; - } + /** + * Gets info about the item this comment is attached to. If the comment is a reply, then the + * item will be another BoxComment. Otherwise, the item will be a {@link BoxFile}. + * + * @return the item this comment is attached to. + */ + public BoxResource.Info getItem() { + return this.item; + } - /** - * Gets info about the user who last modified the comment. - * - * @return info about the user who last modified the comment. - */ - public BoxUser.Info getModifiedBy() { - return this.modifiedBy; - } + /** + * Gets info about the user who last modified the comment. + * + * @return info about the user who last modified the comment. + */ + public BoxUser.Info getModifiedBy() { + return this.modifiedBy; + } - /** - * Gets the time the comment was last modified. - * - * @return the time the comment was last modified. - */ - public Date getModifiedAt() { - return this.modifiedAt; - } + /** + * Gets the time the comment was last modified. + * + * @return the time the comment was last modified. + */ + public Date getModifiedAt() { + return this.modifiedAt; + } - @Override - public BoxComment getResource() { - return BoxComment.this; - } + @Override + public BoxComment getResource() { + return BoxComment.this; + } - @Override - protected void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - String memberName = member.getName(); - JsonValue value = member.getValue(); - - try { - - if (memberName.equals("is_reply_comment")) { - this.isReplyComment = value.asBoolean(); - - } else if (memberName.equals("message")) { - this.message = value.asString(); - - } else if (memberName.equals("tagged_message")) { - this.taggedMessage = value.asString(); - - } else if (memberName.equals("created_by")) { - JsonObject userJSON = value.asObject(); - if (this.createdBy == null) { - String userID = userJSON.get("id").asString(); - BoxUser user = new BoxUser(getAPI(), userID); - this.createdBy = user.new Info(userJSON); - } else { - this.createdBy.update(userJSON); - } - - } else if (memberName.equals("created_at")) { - this.createdAt = BoxDateFormat.parse(value.asString()); - - } else if (memberName.equals("item")) { - this.parseItem(value); - - } else if (memberName.equals("modified_by")) { - JsonObject userJSON = value.asObject(); - if (this.modifiedBy == null) { - String userID = userJSON.get("id").asString(); - BoxUser user = new BoxUser(getAPI(), userID); - this.modifiedBy = user.new Info(userJSON); - } else { - this.modifiedBy.update(userJSON); - } - } else if (memberName.equals("modified_at")) { - this.modifiedAt = BoxDateFormat.parse(value.asString()); - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); - } + @Override + protected void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + String memberName = member.getName(); + JsonValue value = member.getValue(); + + try { + + if (memberName.equals("is_reply_comment")) { + this.isReplyComment = value.asBoolean(); + + } else if (memberName.equals("message")) { + this.message = value.asString(); + + } else if (memberName.equals("tagged_message")) { + this.taggedMessage = value.asString(); + + } else if (memberName.equals("created_by")) { + JsonObject userJSON = value.asObject(); + if (this.createdBy == null) { + String userID = userJSON.get("id").asString(); + BoxUser user = new BoxUser(getAPI(), userID); + this.createdBy = user.new Info(userJSON); + } else { + this.createdBy.update(userJSON); + } + + } else if (memberName.equals("created_at")) { + this.createdAt = BoxDateFormat.parse(value.asString()); + + } else if (memberName.equals("item")) { + this.parseItem(value); + + } else if (memberName.equals("modified_by")) { + JsonObject userJSON = value.asObject(); + if (this.modifiedBy == null) { + String userID = userJSON.get("id").asString(); + BoxUser user = new BoxUser(getAPI(), userID); + this.modifiedBy = user.new Info(userJSON); + } else { + this.modifiedBy.update(userJSON); + } + } else if (memberName.equals("modified_at")) { + this.modifiedAt = BoxDateFormat.parse(value.asString()); } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); + } + } - private void parseItem(JsonValue value) { - JsonObject itemJSON = value.asObject(); - String itemType = itemJSON.get("type").asString(); - if (itemType.equals("file")) { - this.updateItemAsFile(itemJSON); - } else if (itemType.equals("comment")) { - this.updateItemAsComment(itemJSON); - } - } + private void parseItem(JsonValue value) { + JsonObject itemJSON = value.asObject(); + String itemType = itemJSON.get("type").asString(); + if (itemType.equals("file")) { + this.updateItemAsFile(itemJSON); + } else if (itemType.equals("comment")) { + this.updateItemAsComment(itemJSON); + } + } - private void updateItemAsFile(JsonObject itemJSON) { - String itemID = itemJSON.get("id").asString(); - if (this.item != null && this.item instanceof BoxFile.Info && this.item.getID().equals(itemID)) { - this.item.update(itemJSON); - } else { - BoxFile file = new BoxFile(getAPI(), itemID); - this.item = file.new Info(itemJSON); - } - } + private void updateItemAsFile(JsonObject itemJSON) { + String itemID = itemJSON.get("id").asString(); + if (this.item != null + && this.item instanceof BoxFile.Info + && this.item.getID().equals(itemID)) { + this.item.update(itemJSON); + } else { + BoxFile file = new BoxFile(getAPI(), itemID); + this.item = file.new Info(itemJSON); + } + } - private void updateItemAsComment(JsonObject itemJSON) { - String itemID = itemJSON.get("id").asString(); - if (this.item != null && this.item instanceof BoxComment.Info && this.item.getID().equals(itemID)) { - this.item.update(itemJSON); - } else { - BoxComment comment = new BoxComment(getAPI(), itemID); - this.item = comment.new Info(itemJSON); - } - } + private void updateItemAsComment(JsonObject itemJSON) { + String itemID = itemJSON.get("id").asString(); + if (this.item != null + && this.item instanceof BoxComment.Info + && this.item.getID().equals(itemID)) { + this.item.update(itemJSON); + } else { + BoxComment comment = new BoxComment(getAPI(), itemID); + this.item = comment.new Info(itemJSON); + } } + } } diff --git a/src/main/java/com/box/sdk/BoxConfig.java b/src/main/java/com/box/sdk/BoxConfig.java index e90e88f4e..28f369a57 100644 --- a/src/main/java/com/box/sdk/BoxConfig.java +++ b/src/main/java/com/box/sdk/BoxConfig.java @@ -5,184 +5,182 @@ import java.io.IOException; import java.io.Reader; -/** - * Contains Box configurations. - */ +/** Contains Box configurations. */ public class BoxConfig { - private String clientId; - private String clientSecret; - private String enterpriseId; - private JWTEncryptionPreferences jwtEncryptionPreferences; - - /** - * Creates a configuration with a clientId and clientSecret. - * - * @param clientId the client ID of the application - * @param clientSecret the client secret of the application - */ - public BoxConfig(String clientId, String clientSecret) { - this.clientId = clientId; - this.clientSecret = clientSecret; - } - - /** - * Creates a configuration with clientId, clientSecret and JWTEncryptionPreferences. - * - * @param clientId the client ID of the application - * @param clientSecret the client secret of the application - * @param enterpriseId the enterprise ID of the box account - * @param jwtEncryptionPreferences the JWTEncryptionPreferences of the application - */ - public BoxConfig(String clientId, String clientSecret, String enterpriseId, - JWTEncryptionPreferences jwtEncryptionPreferences) { - this.clientId = clientId; - this.clientSecret = clientSecret; - this.enterpriseId = enterpriseId; - this.jwtEncryptionPreferences = jwtEncryptionPreferences; - } - - /** - * Creates a configuration with clientId, clientSecret, publicKeyID, privateKey, privateKeyPassword. - * and an encryptionAlgorithm. - * - * @param clientId the client ID of the application - * @param clientSecret the client secret of the application - * @param enterpriseId the enterprise ID of the box account - * @param publicKeyID the unique ID of the uploaded public key - * @param privateKey the private key used to sign JWT requests - * @param privateKeyPassword the passphrase for the private key - * @param encryptionAlgorithm the encryption algorithm that has to be used for signing JWT requests - */ - public BoxConfig(String clientId, String clientSecret, String enterpriseId, String publicKeyID, - String privateKey, String privateKeyPassword, EncryptionAlgorithm encryptionAlgorithm) { - this.clientId = clientId; - this.clientSecret = clientSecret; - this.enterpriseId = enterpriseId; - this.jwtEncryptionPreferences = new JWTEncryptionPreferences(); - this.jwtEncryptionPreferences.setPublicKeyID(publicKeyID); - this.jwtEncryptionPreferences.setPrivateKey(privateKey); - this.jwtEncryptionPreferences.setPrivateKeyPassword(privateKeyPassword); - this.jwtEncryptionPreferences.setEncryptionAlgorithm(encryptionAlgorithm); - } - - /** - * Creates a configuration with RSA_SHA_256 as the encryption algorithm. - * - * @param clientId the client ID of the application - * @param clientSecret the client secret of the application - * @param enterpriseId the enterprise ID of the box account - * @param publicKeyID the unique ID of the uploaded public key - * @param privateKey the private key used to sign JWT requests - * @param privateKeyPassword the passphrase for the private key - */ - public BoxConfig(String clientId, String clientSecret, String enterpriseId, String publicKeyID, - String privateKey, String privateKeyPassword) { - this.clientId = clientId; - this.clientSecret = clientSecret; - this.enterpriseId = enterpriseId; - this.jwtEncryptionPreferences = new JWTEncryptionPreferences(); - this.jwtEncryptionPreferences.setPublicKeyID(publicKeyID); - this.jwtEncryptionPreferences.setPrivateKey(privateKey); - this.jwtEncryptionPreferences.setPrivateKeyPassword(privateKeyPassword); - this.jwtEncryptionPreferences.setEncryptionAlgorithm(EncryptionAlgorithm.RSA_SHA_256); - } - - /** - * Reads OAuth 2.0 with JWT app configurations from the reader. The file should be in JSON format. - * - * @param reader a reader object which points to a JSON formatted configuration file - * @return a new Instance of BoxConfig - * @throws IOException when unable to access the mapping file's content of the reader - */ - public static BoxConfig readFrom(Reader reader) throws IOException { - return createConfigFrom(Json.parse(reader).asObject()); - } - - /** - * Reads OAuth 2.0 with JWT app configurations from the Json string. - * - * @param jsonString a Json stringrepresenting formatted configuration file - * @return a new Instance of BoxConfig - */ - public static BoxConfig readFrom(String jsonString) { - return createConfigFrom(Json.parse(jsonString).asObject()); - } - - private static BoxConfig createConfigFrom(JsonObject config) { - JsonObject settings = (JsonObject) config.get("boxAppSettings"); - String clientId = settings.get("clientID").asString(); - String clientSecret = settings.get("clientSecret").asString(); - JsonObject appAuth = (JsonObject) settings.get("appAuth"); - String publicKeyId = appAuth.get("publicKeyID").asString(); - String privateKey = appAuth.get("privateKey").asString(); - String passphrase = appAuth.get("passphrase").asString(); - String enterpriseId = config.get("enterpriseID").asString(); - return new BoxConfig(clientId, clientSecret, enterpriseId, publicKeyId, privateKey, passphrase); - } - - /** - * @return client secret - */ - public String getClientSecret() { - return this.clientSecret; - } - - /** - * @param clientSecret client secret of the application - */ - public void setClientSecret(String clientSecret) { - this.clientSecret = clientSecret; - } - - /** - * @return enterprise ID - */ - public String getEnterpriseId() { - return this.enterpriseId; - } - - /** - * @param enterpriseId enterprise ID of the application - */ - public void setEnterpriseId(String enterpriseId) { - this.enterpriseId = enterpriseId; - } - - /** - * @return JWT Encryption Preferences - */ - public JWTEncryptionPreferences getJWTEncryptionPreferences() { - return this.jwtEncryptionPreferences; - } - - /** - * @param jwtEncryptionPreferences encryption preferences for JWT based authentication - */ - public void setJWTEncryptionPreferences(JWTEncryptionPreferences jwtEncryptionPreferences) { - this.jwtEncryptionPreferences = jwtEncryptionPreferences; - } - - /** - * @return client ID - */ - public String getClientId() { - return this.clientId; - } - - /** - * @param clientId client ID of the Application - */ - public void setClientId(String clientId) { - this.clientId = clientId; - } - - /** - * Sets a custom decryptor used for decrypting the private key. - * - * @param privateKeyDecryptor privateKeyDecryptor the decryptor used for decrypting the private key. - */ - public void setPrivateKeyDecryptor(IPrivateKeyDecryptor privateKeyDecryptor) { - this.jwtEncryptionPreferences.setPrivateKeyDecryptor(privateKeyDecryptor); - } + private String clientId; + private String clientSecret; + private String enterpriseId; + private JWTEncryptionPreferences jwtEncryptionPreferences; + + /** + * Creates a configuration with a clientId and clientSecret. + * + * @param clientId the client ID of the application + * @param clientSecret the client secret of the application + */ + public BoxConfig(String clientId, String clientSecret) { + this.clientId = clientId; + this.clientSecret = clientSecret; + } + + /** + * Creates a configuration with clientId, clientSecret and JWTEncryptionPreferences. + * + * @param clientId the client ID of the application + * @param clientSecret the client secret of the application + * @param enterpriseId the enterprise ID of the box account + * @param jwtEncryptionPreferences the JWTEncryptionPreferences of the application + */ + public BoxConfig( + String clientId, + String clientSecret, + String enterpriseId, + JWTEncryptionPreferences jwtEncryptionPreferences) { + this.clientId = clientId; + this.clientSecret = clientSecret; + this.enterpriseId = enterpriseId; + this.jwtEncryptionPreferences = jwtEncryptionPreferences; + } + + /** + * Creates a configuration with clientId, clientSecret, publicKeyID, privateKey, + * privateKeyPassword. and an encryptionAlgorithm. + * + * @param clientId the client ID of the application + * @param clientSecret the client secret of the application + * @param enterpriseId the enterprise ID of the box account + * @param publicKeyID the unique ID of the uploaded public key + * @param privateKey the private key used to sign JWT requests + * @param privateKeyPassword the passphrase for the private key + * @param encryptionAlgorithm the encryption algorithm that has to be used for signing JWT + * requests + */ + public BoxConfig( + String clientId, + String clientSecret, + String enterpriseId, + String publicKeyID, + String privateKey, + String privateKeyPassword, + EncryptionAlgorithm encryptionAlgorithm) { + this.clientId = clientId; + this.clientSecret = clientSecret; + this.enterpriseId = enterpriseId; + this.jwtEncryptionPreferences = new JWTEncryptionPreferences(); + this.jwtEncryptionPreferences.setPublicKeyID(publicKeyID); + this.jwtEncryptionPreferences.setPrivateKey(privateKey); + this.jwtEncryptionPreferences.setPrivateKeyPassword(privateKeyPassword); + this.jwtEncryptionPreferences.setEncryptionAlgorithm(encryptionAlgorithm); + } + + /** + * Creates a configuration with RSA_SHA_256 as the encryption algorithm. + * + * @param clientId the client ID of the application + * @param clientSecret the client secret of the application + * @param enterpriseId the enterprise ID of the box account + * @param publicKeyID the unique ID of the uploaded public key + * @param privateKey the private key used to sign JWT requests + * @param privateKeyPassword the passphrase for the private key + */ + public BoxConfig( + String clientId, + String clientSecret, + String enterpriseId, + String publicKeyID, + String privateKey, + String privateKeyPassword) { + this.clientId = clientId; + this.clientSecret = clientSecret; + this.enterpriseId = enterpriseId; + this.jwtEncryptionPreferences = new JWTEncryptionPreferences(); + this.jwtEncryptionPreferences.setPublicKeyID(publicKeyID); + this.jwtEncryptionPreferences.setPrivateKey(privateKey); + this.jwtEncryptionPreferences.setPrivateKeyPassword(privateKeyPassword); + this.jwtEncryptionPreferences.setEncryptionAlgorithm(EncryptionAlgorithm.RSA_SHA_256); + } + + /** + * Reads OAuth 2.0 with JWT app configurations from the reader. The file should be in JSON format. + * + * @param reader a reader object which points to a JSON formatted configuration file + * @return a new Instance of BoxConfig + * @throws IOException when unable to access the mapping file's content of the reader + */ + public static BoxConfig readFrom(Reader reader) throws IOException { + return createConfigFrom(Json.parse(reader).asObject()); + } + + /** + * Reads OAuth 2.0 with JWT app configurations from the Json string. + * + * @param jsonString a Json stringrepresenting formatted configuration file + * @return a new Instance of BoxConfig + */ + public static BoxConfig readFrom(String jsonString) { + return createConfigFrom(Json.parse(jsonString).asObject()); + } + + private static BoxConfig createConfigFrom(JsonObject config) { + JsonObject settings = (JsonObject) config.get("boxAppSettings"); + String clientId = settings.get("clientID").asString(); + String clientSecret = settings.get("clientSecret").asString(); + JsonObject appAuth = (JsonObject) settings.get("appAuth"); + String publicKeyId = appAuth.get("publicKeyID").asString(); + String privateKey = appAuth.get("privateKey").asString(); + String passphrase = appAuth.get("passphrase").asString(); + String enterpriseId = config.get("enterpriseID").asString(); + return new BoxConfig(clientId, clientSecret, enterpriseId, publicKeyId, privateKey, passphrase); + } + + /** @return client secret */ + public String getClientSecret() { + return this.clientSecret; + } + + /** @param clientSecret client secret of the application */ + public void setClientSecret(String clientSecret) { + this.clientSecret = clientSecret; + } + + /** @return enterprise ID */ + public String getEnterpriseId() { + return this.enterpriseId; + } + + /** @param enterpriseId enterprise ID of the application */ + public void setEnterpriseId(String enterpriseId) { + this.enterpriseId = enterpriseId; + } + + /** @return JWT Encryption Preferences */ + public JWTEncryptionPreferences getJWTEncryptionPreferences() { + return this.jwtEncryptionPreferences; + } + + /** @param jwtEncryptionPreferences encryption preferences for JWT based authentication */ + public void setJWTEncryptionPreferences(JWTEncryptionPreferences jwtEncryptionPreferences) { + this.jwtEncryptionPreferences = jwtEncryptionPreferences; + } + + /** @return client ID */ + public String getClientId() { + return this.clientId; + } + + /** @param clientId client ID of the Application */ + public void setClientId(String clientId) { + this.clientId = clientId; + } + + /** + * Sets a custom decryptor used for decrypting the private key. + * + * @param privateKeyDecryptor privateKeyDecryptor the decryptor used for decrypting the private + * key. + */ + public void setPrivateKeyDecryptor(IPrivateKeyDecryptor privateKeyDecryptor) { + this.jwtEncryptionPreferences.setPrivateKeyDecryptor(privateKeyDecryptor); + } } diff --git a/src/main/java/com/box/sdk/BoxDateFormat.java b/src/main/java/com/box/sdk/BoxDateFormat.java index 692af24d9..792649518 100644 --- a/src/main/java/com/box/sdk/BoxDateFormat.java +++ b/src/main/java/com/box/sdk/BoxDateFormat.java @@ -7,84 +7,87 @@ import java.util.Date; import java.util.TimeZone; -/** - * Contains methods for parsing and formatting dates for use with the Box API. - */ +/** Contains methods for parsing and formatting dates for use with the Box API. */ public final class BoxDateFormat { - private static final ThreadLocal THREAD_LOCAL_DATE_FORMAT_SECONDS = ThreadLocal.withInitial(() -> { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); - sdf.setTimeZone(TimeZone.getTimeZone("UTC")); - return sdf; - }); + private static final ThreadLocal THREAD_LOCAL_DATE_FORMAT_SECONDS = + ThreadLocal.withInitial( + () -> { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); + sdf.setTimeZone(TimeZone.getTimeZone("UTC")); + return sdf; + }); - private static final ThreadLocal THREAD_LOCAL_DATE_FORMAT_MILLISECONDS = ThreadLocal.withInitial(() -> { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX"); - sdf.setTimeZone(TimeZone.getTimeZone("UTC")); - return sdf; - }); + private static final ThreadLocal THREAD_LOCAL_DATE_FORMAT_MILLISECONDS = + ThreadLocal.withInitial( + () -> { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX"); + sdf.setTimeZone(TimeZone.getTimeZone("UTC")); + return sdf; + }); - private static final ThreadLocal THREAD_LOCAL_DATE_ONLY = ThreadLocal.withInitial(() -> { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); - sdf.setTimeZone(TimeZone.getTimeZone("UTC")); - return sdf; - }); + private static final ThreadLocal THREAD_LOCAL_DATE_ONLY = + ThreadLocal.withInitial( + () -> { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + sdf.setTimeZone(TimeZone.getTimeZone("UTC")); + return sdf; + }); - private BoxDateFormat() { - } + private BoxDateFormat() {} - /** - * Parses a date string returned by the Box API into a {@link Date} object. - * - * @param dateString a string containing the date. - * @return the parsed date. - * @throws ParseException if the string cannot be parsed into a valid date. - */ - public static Date parse(String dateString) throws ParseException { - try { - return THREAD_LOCAL_DATE_FORMAT_SECONDS.get().parse(dateString); - } catch (ParseException pe) { - return THREAD_LOCAL_DATE_FORMAT_MILLISECONDS.get().parse(dateString); - } + /** + * Parses a date string returned by the Box API into a {@link Date} object. + * + * @param dateString a string containing the date. + * @return the parsed date. + * @throws ParseException if the string cannot be parsed into a valid date. + */ + public static Date parse(String dateString) throws ParseException { + try { + return THREAD_LOCAL_DATE_FORMAT_SECONDS.get().parse(dateString); + } catch (ParseException pe) { + return THREAD_LOCAL_DATE_FORMAT_MILLISECONDS.get().parse(dateString); } + } - /** - * Parses a date in format of yyyy-MM-dd. - * - * @param date date to parse. - * @return parsed date. - * @throws ParseException if the string cannot be parsed into a valid date. - */ - public static Date parseDateOnly(String date) throws ParseException { - return THREAD_LOCAL_DATE_ONLY.get().parse(date); - } + /** + * Parses a date in format of yyyy-MM-dd. + * + * @param date date to parse. + * @return parsed date. + * @throws ParseException if the string cannot be parsed into a valid date. + */ + public static Date parseDateOnly(String date) throws ParseException { + return THREAD_LOCAL_DATE_ONLY.get().parse(date); + } - /** - * Formats a date as a string that can be sent to the Box API. - * - * @param date the date to format. - * @return a string containing the formatted date. - */ - public static String format(Date date) { - return THREAD_LOCAL_DATE_FORMAT_SECONDS.get().format(date); - } + /** + * Formats a date as a string that can be sent to the Box API. + * + * @param date the date to format. + * @return a string containing the formatted date. + */ + public static String format(Date date) { + return THREAD_LOCAL_DATE_FORMAT_SECONDS.get().format(date); + } - /** - * Formats an Instant as a string that can be sent to the Box API. - * - * @param instant the instant to format. - * @return a string containing the formatted instant. - */ - public static String format(Instant instant) { - return THREAD_LOCAL_DATE_FORMAT_SECONDS.get().format(Date.from(instant)); - } + /** + * Formats an Instant as a string that can be sent to the Box API. + * + * @param instant the instant to format. + * @return a string containing the formatted instant. + */ + public static String format(Instant instant) { + return THREAD_LOCAL_DATE_FORMAT_SECONDS.get().format(Date.from(instant)); + } - /** - * Formats a date as a string yyyy-MM-dd that can be sent to the Box API. - * - * @param date the date to format. - * @return a yyyy-MM-dd string containing the formatted date. - */ - public static String formatAsDateOnly(Date date) { - return THREAD_LOCAL_DATE_ONLY.get().format(date); - } + /** + * Formats a date as a string yyyy-MM-dd that can be sent to the Box API. + * + * @param date the date to format. + * @return a yyyy-MM-dd string containing the formatted date. + */ + public static String formatAsDateOnly(Date date) { + return THREAD_LOCAL_DATE_ONLY.get().format(date); + } } diff --git a/src/main/java/com/box/sdk/BoxDeserializationException.java b/src/main/java/com/box/sdk/BoxDeserializationException.java index 5a6dd0633..9ae3c822c 100644 --- a/src/main/java/com/box/sdk/BoxDeserializationException.java +++ b/src/main/java/com/box/sdk/BoxDeserializationException.java @@ -1,53 +1,56 @@ package com.box.sdk; -/** - * A class representing exceptions caused from deserializing errors. - */ +/** A class representing exceptions caused from deserializing errors. */ public class BoxDeserializationException extends RuntimeException { - static final long serialVersionUID = 4266400750306343595L; - private final String fieldName; - private final String fieldValue; + static final long serialVersionUID = 4266400750306343595L; + private final String fieldName; + private final String fieldValue; - /** - * Initializes the BoxDeserializationException class. - * - * @param member the key of the json member the deserialization occurred on. - * @param value the value of the json member the deserialization occurred on. - * @param e the throwable cause for the exception. - */ - public BoxDeserializationException(String member, String value, Exception e) { - super(constructExceptionMessage(member, value), e); - this.fieldName = member; - this.fieldValue = value; - } + /** + * Initializes the BoxDeserializationException class. + * + * @param member the key of the json member the deserialization occurred on. + * @param value the value of the json member the deserialization occurred on. + * @param e the throwable cause for the exception. + */ + public BoxDeserializationException(String member, String value, Exception e) { + super(constructExceptionMessage(member, value), e); + this.fieldName = member; + this.fieldValue = value; + } - /** - * Private helper function to construct the exception message for the deserialization error. - * - * @param member the field member to include in the exception message. - * @param value the field value to include in the exception message. - * @return the constructed exception message. - */ - private static String constructExceptionMessage(String member, String value) { - return "Deserialization failed on: [ " + "\"field name\": " + member + " | " - + "\"field value\": " + value + " ]"; - } + /** + * Private helper function to construct the exception message for the deserialization error. + * + * @param member the field member to include in the exception message. + * @param value the field value to include in the exception message. + * @return the constructed exception message. + */ + private static String constructExceptionMessage(String member, String value) { + return "Deserialization failed on: [ " + + "\"field name\": " + + member + + " | " + + "\"field value\": " + + value + + " ]"; + } - /** - * Retrieves the field name of the deserialization error. - * - * @return field name the error occurred on. - */ - public String getFieldName() { - return this.fieldName; - } + /** + * Retrieves the field name of the deserialization error. + * + * @return field name the error occurred on. + */ + public String getFieldName() { + return this.fieldName; + } - /** - * Retrieves the field value of the deserialization error. - * - * @return field value the error occurred on. - */ - public String getFieldValue() { - return this.fieldValue; - } + /** + * Retrieves the field value of the deserialization error. + * + * @return field value the error occurred on. + */ + public String getFieldValue() { + return this.fieldValue; + } } diff --git a/src/main/java/com/box/sdk/BoxDeveloperEditionAPIConnection.java b/src/main/java/com/box/sdk/BoxDeveloperEditionAPIConnection.java index 630e9bb92..6a7b138a0 100644 --- a/src/main/java/com/box/sdk/BoxDeveloperEditionAPIConnection.java +++ b/src/main/java/com/box/sdk/BoxDeveloperEditionAPIConnection.java @@ -17,505 +17,527 @@ /** * Represents an authenticated Box Developer Edition connection to the Box API. * - *

This class handles everything for Box Developer Edition that isn't already handled by BoxAPIConnection.

+ *

This class handles everything for Box Developer Edition that isn't already handled by + * BoxAPIConnection. */ public class BoxDeveloperEditionAPIConnection extends BoxAPIConnection { - private static final String JWT_AUDIENCE = "https://api.box.com/oauth2/token"; - private static final String JWT_GRANT_TYPE = - "grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&client_id=%s&client_secret=%s&assertion=%s"; - private static final int DEFAULT_MAX_ENTRIES = 100; - - private final String entityID; - private final DeveloperEditionEntityType entityType; - private final EncryptionAlgorithm encryptionAlgorithm; - private final String publicKeyID; - private final String privateKey; - private final String privateKeyPassword; - private BackoffCounter backoffCounter; - private final IAccessTokenCache accessTokenCache; - private final IPrivateKeyDecryptor privateKeyDecryptor; - - /** - * Constructs a new BoxDeveloperEditionAPIConnection leveraging an access token cache. - * - * @param entityId enterprise ID or a user ID. - * @param entityType the type of entityId. - * @param clientID the client ID to use when exchanging the JWT assertion for an access token. - * @param clientSecret the client secret to use when exchanging the JWT assertion for an access token. - * @param encryptionPref the encryption preferences for signing the JWT. - * @param accessTokenCache the cache for storing access token information (to minimize fetching new tokens) - */ - public BoxDeveloperEditionAPIConnection(String entityId, DeveloperEditionEntityType entityType, - String clientID, String clientSecret, - JWTEncryptionPreferences encryptionPref, - IAccessTokenCache accessTokenCache) { - - super(clientID, clientSecret); - - this.entityID = entityId; - this.entityType = entityType; - this.publicKeyID = encryptionPref.getPublicKeyID(); - this.privateKey = encryptionPref.getPrivateKey(); - this.privateKeyPassword = encryptionPref.getPrivateKeyPassword(); - this.encryptionAlgorithm = encryptionPref.getEncryptionAlgorithm(); - this.privateKeyDecryptor = encryptionPref.getPrivateKeyDecryptor(); - this.accessTokenCache = accessTokenCache; - this.backoffCounter = new BackoffCounter(new Time()); - } - - /** - * Constructs a new BoxDeveloperEditionAPIConnection. - * Uses {@link InMemoryLRUAccessTokenCache} with a size of 100 to prevent unneeded - * requests to Box for access tokens. - * - * @param entityId enterprise ID or a user ID. - * @param entityType the type of entityId. - * @param clientID the client ID to use when exchanging the JWT assertion for an access token. - * @param clientSecret the client secret to use when exchanging the JWT assertion for an access token. - * @param encryptionPref the encryption preferences for signing the JWT. - */ - public BoxDeveloperEditionAPIConnection( - String entityId, - DeveloperEditionEntityType entityType, - String clientID, - String clientSecret, - JWTEncryptionPreferences encryptionPref - ) { - - this( - entityId, - entityType, - clientID, + private static final String JWT_AUDIENCE = "https://api.box.com/oauth2/token"; + private static final String JWT_GRANT_TYPE = + "grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&client_id=%s&client_secret=%s&assertion=%s"; + private static final int DEFAULT_MAX_ENTRIES = 100; + + private final String entityID; + private final DeveloperEditionEntityType entityType; + private final EncryptionAlgorithm encryptionAlgorithm; + private final String publicKeyID; + private final String privateKey; + private final String privateKeyPassword; + private BackoffCounter backoffCounter; + private final IAccessTokenCache accessTokenCache; + private final IPrivateKeyDecryptor privateKeyDecryptor; + + /** + * Constructs a new BoxDeveloperEditionAPIConnection leveraging an access token cache. + * + * @param entityId enterprise ID or a user ID. + * @param entityType the type of entityId. + * @param clientID the client ID to use when exchanging the JWT assertion for an access token. + * @param clientSecret the client secret to use when exchanging the JWT assertion for an access + * token. + * @param encryptionPref the encryption preferences for signing the JWT. + * @param accessTokenCache the cache for storing access token information (to minimize fetching + * new tokens) + */ + public BoxDeveloperEditionAPIConnection( + String entityId, + DeveloperEditionEntityType entityType, + String clientID, + String clientSecret, + JWTEncryptionPreferences encryptionPref, + IAccessTokenCache accessTokenCache) { + + super(clientID, clientSecret); + + this.entityID = entityId; + this.entityType = entityType; + this.publicKeyID = encryptionPref.getPublicKeyID(); + this.privateKey = encryptionPref.getPrivateKey(); + this.privateKeyPassword = encryptionPref.getPrivateKeyPassword(); + this.encryptionAlgorithm = encryptionPref.getEncryptionAlgorithm(); + this.privateKeyDecryptor = encryptionPref.getPrivateKeyDecryptor(); + this.accessTokenCache = accessTokenCache; + this.backoffCounter = new BackoffCounter(new Time()); + } + + /** + * Constructs a new BoxDeveloperEditionAPIConnection. Uses {@link InMemoryLRUAccessTokenCache} + * with a size of 100 to prevent unneeded requests to Box for access tokens. + * + * @param entityId enterprise ID or a user ID. + * @param entityType the type of entityId. + * @param clientID the client ID to use when exchanging the JWT assertion for an access token. + * @param clientSecret the client secret to use when exchanging the JWT assertion for an access + * token. + * @param encryptionPref the encryption preferences for signing the JWT. + */ + public BoxDeveloperEditionAPIConnection( + String entityId, + DeveloperEditionEntityType entityType, + String clientID, + String clientSecret, + JWTEncryptionPreferences encryptionPref) { + + this( + entityId, + entityType, + clientID, + clientSecret, + encryptionPref, + new InMemoryLRUAccessTokenCache(DEFAULT_MAX_ENTRIES)); + } + + /** + * Constructs a new BoxDeveloperEditionAPIConnection. + * + * @param entityId enterprise ID or a user ID. + * @param entityType the type of entityId. + * @param boxConfig box configuration settings object + * @param accessTokenCache the cache for storing access token information (to minimize fetching + * new tokens) + */ + public BoxDeveloperEditionAPIConnection( + String entityId, + DeveloperEditionEntityType entityType, + BoxConfig boxConfig, + IAccessTokenCache accessTokenCache) { + + this( + entityId, + entityType, + boxConfig.getClientId(), + boxConfig.getClientSecret(), + boxConfig.getJWTEncryptionPreferences(), + accessTokenCache); + } + + /** + * Creates a new Box Developer Edition connection with enterprise token leveraging an access token + * cache. + * + * @param enterpriseId the enterprise ID to use for requesting access token. + * @param clientId the client ID to use when exchanging the JWT assertion for an access token. + * @param clientSecret the client secret to use when exchanging the JWT assertion for an access + * token. + * @param encryptionPref the encryption preferences for signing the JWT. + * @param accessTokenCache the cache for storing access token information (to minimize fetching + * new tokens) + * @return a new instance of BoxAPIConnection. + */ + public static BoxDeveloperEditionAPIConnection getAppEnterpriseConnection( + String enterpriseId, + String clientId, + String clientSecret, + JWTEncryptionPreferences encryptionPref, + IAccessTokenCache accessTokenCache) { + + BoxDeveloperEditionAPIConnection connection = + new BoxDeveloperEditionAPIConnection( + enterpriseId, + DeveloperEditionEntityType.ENTERPRISE, + clientId, clientSecret, encryptionPref, - new InMemoryLRUAccessTokenCache(DEFAULT_MAX_ENTRIES) - ); - } - - /** - * Constructs a new BoxDeveloperEditionAPIConnection. - * - * @param entityId enterprise ID or a user ID. - * @param entityType the type of entityId. - * @param boxConfig box configuration settings object - * @param accessTokenCache the cache for storing access token information (to minimize fetching new tokens) - */ - public BoxDeveloperEditionAPIConnection(String entityId, DeveloperEditionEntityType entityType, - BoxConfig boxConfig, IAccessTokenCache accessTokenCache) { - - this(entityId, entityType, boxConfig.getClientId(), boxConfig.getClientSecret(), - boxConfig.getJWTEncryptionPreferences(), accessTokenCache); - } - - /** - * Creates a new Box Developer Edition connection with enterprise token leveraging an access token cache. - * - * @param enterpriseId the enterprise ID to use for requesting access token. - * @param clientId the client ID to use when exchanging the JWT assertion for an access token. - * @param clientSecret the client secret to use when exchanging the JWT assertion for an access token. - * @param encryptionPref the encryption preferences for signing the JWT. - * @param accessTokenCache the cache for storing access token information (to minimize fetching new tokens) - * @return a new instance of BoxAPIConnection. - */ - public static BoxDeveloperEditionAPIConnection getAppEnterpriseConnection( - String enterpriseId, - String clientId, - String clientSecret, - JWTEncryptionPreferences encryptionPref, - IAccessTokenCache accessTokenCache - ) { - - BoxDeveloperEditionAPIConnection connection = new BoxDeveloperEditionAPIConnection(enterpriseId, - DeveloperEditionEntityType.ENTERPRISE, clientId, clientSecret, encryptionPref, accessTokenCache); - - connection.tryRestoreUsingAccessTokenCache(); - - return connection; - } - - /** - * Creates a new Box Developer Edition connection with enterprise token. - * Uses {@link InMemoryLRUAccessTokenCache} with a size of 100 to prevent unneeded - * requests to Box for access tokens. - * - * @param enterpriseId the enterprise ID to use for requesting access token. - * @param clientId the client ID to use when exchanging the JWT assertion for an access token. - * @param clientSecret the client secret to use when exchanging the JWT assertion for an access token. - * @param encryptionPref the encryption preferences for signing the JWT. - * @return a new instance of BoxAPIConnection. - */ - public static BoxDeveloperEditionAPIConnection getAppEnterpriseConnection( - String enterpriseId, - String clientId, - String clientSecret, - JWTEncryptionPreferences encryptionPref - ) { - - BoxDeveloperEditionAPIConnection connection = new BoxDeveloperEditionAPIConnection( + accessTokenCache); + + connection.tryRestoreUsingAccessTokenCache(); + + return connection; + } + + /** + * Creates a new Box Developer Edition connection with enterprise token. Uses {@link + * InMemoryLRUAccessTokenCache} with a size of 100 to prevent unneeded requests to Box for access + * tokens. + * + * @param enterpriseId the enterprise ID to use for requesting access token. + * @param clientId the client ID to use when exchanging the JWT assertion for an access token. + * @param clientSecret the client secret to use when exchanging the JWT assertion for an access + * token. + * @param encryptionPref the encryption preferences for signing the JWT. + * @return a new instance of BoxAPIConnection. + */ + public static BoxDeveloperEditionAPIConnection getAppEnterpriseConnection( + String enterpriseId, + String clientId, + String clientSecret, + JWTEncryptionPreferences encryptionPref) { + + BoxDeveloperEditionAPIConnection connection = + new BoxDeveloperEditionAPIConnection( enterpriseId, DeveloperEditionEntityType.ENTERPRISE, clientId, clientSecret, - encryptionPref - ); - - connection.authenticate(); - - return connection; - } - - /** - * Creates a new Box Developer Edition connection with enterprise token leveraging BoxConfig and access token cache. - * - * @param boxConfig box configuration settings object - * @param accessTokenCache the cache for storing access token information (to minimize fetching new tokens) - * @return a new instance of BoxAPIConnection. - */ - public static BoxDeveloperEditionAPIConnection getAppEnterpriseConnection(BoxConfig boxConfig, - IAccessTokenCache accessTokenCache) { - - return getAppEnterpriseConnection( - boxConfig.getEnterpriseId(), - boxConfig.getClientId(), - boxConfig.getClientSecret(), - boxConfig.getJWTEncryptionPreferences(), - accessTokenCache - ); - } - - /** - * Creates a new Box Developer Edition connection with enterprise token leveraging BoxConfig. - * Uses {@link InMemoryLRUAccessTokenCache} with a size of 100 to prevent unneeded - * requests to Box for access tokens. - * - * @param boxConfig box configuration settings object - * @return a new instance of BoxAPIConnection. - */ - public static BoxDeveloperEditionAPIConnection getAppEnterpriseConnection(BoxConfig boxConfig) { - - return getAppEnterpriseConnection( - boxConfig.getEnterpriseId(), - boxConfig.getClientId(), - boxConfig.getClientSecret(), - boxConfig.getJWTEncryptionPreferences() - ); - } - - /** - * Creates a new Box Developer Edition connection with App User or Managed User token. - * - * @param userId the user ID to use for an App User. - * @param clientId the client ID to use when exchanging the JWT assertion for an access token. - * @param clientSecret the client secret to use when exchanging the JWT assertion for an access token. - * @param encryptionPref the encryption preferences for signing the JWT. - * @param accessTokenCache the cache for storing access token information (to minimize fetching new tokens) - * @return a new instance of BoxAPIConnection. - */ - public static BoxDeveloperEditionAPIConnection getUserConnection( - String userId, - String clientId, - String clientSecret, - JWTEncryptionPreferences encryptionPref, - IAccessTokenCache accessTokenCache - ) { - BoxDeveloperEditionAPIConnection connection = new BoxDeveloperEditionAPIConnection( + encryptionPref); + + connection.authenticate(); + + return connection; + } + + /** + * Creates a new Box Developer Edition connection with enterprise token leveraging BoxConfig and + * access token cache. + * + * @param boxConfig box configuration settings object + * @param accessTokenCache the cache for storing access token information (to minimize fetching + * new tokens) + * @return a new instance of BoxAPIConnection. + */ + public static BoxDeveloperEditionAPIConnection getAppEnterpriseConnection( + BoxConfig boxConfig, IAccessTokenCache accessTokenCache) { + + return getAppEnterpriseConnection( + boxConfig.getEnterpriseId(), + boxConfig.getClientId(), + boxConfig.getClientSecret(), + boxConfig.getJWTEncryptionPreferences(), + accessTokenCache); + } + + /** + * Creates a new Box Developer Edition connection with enterprise token leveraging BoxConfig. Uses + * {@link InMemoryLRUAccessTokenCache} with a size of 100 to prevent unneeded requests to Box for + * access tokens. + * + * @param boxConfig box configuration settings object + * @return a new instance of BoxAPIConnection. + */ + public static BoxDeveloperEditionAPIConnection getAppEnterpriseConnection(BoxConfig boxConfig) { + + return getAppEnterpriseConnection( + boxConfig.getEnterpriseId(), + boxConfig.getClientId(), + boxConfig.getClientSecret(), + boxConfig.getJWTEncryptionPreferences()); + } + + /** + * Creates a new Box Developer Edition connection with App User or Managed User token. + * + * @param userId the user ID to use for an App User. + * @param clientId the client ID to use when exchanging the JWT assertion for an access token. + * @param clientSecret the client secret to use when exchanging the JWT assertion for an access + * token. + * @param encryptionPref the encryption preferences for signing the JWT. + * @param accessTokenCache the cache for storing access token information (to minimize fetching + * new tokens) + * @return a new instance of BoxAPIConnection. + */ + public static BoxDeveloperEditionAPIConnection getUserConnection( + String userId, + String clientId, + String clientSecret, + JWTEncryptionPreferences encryptionPref, + IAccessTokenCache accessTokenCache) { + BoxDeveloperEditionAPIConnection connection = + new BoxDeveloperEditionAPIConnection( userId, DeveloperEditionEntityType.USER, clientId, clientSecret, encryptionPref, - accessTokenCache - ); - - connection.tryRestoreUsingAccessTokenCache(); - - return connection; + accessTokenCache); + + connection.tryRestoreUsingAccessTokenCache(); + + return connection; + } + + /** + * Creates a new Box Developer Edition connection with App User or Managed User token leveraging + * BoxConfig and access token cache. + * + * @param userId the user ID to use for an App User. + * @param boxConfig box configuration settings object + * @param accessTokenCache the cache for storing access token information (to minimize fetching + * new tokens) + * @return a new instance of BoxAPIConnection. + */ + public static BoxDeveloperEditionAPIConnection getUserConnection( + String userId, BoxConfig boxConfig, IAccessTokenCache accessTokenCache) { + return getUserConnection( + userId, + boxConfig.getClientId(), + boxConfig.getClientSecret(), + boxConfig.getJWTEncryptionPreferences(), + accessTokenCache); + } + + /** + * Creates a new Box Developer Edition connection with App User or Managed User token. Uses {@link + * InMemoryLRUAccessTokenCache} with a size of 100 to prevent unneeded requests to Box for access + * tokens. + * + * @param userId the user ID to use for an App User. + * @param boxConfig box configuration settings object + * @return a new instance of BoxAPIConnection. + */ + public static BoxDeveloperEditionAPIConnection getUserConnection( + String userId, BoxConfig boxConfig) { + return getUserConnection( + userId, + boxConfig.getClientId(), + boxConfig.getClientSecret(), + boxConfig.getJWTEncryptionPreferences(), + new InMemoryLRUAccessTokenCache(DEFAULT_MAX_ENTRIES)); + } + + /** + * Disabling the non-Box Developer Edition authenticate method. + * + * @param authCode an auth code obtained from the first half of the OAuth process. + */ + public void authenticate(String authCode) { + throw new BoxAPIException( + "BoxDeveloperEditionAPIConnection does not allow authenticating with an auth code."); + } + + /** Authenticates the API connection for Box Developer Edition. */ + public void authenticate() { + URL url; + try { + url = new URL(this.getTokenURL()); + } catch (MalformedURLException e) { + assert false : "An invalid token URL indicates a bug in the SDK."; + throw new RuntimeException("An invalid token URL indicates a bug in the SDK.", e); } - /** - * Creates a new Box Developer Edition connection with App User or Managed User token leveraging BoxConfig - * and access token cache. - * - * @param userId the user ID to use for an App User. - * @param boxConfig box configuration settings object - * @param accessTokenCache the cache for storing access token information (to minimize fetching new tokens) - * @return a new instance of BoxAPIConnection. - */ - public static BoxDeveloperEditionAPIConnection getUserConnection( - String userId, - BoxConfig boxConfig, - IAccessTokenCache accessTokenCache - ) { - return getUserConnection( - userId, - boxConfig.getClientId(), - boxConfig.getClientSecret(), - boxConfig.getJWTEncryptionPreferences(), - accessTokenCache - ); - } - - /** - * Creates a new Box Developer Edition connection with App User or Managed User token. - * Uses {@link InMemoryLRUAccessTokenCache} with a size of 100 to prevent unneeded - * requests to Box for access tokens. - * - * @param userId the user ID to use for an App User. - * @param boxConfig box configuration settings object - * @return a new instance of BoxAPIConnection. - */ - public static BoxDeveloperEditionAPIConnection getUserConnection(String userId, BoxConfig boxConfig) { - return getUserConnection( - userId, - boxConfig.getClientId(), - boxConfig.getClientSecret(), - boxConfig.getJWTEncryptionPreferences(), - new InMemoryLRUAccessTokenCache(DEFAULT_MAX_ENTRIES)); - } - - /** - * Disabling the non-Box Developer Edition authenticate method. - * - * @param authCode an auth code obtained from the first half of the OAuth process. - */ - public void authenticate(String authCode) { - throw new BoxAPIException("BoxDeveloperEditionAPIConnection does not allow authenticating with an auth code."); - } - - /** - * Authenticates the API connection for Box Developer Edition. - */ - public void authenticate() { - URL url; - try { - url = new URL(this.getTokenURL()); - } catch (MalformedURLException e) { - assert false : "An invalid token URL indicates a bug in the SDK."; - throw new RuntimeException("An invalid token URL indicates a bug in the SDK.", e); + this.backoffCounter.reset(this.getMaxRetryAttempts() + 1); + NumericDate jwtTime = null; + String jwtAssertion; + String urlParameters; + BoxAPIRequest request; + String json = null; + final BoxLogger logger = BoxLogger.defaultLogger(); + + while (this.backoffCounter.getAttemptsRemaining() > 0) { + // Reconstruct the JWT assertion, which regenerates the jti claim, with the new "current" time + jwtAssertion = this.constructJWTAssertion(jwtTime); + urlParameters = + String.format(JWT_GRANT_TYPE, this.getClientID(), this.getClientSecret(), jwtAssertion); + + request = new BoxAPIRequest(this, url, "POST"); + request.shouldAuthenticate(false); + request.setBody(urlParameters); + + try (BoxJSONResponse response = (BoxJSONResponse) request.sendWithoutRetry()) { + // authentication uses form url encoded but response is JSON + json = response.getJSON(); + break; + } catch (BoxAPIException apiException) { + long responseReceivedTime = System.currentTimeMillis(); + + if (!this.backoffCounter.decrement() + || (!BoxAPIRequest.isRequestRetryable(apiException) + && !isResponseRetryable(apiException))) { + throw apiException; } - this.backoffCounter.reset(this.getMaxRetryAttempts() + 1); - NumericDate jwtTime = null; - String jwtAssertion; - String urlParameters; - BoxAPIRequest request; - String json = null; - final BoxLogger logger = BoxLogger.defaultLogger(); - - while (this.backoffCounter.getAttemptsRemaining() > 0) { - // Reconstruct the JWT assertion, which regenerates the jti claim, with the new "current" time - jwtAssertion = this.constructJWTAssertion(jwtTime); - urlParameters = String.format(JWT_GRANT_TYPE, this.getClientID(), this.getClientSecret(), jwtAssertion); - - request = new BoxAPIRequest(this, url, "POST"); - request.shouldAuthenticate(false); - request.setBody(urlParameters); - - try (BoxJSONResponse response = (BoxJSONResponse) request.sendWithoutRetry()) { - // authentication uses form url encoded but response is JSON - json = response.getJSON(); - break; - } catch (BoxAPIException apiException) { - long responseReceivedTime = System.currentTimeMillis(); - - if (!this.backoffCounter.decrement() - || (!BoxAPIRequest.isRequestRetryable(apiException) && !isResponseRetryable(apiException))) { - throw apiException; - } - - logger.warn(String.format( - "Retrying authentication request due to transient error status=%d body=%s", - apiException.getResponseCode(), - apiException.getResponse() - )); - - try { - List retryAfterHeader = apiException.getHeaders().get("Retry-After"); - if (retryAfterHeader == null) { - this.backoffCounter.waitBackoff(); - } else { - int retryAfterDelay = Integer.parseInt(retryAfterHeader.get(0)) * 1000; - this.backoffCounter.waitBackoff(retryAfterDelay); - } - } catch (InterruptedException interruptedException) { - Thread.currentThread().interrupt(); - throw apiException; - } - - long endWaitTime = System.currentTimeMillis(); - long secondsSinceResponseReceived = (endWaitTime - responseReceivedTime) / 1000; - - try { - // Use the Date advertised by the Box server in the exception - // as the current time to synchronize clocks - jwtTime = this.getDateForJWTConstruction(apiException, secondsSinceResponseReceived); - } catch (Exception e) { - throw apiException; - } - - } - } + logger.warn( + String.format( + "Retrying authentication request due to transient error status=%d body=%s", + apiException.getResponseCode(), apiException.getResponse())); - if (json == null) { - throw new RuntimeException("Unable to read authentication response in SDK."); + try { + List retryAfterHeader = apiException.getHeaders().get("Retry-After"); + if (retryAfterHeader == null) { + this.backoffCounter.waitBackoff(); + } else { + int retryAfterDelay = Integer.parseInt(retryAfterHeader.get(0)) * 1000; + this.backoffCounter.waitBackoff(retryAfterDelay); + } + } catch (InterruptedException interruptedException) { + Thread.currentThread().interrupt(); + throw apiException; } - JsonObject jsonObject = Json.parse(json).asObject(); - this.setAccessToken(jsonObject.get("access_token").asString()); - this.setLastRefresh(System.currentTimeMillis()); - this.setExpires(jsonObject.get("expires_in").asLong() * 1000); + long endWaitTime = System.currentTimeMillis(); + long secondsSinceResponseReceived = (endWaitTime - responseReceivedTime) / 1000; - //if token cache is specified, save to cache - if (this.accessTokenCache != null) { - String key = this.getAccessTokenCacheKey(); - JsonObject accessTokenCacheInfo = new JsonObject() - .add("accessToken", this.getAccessToken()) - .add("lastRefresh", this.getLastRefresh()) - .add("expires", this.getExpires()); - - this.accessTokenCache.put(key, accessTokenCacheInfo.toString()); + try { + // Use the Date advertised by the Box server in the exception + // as the current time to synchronize clocks + jwtTime = this.getDateForJWTConstruction(apiException, secondsSinceResponseReceived); + } catch (Exception e) { + throw apiException; } + } } - private boolean isResponseRetryable(BoxAPIException apiException) { - return BoxAPIRequest.isResponseRetryable(apiException.getResponseCode(), apiException) - || isJtiNonUniqueError(apiException); + if (json == null) { + throw new RuntimeException("Unable to read authentication response in SDK."); } - private boolean isJtiNonUniqueError(BoxAPIException apiException) { - return apiException.getResponseCode() == 400 - && apiException.getResponse().contains("A unique 'jti' value is required"); + JsonObject jsonObject = Json.parse(json).asObject(); + this.setAccessToken(jsonObject.get("access_token").asString()); + this.setLastRefresh(System.currentTimeMillis()); + this.setExpires(jsonObject.get("expires_in").asLong() * 1000); + + // if token cache is specified, save to cache + if (this.accessTokenCache != null) { + String key = this.getAccessTokenCacheKey(); + JsonObject accessTokenCacheInfo = + new JsonObject() + .add("accessToken", this.getAccessToken()) + .add("lastRefresh", this.getLastRefresh()) + .add("expires", this.getExpires()); + + this.accessTokenCache.put(key, accessTokenCacheInfo.toString()); } - - private NumericDate getDateForJWTConstruction(BoxAPIException apiException, long secondsSinceResponseDateReceived) { - NumericDate currentTime; - List responseDates = apiException.getHeaders().get("Date"); - - if (responseDates != null) { - String responseDate = responseDates.get(0); - SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss zzz"); - try { - Date date = dateFormat.parse(responseDate); - currentTime = NumericDate.fromMilliseconds(date.getTime()); - currentTime.addSeconds(secondsSinceResponseDateReceived); - } catch (ParseException e) { - currentTime = NumericDate.now(); - } - } else { - currentTime = NumericDate.now(); - } - return currentTime; + } + + private boolean isResponseRetryable(BoxAPIException apiException) { + return BoxAPIRequest.isResponseRetryable(apiException.getResponseCode(), apiException) + || isJtiNonUniqueError(apiException); + } + + private boolean isJtiNonUniqueError(BoxAPIException apiException) { + return apiException.getResponseCode() == 400 + && apiException.getResponse().contains("A unique 'jti' value is required"); + } + + private NumericDate getDateForJWTConstruction( + BoxAPIException apiException, long secondsSinceResponseDateReceived) { + NumericDate currentTime; + List responseDates = apiException.getHeaders().get("Date"); + + if (responseDates != null) { + String responseDate = responseDates.get(0); + SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss zzz"); + try { + Date date = dateFormat.parse(responseDate); + currentTime = NumericDate.fromMilliseconds(date.getTime()); + currentTime.addSeconds(secondsSinceResponseDateReceived); + } catch (ParseException e) { + currentTime = NumericDate.now(); + } + } else { + currentTime = NumericDate.now(); } - - void setBackoffCounter(BackoffCounter counter) { - this.backoffCounter = counter; + return currentTime; + } + + void setBackoffCounter(BackoffCounter counter) { + this.backoffCounter = counter; + } + + /** + * BoxDeveloperEditionAPIConnection can always refresh, but this method is required elsewhere. + * + * @return true always. + */ + public boolean canRefresh() { + return true; + } + + /** + * Refresh's this connection's access token using Box Developer Edition. + * + * @throws IllegalStateException if this connection's access token cannot be refreshed. + */ + public void refresh() { + this.getRefreshLock().writeLock().lock(); + + try { + this.authenticate(); + } catch (BoxAPIException e) { + this.notifyError(e); + this.getRefreshLock().writeLock().unlock(); + throw e; } - /** - * BoxDeveloperEditionAPIConnection can always refresh, but this method is required elsewhere. - * - * @return true always. - */ - public boolean canRefresh() { - return true; + this.notifyRefresh(); + this.getRefreshLock().writeLock().unlock(); + } + + private String getAccessTokenCacheKey() { + return String.format( + "/%s/%s/%s/%s", + this.getUserAgent(), this.getClientID(), this.entityType.toString(), this.entityID); + } + + /** Tries to restore the connection using the access token cache. */ + public void tryRestoreUsingAccessTokenCache() { + if (this.accessTokenCache == null) { + // no cache specified so force authentication + this.authenticate(); + } else { + String cachedTokenInfo = this.accessTokenCache.get(this.getAccessTokenCacheKey()); + if (cachedTokenInfo == null) { + // not found; probably first time for this client config so authenticate; info will then be + // cached + this.authenticate(); + } else { + // pull access token cache info; authentication will occur as needed (if token is expired) + JsonObject json = Json.parse(cachedTokenInfo).asObject(); + this.setAccessToken(json.get("accessToken").asString()); + this.setLastRefresh(json.get("lastRefresh").asLong()); + this.setExpires(json.get("expires").asLong()); + } } - - /** - * Refresh's this connection's access token using Box Developer Edition. - * - * @throws IllegalStateException if this connection's access token cannot be refreshed. - */ - public void refresh() { - this.getRefreshLock().writeLock().lock(); - - try { - this.authenticate(); - } catch (BoxAPIException e) { - this.notifyError(e); - this.getRefreshLock().writeLock().unlock(); - throw e; - } - - this.notifyRefresh(); - this.getRefreshLock().writeLock().unlock(); + } + + private String constructJWTAssertion(NumericDate now) { + JwtClaims claims = new JwtClaims(); + claims.setIssuer(this.getClientID()); + claims.setAudience(JWT_AUDIENCE); + if (now == null) { + claims.setExpirationTimeMinutesInTheFuture(0.5f); + } else { + now.addSeconds(30L); + claims.setExpirationTime(now); } - - private String getAccessTokenCacheKey() { - return String.format("/%s/%s/%s/%s", this.getUserAgent(), this.getClientID(), - this.entityType.toString(), this.entityID); - } - - /** - * Tries to restore the connection using the access token cache. - */ - public void tryRestoreUsingAccessTokenCache() { - if (this.accessTokenCache == null) { - //no cache specified so force authentication - this.authenticate(); - } else { - String cachedTokenInfo = this.accessTokenCache.get(this.getAccessTokenCacheKey()); - if (cachedTokenInfo == null) { - //not found; probably first time for this client config so authenticate; info will then be cached - this.authenticate(); - } else { - //pull access token cache info; authentication will occur as needed (if token is expired) - JsonObject json = Json.parse(cachedTokenInfo).asObject(); - this.setAccessToken(json.get("accessToken").asString()); - this.setLastRefresh(json.get("lastRefresh").asLong()); - this.setExpires(json.get("expires").asLong()); - } - } + claims.setSubject(this.entityID); + claims.setClaim("box_sub_type", this.entityType.toString()); + claims.setGeneratedJwtId(64); + + JsonWebSignature jws = new JsonWebSignature(); + jws.setPayload(claims.toJson()); + jws.setKey( + this.privateKeyDecryptor.decryptPrivateKey(this.privateKey, this.privateKeyPassword)); + jws.setAlgorithmHeaderValue(this.getAlgorithmIdentifier()); + jws.setHeader("typ", "JWT"); + if ((this.publicKeyID != null) && !this.publicKeyID.isEmpty()) { + jws.setHeader("kid", this.publicKeyID); } - private String constructJWTAssertion(NumericDate now) { - JwtClaims claims = new JwtClaims(); - claims.setIssuer(this.getClientID()); - claims.setAudience(JWT_AUDIENCE); - if (now == null) { - claims.setExpirationTimeMinutesInTheFuture(0.5f); - } else { - now.addSeconds(30L); - claims.setExpirationTime(now); - } - claims.setSubject(this.entityID); - claims.setClaim("box_sub_type", this.entityType.toString()); - claims.setGeneratedJwtId(64); - - JsonWebSignature jws = new JsonWebSignature(); - jws.setPayload(claims.toJson()); - jws.setKey(this.privateKeyDecryptor.decryptPrivateKey(this.privateKey, this.privateKeyPassword)); - jws.setAlgorithmHeaderValue(this.getAlgorithmIdentifier()); - jws.setHeader("typ", "JWT"); - if ((this.publicKeyID != null) && !this.publicKeyID.isEmpty()) { - jws.setHeader("kid", this.publicKeyID); - } - - String assertion; + String assertion; - try { - assertion = jws.getCompactSerialization(); - } catch (JoseException e) { - throw new BoxAPIException("Error serializing JSON Web Token assertion.", e); - } - - return assertion; + try { + assertion = jws.getCompactSerialization(); + } catch (JoseException e) { + throw new BoxAPIException("Error serializing JSON Web Token assertion.", e); } - private String getAlgorithmIdentifier() { - String algorithmId = AlgorithmIdentifiers.RSA_USING_SHA256; - switch (this.encryptionAlgorithm) { - case RSA_SHA_384: - algorithmId = AlgorithmIdentifiers.RSA_USING_SHA384; - break; - case RSA_SHA_512: - algorithmId = AlgorithmIdentifiers.RSA_USING_SHA512; - break; - case RSA_SHA_256: - default: - break; - } - - return algorithmId; + return assertion; + } + + private String getAlgorithmIdentifier() { + String algorithmId = AlgorithmIdentifiers.RSA_USING_SHA256; + switch (this.encryptionAlgorithm) { + case RSA_SHA_384: + algorithmId = AlgorithmIdentifiers.RSA_USING_SHA384; + break; + case RSA_SHA_512: + algorithmId = AlgorithmIdentifiers.RSA_USING_SHA512; + break; + case RSA_SHA_256: + default: + break; } + + return algorithmId; + } } diff --git a/src/main/java/com/box/sdk/BoxDevicePin.java b/src/main/java/com/box/sdk/BoxDevicePin.java index 89d81477f..4ef27be32 100644 --- a/src/main/java/com/box/sdk/BoxDevicePin.java +++ b/src/main/java/com/box/sdk/BoxDevicePin.java @@ -1,240 +1,222 @@ -package com.box.sdk; - -import com.eclipsesource.json.Json; -import com.eclipsesource.json.JsonObject; -import com.eclipsesource.json.JsonValue; -import java.net.URL; -import java.text.ParseException; -import java.util.Date; - -/** - * Represents a device pin. - * - *

Unless otherwise noted, the methods in this class can throw an unchecked {@link BoxAPIException} (unchecked - * meaning that the compiler won't force you to handle it) if an error occurs. If you wish to implement custom error - * handling for errors related to the Box REST API, you should capture this exception explicitly.

- */ -@BoxResourceType("device_pin") -public class BoxDevicePin extends BoxResource { - - /** - * The URL template used for operation with the device pin. - */ - public static final URLTemplate DEVICE_PIN_URL_TEMPLATE = new URLTemplate("device_pinners/%s"); - - /** - * The URL template used to get all the device pins within a given enterprise. - */ - public static final URLTemplate ENTERPRISE_DEVICE_PINS_TEMPLATE = new URLTemplate("enterprises/%s/device_pinners"); - - /** - * Default limit of the device info entries per one response page. - */ - private static final int DEVICES_DEFAULT_LIMIT = 100; - - /** - * Constructs a device pin for a resource with a given ID. - * - * @param api the API connection to be used by the resource. - * @param id the ID of the resource. - */ - public BoxDevicePin(BoxAPIConnection api, String id) { - super(api, id); - } - - /** - * Returns iterable with all the device pins within a given enterprise. - * Must be an enterprise admin with the manage enterprise scope to make this call. - * - * @param api API used to connect the Box. - * @param enterpriseID ID of the enterprise to get all the device pins within. - * @param fields the optional fields to retrieve. - * @return iterable with all the device pins within a given enterprise. - */ - public static Iterable getEnterpriceDevicePins(final BoxAPIConnection api, String enterpriseID, - String... fields) { - return getEnterpriceDevicePins(api, enterpriseID, DEVICES_DEFAULT_LIMIT, fields); - } - - /** - * Returns iterable with all the device pins within a given enterprise. - * Must be an enterprise admin with the manage enterprise scope to make this call. - * - * @param api API used to connect the Box. - * @param enterpriseID ID of the enterprise to get all the device pins within. - * @param limit the maximum number of items per single response. - * @param fields the optional fields to retrieve. - * @return iterable with all the device pins within a given enterprise. - */ - public static Iterable getEnterpriceDevicePins(final BoxAPIConnection api, String enterpriseID, - int limit, String... fields) { - QueryStringBuilder builder = new QueryStringBuilder(); - if (fields.length > 0) { - builder.appendParam("fields", fields); - } - return new BoxResourceIterable(api, - ENTERPRISE_DEVICE_PINS_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString(), enterpriseID), - limit) { - - @Override - protected BoxDevicePin.Info factory(JsonObject jsonObject) { - BoxDevicePin pin = new BoxDevicePin(api, jsonObject.get("id").asString()); - return pin.new Info(jsonObject); - } - }; - } - - /** - * Gets information about the device pin. - * - * @param fields the fields to retrieve. - * @return info about the device pin. - */ - public Info getInfo(String... fields) { - QueryStringBuilder builder = new QueryStringBuilder(); - if (fields.length > 0) { - builder.appendParam("fields", fields); - } - URL url = DEVICE_PIN_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), builder.toString(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - return new Info(responseJSON); - } - } - - /** - * Deletes the device pin. - */ - public void delete() { - URL url = DEVICE_PIN_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); - request.send().close(); - } - - /** - * Contains information about a task assignment. - */ - public class Info extends BoxResource.Info { - - /** - * @see #getOwnedBy() - */ - private BoxUser.Info ownedBy; - - /** - * @see #getProductName() - */ - private String productName; - - /** - * @see #getCreatedAt() - */ - private Date createdAt; - - /** - * @see #getModifiedAt() - */ - private Date modifiedAt; - - /** - * Constructs an empty Info object. - */ - public Info() { - super(); - } - - /** - * Constructs an Info object by parsing information from a JSON string. - * - * @param json the JSON string to parse. - */ - public Info(String json) { - super(json); - } - - /** - * Constructs an Info object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - Info(JsonObject jsonObject) { - super(jsonObject); - } - - /** - * {@inheritDoc} - */ - @Override - public BoxResource getResource() { - return BoxDevicePin.this; - } - - /** - * Gets ID of the user that the pin belongs to. - * - * @return ID of the user that the pin belongs to. - */ - public BoxUser.Info getOwnedBy() { - return this.ownedBy; - } - - /** - * Gets the type of device being pinned. - * - * @return the type of device being pinned. - */ - public String getProductName() { - return this.productName; - } - - /** - * Gets the time this pin was created. - * - * @return the time this pin was created. - */ - public Date getCreatedAt() { - return this.createdAt; - } - - /** - * Gets the time this pin was modified. - * - * @return the time this pin was modified. - */ - public Date getModifiedAt() { - return this.modifiedAt; - } - - /** - * {@inheritDoc} - */ - @Override - void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - - String memberName = member.getName(); - JsonValue value = member.getValue(); - try { - if (memberName.equals("owned_by")) { - JsonObject userJSON = value.asObject(); - if (this.ownedBy == null) { - String userID = userJSON.get("id").asString(); - BoxUser user = new BoxUser(getAPI(), userID); - this.ownedBy = user.new Info(userJSON); - } else { - this.ownedBy.update(userJSON); - } - } else if (memberName.equals("product_name")) { - this.productName = value.asString(); - } else if (memberName.equals("created_at")) { - this.createdAt = BoxDateFormat.parse(value.asString()); - } else if (memberName.equals("modified_at")) { - this.modifiedAt = BoxDateFormat.parse(value.asString()); - } - } catch (ParseException e) { - assert false : "A ParseException indicates a bug in the SDK."; - } - } - } -} +package com.box.sdk; + +import com.eclipsesource.json.Json; +import com.eclipsesource.json.JsonObject; +import com.eclipsesource.json.JsonValue; +import java.net.URL; +import java.text.ParseException; +import java.util.Date; + +/** + * Represents a device pin. + * + *

Unless otherwise noted, the methods in this class can throw an unchecked {@link + * BoxAPIException} (unchecked meaning that the compiler won't force you to handle it) if an error + * occurs. If you wish to implement custom error handling for errors related to the Box REST API, + * you should capture this exception explicitly. + */ +@BoxResourceType("device_pin") +public class BoxDevicePin extends BoxResource { + + /** The URL template used for operation with the device pin. */ + public static final URLTemplate DEVICE_PIN_URL_TEMPLATE = new URLTemplate("device_pinners/%s"); + + /** The URL template used to get all the device pins within a given enterprise. */ + public static final URLTemplate ENTERPRISE_DEVICE_PINS_TEMPLATE = + new URLTemplate("enterprises/%s/device_pinners"); + + /** Default limit of the device info entries per one response page. */ + private static final int DEVICES_DEFAULT_LIMIT = 100; + + /** + * Constructs a device pin for a resource with a given ID. + * + * @param api the API connection to be used by the resource. + * @param id the ID of the resource. + */ + public BoxDevicePin(BoxAPIConnection api, String id) { + super(api, id); + } + + /** + * Returns iterable with all the device pins within a given enterprise. Must be an enterprise + * admin with the manage enterprise scope to make this call. + * + * @param api API used to connect the Box. + * @param enterpriseID ID of the enterprise to get all the device pins within. + * @param fields the optional fields to retrieve. + * @return iterable with all the device pins within a given enterprise. + */ + public static Iterable getEnterpriceDevicePins( + final BoxAPIConnection api, String enterpriseID, String... fields) { + return getEnterpriceDevicePins(api, enterpriseID, DEVICES_DEFAULT_LIMIT, fields); + } + + /** + * Returns iterable with all the device pins within a given enterprise. Must be an enterprise + * admin with the manage enterprise scope to make this call. + * + * @param api API used to connect the Box. + * @param enterpriseID ID of the enterprise to get all the device pins within. + * @param limit the maximum number of items per single response. + * @param fields the optional fields to retrieve. + * @return iterable with all the device pins within a given enterprise. + */ + public static Iterable getEnterpriceDevicePins( + final BoxAPIConnection api, String enterpriseID, int limit, String... fields) { + QueryStringBuilder builder = new QueryStringBuilder(); + if (fields.length > 0) { + builder.appendParam("fields", fields); + } + return new BoxResourceIterable( + api, + ENTERPRISE_DEVICE_PINS_TEMPLATE.buildWithQuery( + api.getBaseURL(), builder.toString(), enterpriseID), + limit) { + + @Override + protected BoxDevicePin.Info factory(JsonObject jsonObject) { + BoxDevicePin pin = new BoxDevicePin(api, jsonObject.get("id").asString()); + return pin.new Info(jsonObject); + } + }; + } + + /** + * Gets information about the device pin. + * + * @param fields the fields to retrieve. + * @return info about the device pin. + */ + public Info getInfo(String... fields) { + QueryStringBuilder builder = new QueryStringBuilder(); + if (fields.length > 0) { + builder.appendParam("fields", fields); + } + URL url = + DEVICE_PIN_URL_TEMPLATE.buildWithQuery( + this.getAPI().getBaseURL(), builder.toString(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + return new Info(responseJSON); + } + } + + /** Deletes the device pin. */ + public void delete() { + URL url = DEVICE_PIN_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); + request.send().close(); + } + + /** Contains information about a task assignment. */ + public class Info extends BoxResource.Info { + + /** @see #getOwnedBy() */ + private BoxUser.Info ownedBy; + + /** @see #getProductName() */ + private String productName; + + /** @see #getCreatedAt() */ + private Date createdAt; + + /** @see #getModifiedAt() */ + private Date modifiedAt; + + /** Constructs an empty Info object. */ + public Info() { + super(); + } + + /** + * Constructs an Info object by parsing information from a JSON string. + * + * @param json the JSON string to parse. + */ + public Info(String json) { + super(json); + } + + /** + * Constructs an Info object using an already parsed JSON object. + * + * @param jsonObject the parsed JSON object. + */ + Info(JsonObject jsonObject) { + super(jsonObject); + } + + /** {@inheritDoc} */ + @Override + public BoxResource getResource() { + return BoxDevicePin.this; + } + + /** + * Gets ID of the user that the pin belongs to. + * + * @return ID of the user that the pin belongs to. + */ + public BoxUser.Info getOwnedBy() { + return this.ownedBy; + } + + /** + * Gets the type of device being pinned. + * + * @return the type of device being pinned. + */ + public String getProductName() { + return this.productName; + } + + /** + * Gets the time this pin was created. + * + * @return the time this pin was created. + */ + public Date getCreatedAt() { + return this.createdAt; + } + + /** + * Gets the time this pin was modified. + * + * @return the time this pin was modified. + */ + public Date getModifiedAt() { + return this.modifiedAt; + } + + /** {@inheritDoc} */ + @Override + void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + + String memberName = member.getName(); + JsonValue value = member.getValue(); + try { + if (memberName.equals("owned_by")) { + JsonObject userJSON = value.asObject(); + if (this.ownedBy == null) { + String userID = userJSON.get("id").asString(); + BoxUser user = new BoxUser(getAPI(), userID); + this.ownedBy = user.new Info(userJSON); + } else { + this.ownedBy.update(userJSON); + } + } else if (memberName.equals("product_name")) { + this.productName = value.asString(); + } else if (memberName.equals("created_at")) { + this.createdAt = BoxDateFormat.parse(value.asString()); + } else if (memberName.equals("modified_at")) { + this.modifiedAt = BoxDateFormat.parse(value.asString()); + } + } catch (ParseException e) { + assert false : "A ParseException indicates a bug in the SDK."; + } + } + } +} diff --git a/src/main/java/com/box/sdk/BoxEnterprise.java b/src/main/java/com/box/sdk/BoxEnterprise.java index 1b0447c03..d001c8359 100644 --- a/src/main/java/com/box/sdk/BoxEnterprise.java +++ b/src/main/java/com/box/sdk/BoxEnterprise.java @@ -3,58 +3,53 @@ import com.eclipsesource.json.JsonObject; import com.eclipsesource.json.JsonValue; -/** - * Represents an enterprise organization on Box. - */ +/** Represents an enterprise organization on Box. */ public class BoxEnterprise extends BoxJSONObject { - private String id; - private String name; - - /** - * Constructs a BoxEnterprise with default settings. - */ - public BoxEnterprise() { - } - - /** - * Constructs a BoxEnterprise from a JSON string. - * - * @param json the JSON encoded enterprise. - */ - public BoxEnterprise(String json) { - super(json); - } - - BoxEnterprise(JsonObject jsonObject) { - super(jsonObject); - } - - /** - * Gets the ID of this enterprise. - * - * @return the ID of this enterprise. - */ - public String getID() { - return this.id; - } - - /** - * Gets the name of this enterprise. - * - * @return the name of this enterprise. - */ - public String getName() { - return this.name; - } - - @Override - void parseJSONMember(JsonObject.Member member) { - JsonValue value = member.getValue(); - String memberName = member.getName(); - if (memberName.equals("id")) { - this.id = value.asString(); - } else if (memberName.equals("name")) { - this.name = value.asString(); - } + private String id; + private String name; + + /** Constructs a BoxEnterprise with default settings. */ + public BoxEnterprise() {} + + /** + * Constructs a BoxEnterprise from a JSON string. + * + * @param json the JSON encoded enterprise. + */ + public BoxEnterprise(String json) { + super(json); + } + + BoxEnterprise(JsonObject jsonObject) { + super(jsonObject); + } + + /** + * Gets the ID of this enterprise. + * + * @return the ID of this enterprise. + */ + public String getID() { + return this.id; + } + + /** + * Gets the name of this enterprise. + * + * @return the name of this enterprise. + */ + public String getName() { + return this.name; + } + + @Override + void parseJSONMember(JsonObject.Member member) { + JsonValue value = member.getValue(); + String memberName = member.getName(); + if (memberName.equals("id")) { + this.id = value.asString(); + } else if (memberName.equals("name")) { + this.name = value.asString(); } + } } diff --git a/src/main/java/com/box/sdk/BoxEvent.java b/src/main/java/com/box/sdk/BoxEvent.java index b2738e090..0a107d255 100644 --- a/src/main/java/com/box/sdk/BoxEvent.java +++ b/src/main/java/com/box/sdk/BoxEvent.java @@ -8,966 +8,690 @@ import java.util.HashMap; import java.util.Map; -/** - * Represents an event that was fired off by the Box events API. - */ +/** Represents an event that was fired off by the Box events API. */ @BoxResourceType("event") public class BoxEvent extends BoxResource { - private BoxResource.Info sourceInfo; - private BoxEvent.EventType eventType; - private String typeName; - private JsonObject sourceJSON; - private Date createdAt; - private String ipAddress; - private JsonObject additionalDetails; - private BoxCollaborator.Info accessibleBy; - private BoxUser.Info createdBy; - private String sessionID; - private BoxUser.Info actionBy; + private BoxResource.Info sourceInfo; + private BoxEvent.EventType eventType; + private String typeName; + private JsonObject sourceJSON; + private Date createdAt; + private String ipAddress; + private JsonObject additionalDetails; + private BoxCollaborator.Info accessibleBy; + private BoxUser.Info createdBy; + private String sessionID; + private BoxUser.Info actionBy; + + /** + * Constructs a BoxEvent from a JSON string. + * + * @param api the API connection to be used by the file. + * @param json the JSON encoded event. + */ + public BoxEvent(BoxAPIConnection api, String json) { + this(api, Json.parse(json).asObject()); + } + + BoxEvent(BoxAPIConnection api, JsonObject jsonObject) { + super(api, jsonObject.get("event_id").asString()); + + for (JsonObject.Member member : jsonObject) { + if (member.getValue().isNull()) { + continue; + } + + this.parseJsonMember(member); + } + } + + /** + * Gets info about the source of this event. + * + *

Note that there is a bug in the enterprise event stream where certain event sources don't + * correctly map to a BoxResource.Info. In the case where the event source JSON cannot be mapped + * to a BoxResource.Info, you can use the {@link #getSourceJSON} method to access the raw JSON + * representation of the event source. + * + * @return info about the source of this event. + */ + public BoxResource.Info getSourceInfo() { + return this.sourceInfo; + } + + /** + * Gets the raw JSON object containing information about the source of this event. + * + *

This method can be used to work around bugs in the enterprise events API where some + * enterprise event sources don't correctly map to a BoxResource.Info. In this case, this method + * can be used to access the raw JSON directly. + * + * @return the JSON representation of the source of this event. + */ + public JsonObject getSourceJSON() { + return this.sourceJSON; + } + + /** + * Gets the type of this event. + * + * @return the type of this event. + */ + public BoxEvent.EventType getEventType() { + return this.eventType; + } + + /** + * Gets the type name as String. Every BoxEvent will have typeName, some will have eventType set + * to specific value and some will have eventType = UNKNOWN. + * + * @return the name of the type of this event. + */ + public String getTypeName() { + return this.typeName; + } + + /** + * Gets the time that this event was created. + * + * @return the time that this event was created. + */ + public Date getCreatedAt() { + return this.createdAt; + } + + /** + * Gets the IP address of the user that triggered this event. + * + * @return the IP address of the user that triggered this event. + */ + public String getIPAddress() { + return this.ipAddress; + } + + /** + * Gets a JSON object containing additional details about this event. + * + *

The fields and data within the returned JSON object will vary depending on the type of the + * event. + * + * @return a JSON object containing additional details about this event. + */ + public JsonObject getAdditionalDetails() { + return this.additionalDetails; + } + + /** + * Gets info about the collaborator who was given access to a folder within the current + * enterprise. + * + *

This field is only populated when the event is related to a collaboration that occurred + * within an enterprise. + * + * @return info about the collaborator who was given access to a folder within the current + * enterprise. + */ + public BoxCollaborator.Info getAccessibleBy() { + return this.accessibleBy; + } + + /** + * Gets info about the user that triggered this event. + * + * @return info about the user that triggered this event. + */ + public BoxUser.Info getCreatedBy() { + return this.createdBy; + } + + /** + * Gets the session ID of the user that triggered this event. + * + * @return the session ID of the user that triggered this event. + */ + public String getSessionID() { + return this.sessionID; + } + + /** + * Gets the user that performed the action for this event. + * + * @return info about the user that performed that action for this event. + */ + public BoxUser.Info getActionBy() { + return this.actionBy; + } + + void parseJsonMember(JsonObject.Member member) { + JsonValue value = member.getValue(); + if (value.isNull()) { + return; + } - /** - * Constructs a BoxEvent from a JSON string. - * - * @param api the API connection to be used by the file. - * @param json the JSON encoded event. - */ - public BoxEvent(BoxAPIConnection api, String json) { - this(api, Json.parse(json).asObject()); + String memberName = member.getName(); + switch (memberName) { + case "source": + // Parsing the source might fail due to a bug in the enterprise event stream where the API + // returns + // JSON that doesn't correctly map to a BoxResource.Info. If this happens, we set the + // sourceInfo to null + // and expect the caller to use the getSourceJSON() method instead. + try { + this.sourceInfo = BoxResource.parseInfo(this.getAPI(), value.asObject()); + } catch (Exception e) { + this.sourceInfo = null; + } + this.sourceJSON = JsonObject.unmodifiableObject(value.asObject()); + break; + case "event_type": + String stringValue = value.asString(); + this.typeName = stringValue; + this.eventType = EventType.lookupByValue(stringValue); + if (this.eventType == null) { + this.eventType = EventType.UNKNOWN; + } + break; + case "created_at": + try { + this.createdAt = BoxDateFormat.parse(value.asString()); + } catch (ParseException e) { + assert false : "A ParseException indicates a bug in the SDK."; + } + break; + case "ip_address": + this.ipAddress = value.asString(); + break; + case "additional_details": + this.additionalDetails = value.asObject(); + break; + case "accessible_by": + this.accessibleBy = + (BoxCollaborator.Info) BoxResource.parseInfo(this.getAPI(), value.asObject()); + break; + case "created_by": + this.createdBy = (BoxUser.Info) BoxResource.parseInfo(this.getAPI(), value.asObject()); + break; + case "session_id": + this.sessionID = value.asString(); + break; + case "action_by": + this.actionBy = (BoxUser.Info) BoxResource.parseInfo(this.getAPI(), value.asObject()); + break; + default: + break; } + } - BoxEvent(BoxAPIConnection api, JsonObject jsonObject) { - super(api, jsonObject.get("event_id").asString()); + /** Enumerates the possible types for an event. */ + public enum EventType { + /** The type of the event is unknown. */ + UNKNOWN("UNKNOWN"), - for (JsonObject.Member member : jsonObject) { - if (member.getValue().isNull()) { - continue; - } + /** An file or folder was created. */ + ITEM_CREATE("ITEM_CREATE"), - this.parseJsonMember(member); - } - } + /** An file or folder was uploaded. */ + ITEM_UPLOAD("ITEM_UPLOAD"), - /** - * Gets info about the source of this event. - * - *

Note that there is a bug in the enterprise event stream where certain event sources don't correctly map to a - * BoxResource.Info. In the case where the event source JSON cannot be mapped to a BoxResource.Info, you can use the - * {@link #getSourceJSON} method to access the raw JSON representation of the event source.

- * - * @return info about the source of this event. - */ - public BoxResource.Info getSourceInfo() { - return this.sourceInfo; - } + /** A comment was created on a folder, file, or other comment. */ + COMMENT_CREATE("COMMENT_CREATE"), - /** - * Gets the raw JSON object containing information about the source of this event. - * - *

This method can be used to work around bugs in the enterprise events API where some enterprise event sources - * don't correctly map to a BoxResource.Info. In this case, this method can be used to access the raw JSON - * directly.

- * - * @return the JSON representation of the source of this event. - */ - public JsonObject getSourceJSON() { - return this.sourceJSON; - } + /** A comment was deleted on a folder, file, or other comment. */ + COMMENT_DELETE("COMMENT_DELETE"), - /** - * Gets the type of this event. - * - * @return the type of this event. - */ - public BoxEvent.EventType getEventType() { - return this.eventType; - } + /** An file or folder was downloaded. */ + ITEM_DOWNLOAD("ITEM_DOWNLOAD"), - /** - * Gets the type name as String. Every BoxEvent will have typeName, some will have - * eventType set to specific value and some will have eventType = UNKNOWN. - * - * @return the name of the type of this event. - */ - public String getTypeName() { - return this.typeName; - } + /** A file was previewed. */ + ITEM_PREVIEW("ITEM_PREVIEW"), - /** - * Gets the time that this event was created. - * - * @return the time that this event was created. - */ - public Date getCreatedAt() { - return this.createdAt; - } + /** A file or folder was moved. */ + ITEM_MOVE("ITEM_MOVE"), - /** - * Gets the IP address of the user that triggered this event. - * - * @return the IP address of the user that triggered this event. - */ - public String getIPAddress() { - return this.ipAddress; - } + /** A file or folder was copied. */ + ITEM_COPY("ITEM_COPY"), + + /** A task was assigned. */ + TASK_ASSIGNMENT_CREATE("TASK_ASSIGNMENT_CREATE"), + + /** A task was assignment was completed. */ + TASK_ASSIGNMENT_COMPLETE("TASK_ASSIGNMENT_COMPLETE"), + + /** A task was assignment was updated. */ + TASK_ASSIGNMENT_UPDATE("TASK_ASSIGNMENT_UPDATE"), + + /** A task was created. */ + TASK_CREATE("TASK_CREATE"), + + /** A file was locked. */ + LOCK_CREATE("LOCK_CREATE"), + + /** A file was unlocked. */ + LOCK_DESTROY("LOCK_DESTROY"), + + /** A file or folder was deleted. */ + ITEM_TRASH("ITEM_TRASH"), + + /** A file or folder was recovered from the trash. */ + ITEM_UNDELETE_VIA_TRASH("ITEM_UNDELETE_VIA_TRASH"), + + /** A collaborator was added to a folder. */ + COLLAB_ADD_COLLABORATOR("COLLAB_ADD_COLLABORATOR"), + + /** A collaborator's role was change in a folder. */ + COLLAB_ROLE_CHANGE("COLLAB_ROLE_CHANGE"), + + /** A collaborator was invited to a folder. */ + COLLAB_INVITE_COLLABORATOR("COLLAB_INVITE_COLLABORATOR"), + + /** A collaborator was removed from a folder. */ + COLLAB_REMOVE_COLLABORATOR("COLLAB_REMOVE_COLLABORATOR"), + + /** A folder was marked for sync. */ + ITEM_SYNC("ITEM_SYNC"), + + /** A folder was un-marked for sync. */ + ITEM_UNSYNC("ITEM_UNSYNC"), + + /** A file or folder was renamed. */ + ITEM_RENAME("ITEM_RENAME"), + + /** A file or folder was enabled for sharing. */ + ITEM_SHARED_CREATE("ITEM_SHARED_CREATE"), + + /** A file or folder was disabled for sharing. */ + ITEM_SHARED_UNSHARE("ITEM_SHARED_UNSHARE"), + + /** A folder was shared. */ + ITEM_SHARED("ITEM_SHARED"), + + /** A previous version of a file was promoted to the current version. */ + ITEM_MAKE_CURRENT_VERSION("ITEM_MAKE_CURRENT_VERSION"), + + /** A tag was added to a file or folder. */ + TAG_ITEM_CREATE("TAG_ITEM_CREATE"), + + /** 2 factor authentication enabled by user. */ + ENABLE_TWO_FACTOR_AUTH("ENABLE_TWO_FACTOR_AUTH"), + + /** Free user accepts invitation to become a managed user. */ + ADMIN_INVITE_ACCEPT("MASTER_INVITE_ACCEPT"), + + /** Free user rejects invitation to become a managed user. */ + ADMIN_INVITE_REJECT("MASTER_INVITE_REJECT"), + + /** Granted Box access to account. */ + ACCESS_GRANTED("ACCESS_GRANTED"), + + /** Revoke Box access to account. */ + ACCESS_REVOKED("ACCESS_REVOKED"), + + /** A user logged in from a new device. */ + ADD_LOGIN_ACTIVITY_DEVICE("ADD_LOGIN_ACTIVITY_DEVICE"), + + /** A user session associated with an app was invalidated. */ + REMOVE_LOGIN_ACTIVITY_DEVICE("REMOVE_LOGIN_ACTIVITY_DEVICE"), + + /** An admin role changed for a user. */ + CHANGE_ADMIN_ROLE("CHANGE_ADMIN_ROLE"), + + /** A user was added to a group. This is an enterprise-only event. */ + GROUP_ADD_USER("GROUP_ADD_USER"), + + /** A user was created. This is an enterprise-only event. */ + NEW_USER("NEW_USER"), + + /** A group was created. This is an enterprise-only event. */ + GROUP_CREATION("GROUP_CREATION"), + + /** A group was deleted. This is an enterprise-only event. */ + GROUP_DELETION("GROUP_DELETION"), + + /** A user was deleted. This is an enterprise-only event. */ + DELETE_USER("DELETE_USER"), + + /** A group was edited. This is an enterprise-only event. */ + GROUP_EDITED("GROUP_EDITED"), + + /** A user was edited. This is an enterprise-only event. */ + EDIT_USER("EDIT_USER"), + + /** A group was granted access to a folder. This is an enterprise-only event. */ + GROUP_ADD_FOLDER("GROUP_ADD_FOLDER"), + + /** A group was granted access to a file. This is an enterprise-only event. */ + GROUP_ADD_FILE("GROUP_ADD_FILE"), + + /** A user was removed from a group. This is an enterprise-only event. */ + GROUP_REMOVE_USER("GROUP_REMOVE_USER"), + + /** A group had its access to a folder removed. This is an enterprise-only event. */ + GROUP_REMOVE_FOLDER("GROUP_REMOVE_FOLDER"), + + /** A group had its access to a file removed. This is an enterprise-only event. */ + GROUP_REMOVE_FILE("GROUP_REMOVE_FILE"), + + /** An administrator logged in. This is an enterprise-only event. */ + ADMIN_LOGIN("ADMIN_LOGIN"), + + /** A device was associated with a user. This is an enterprise-only event. */ + ADD_DEVICE_ASSOCIATION("ADD_DEVICE_ASSOCIATION"), + + /** There was a failed login attempt. This is an enterprise-only event. */ + FAILED_LOGIN("FAILED_LOGIN"), + + /** There was a successful login. This is an enterprise-only event. */ + LOGIN("LOGIN"), + + /** A user's OAuth2 access token was refreshed. This is an enterprise-only event. */ + USER_AUTHENTICATE_OAUTH2_TOKEN_REFRESH("USER_AUTHENTICATE_OAUTH2_TOKEN_REFRESH"), + + /** A device was disassociated with a user. This is an enterprise-only event. */ + REMOVE_DEVICE_ASSOCIATION("REMOVE_DEVICE_ASSOCIATION"), + + /** A user agreed to the terms of service. This is an enterprise-only event. */ + TERMS_OF_SERVICE_AGREE("TERMS_OF_SERVICE_AGREE"), + + /** A user rejected the terms of service. This is an enterprise-only event. */ + TERMS_OF_SERVICE_REJECT("TERMS_OF_SERVICE_REJECT"), /** - * Gets a JSON object containing additional details about this event. - * - *

The fields and data within the returned JSON object will vary depending on the type of the event.

- * - * @return a JSON object containing additional details about this event. + * Virus found on a file. Event is only received by enterprises that have opted in to be + * notified. This is an enterprise-only event. */ - public JsonObject getAdditionalDetails() { - return this.additionalDetails; - } + FILE_MARKED_MALICIOUS("FILE_MARKED_MALICIOUS"), + + /** An item was copied. This is an enterprise-only event. */ + COPY("COPY"), + + /** An item was deleted. This is an enterprise-only event. */ + DELETE("DELETE"), + + /** An item was downloaded. This is an enterprise-only event. */ + DOWNLOAD("DOWNLOAD"), + + /** An item was edited. This is an enterprise-only event. */ + EDIT("EDIT"), + + /** An item was locked. This is an enterprise-only event. */ + LOCK("LOCK"), + + /** An item was moved. This is an enterprise-only event. */ + MOVE("MOVE"), + + /** An item was previewed. This is an enterprise-only event. */ + PREVIEW("PREVIEW"), + + /** An item was renamed. This is an enterprise-only event. */ + RENAME("RENAME"), + + /** An item was set to be auto-deleted. This is an enterprise-only event. */ + STORAGE_EXPIRATION("STORAGE_EXPIRATION"), + + /** An item was undeleted. This is an enterprise-only event. */ + UNDELETE("UNDELETE"), + + /** An item was unlocked. This is an enterprise-only event. */ + UNLOCK("UNLOCK"), + + /** An item was uploaded. This is an enterprise-only event. */ + UPLOAD("UPLOAD"), + + /** An shared link was created for an item. This is an enterprise-only event. */ + SHARE("SHARE"), + + /** The shared link for an item was updated. This is an enterprise-only event. */ + ITEM_SHARED_UPDATE("ITEM_SHARED_UPDATE"), + + /** The expiration time for a shared link was extended. This is an enterprise-only event. */ + UPDATE_SHARE_EXPIRATION("UPDATE_SHARE_EXPIRATION"), + + /** The expiration time was set for a shared link. This is an enterprise-only event. */ + SHARE_EXPIRATION("SHARE_EXPIRATION"), /** - * Gets info about the collaborator who was given access to a folder within the current enterprise. - * - *

This field is only populated when the event is related to a collaboration that occurred within an enterprise. - *

- * - * @return info about the collaborator who was given access to a folder within the current enterprise. + * The shared link for an item was REMOVE_DEVICE_ASSOCIATION. This is an enterprise-only event. */ - public BoxCollaborator.Info getAccessibleBy() { - return this.accessibleBy; - } + UNSHARE("UNSHARE"), + + /** A user accepted a collaboration invite. This is an enterprise-only event. */ + COLLABORATION_ACCEPT("COLLABORATION_ACCEPT"), + + /** A user's collaboration role was changed. This is an enterprise-only event. */ + COLLABORATION_ROLE_CHANGE("COLLABORATION_ROLE_CHANGE"), + + /** The expiration time for a collaboration was extended. This is an enterprise-only event. */ + UPDATE_COLLABORATION_EXPIRATION("UPDATE_COLLABORATION_EXPIRATION"), + + /** A collaboration was removed from a folder. This is an enterprise-only event. */ + COLLABORATION_REMOVE("COLLABORATION_REMOVE"), + + /** A user was invited to collaborate on a folder. This is an enterprise-only event. */ + COLLABORATION_INVITE("COLLABORATION_INVITE"), + + /** An expiration time was set for a collaboration. This is an enterprise-only event. */ + COLLABORATION_EXPIRATION("COLLABORATION_EXPIRATION"), + + /** Creation of metadata instance. This is an enterprise-only event. */ + METADATA_INSTANCE_CREATE("METADATA_INSTANCE_CREATE"), + + /** Update of metadata instance. This is an enterprise-only event. */ + METADATA_INSTANCE_UPDATE("METADATA_INSTANCE_UPDATE"), + + /** Deletion of metadata instance. This is an enterprise-only event. */ + METADATA_INSTANCE_DELETE("METADATA_INSTANCE_DELETE"), + + /** Content Workflow upload policy violation. This is an enterprise-only event. */ + CONTENT_WORKFLOW_UPLOAD_POLICY_VIOLATION("CONTENT_WORKFLOW_UPLOAD_POLICY_VIOLATION"), + + /** Edit the permissions on a folder. This is an enterprise-only-event. */ + CHANGE_FOLDER_PERMISSION("CHANGE_FOLDER_PERMISSION"), + + /** A task assignment is deleted. This is an enterprise-only event. */ + TASK_ASSIGNMENT_DELETE("TASK_ASSIGNMENT_DELETE"), + + /** Retention is removed. This is an enterprise-only event. */ + DATA_RETENTION_REMOVE_RETENTION("DATA_RETENTION_REMOVE_RETENTION"), + + /** Retention is created. This is an enterprise-only event. */ + DATA_RETENTION_CREATE_RETENTION("DATA_RETENTION_CREATE_RETENTION"), + + /** A retention policy assignment is added. This is an enterprise-only event. */ + RETENTION_POLICY_ASSIGNMENT_ADD("RETENTION_POLICY_ASSIGNMENT_ADD"), + + /** A legal hold assignment is created. This is an enterprise-only event. */ + LEGAL_HOLD_ASSIGNMENT_CREATE("LEGAL_HOLD_ASSIGNMENT_CREATE"), + + /** A legal hold assignment is deleted. This is an enterprise-only event. */ + LEGAL_HOLD_ASSIGNMENT_DELETE("LEGAL_HOLD_ASSIGNMENT_DELETE"), + + /** A legal hold policy is deleted. This is an enterprise-only event. */ + LEGAL_HOLD_POLICY_DELETE("LEGAL_HOLD_POLICY_DELETE"), + + /** There is a sharing policy violation. This is an enterprise-only event. */ + CONTENT_WORKFLOW_SHARING_POLICY_VIOLATION("CONTENT_WORKFLOW_SHARING_POLICY_VIOLATION"), + + /** An application public key is added. This is an enterprise-only event. */ + APPLICATION_PUBLIC_KEY_ADDED("APPLICATION_PUBLIC_KEY_ADDED"), + + /** An application public key is deleted. This is an enterprise-only event. */ + APPLICATION_PUBLIC_KEY_DELETED("APPLICATION_PUBLIC_KEY_DELETED"), + + /** A content policy is added. This is an enterprise-only event. */ + CONTENT_WORKFLOW_POLICY_ADD("CONTENT_WORKFLOW_POLICY_ADD"), + + /** An automation is added. This is an enterprise-only event. */ + CONTENT_WORKFLOW_AUTOMATION_ADD("CONTENT_WORKFLOW_AUTOMATION_ADD"), + + /** An automation is deleted. This is an enterprise-only event. */ + CONTENT_WORKFLOW_AUTOMATION_DELETE("CONTENT_WORKFLOW_AUTOMATION_DELETE"), + + /** A user email alias is confirmed. This is an enterprise-only event. */ + EMAIL_ALIAS_CONFIRM("EMAIL_ALIAS_CONFIRM"), + + /** A user email alias is removed. This is an enterprise-only event. */ + EMAIL_ALIAS_REMOVE("EMAIL_ALIAS_REMOVE"), + + /** A watermark is added to a file. This is an enterprise-only event. */ + WATERMARK_LABEL_CREATE("WATERMARK_LABEL_CREATE"), + + /** A watermark is removed from a file. This is an enterprise-only event. */ + WATERMARK_LABEL_DELETE("WATERMARK_LABEL_DELETE"), + + /** Creation of metadata template instance. This is an enterprise-only event. */ + METADATA_TEMPLATE_CREATE("METADATA_TEMPLATE_CREATE"), + + /** Update of metadata template instance. This is an enterprise-only event. */ + METADATA_TEMPLATE_UPDATE("METADATA_TEMPLATE_UPDATE"), + + /** Deletion of metadata template instance. This is an enterprise-only event. */ + METADATA_TEMPLATE_DELETE("METADATA_TEMPLATE_DELETE"), + + /** Item was opened. This is an enterprise-only event. */ + ITEM_OPEN("ITEM_OPEN"), + + /** Item was modified. This is an enterprise-only event. */ + ITEM_MODIFY("ITEM_MODIFY"), + + /** When a policy set in the Admin console is triggered. This is an enterprise-only event, */ + CONTENT_WORKFLOW_ABNORMAL_DOWNLOAD_ACTIVITY("CONTENT_WORKFLOW_ABNORMAL_DOWNLOAD_ACTIVITY"), + + /** Folders were removed from a group in the Admin console. This is an enterprise-only event. */ + GROUP_REMOVE_ITEM("GROUP_REMOVE_ITEM"), + + /** Folders were added to a group in the Admin console. This is an enterprise-only event. */ + GROUP_ADD_ITEM("GROUP_ADD_ITEM"), + + /** An OAuth2 access token was created for a user. This is an enterprise-only event. */ + USER_AUTHENTICATE_OAUTH2_ACCESS_TOKEN_CREATE("USER_AUTHENTICATE_OAUTH2_ACCESS_TOKEN_CREATE"), + + /** Event for file tag updates. */ + CONTENT_ACCESS("CONTENT_ACCESS"), + + /** A Shield justification is approved. */ + SHIELD_JUSTIFICATION_APPROVAL("SHIELD_JUSTIFICATION_APPROVAL"), + + /** A task's comment is edited. */ + TASK_UPDATE("TASK_UPDATE"), + + /** A file is retored to previous version. */ + FILE_VERSION_RESTORE("FILE_VERSION_RESTORE"), + + /** Advanced settings of a folder are updated. */ + ADVANCED_FOLDER_SETTINGS_UPDATE("ADVANCED_FOLDER_SETTINGS_UPDATE"), + + /** A new application is created in the Box Developer Console. */ + APPLICATION_CREATED("APPLICATION_CREATED"), + + /** Device Trust check failed. */ + DEVICE_TRUST_CHECK_FAILED("DEVICE_TRUST_CHECK_FAILED"), + + /** When a JWT application has been authorized or reauthorized. */ + ENTERPRISE_APP_AUTHORIZATION_UPDATE("ENTERPRISE_APP_AUTHORIZATION_UPDATE"), + + /** A watermarked file is downloaded. */ + FILE_WATERMARKED_DOWNLOAD("FILE_WATERMARKED_DOWNLOAD"), + + /** A legal hold policy is created. */ + LEGAL_HOLD_POLICY_CREATE("LEGAL_HOLD_POLICY_CREATE"), + + /** A legal hold policy is updated. */ + LEGAL_HOLD_POLICY_UPDATE("LEGAL_HOLD_POLICY_UPDATE"), /** - * Gets info about the user that triggered this event. - * - * @return info about the user that triggered this event. + * Shield detected an anomalous download, session, location, or malicious content based on + * enterprise Shield rules. See shield alert events for more information. */ - public BoxUser.Info getCreatedBy() { - return this.createdBy; + SHIELD_ALERT("SHIELD_ALERT"), + + /** Access to an external collaboration is blocked. */ + SHIELD_EXTERNAL_COLLAB_ACCESS_BLOCKED("SHIELD_EXTERNAL_COLLAB_ACCESS_BLOCKED"), + + /** Access to an external collaboration is blocked due to missing a justification. */ + SHIELD_EXTERNAL_COLLAB_ACCESS_BLOCKED_MISSING_JUSTIFICATION( + "SHIELD_EXTERNAL_COLLAB_ACCESS_BLOCKED_MISSING_JUSTIFICATION"), + + /** An invite to externally collaborate is blocked. */ + SHIELD_EXTERNAL_COLLAB_INVITE_BLOCKED("SHIELD_EXTERNAL_COLLAB_INVITE_BLOCKED"), + + /** An invite to externally collaborate is blocked due to missing a justification. */ + SHIELD_EXTERNAL_COLLAB_INVITE_BLOCKED_MISSING_JUSTIFICATION( + "SHIELD_EXTERNAL_COLLAB_INVITE_BLOCKED_MISSING_JUSTIFICATION"), + + /** A sign request was sent to a signer. */ + SIGN_DOCUMENT_ASSIGNED("SIGN_DOCUMENT_ASSIGNED"), + + /** A sign request was cancelled via API or UI. */ + SIGN_DOCUMENT_CANCELLED("SIGN_DOCUMENT_CANCELLED"), + + /** A sign request was signed by all signers. */ + SIGN_DOCUMENT_COMPLETED("SIGN_DOCUMENT_COMPLETED"), + + /** A sign request was converted to a .pdf for signing. */ + SIGN_DOCUMENT_CONVERTED("SIGN_DOCUMENT_CONVERTED"), + + /** A sign request was created via API or UI. The document is not yet sent to signers. */ + SIGN_DOCUMENT_CREATED("SIGN_DOCUMENT_CREATED"), + + /** A sign request was declined by a signer. */ + SIGN_DOCUMENT_DECLINED("SIGN_DOCUMENT_DECLINED"), + + /** A sign request expired with incomplete signatures. */ + SIGN_DOCUMENT_EXPIRED("SIGN_DOCUMENT_EXPIRED"), + + /** A sign request was signed by a signer. */ + SIGN_DOCUMENT_SIGNED("SIGN_DOCUMENT_SIGNED"), + + /** A signer clicked on Review Document in the signer email or visited the signing URL. */ + SIGN_DOCUMENT_VIEWED_BY_SIGNER("SIGN_DOCUMENT_VIEWED_BY_SIGNER"), + + /** A signer downloaded the signing document. */ + SIGNER_DOWNLOADED("SIGNER_DOWNLOADED"), + + /** A signer forwarded the signing document. */ + SIGNER_FORWARDED("SIGNER_FORWARDED"), + + /** Accepted terms. */ + TERMS_OF_SERVICE_ACCEPT("TERMS_OF_SERVICE_ACCEPT"); + + /** Static map of all EventTypes. */ + private static final Map EVENT_TYPE_MAP = + new HashMap<>(EventType.values().length); + + /* + EVENT_TYPE_MAP initialization. + */ + static { + for (BoxEvent.EventType event : BoxEvent.EventType.values()) { + EVENT_TYPE_MAP.put(event.jsonValue, event); + } } + /** String representation of the eventType. */ + private final String jsonValue; + /** - * Gets the session ID of the user that triggered this event. + * Constructor. * - * @return the session ID of the user that triggered this event. + * @param jsonValue string representation of the eventType. */ - public String getSessionID() { - return this.sessionID; + EventType(String jsonValue) { + this.jsonValue = jsonValue; } /** - * Gets the user that performed the action for this event. + * Custom implementation of valueOf(). * - * @return info about the user that performed that action for this event. + * @param jsonValue of the EventType. + * @return EventType. */ - public BoxUser.Info getActionBy() { - return this.actionBy; + static BoxEvent.EventType lookupByValue(String jsonValue) { + return EVENT_TYPE_MAP.get(jsonValue); } - void parseJsonMember(JsonObject.Member member) { - JsonValue value = member.getValue(); - if (value.isNull()) { - return; - } - - String memberName = member.getName(); - switch (memberName) { - case "source": - // Parsing the source might fail due to a bug in the enterprise event stream where the API returns - // JSON that doesn't correctly map to a BoxResource.Info. If this happens, we set the sourceInfo to null - // and expect the caller to use the getSourceJSON() method instead. - try { - this.sourceInfo = BoxResource.parseInfo(this.getAPI(), value.asObject()); - } catch (Exception e) { - this.sourceInfo = null; - } - this.sourceJSON = JsonObject.unmodifiableObject(value.asObject()); - break; - case "event_type": - String stringValue = value.asString(); - this.typeName = stringValue; - this.eventType = EventType.lookupByValue(stringValue); - if (this.eventType == null) { - this.eventType = EventType.UNKNOWN; - } - break; - case "created_at": - try { - this.createdAt = BoxDateFormat.parse(value.asString()); - } catch (ParseException e) { - assert false : "A ParseException indicates a bug in the SDK."; - } - break; - case "ip_address": - this.ipAddress = value.asString(); - break; - case "additional_details": - this.additionalDetails = value.asObject(); - break; - case "accessible_by": - this.accessibleBy = (BoxCollaborator.Info) BoxResource.parseInfo(this.getAPI(), value.asObject()); - break; - case "created_by": - this.createdBy = (BoxUser.Info) BoxResource.parseInfo(this.getAPI(), value.asObject()); - break; - case "session_id": - this.sessionID = value.asString(); - break; - case "action_by": - this.actionBy = (BoxUser.Info) BoxResource.parseInfo(this.getAPI(), value.asObject()); - break; - default: - break; - } - } - - /** - * Enumerates the possible types for an event. - */ - public enum EventType { - /** - * The type of the event is unknown. - */ - UNKNOWN("UNKNOWN"), - - /** - * An file or folder was created. - */ - ITEM_CREATE("ITEM_CREATE"), - - /** - * An file or folder was uploaded. - */ - ITEM_UPLOAD("ITEM_UPLOAD"), - - /** - * A comment was created on a folder, file, or other comment. - */ - COMMENT_CREATE("COMMENT_CREATE"), - - /** - * A comment was deleted on a folder, file, or other comment. - */ - COMMENT_DELETE("COMMENT_DELETE"), - - /** - * An file or folder was downloaded. - */ - ITEM_DOWNLOAD("ITEM_DOWNLOAD"), - - /** - * A file was previewed. - */ - ITEM_PREVIEW("ITEM_PREVIEW"), - - /** - * A file or folder was moved. - */ - ITEM_MOVE("ITEM_MOVE"), - - /** - * A file or folder was copied. - */ - ITEM_COPY("ITEM_COPY"), - - /** - * A task was assigned. - */ - TASK_ASSIGNMENT_CREATE("TASK_ASSIGNMENT_CREATE"), - - /** - * A task was assignment was completed. - */ - TASK_ASSIGNMENT_COMPLETE("TASK_ASSIGNMENT_COMPLETE"), - - /** - * A task was assignment was updated. - */ - TASK_ASSIGNMENT_UPDATE("TASK_ASSIGNMENT_UPDATE"), - - /** - * A task was created. - */ - TASK_CREATE("TASK_CREATE"), - - /** - * A file was locked. - */ - LOCK_CREATE("LOCK_CREATE"), - - /** - * A file was unlocked. - */ - LOCK_DESTROY("LOCK_DESTROY"), - - /** - * A file or folder was deleted. - */ - ITEM_TRASH("ITEM_TRASH"), - - /** - * A file or folder was recovered from the trash. - */ - ITEM_UNDELETE_VIA_TRASH("ITEM_UNDELETE_VIA_TRASH"), - - /** - * A collaborator was added to a folder. - */ - COLLAB_ADD_COLLABORATOR("COLLAB_ADD_COLLABORATOR"), - - /** - * A collaborator's role was change in a folder. - */ - COLLAB_ROLE_CHANGE("COLLAB_ROLE_CHANGE"), - - /** - * A collaborator was invited to a folder. - */ - COLLAB_INVITE_COLLABORATOR("COLLAB_INVITE_COLLABORATOR"), - - /** - * A collaborator was removed from a folder. - */ - COLLAB_REMOVE_COLLABORATOR("COLLAB_REMOVE_COLLABORATOR"), - - /** - * A folder was marked for sync. - */ - ITEM_SYNC("ITEM_SYNC"), - - /** - * A folder was un-marked for sync. - */ - ITEM_UNSYNC("ITEM_UNSYNC"), - - /** - * A file or folder was renamed. - */ - ITEM_RENAME("ITEM_RENAME"), - - /** - * A file or folder was enabled for sharing. - */ - ITEM_SHARED_CREATE("ITEM_SHARED_CREATE"), - - /** - * A file or folder was disabled for sharing. - */ - ITEM_SHARED_UNSHARE("ITEM_SHARED_UNSHARE"), - - /** - * A folder was shared. - */ - ITEM_SHARED("ITEM_SHARED"), - - /** - * A previous version of a file was promoted to the current version. - */ - ITEM_MAKE_CURRENT_VERSION("ITEM_MAKE_CURRENT_VERSION"), - - /** - * A tag was added to a file or folder. - */ - TAG_ITEM_CREATE("TAG_ITEM_CREATE"), - - /** - * 2 factor authentication enabled by user. - */ - ENABLE_TWO_FACTOR_AUTH("ENABLE_TWO_FACTOR_AUTH"), - - /** - * Free user accepts invitation to become a managed user. - */ - ADMIN_INVITE_ACCEPT("MASTER_INVITE_ACCEPT"), - - /** - * Free user rejects invitation to become a managed user. - */ - ADMIN_INVITE_REJECT("MASTER_INVITE_REJECT"), - - /** - * Granted Box access to account. - */ - ACCESS_GRANTED("ACCESS_GRANTED"), - - /** - * Revoke Box access to account. - */ - ACCESS_REVOKED("ACCESS_REVOKED"), - - /** - * A user logged in from a new device. - */ - ADD_LOGIN_ACTIVITY_DEVICE("ADD_LOGIN_ACTIVITY_DEVICE"), - - /** - * A user session associated with an app was invalidated. - */ - REMOVE_LOGIN_ACTIVITY_DEVICE("REMOVE_LOGIN_ACTIVITY_DEVICE"), - - /** - * An admin role changed for a user. - */ - CHANGE_ADMIN_ROLE("CHANGE_ADMIN_ROLE"), - - /** - * A user was added to a group. This is an enterprise-only event. - */ - GROUP_ADD_USER("GROUP_ADD_USER"), - - /** - * A user was created. This is an enterprise-only event. - */ - NEW_USER("NEW_USER"), - - /** - * A group was created. This is an enterprise-only event. - */ - GROUP_CREATION("GROUP_CREATION"), - - /** - * A group was deleted. This is an enterprise-only event. - */ - GROUP_DELETION("GROUP_DELETION"), - - /** - * A user was deleted. This is an enterprise-only event. - */ - DELETE_USER("DELETE_USER"), - - /** - * A group was edited. This is an enterprise-only event. - */ - GROUP_EDITED("GROUP_EDITED"), - - /** - * A user was edited. This is an enterprise-only event. - */ - EDIT_USER("EDIT_USER"), - - /** - * A group was granted access to a folder. This is an enterprise-only event. - */ - GROUP_ADD_FOLDER("GROUP_ADD_FOLDER"), - - /** - * A group was granted access to a file. This is an enterprise-only event. - */ - GROUP_ADD_FILE("GROUP_ADD_FILE"), - - /** - * A user was removed from a group. This is an enterprise-only event. - */ - GROUP_REMOVE_USER("GROUP_REMOVE_USER"), - - /** - * A group had its access to a folder removed. This is an enterprise-only event. - */ - GROUP_REMOVE_FOLDER("GROUP_REMOVE_FOLDER"), - - /** - * A group had its access to a file removed. This is an enterprise-only event. - */ - GROUP_REMOVE_FILE("GROUP_REMOVE_FILE"), - - /** - * An administrator logged in. This is an enterprise-only event. - */ - ADMIN_LOGIN("ADMIN_LOGIN"), - - /** - * A device was associated with a user. This is an enterprise-only event. - */ - ADD_DEVICE_ASSOCIATION("ADD_DEVICE_ASSOCIATION"), - - /** - * There was a failed login attempt. This is an enterprise-only event. - */ - FAILED_LOGIN("FAILED_LOGIN"), - - /** - * There was a successful login. This is an enterprise-only event. - */ - LOGIN("LOGIN"), - - /** - * A user's OAuth2 access token was refreshed. This is an enterprise-only event. - */ - USER_AUTHENTICATE_OAUTH2_TOKEN_REFRESH("USER_AUTHENTICATE_OAUTH2_TOKEN_REFRESH"), - - /** - * A device was disassociated with a user. This is an enterprise-only event. - */ - REMOVE_DEVICE_ASSOCIATION("REMOVE_DEVICE_ASSOCIATION"), - - /** - * A user agreed to the terms of service. This is an enterprise-only event. - */ - TERMS_OF_SERVICE_AGREE("TERMS_OF_SERVICE_AGREE"), - - /** - * A user rejected the terms of service. This is an enterprise-only event. - */ - TERMS_OF_SERVICE_REJECT("TERMS_OF_SERVICE_REJECT"), - - /** - * Virus found on a file. Event is only received by enterprises that have opted in to be notified. - * This is an enterprise-only event. - */ - FILE_MARKED_MALICIOUS("FILE_MARKED_MALICIOUS"), - - /** - * An item was copied. This is an enterprise-only event. - */ - COPY("COPY"), - - /** - * An item was deleted. This is an enterprise-only event. - */ - DELETE("DELETE"), - - /** - * An item was downloaded. This is an enterprise-only event. - */ - DOWNLOAD("DOWNLOAD"), - - /** - * An item was edited. This is an enterprise-only event. - */ - EDIT("EDIT"), - - /** - * An item was locked. This is an enterprise-only event. - */ - LOCK("LOCK"), - - /** - * An item was moved. This is an enterprise-only event. - */ - MOVE("MOVE"), - - /** - * An item was previewed. This is an enterprise-only event. - */ - PREVIEW("PREVIEW"), - - /** - * An item was renamed. This is an enterprise-only event. - */ - RENAME("RENAME"), - - /** - * An item was set to be auto-deleted. This is an enterprise-only event. - */ - STORAGE_EXPIRATION("STORAGE_EXPIRATION"), - - /** - * An item was undeleted. This is an enterprise-only event. - */ - UNDELETE("UNDELETE"), - - /** - * An item was unlocked. This is an enterprise-only event. - */ - UNLOCK("UNLOCK"), - - /** - * An item was uploaded. This is an enterprise-only event. - */ - UPLOAD("UPLOAD"), - - /** - * An shared link was created for an item. This is an enterprise-only event. - */ - SHARE("SHARE"), - - /** - * The shared link for an item was updated. This is an enterprise-only event. - */ - ITEM_SHARED_UPDATE("ITEM_SHARED_UPDATE"), - - /** - * The expiration time for a shared link was extended. This is an enterprise-only event. - */ - UPDATE_SHARE_EXPIRATION("UPDATE_SHARE_EXPIRATION"), - - /** - * The expiration time was set for a shared link. This is an enterprise-only event. - */ - SHARE_EXPIRATION("SHARE_EXPIRATION"), - - /** - * The shared link for an item was REMOVE_DEVICE_ASSOCIATION. This is an enterprise-only event. - */ - UNSHARE("UNSHARE"), - - /** - * A user accepted a collaboration invite. This is an enterprise-only event. - */ - COLLABORATION_ACCEPT("COLLABORATION_ACCEPT"), - - /** - * A user's collaboration role was changed. This is an enterprise-only event. - */ - COLLABORATION_ROLE_CHANGE("COLLABORATION_ROLE_CHANGE"), - - /** - * The expiration time for a collaboration was extended. This is an enterprise-only event. - */ - UPDATE_COLLABORATION_EXPIRATION("UPDATE_COLLABORATION_EXPIRATION"), - - /** - * A collaboration was removed from a folder. This is an enterprise-only event. - */ - COLLABORATION_REMOVE("COLLABORATION_REMOVE"), - - /** - * A user was invited to collaborate on a folder. This is an enterprise-only event. - */ - COLLABORATION_INVITE("COLLABORATION_INVITE"), - - /** - * An expiration time was set for a collaboration. This is an enterprise-only event. - */ - COLLABORATION_EXPIRATION("COLLABORATION_EXPIRATION"), - - /** - * Creation of metadata instance. This is an enterprise-only event. - */ - METADATA_INSTANCE_CREATE("METADATA_INSTANCE_CREATE"), - - /** - * Update of metadata instance. This is an enterprise-only event. - */ - METADATA_INSTANCE_UPDATE("METADATA_INSTANCE_UPDATE"), - - /** - * Deletion of metadata instance. This is an enterprise-only event. - */ - METADATA_INSTANCE_DELETE("METADATA_INSTANCE_DELETE"), - - /** - * Content Workflow upload policy violation. This is an enterprise-only event. - */ - CONTENT_WORKFLOW_UPLOAD_POLICY_VIOLATION("CONTENT_WORKFLOW_UPLOAD_POLICY_VIOLATION"), - - /** - * Edit the permissions on a folder. This is an enterprise-only-event. - */ - CHANGE_FOLDER_PERMISSION("CHANGE_FOLDER_PERMISSION"), - - /** - * A task assignment is deleted. This is an enterprise-only event. - */ - TASK_ASSIGNMENT_DELETE("TASK_ASSIGNMENT_DELETE"), - - /** - * Retention is removed. This is an enterprise-only event. - */ - DATA_RETENTION_REMOVE_RETENTION("DATA_RETENTION_REMOVE_RETENTION"), - - /** - * Retention is created. This is an enterprise-only event. - */ - DATA_RETENTION_CREATE_RETENTION("DATA_RETENTION_CREATE_RETENTION"), - - /** - * A retention policy assignment is added. This is an enterprise-only event. - */ - RETENTION_POLICY_ASSIGNMENT_ADD("RETENTION_POLICY_ASSIGNMENT_ADD"), - - /** - * A legal hold assignment is created. This is an enterprise-only event. - */ - LEGAL_HOLD_ASSIGNMENT_CREATE("LEGAL_HOLD_ASSIGNMENT_CREATE"), - - /** - * A legal hold assignment is deleted. This is an enterprise-only event. - */ - LEGAL_HOLD_ASSIGNMENT_DELETE("LEGAL_HOLD_ASSIGNMENT_DELETE"), - - /** - * A legal hold policy is deleted. This is an enterprise-only event. - */ - LEGAL_HOLD_POLICY_DELETE("LEGAL_HOLD_POLICY_DELETE"), - - /** - * There is a sharing policy violation. This is an enterprise-only event. - */ - CONTENT_WORKFLOW_SHARING_POLICY_VIOLATION("CONTENT_WORKFLOW_SHARING_POLICY_VIOLATION"), - - /** - * An application public key is added. This is an enterprise-only event. - */ - APPLICATION_PUBLIC_KEY_ADDED("APPLICATION_PUBLIC_KEY_ADDED"), - - /** - * An application public key is deleted. This is an enterprise-only event. - */ - APPLICATION_PUBLIC_KEY_DELETED("APPLICATION_PUBLIC_KEY_DELETED"), - - /** - * A content policy is added. This is an enterprise-only event. - */ - CONTENT_WORKFLOW_POLICY_ADD("CONTENT_WORKFLOW_POLICY_ADD"), - - /** - * An automation is added. This is an enterprise-only event. - */ - CONTENT_WORKFLOW_AUTOMATION_ADD("CONTENT_WORKFLOW_AUTOMATION_ADD"), - - /** - * An automation is deleted. This is an enterprise-only event. - */ - CONTENT_WORKFLOW_AUTOMATION_DELETE("CONTENT_WORKFLOW_AUTOMATION_DELETE"), - - /** - * A user email alias is confirmed. This is an enterprise-only event. - */ - EMAIL_ALIAS_CONFIRM("EMAIL_ALIAS_CONFIRM"), - - /** - * A user email alias is removed. This is an enterprise-only event. - */ - EMAIL_ALIAS_REMOVE("EMAIL_ALIAS_REMOVE"), - - /** - * A watermark is added to a file. This is an enterprise-only event. - */ - WATERMARK_LABEL_CREATE("WATERMARK_LABEL_CREATE"), - - /** - * A watermark is removed from a file. This is an enterprise-only event. - */ - WATERMARK_LABEL_DELETE("WATERMARK_LABEL_DELETE"), - - /** - * Creation of metadata template instance. This is an enterprise-only event. - */ - METADATA_TEMPLATE_CREATE("METADATA_TEMPLATE_CREATE"), - - /** - * Update of metadata template instance. This is an enterprise-only event. - */ - METADATA_TEMPLATE_UPDATE("METADATA_TEMPLATE_UPDATE"), - - /** - * Deletion of metadata template instance. This is an enterprise-only event. - */ - METADATA_TEMPLATE_DELETE("METADATA_TEMPLATE_DELETE"), - - /** - * Item was opened. This is an enterprise-only event. - */ - ITEM_OPEN("ITEM_OPEN"), - - /** - * Item was modified. This is an enterprise-only event. - */ - ITEM_MODIFY("ITEM_MODIFY"), - - /** - * When a policy set in the Admin console is triggered. This is an enterprise-only event, - */ - CONTENT_WORKFLOW_ABNORMAL_DOWNLOAD_ACTIVITY("CONTENT_WORKFLOW_ABNORMAL_DOWNLOAD_ACTIVITY"), - - /** - * Folders were removed from a group in the Admin console. This is an enterprise-only event. - */ - GROUP_REMOVE_ITEM("GROUP_REMOVE_ITEM"), - - /** - * Folders were added to a group in the Admin console. This is an enterprise-only event. - */ - GROUP_ADD_ITEM("GROUP_ADD_ITEM"), - - /** - * An OAuth2 access token was created for a user. This is an enterprise-only event. - */ - USER_AUTHENTICATE_OAUTH2_ACCESS_TOKEN_CREATE("USER_AUTHENTICATE_OAUTH2_ACCESS_TOKEN_CREATE"), - - /** - * Event for file tag updates. - */ - CONTENT_ACCESS("CONTENT_ACCESS"), - - /** - * A Shield justification is approved. - */ - SHIELD_JUSTIFICATION_APPROVAL("SHIELD_JUSTIFICATION_APPROVAL"), - - /** - * A task's comment is edited. - */ - TASK_UPDATE("TASK_UPDATE"), - - /** - * A file is retored to previous version. - */ - FILE_VERSION_RESTORE("FILE_VERSION_RESTORE"), - - /** - * Advanced settings of a folder are updated. - */ - ADVANCED_FOLDER_SETTINGS_UPDATE("ADVANCED_FOLDER_SETTINGS_UPDATE"), - - /** - * A new application is created in the Box Developer Console. - */ - APPLICATION_CREATED("APPLICATION_CREATED"), - - /** - * Device Trust check failed. - */ - DEVICE_TRUST_CHECK_FAILED("DEVICE_TRUST_CHECK_FAILED"), - - /** - * When a JWT application has been authorized or reauthorized. - */ - ENTERPRISE_APP_AUTHORIZATION_UPDATE("ENTERPRISE_APP_AUTHORIZATION_UPDATE"), - - /** - * A watermarked file is downloaded. - */ - FILE_WATERMARKED_DOWNLOAD("FILE_WATERMARKED_DOWNLOAD"), - - /** - * A legal hold policy is created. - */ - LEGAL_HOLD_POLICY_CREATE("LEGAL_HOLD_POLICY_CREATE"), - - /** - * A legal hold policy is updated. - */ - LEGAL_HOLD_POLICY_UPDATE("LEGAL_HOLD_POLICY_UPDATE"), - - /** - * Shield detected an anomalous download, session, location, or malicious content based on - * enterprise Shield rules. See shield alert events for more information. - */ - SHIELD_ALERT("SHIELD_ALERT"), - - /** - * Access to an external collaboration is blocked. - */ - SHIELD_EXTERNAL_COLLAB_ACCESS_BLOCKED("SHIELD_EXTERNAL_COLLAB_ACCESS_BLOCKED"), - - /** - * Access to an external collaboration is blocked due to missing a justification. - */ - SHIELD_EXTERNAL_COLLAB_ACCESS_BLOCKED_MISSING_JUSTIFICATION( - "SHIELD_EXTERNAL_COLLAB_ACCESS_BLOCKED_MISSING_JUSTIFICATION"), - - /** - * An invite to externally collaborate is blocked. - */ - SHIELD_EXTERNAL_COLLAB_INVITE_BLOCKED("SHIELD_EXTERNAL_COLLAB_INVITE_BLOCKED"), - - /** - * An invite to externally collaborate is blocked due to missing a justification. - */ - SHIELD_EXTERNAL_COLLAB_INVITE_BLOCKED_MISSING_JUSTIFICATION( - "SHIELD_EXTERNAL_COLLAB_INVITE_BLOCKED_MISSING_JUSTIFICATION"), - - /** - * A sign request was sent to a signer. - */ - SIGN_DOCUMENT_ASSIGNED("SIGN_DOCUMENT_ASSIGNED"), - - /** - * A sign request was cancelled via API or UI. - */ - SIGN_DOCUMENT_CANCELLED("SIGN_DOCUMENT_CANCELLED"), - - /** - * A sign request was signed by all signers. - */ - SIGN_DOCUMENT_COMPLETED("SIGN_DOCUMENT_COMPLETED"), - - /** - * A sign request was converted to a .pdf for signing. - */ - SIGN_DOCUMENT_CONVERTED("SIGN_DOCUMENT_CONVERTED"), - - /** - * A sign request was created via API or UI. The document is not yet sent to signers. - */ - SIGN_DOCUMENT_CREATED("SIGN_DOCUMENT_CREATED"), - - /** - * A sign request was declined by a signer. - */ - SIGN_DOCUMENT_DECLINED("SIGN_DOCUMENT_DECLINED"), - - /** - * A sign request expired with incomplete signatures. - */ - SIGN_DOCUMENT_EXPIRED("SIGN_DOCUMENT_EXPIRED"), - - /** - * A sign request was signed by a signer. - */ - SIGN_DOCUMENT_SIGNED("SIGN_DOCUMENT_SIGNED"), - - /** - * A signer clicked on Review Document in the signer email or visited the signing URL. - */ - SIGN_DOCUMENT_VIEWED_BY_SIGNER("SIGN_DOCUMENT_VIEWED_BY_SIGNER"), - - /** - * A signer downloaded the signing document. - */ - SIGNER_DOWNLOADED("SIGNER_DOWNLOADED"), - - /** - * A signer forwarded the signing document. - */ - SIGNER_FORWARDED("SIGNER_FORWARDED"), - - /** - * Accepted terms. - */ - TERMS_OF_SERVICE_ACCEPT("TERMS_OF_SERVICE_ACCEPT"); - - /** - * Static map of all EventTypes. - */ - private static final Map EVENT_TYPE_MAP = new HashMap<>(EventType.values().length); - - /* - EVENT_TYPE_MAP initialization. - */ - static { - for (BoxEvent.EventType event : BoxEvent.EventType.values()) { - EVENT_TYPE_MAP.put(event.jsonValue, event); - } - } - - /** - * String representation of the eventType. - */ - private final String jsonValue; - - /** - * Constructor. - * - * @param jsonValue string representation of the eventType. - */ - EventType(String jsonValue) { - this.jsonValue = jsonValue; - } - - /** - * Custom implementation of valueOf(). - * - * @param jsonValue of the EventType. - * @return EventType. - */ - static BoxEvent.EventType lookupByValue(String jsonValue) { - return EVENT_TYPE_MAP.get(jsonValue); - } - - /** - * @return string representation of the eventType. - */ - String toJSONString() { - return this.jsonValue; - } + /** @return string representation of the eventType. */ + String toJSONString() { + return this.jsonValue; } + } } diff --git a/src/main/java/com/box/sdk/BoxFile.java b/src/main/java/com/box/sdk/BoxFile.java index 61e37d0ca..25560f7d8 100644 --- a/src/main/java/com/box/sdk/BoxFile.java +++ b/src/main/java/com/box/sdk/BoxFile.java @@ -30,2049 +30,2091 @@ import java.util.Set; import java.util.concurrent.TimeUnit; - /** - * Represents an individual file on Box. This class can be used to download a file's contents, upload new versions, and - * perform other common file operations (move, copy, delete, etc.). + * Represents an individual file on Box. This class can be used to download a file's contents, + * upload new versions, and perform other common file operations (move, copy, delete, etc.). * - *

Unless otherwise noted, the methods in this class can throw an unchecked {@link BoxAPIException} (unchecked - * meaning that the compiler won't force you to handle it) if an error occurs. If you wish to implement custom error - * handling for errors related to the Box REST API, you should capture this exception explicitly. + *

Unless otherwise noted, the methods in this class can throw an unchecked {@link + * BoxAPIException} (unchecked meaning that the compiler won't force you to handle it) if an error + * occurs. If you wish to implement custom error handling for errors related to the Box REST API, + * you should capture this exception explicitly. */ @BoxResourceType("file") public class BoxFile extends BoxItem { - /** - * An array of all possible file fields that can be requested when calling {@link #getInfo(String...)}. - */ - public static final String[] ALL_FIELDS = {"type", "id", "sequence_id", "etag", "sha1", "name", - "description", "size", "path_collection", "created_at", "modified_at", - "trashed_at", "purged_at", "content_created_at", "content_modified_at", - "created_by", "modified_by", "owned_by", "shared_link", "parent", - "item_status", "version_number", "comment_count", "permissions", "tags", - "lock", "extension", "is_package", "file_version", "collections", - "watermark_info", "metadata", "representations", - "is_external_only", "expiring_embed_link", "allowed_invitee_roles", - "has_collaborations", "disposition_at", "is_accessible_via_shared_link"}; - - /** - * An array of all possible version fields that can be requested when calling {@link #getVersions(String...)}. - */ - public static final String[] ALL_VERSION_FIELDS = {"id", "sha1", "name", "size", "uploader_display_name", - "created_at", "modified_at", "modified_by", "trashed_at", "trashed_by", "restored_at", "restored_by", - "purged_at", "file_version", "version_number"}; - /** - * File URL Template. - */ - public static final URLTemplate FILE_URL_TEMPLATE = new URLTemplate("files/%s"); - /** - * Content URL Template. - */ - public static final URLTemplate CONTENT_URL_TEMPLATE = new URLTemplate("files/%s/content"); - /** - * Versions URL Template. - */ - public static final URLTemplate VERSIONS_URL_TEMPLATE = new URLTemplate("files/%s/versions"); - /** - * Copy URL Template. - */ - public static final URLTemplate COPY_URL_TEMPLATE = new URLTemplate("files/%s/copy"); - /** - * Add Comment URL Template. - */ - public static final URLTemplate ADD_COMMENT_URL_TEMPLATE = new URLTemplate("comments"); - /** - * Get Comments URL Template. - */ - public static final URLTemplate GET_COMMENTS_URL_TEMPLATE = new URLTemplate("files/%s/comments"); - /** - * Metadata URL Template. - */ - public static final URLTemplate METADATA_URL_TEMPLATE = new URLTemplate("files/%s/metadata/%s/%s"); - /** - * Add Task URL Template. - */ - public static final URLTemplate ADD_TASK_URL_TEMPLATE = new URLTemplate("tasks"); - /** - * Get Tasks URL Template. - */ - public static final URLTemplate GET_TASKS_URL_TEMPLATE = new URLTemplate("files/%s/tasks"); - /** - * Get Thumbnail PNG Template. - */ - public static final URLTemplate GET_THUMBNAIL_PNG_TEMPLATE = new URLTemplate("files/%s/thumbnail.png"); - /** - * Get Thumbnail JPG Template. - */ - public static final URLTemplate GET_THUMBNAIL_JPG_TEMPLATE = new URLTemplate("files/%s/thumbnail.jpg"); - /** - * Upload Session URL Template. - */ - public static final URLTemplate UPLOAD_SESSION_URL_TEMPLATE = new URLTemplate("files/%s/upload_sessions"); - /** - * Upload Session Status URL Template. - */ - public static final URLTemplate UPLOAD_SESSION_STATUS_URL_TEMPLATE = new URLTemplate( - "files/upload_sessions/%s/status"); - /** - * Abort Upload Session URL Template. - */ - public static final URLTemplate ABORT_UPLOAD_SESSION_URL_TEMPLATE = new URLTemplate("files/upload_sessions/%s"); - /** - * Add Collaborations URL Template. - */ - public static final URLTemplate ADD_COLLABORATION_URL = new URLTemplate("collaborations"); - /** - * Get All File Collaborations URL Template. - */ - public static final URLTemplate GET_ALL_FILE_COLLABORATIONS_URL = new URLTemplate("files/%s/collaborations"); - /** - * Describes file item type. - */ - static final String TYPE = "file"; - private static final int GET_COLLABORATORS_PAGE_SIZE = 1000; - - /** - * Constructs a BoxFile for a file with a given ID. - * - * @param api the API connection to be used by the file. - * @param id the ID of the file. - */ - public BoxFile(BoxAPIConnection api, String id) { - super(api, id); - } - - /** - * {@inheritDoc} - */ - @Override - protected URL getItemURL() { - return FILE_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - } - - /** - * Creates a shared link. - * - * @param sharedLinkRequest Shared link to create - * @return Created shared link. - */ - public BoxSharedLink createSharedLink(BoxSharedLinkRequest sharedLinkRequest) { - return createSharedLink(sharedLinkRequest.asSharedLink()); - } - - private BoxSharedLink createSharedLink(BoxSharedLink sharedLink) { - Info info = new Info(); - info.setSharedLink(sharedLink); - - this.updateInfo(info); - return info.getSharedLink(); - } - - /** - * Adds new {@link BoxWebHook} to this {@link BoxFile}. - * - * @param address {@link BoxWebHook.Info#getAddress()} - * @param triggers {@link BoxWebHook.Info#getTriggers()} - * @return created {@link BoxWebHook.Info} - */ - public BoxWebHook.Info addWebHook(URL address, BoxWebHook.Trigger... triggers) { - return BoxWebHook.create(this, address, triggers); - } - - /** - * Adds a comment to this file. The message can contain @mentions by using the string @[userid:username] anywhere - * within the message, where userid and username are the ID and username of the person being mentioned. - * - * @param message the comment's message. - * @return information about the newly added comment. - * @see the tagged_message field - * for including @mentions. - */ - public BoxComment.Info addComment(String message) { - JsonObject itemJSON = new JsonObject(); - itemJSON.add("type", "file"); - itemJSON.add("id", this.getID()); - - JsonObject requestJSON = new JsonObject(); - requestJSON.add("item", itemJSON); - if (BoxComment.messageContainsMention(message)) { - requestJSON.add("tagged_message", message); + /** + * An array of all possible file fields that can be requested when calling {@link + * #getInfo(String...)}. + */ + public static final String[] ALL_FIELDS = { + "type", + "id", + "sequence_id", + "etag", + "sha1", + "name", + "description", + "size", + "path_collection", + "created_at", + "modified_at", + "trashed_at", + "purged_at", + "content_created_at", + "content_modified_at", + "created_by", + "modified_by", + "owned_by", + "shared_link", + "parent", + "item_status", + "version_number", + "comment_count", + "permissions", + "tags", + "lock", + "extension", + "is_package", + "file_version", + "collections", + "watermark_info", + "metadata", + "representations", + "is_external_only", + "expiring_embed_link", + "allowed_invitee_roles", + "has_collaborations", + "disposition_at", + "is_accessible_via_shared_link" + }; + + /** + * An array of all possible version fields that can be requested when calling {@link + * #getVersions(String...)}. + */ + public static final String[] ALL_VERSION_FIELDS = { + "id", + "sha1", + "name", + "size", + "uploader_display_name", + "created_at", + "modified_at", + "modified_by", + "trashed_at", + "trashed_by", + "restored_at", + "restored_by", + "purged_at", + "file_version", + "version_number" + }; + /** File URL Template. */ + public static final URLTemplate FILE_URL_TEMPLATE = new URLTemplate("files/%s"); + /** Content URL Template. */ + public static final URLTemplate CONTENT_URL_TEMPLATE = new URLTemplate("files/%s/content"); + /** Versions URL Template. */ + public static final URLTemplate VERSIONS_URL_TEMPLATE = new URLTemplate("files/%s/versions"); + /** Copy URL Template. */ + public static final URLTemplate COPY_URL_TEMPLATE = new URLTemplate("files/%s/copy"); + /** Add Comment URL Template. */ + public static final URLTemplate ADD_COMMENT_URL_TEMPLATE = new URLTemplate("comments"); + /** Get Comments URL Template. */ + public static final URLTemplate GET_COMMENTS_URL_TEMPLATE = new URLTemplate("files/%s/comments"); + /** Metadata URL Template. */ + public static final URLTemplate METADATA_URL_TEMPLATE = + new URLTemplate("files/%s/metadata/%s/%s"); + /** Add Task URL Template. */ + public static final URLTemplate ADD_TASK_URL_TEMPLATE = new URLTemplate("tasks"); + /** Get Tasks URL Template. */ + public static final URLTemplate GET_TASKS_URL_TEMPLATE = new URLTemplate("files/%s/tasks"); + /** Get Thumbnail PNG Template. */ + public static final URLTemplate GET_THUMBNAIL_PNG_TEMPLATE = + new URLTemplate("files/%s/thumbnail.png"); + /** Get Thumbnail JPG Template. */ + public static final URLTemplate GET_THUMBNAIL_JPG_TEMPLATE = + new URLTemplate("files/%s/thumbnail.jpg"); + /** Upload Session URL Template. */ + public static final URLTemplate UPLOAD_SESSION_URL_TEMPLATE = + new URLTemplate("files/%s/upload_sessions"); + /** Upload Session Status URL Template. */ + public static final URLTemplate UPLOAD_SESSION_STATUS_URL_TEMPLATE = + new URLTemplate("files/upload_sessions/%s/status"); + /** Abort Upload Session URL Template. */ + public static final URLTemplate ABORT_UPLOAD_SESSION_URL_TEMPLATE = + new URLTemplate("files/upload_sessions/%s"); + /** Add Collaborations URL Template. */ + public static final URLTemplate ADD_COLLABORATION_URL = new URLTemplate("collaborations"); + /** Get All File Collaborations URL Template. */ + public static final URLTemplate GET_ALL_FILE_COLLABORATIONS_URL = + new URLTemplate("files/%s/collaborations"); + /** Describes file item type. */ + static final String TYPE = "file"; + + private static final int GET_COLLABORATORS_PAGE_SIZE = 1000; + + /** + * Constructs a BoxFile for a file with a given ID. + * + * @param api the API connection to be used by the file. + * @param id the ID of the file. + */ + public BoxFile(BoxAPIConnection api, String id) { + super(api, id); + } + + /** {@inheritDoc} */ + @Override + protected URL getItemURL() { + return FILE_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + } + + /** + * Creates a shared link. + * + * @param sharedLinkRequest Shared link to create + * @return Created shared link. + */ + public BoxSharedLink createSharedLink(BoxSharedLinkRequest sharedLinkRequest) { + return createSharedLink(sharedLinkRequest.asSharedLink()); + } + + private BoxSharedLink createSharedLink(BoxSharedLink sharedLink) { + Info info = new Info(); + info.setSharedLink(sharedLink); + + this.updateInfo(info); + return info.getSharedLink(); + } + + /** + * Adds new {@link BoxWebHook} to this {@link BoxFile}. + * + * @param address {@link BoxWebHook.Info#getAddress()} + * @param triggers {@link BoxWebHook.Info#getTriggers()} + * @return created {@link BoxWebHook.Info} + */ + public BoxWebHook.Info addWebHook(URL address, BoxWebHook.Trigger... triggers) { + return BoxWebHook.create(this, address, triggers); + } + + /** + * Adds a comment to this file. The message can contain @mentions by using the + * string @[userid:username] anywhere within the message, where userid and username are the ID and + * username of the person being mentioned. + * + * @param message the comment's message. + * @return information about the newly added comment. + * @see the + * tagged_message field for including @mentions. + */ + public BoxComment.Info addComment(String message) { + JsonObject itemJSON = new JsonObject(); + itemJSON.add("type", "file"); + itemJSON.add("id", this.getID()); + + JsonObject requestJSON = new JsonObject(); + requestJSON.add("item", itemJSON); + if (BoxComment.messageContainsMention(message)) { + requestJSON.add("tagged_message", message); + } else { + requestJSON.add("message", message); + } + + URL url = ADD_COMMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); + request.setBody(requestJSON.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + + BoxComment addedComment = new BoxComment(this.getAPI(), responseJSON.get("id").asString()); + return addedComment.new Info(responseJSON); + } + } + + /** + * Adds a new task to this file. The task can have an optional message to include, and a due date. + * + * @param action the action the task assignee will be prompted to do. + * @param message an optional message to include with the task. + * @param dueAt the day at which this task is due. + * @return information about the newly added task. + */ + public BoxTask.Info addTask(BoxTask.Action action, String message, Date dueAt) { + return this.addTask(action, message, dueAt, null); + } + + /** + * Adds a new task to this file. The task can have an optional message to include, due date, and + * task completion rule. + * + * @param action the action the task assignee will be prompted to do. + * @param message an optional message to include with the task. + * @param dueAt the day at which this task is due. + * @param completionRule the rule for completing the task. + * @return information about the newly added task. + */ + public BoxTask.Info addTask( + BoxTask.Action action, String message, Date dueAt, BoxTask.CompletionRule completionRule) { + JsonObject itemJSON = new JsonObject(); + itemJSON.add("type", "file"); + itemJSON.add("id", this.getID()); + + JsonObject requestJSON = new JsonObject(); + requestJSON.add("item", itemJSON); + requestJSON.add("action", action.toJSONString()); + + if (message != null && !message.isEmpty()) { + requestJSON.add("message", message); + } + + if (dueAt != null) { + requestJSON.add("due_at", BoxDateFormat.format(dueAt)); + } + + if (completionRule != null) { + requestJSON.add("completion_rule", completionRule.toJSONString()); + } + + URL url = ADD_TASK_URL_TEMPLATE.build(this.getAPI().getBaseURL()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); + request.setBody(requestJSON.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + + BoxTask addedTask = new BoxTask(this.getAPI(), responseJSON.get("id").asString()); + return addedTask.new Info(responseJSON); + } + } + + /** + * Gets an expiring URL for downloading a file directly from Box. This can be user, for example, + * for sending as a redirect to a browser to cause the browser to download the file directly from + * Box. + * + * @return the temporary download URL + */ + public URL getDownloadURL() { + URL url = getDownloadUrl(); + BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); + request.setFollowRedirects(false); + + try (BoxAPIResponse response = request.send()) { + String location = response.getHeaderField("location"); + + try { + return new URL(location); + } catch (MalformedURLException e) { + throw new RuntimeException(e); + } + } + } + + /** + * Downloads the contents of this file to a given OutputStream. + * + * @param output the stream to where the file will be written. + */ + public void download(OutputStream output) { + this.download(output, null); + } + + /** + * Downloads the contents of this file to a given OutputStream while reporting the progress to a + * ProgressListener. + * + * @param output the stream to where the file will be written. + * @param listener a listener for monitoring the download's progress. + */ + public void download(OutputStream output, ProgressListener listener) { + URL url = getDownloadUrl(); + BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); + BoxAPIResponse response = request.send(); + writeStream(response, output, listener); + } + + /** + * Downloads the content of the file to a given OutputStream using the provided shared link. + * + * @param api the API connection to be used to get download URL of the file. + * @param output the stream to where the file will be written. + * @param sharedLink the shared link of the file. + */ + public static void downloadFromSharedLink( + BoxAPIConnection api, OutputStream output, String sharedLink) { + downloadFromSharedLink(api, output, sharedLink, null, null); + } + + /** + * Downloads the content of the file to a given OutputStream using the provided shared link. + * + * @param api the API connection to be used to get download URL of the file. + * @param output the stream to where the file will be written. + * @param sharedLink the shared link of the file. + * @param password the password for the shared link. + */ + public static void downloadFromSharedLink( + BoxAPIConnection api, OutputStream output, String sharedLink, String password) { + downloadFromSharedLink(api, output, sharedLink, password, null); + } + + /** + * Downloads the content of the file to a given OutputStream using the provided shared link. + * + * @param api the API connection to be used to get download URL of the file. + * @param output the stream to where the file will be written. + * @param sharedLink the shared link of the file. + * @param listener a listener for monitoring the download's progress. + */ + public static void downloadFromSharedLink( + BoxAPIConnection api, OutputStream output, String sharedLink, ProgressListener listener) { + downloadFromSharedLink(api, output, sharedLink, null, listener); + } + + /** + * Downloads the content of the file to a given OutputStream using the provided shared link. + * + * @param api the API connection to be used to get download URL of the file. + * @param output the stream to where the file will be written. + * @param sharedLink the shared link of the file. + * @param password the password for the shared link. + * @param listener a listener for monitoring the download's progress. + */ + public static void downloadFromSharedLink( + BoxAPIConnection api, + OutputStream output, + String sharedLink, + String password, + ProgressListener listener) { + BoxItem.Info item = BoxItem.getSharedItem(api, sharedLink, password, "id"); + if (!(item instanceof BoxFile.Info)) { + throw new BoxAPIException("The shared link provided is not a shared link for a file."); + } + BoxFile sharedFile = new BoxFile(api, item.getID()); + URL url = sharedFile.getDownloadUrl(); + BoxAPIRequest request = new BoxAPIRequest(api, url, "GET"); + request.addHeader("BoxApi", BoxSharedLink.getSharedLinkHeaderValue(sharedLink, password)); + BoxAPIResponse response = request.send(); + writeStream(response, output, listener); + } + + /** + * Downloads a part of this file's contents, starting at specified byte offset. + * + * @param output the stream to where the file will be written. + * @param offset the byte offset at which to start the download. + */ + public void downloadRange(OutputStream output, long offset) { + this.downloadRange(output, offset, -1); + } + + /** + * Downloads a part of this file's contents, starting at rangeStart and stopping at rangeEnd. + * + * @param output the stream to where the file will be written. + * @param rangeStart the byte offset at which to start the download. + * @param rangeEnd the byte offset at which to stop the download. + */ + public void downloadRange(OutputStream output, long rangeStart, long rangeEnd) { + this.downloadRange(output, rangeStart, rangeEnd, null); + } + + /** + * Downloads a part of this file's contents, starting at rangeStart and stopping at rangeEnd, + * while reporting the progress to a ProgressListener. + * + * @param output the stream to where the file will be written. + * @param rangeStart the byte offset at which to start the download. + * @param rangeEnd the byte offset at which to stop the download. + * @param listener a listener for monitoring the download's progress. + */ + public void downloadRange( + OutputStream output, long rangeStart, long rangeEnd, ProgressListener listener) { + URL url = getDownloadUrl(); + BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); + if (rangeEnd > 0) { + request.addHeader("Range", String.format("bytes=%s-%s", rangeStart, rangeEnd)); + } else { + request.addHeader("Range", String.format("bytes=%s-", rangeStart)); + } + writeStream(request.send(), output, listener); + } + + /** + * Can be used to override the URL used for file download. + * + * @return URL for file downalod + */ + protected URL getDownloadUrl() { + return CONTENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + } + + @Override + public BoxFile.Info copy(BoxFolder destination) { + return this.copy(destination, null); + } + + @Override + public BoxFile.Info copy(BoxFolder destination, String newName) { + URL url = COPY_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + + JsonObject parent = new JsonObject(); + parent.add("id", destination.getID()); + + JsonObject copyInfo = new JsonObject(); + copyInfo.add("parent", parent); + if (newName != null) { + copyInfo.add("name", newName); + } + + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); + request.setBody(copyInfo.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + BoxFile copiedFile = new BoxFile(this.getAPI(), responseJSON.get("id").asString()); + return copiedFile.new Info(responseJSON); + } + } + + /** Deletes this file by moving it to the trash. */ + public void delete() { + URL url = FILE_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); + request.send().close(); + } + + @Override + public BoxItem.Info move(BoxFolder destination) { + return this.move(destination, null); + } + + @Override + public BoxItem.Info move(BoxFolder destination, String newName) { + URL url = FILE_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); + + JsonObject parent = new JsonObject(); + parent.add("id", destination.getID()); + + JsonObject updateInfo = new JsonObject(); + updateInfo.add("parent", parent); + if (newName != null) { + updateInfo.add("name", newName); + } + + request.setBody(updateInfo.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + BoxFile movedFile = new BoxFile(this.getAPI(), responseJSON.get("id").asString()); + return movedFile.new Info(responseJSON); + } + } + + /** + * Renames this file. + * + * @param newName the new name of the file. + */ + public void rename(String newName) { + URL url = FILE_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); + + JsonObject updateInfo = new JsonObject(); + updateInfo.add("name", newName); + + request.setBody(updateInfo.toString()); + try (BoxJSONResponse response = request.send()) { + response.getJSON(); + } + } + + @Override + public BoxFile.Info getInfo(String... fields) { + URL url = FILE_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + if (fields.length > 0) { + String queryString = new QueryStringBuilder().appendParam("fields", fields).toString(); + url = FILE_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID()); + } + + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); + try (BoxJSONResponse response = request.send()) { + return new Info(response.getJSON()); + } + } + + /** + * Gets information about this item including a specified set of representations. + * + * @param representationHints hints for representations to be retrieved + * @param fields the fields to retrieve. + * @return info about this item containing only the specified fields, including representations. + * @see X-Rep-Hints + * Header + */ + public BoxFile.Info getInfoWithRepresentations(String representationHints, String... fields) { + if (representationHints.matches(Representation.X_REP_HINTS_PATTERN)) { + // Since the user intends to get representations, add it to fields, even if user has missed it + Set fieldsSet = new HashSet<>(Arrays.asList(fields)); + fieldsSet.add("representations"); + String queryString = + new QueryStringBuilder() + .appendParam("fields", fieldsSet.toArray(new String[0])) + .toString(); + URL url = + FILE_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID()); + + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); + request.addHeader("X-Rep-Hints", representationHints); + try (BoxJSONResponse response = request.send()) { + return new Info(response.getJSON()); + } + } else { + throw new BoxAPIException( + "Represention hints is not valid. Refer documention on how to construct X-Rep-Hints Header"); + } + } + + /** + * Fetches the contents of a file representation and writes them to the provided output stream. + * + * @param representationHint the X-Rep-Hints query for the representation to fetch. + * @param output the output stream to write the contents to. + * @see X-Rep-Hints + * Header + */ + public void getRepresentationContent(String representationHint, OutputStream output) { + + this.getRepresentationContent(representationHint, "", output); + } + + /** + * Fetches the contents of a file representation with asset path and writes them to the provided + * output stream. + * + * @param representationHint the X-Rep-Hints query for the representation to fetch. + * @param assetPath the path of the asset for representations containing multiple files. + * @param output the output stream to write the contents to. + * @see X-Rep-Hints + * Header + */ + public void getRepresentationContent( + String representationHint, String assetPath, OutputStream output) { + this.getRepresentationContent(representationHint, assetPath, output, Integer.MAX_VALUE); + } + + /** + * Fetches the contents of a file representation with asset path and writes them to the provided + * output stream. + * + * @param representationHint the X-Rep-Hints query for the representation to fetch. + * @param assetPath the path of the asset for representations containing multiple files. + * @param output the output stream to write the contents to. + * @param maxRetries the maximum number of attempts to call the request for retrieving status + * information indicating whether the representation has been generated and is ready to fetch. + * If the number of attempts is exceeded, the method will throw a BoxApiException. + * @see X-Rep-Hints + * Header + */ + public void getRepresentationContent( + String representationHint, String assetPath, OutputStream output, int maxRetries) { + List reps = + this.getInfoWithRepresentations(representationHint).getRepresentations(); + if (reps.size() < 1) { + throw new BoxAPIException( + "No matching representations found for requested '" + representationHint + "' hint"); + } + Representation representation = reps.get(0); + String repState = representation.getStatus().getState(); + + switch (repState) { + case "viewable": + case "success": + this.makeRepresentationContentRequest( + representation.getContent().getUrlTemplate(), assetPath, output); + break; + case "pending": + case "none": + String repContentURLString = null; + int attemptNumber = 0; + while (repContentURLString == null && attemptNumber < maxRetries) { + repContentURLString = this.pollRepInfo(representation.getInfo().getUrl()); + try { + Thread.sleep(100); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + attemptNumber++; + } + + if (repContentURLString != null) { + this.makeRepresentationContentRequest(repContentURLString, assetPath, output); } else { - requestJSON.add("message", message); - } + throw new BoxAPIException( + "Representation did not have a success status allowing it to be retrieved after " + + maxRetries + + " attempts"); + } + + break; + case "error": + throw new BoxAPIException("Representation had error status"); + default: + throw new BoxAPIException("Representation had unknown status"); + } + } + + private String pollRepInfo(URL infoURL) { + + BoxJSONRequest infoRequest = new BoxJSONRequest(this.getAPI(), infoURL, HttpMethod.GET); + try (BoxJSONResponse infoResponse = infoRequest.send()) { + JsonObject response = infoResponse.getJsonObject(); + + Representation rep = new Representation(response); + + String repState = rep.getStatus().getState(); + + switch (repState) { + case "viewable": + case "success": + return rep.getContent().getUrlTemplate(); + case "pending": + case "none": + return null; + case "error": + throw new BoxAPIException("Representation had error status"); + default: + throw new BoxAPIException("Representation had unknown status"); + } + } + } + + private void makeRepresentationContentRequest( + String representationURLTemplate, String assetPath, OutputStream output) { + try { + URL repURL = new URL(representationURLTemplate.replace("{+asset_path}", assetPath)); + BoxAPIRequest repContentReq = new BoxAPIRequest(this.getAPI(), repURL, HttpMethod.GET); + BoxAPIResponse response = repContentReq.send(); + writeStreamWithContentLength(response, output); + } catch (MalformedURLException ex) { + + throw new BoxAPIException("Could not generate representation content URL"); + } + } + + /** + * Updates the information about this file with any info fields that have been modified locally. + * + *

The only fields that will be updated are the ones that have been modified locally. For + * example, the following code won't update any information (or even send a network request) since + * none of the info's fields were changed: + * + *

BoxFile file = new File(api, id);
+   * BoxFile.Info info = file.getInfo();
+   * file.updateInfo(info);
+ * + * @param info the updated info. + */ + public void updateInfo(BoxFile.Info info) { + URL url = FILE_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); + request.setBody(info.getPendingChanges()); + try (BoxJSONResponse response = request.send()) { + JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); + info.update(jsonObject); + } + } + + /** + * Retrieve a specific file version. + * + * @param fileVersionID the ID of the file version to retrieve. + * @param fields the optional fields to retrieve. + * @return a specific file version. + */ + public BoxFileVersion getVersionByID(String fileVersionID, String... fields) { + URL url = + BoxFileVersion.VERSION_URL_TEMPLATE.build( + this.getAPI().getBaseURL(), this.getID(), fileVersionID); + if (fields.length > 0) { + String queryString = new QueryStringBuilder().appendParam("fields", fields).toString(); + url = + BoxFileVersion.VERSION_URL_TEMPLATE.buildWithQuery( + this.getAPI().getBaseURL(), queryString, this.getID(), fileVersionID); + } + + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); + return new BoxFileVersion(this.getAPI(), jsonObject, this.getID()); + } + } + + /** + * Gets up to 1000 versions of this file. Note that only users with premium accounts will be able + * to retrieve previous versions of their files. `fields` parameter is optional, if specified only + * requested fields will be returned: + * + *
{@code
+   * new BoxFile(api, file_id).getVersions()       // will return all default fields
+   * new BoxFile(api, file_id).getVersions("name") // will return only specified fields
+   * }
+ * + * @param fields the fields to retrieve. If nothing provided default fields will be returned. You + * can find list of available fields at {@link BoxFile#ALL_VERSION_FIELDS} + * @return a list of previous file versions. + */ + public Collection getVersions(String... fields) { + return getVersionsRange(0, BoxFileVersion.DEFAULT_LIMIT, fields); + } + + /** + * Retrieves a specific range of versions of this file. + * + * @param offset the index of the first version of this file to retrieve. + * @param limit the maximum number of versions to retrieve after the offset. + * @param fields the fields to retrieve. + * @return a partial collection containing the specified range of versions of this file. + */ + public PartialCollection getVersionsRange( + long offset, long limit, String... fields) { + QueryStringBuilder builder = + new QueryStringBuilder().appendParam("limit", limit).appendParam("offset", offset); + + if (fields.length > 0) { + builder.appendParam("fields", fields); + } + + URL url = + VERSIONS_URL_TEMPLATE.buildWithQuery( + this.getAPI().getBaseURL(), builder.toString(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); + try (BoxJSONResponse response = request.send()) { + + JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); + String totalCountString = jsonObject.get("total_count").toString(); + long fullSize = Double.valueOf(totalCountString).longValue(); + PartialCollection versions = new PartialCollection<>(offset, limit, fullSize); + JsonArray entries = jsonObject.get("entries").asArray(); + for (JsonValue entry : entries) { + versions.add(new BoxFileVersion(this.getAPI(), entry.asObject(), this.getID())); + } + + return versions; + } + } + + /** + * Checks if a new version of the file can be uploaded with the specified name. + * + * @param name the new name for the file. + * @return whether or not the file version can be uploaded. + */ + public boolean canUploadVersion(String name) { + return this.canUploadVersion(name, 0); + } + + /** + * Checks if a new version of the file can be uploaded with the specified name and size. + * + * @param name the new name for the file. + * @param fileSize the size of the new version content in bytes. + * @return whether the file version can be uploaded. + */ + public boolean canUploadVersion(String name, long fileSize) { + + URL url = getDownloadUrl(); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "OPTIONS"); + + JsonObject preflightInfo = new JsonObject(); + if (name != null) { + preflightInfo.add("name", name); + } + + preflightInfo.add("size", fileSize); + + request.setBody(preflightInfo.toString()); + try (BoxAPIResponse response = request.send()) { + return response.getResponseCode() == 200; + } catch (BoxAPIException ex) { + if (ex.getResponseCode() >= 400 && ex.getResponseCode() < 500) { + // This looks like an error response, meaning the upload would fail + return false; + } else { + // This looks like a network error or server error, rethrow exception + throw ex; + } + } + } + + /** + * Uploads a new version of this file, replacing the current version. Note that only users with + * premium accounts will be able to view and recover previous versions of the file. + * + * @param fileContent a stream containing the new file contents. + * @return the uploaded file version. + */ + public BoxFile.Info uploadNewVersion(InputStream fileContent) { + return this.uploadNewVersion(fileContent, null); + } + + /** + * Uploads a new version of this file, replacing the current version. Note that only users with + * premium accounts will be able to view and recover previous versions of the file. + * + * @param fileContent a stream containing the new file contents. + * @param fileContentSHA1 a string containing the SHA1 hash of the new file contents. + * @return the uploaded file version. + */ + public BoxFile.Info uploadNewVersion(InputStream fileContent, String fileContentSHA1) { + return this.uploadNewVersion(fileContent, fileContentSHA1, null); + } + + /** + * Uploads a new version of this file, replacing the current version. Note that only users with + * premium accounts will be able to view and recover previous versions of the file. + * + * @param fileContent a stream containing the new file contents. + * @param fileContentSHA1 a string containing the SHA1 hash of the new file contents. + * @param modified the date that the new version was modified. + * @return the uploaded file version. + */ + public BoxFile.Info uploadNewVersion( + InputStream fileContent, String fileContentSHA1, Date modified) { + return this.uploadNewVersion(fileContent, fileContentSHA1, modified, 0, null); + } + + /** + * Uploads a new version of this file, replacing the current version. Note that only users with + * premium accounts will be able to view and recover previous versions of the file. + * + * @param fileContent a stream containing the new file contents. + * @param fileContentSHA1 a string containing the SHA1 hash of the new file contents. + * @param modified the date that the new version was modified. + * @param name the new name for the file + * @return the uploaded file version. + */ + public BoxFile.Info uploadNewVersion( + InputStream fileContent, String fileContentSHA1, Date modified, String name) { + return this.uploadNewVersion(fileContent, fileContentSHA1, modified, name, 0, null); + } + + /** + * Uploads a new version of this file, replacing the current version, while reporting the progress + * to a ProgressListener. Note that only users with premium accounts will be able to view and + * recover previous versions of the file. + * + * @param fileContent a stream containing the new file contents. + * @param modified the date that the new version was modified. + * @param fileSize the size of the file used for determining the progress of the upload. + * @param listener a listener for monitoring the upload's progress. + * @return the uploaded file version. + */ + public BoxFile.Info uploadNewVersion( + InputStream fileContent, Date modified, long fileSize, ProgressListener listener) { + return this.uploadNewVersion(fileContent, null, modified, fileSize, listener); + } + + /** + * Uploads a new version of this file, replacing the current version, while reporting the progress + * to a ProgressListener. Note that only users with premium accounts will be able to view and + * recover previous versions of the file. + * + * @param fileContent a stream containing the new file contents. + * @param fileContentSHA1 the SHA1 hash of the file contents. will be sent along in the + * Content-MD5 header + * @param modified the date that the new version was modified. + * @param fileSize the size of the file used for determining the progress of the upload. + * @param listener a listener for monitoring the upload's progress. + * @return the uploaded file version. + */ + public BoxFile.Info uploadNewVersion( + InputStream fileContent, + String fileContentSHA1, + Date modified, + long fileSize, + ProgressListener listener) { + return this.uploadNewVersion(fileContent, fileContentSHA1, modified, null, fileSize, listener); + } + + /** + * Uploads a new version of this file, replacing the current version, while reporting the progress + * to a ProgressListener. Note that only users with premium accounts will be able to view and + * recover previous versions of the file. + * + * @param fileContent a stream containing the new file contents. + * @param fileContentSHA1 the SHA1 hash of the file contents. will be sent along in the + * Content-MD5 header + * @param modified the date that the new version was modified. + * @param name the new name for the file + * @param fileSize the size of the file used for determining the progress of the upload. + * @param listener a listener for monitoring the upload's progress. + * @return the uploaded file version. + */ + public BoxFile.Info uploadNewVersion( + InputStream fileContent, + String fileContentSHA1, + Date modified, + String name, + long fileSize, + ProgressListener listener) { + URL uploadURL = CONTENT_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL(), this.getID()); + BoxMultipartRequest request = new BoxMultipartRequest(getAPI(), uploadURL); + + if (fileSize > 0) { + request.setFile(fileContent, "", fileSize); + } else { + request.setFile(fileContent, ""); + } + + if (fileContentSHA1 != null) { + request.setContentSHA1(fileContentSHA1); + } + + JsonObject attributesJSON = new JsonObject(); + if (modified != null) { + attributesJSON.add("content_modified_at", BoxDateFormat.format(modified)); + } + + if (name != null) { + attributesJSON.add("name", name); + } + + request.putField("attributes", attributesJSON.toString()); + + BoxJSONResponse response = null; + try { + if (listener == null) { + // upload is multipart request but response is JSON + response = (BoxJSONResponse) request.send(); + } else { + // upload is multipart request but response is JSON + response = (BoxJSONResponse) request.send(listener); + } + + String fileJSON = response.getJsonObject().get("entries").asArray().get(0).toString(); + + return new BoxFile.Info(fileJSON); + } finally { + Optional.ofNullable(response).ifPresent(BoxAPIResponse::close); + } + } + + /** + * Gets an expiring URL for creating an embedded preview session. The URL will expire after 60 + * seconds and the preview session will expire after 60 minutes. + * + * @return the expiring preview link + */ + public URL getPreviewLink() { + BoxFile.Info info = this.getInfo("expiring_embed_link"); + + return info.getPreviewLink(); + } + + /** + * Gets a list of any comments on this file. + * + * @return a list of comments on this file. + */ + public List getComments() { + URL url = GET_COMMENTS_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + + int totalCount = responseJSON.get("total_count").asInt(); + List comments = new ArrayList<>(totalCount); + JsonArray entries = responseJSON.get("entries").asArray(); + for (JsonValue value : entries) { + JsonObject commentJSON = value.asObject(); + BoxComment comment = new BoxComment(this.getAPI(), commentJSON.get("id").asString()); + BoxComment.Info info = comment.new Info(commentJSON); + comments.add(info); + } + + return comments; + } + } + + /** + * Gets a list of any tasks on this file with requested fields. + * + * @param fields optional fields to retrieve for this task. + * @return a list of tasks on this file. + */ + public List getTasks(String... fields) { + QueryStringBuilder builder = new QueryStringBuilder(); + if (fields.length > 0) { + builder.appendParam("fields", fields); + } + URL url = + GET_TASKS_URL_TEMPLATE.buildWithQuery( + this.getAPI().getBaseURL(), builder.toString(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + + int totalCount = responseJSON.get("total_count").asInt(); + List tasks = new ArrayList<>(totalCount); + JsonArray entries = responseJSON.get("entries").asArray(); + for (JsonValue value : entries) { + JsonObject taskJSON = value.asObject(); + BoxTask task = new BoxTask(this.getAPI(), taskJSON.get("id").asString()); + BoxTask.Info info = task.new Info(taskJSON); + tasks.add(info); + } + + return tasks; + } + } + + /** + * Creates metadata on this file in the global properties template. + * + * @param metadata The new metadata values. + * @return the metadata returned from the server. + */ + public Metadata createMetadata(Metadata metadata) { + return this.createMetadata(Metadata.DEFAULT_METADATA_TYPE, metadata); + } + + /** + * Creates metadata on this file in the specified template type. + * + * @param typeName the metadata template type name. + * @param metadata the new metadata values. + * @return the metadata returned from the server. + */ + public Metadata createMetadata(String typeName, Metadata metadata) { + String scope = Metadata.scopeBasedOnType(typeName); + return this.createMetadata(typeName, scope, metadata); + } + + /** + * Creates metadata on this file in the specified template type. + * + * @param typeName the metadata template type name. + * @param scope the metadata scope (global or enterprise). + * @param metadata the new metadata values. + * @return the metadata returned from the server. + */ + public Metadata createMetadata(String typeName, String scope, Metadata metadata) { + URL url = + METADATA_URL_TEMPLATE.buildAlpha(this.getAPI().getBaseURL(), this.getID(), scope, typeName); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); + request.setBody(metadata.toString()); + try (BoxJSONResponse response = request.send()) { + return new Metadata(Json.parse(response.getJSON()).asObject()); + } + } + + /** + * Sets the provided metadata on the file. If metadata has already been created on this file, it + * overwrites metadata keys specified in the `metadata` param. + * + * @param templateName the name of the metadata template. + * @param scope the scope of the template (usually "global" or "enterprise"). + * @param metadata the new metadata values. + * @return the metadata returned from the server. + */ + public Metadata setMetadata(String templateName, String scope, Metadata metadata) { + try { + return this.createMetadata(templateName, scope, metadata); + } catch (BoxAPIException e) { + if (e.getResponseCode() == 409) { + if (metadata.getOperations().isEmpty()) { + return getMetadata(); + } else { + return updateExistingTemplate(templateName, scope, metadata); + } + } else { + throw e; + } + } + } + + private Metadata updateExistingTemplate(String templateName, String scope, Metadata metadata) { + Metadata metadataToUpdate = new Metadata(scope, templateName); + for (JsonValue value : metadata.getOperations()) { + if (value.asObject().get("value").isNumber()) { + metadataToUpdate.add( + value.asObject().get("path").asString(), value.asObject().get("value").asDouble()); + } else if (value.asObject().get("value").isString()) { + metadataToUpdate.add( + value.asObject().get("path").asString(), value.asObject().get("value").asString()); + } else if (value.asObject().get("value").isArray()) { + ArrayList list = new ArrayList<>(); + for (JsonValue jsonValue : value.asObject().get("value").asArray()) { + list.add(jsonValue.asString()); + } + metadataToUpdate.add(value.asObject().get("path").asString(), list); + } + } + return this.updateMetadata(metadataToUpdate); + } + + /** + * Adds a metadata classification to the specified file. + * + * @param classificationType the metadata classification type. + * @return the metadata classification type added to the file. + */ + public String addClassification(String classificationType) { + Metadata metadata = new Metadata().add(Metadata.CLASSIFICATION_KEY, classificationType); + Metadata classification = + this.createMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, "enterprise", metadata); + + return classification.getString(Metadata.CLASSIFICATION_KEY); + } + + /** + * Updates a metadata classification on the specified file. + * + * @param classificationType the metadata classification type. + * @return the new metadata classification type updated on the file. + */ + public String updateClassification(String classificationType) { + Metadata metadata = new Metadata("enterprise", Metadata.CLASSIFICATION_TEMPLATE_KEY); + metadata.add("/Box__Security__Classification__Key", classificationType); + Metadata classification = this.updateMetadata(metadata); + + return classification.getString(Metadata.CLASSIFICATION_KEY); + } + + /** + * Attempts to add classification to a file. If classification already exists then do update. + * + * @param classificationType the metadata classification type. + * @return the metadata classification type on the file. + */ + public String setClassification(String classificationType) { + Metadata metadata = new Metadata().add(Metadata.CLASSIFICATION_KEY, classificationType); + Metadata classification; + + try { + classification = + this.createMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, "enterprise", metadata); + } catch (BoxAPIException e) { + if (e.getResponseCode() == 409) { + metadata = new Metadata("enterprise", Metadata.CLASSIFICATION_TEMPLATE_KEY); + metadata.replace(Metadata.CLASSIFICATION_KEY, classificationType); + classification = this.updateMetadata(metadata); + } else { + throw e; + } + } + + return classification.getString(Metadata.CLASSIFICATION_KEY); + } + + /** + * Gets the classification type for the specified file. + * + * @return the metadata classification type on the file. + */ + public String getClassification() { + Metadata metadata; + try { + metadata = this.getMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY); + + } catch (BoxAPIException e) { + JsonObject responseObject = Json.parse(e.getResponse()).asObject(); + String code = responseObject.get("code").asString(); + + if (e.getResponseCode() == 404 && code.equals("instance_not_found")) { + return null; + } else { + throw e; + } + } + + return metadata.getString(Metadata.CLASSIFICATION_KEY); + } + + /** Deletes the classification on the file. */ + public void deleteClassification() { + this.deleteMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, "enterprise"); + } + + /** + * Locks a file. + * + * @return the lock returned from the server. + */ + public BoxLock lock() { + return this.lock(null, false); + } + + /** + * Locks a file. + * + * @param isDownloadPrevented is downloading of file prevented when locked. + * @return the lock returned from the server. + */ + public BoxLock lock(boolean isDownloadPrevented) { + return this.lock(null, isDownloadPrevented); + } + + /** + * Locks a file. + * + * @param expiresAt expiration date of the lock. + * @return the lock returned from the server. + */ + public BoxLock lock(Date expiresAt) { + return this.lock(expiresAt, false); + } + + /** + * Locks a file. + * + * @param expiresAt expiration date of the lock. + * @param isDownloadPrevented is downloading of file prevented when locked. + * @return the lock returned from the server. + */ + public BoxLock lock(Date expiresAt, boolean isDownloadPrevented) { + String queryString = new QueryStringBuilder().appendParam("fields", "lock").toString(); + URL url = + FILE_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); + + JsonObject lockConfig = new JsonObject(); + lockConfig.add("type", "lock"); + if (expiresAt != null) { + lockConfig.add("expires_at", BoxDateFormat.format(expiresAt)); + } + lockConfig.add("is_download_prevented", isDownloadPrevented); + + JsonObject requestJSON = new JsonObject(); + requestJSON.add("lock", lockConfig); + request.setBody(requestJSON.toString()); + + try (BoxJSONResponse response = request.send()) { + + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + JsonValue lockValue = responseJSON.get("lock"); + JsonObject lockJSON = Json.parse(lockValue.toString()).asObject(); + + return new BoxLock(lockJSON, this.getAPI()); + } + } + + /** Unlocks a file. */ + public void unlock() { + String queryString = new QueryStringBuilder().appendParam("fields", "lock").toString(); + URL url = + FILE_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID()); + BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "PUT"); + + JsonObject lockObject = new JsonObject(); + lockObject.add("lock", NULL); + + request.setBody(lockObject.toString()); + request.send().close(); + } + + /** + * Used to retrieve all metadata associated with the file. + * + * @param fields the optional fields to retrieve. + * @return An iterable of metadata instances associated with the file. + */ + public Iterable getAllMetadata(String... fields) { + return Metadata.getAllMetadata(this, fields); + } + + /** + * Gets the file properties metadata. + * + * @return the metadata returned from the server. + */ + public Metadata getMetadata() { + return this.getMetadata(Metadata.DEFAULT_METADATA_TYPE); + } + + /** + * Gets the file metadata of specified template type. + * + * @param typeName the metadata template type name. + * @return the metadata returned from the server. + */ + public Metadata getMetadata(String typeName) { + String scope = Metadata.scopeBasedOnType(typeName); + return this.getMetadata(typeName, scope); + } + + /** + * Gets the file metadata of specified template type. + * + * @param typeName the metadata template type name. + * @param scope the metadata scope (global or enterprise). + * @return the metadata returned from the server. + */ + public Metadata getMetadata(String typeName, String scope) { + URL url = + METADATA_URL_TEMPLATE.buildAlpha(this.getAPI().getBaseURL(), this.getID(), scope, typeName); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); + try (BoxJSONResponse response = request.send()) { + return new Metadata(Json.parse(response.getJSON()).asObject()); + } + } + + /** + * Updates the file metadata. + * + * @param metadata the new metadata values. + * @return the metadata returned from the server. + */ + public Metadata updateMetadata(Metadata metadata) { + String scope; + if (metadata.getScope().equals(Metadata.GLOBAL_METADATA_SCOPE)) { + scope = Metadata.GLOBAL_METADATA_SCOPE; + } else if (metadata.getScope().startsWith(Metadata.ENTERPRISE_METADATA_SCOPE)) { + scope = metadata.getScope(); + } else { + scope = Metadata.ENTERPRISE_METADATA_SCOPE; + } + + URL url = + METADATA_URL_TEMPLATE.buildAlpha( + this.getAPI().getBaseURL(), this.getID(), scope, metadata.getTemplateName()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT", APPLICATION_JSON_PATCH); + request.setBody(metadata.getPatch()); + try (BoxJSONResponse response = request.send()) { + return new Metadata(Json.parse(response.getJSON()).asObject()); + } + } + + /** Deletes the file properties metadata. */ + public void deleteMetadata() { + this.deleteMetadata(Metadata.DEFAULT_METADATA_TYPE); + } + + /** + * Deletes the file metadata of specified template type. + * + * @param typeName the metadata template type name. + */ + public void deleteMetadata(String typeName) { + String scope = Metadata.scopeBasedOnType(typeName); + this.deleteMetadata(typeName, scope); + } + + /** + * Deletes the file metadata of specified template type. + * + * @param typeName the metadata template type name. + * @param scope the metadata scope (global or enterprise). + */ + public void deleteMetadata(String typeName, String scope) { + URL url = + METADATA_URL_TEMPLATE.buildAlpha(this.getAPI().getBaseURL(), this.getID(), scope, typeName); + BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); + request.send().close(); + } + + /** + * Used to retrieve the watermark for the file. If the file does not have a watermark applied to + * it, a 404 Not Found will be returned by API. + * + * @param fields the fields to retrieve. + * @return the watermark associated with the file. + */ + public BoxWatermark getWatermark(String... fields) { + return this.getWatermark(FILE_URL_TEMPLATE, fields); + } + + /** + * Used to apply or update the watermark for the file. + * + * @return the watermark associated with the file. + */ + public BoxWatermark applyWatermark() { + return this.applyWatermark(FILE_URL_TEMPLATE, BoxWatermark.WATERMARK_DEFAULT_IMPRINT); + } + + /** + * Removes a watermark from the file. If the file did not have a watermark applied to it, a 404 + * Not Found will be returned by API. + */ + public void removeWatermark() { + this.removeWatermark(FILE_URL_TEMPLATE); + } + + /** {@inheritDoc} */ + @Override + public BoxFile.Info setCollections(BoxCollection... collections) { + JsonArray jsonArray = new JsonArray(); + for (BoxCollection collection : collections) { + JsonObject collectionJSON = new JsonObject(); + collectionJSON.add("id", collection.getID()); + jsonArray.add(collectionJSON); + } + JsonObject infoJSON = new JsonObject(); + infoJSON.add("collections", jsonArray); + + String queryString = new QueryStringBuilder().appendParam("fields", ALL_FIELDS).toString(); + URL url = + FILE_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); + request.setBody(infoJSON.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); + return new Info(jsonObject); + } + } + + /** + * Creates an upload session to create a new version of a file in chunks. This will first verify + * that the version can be created and then open a session for uploading pieces of the file. + * + * @param fileSize the size of the file that will be uploaded. + * @return the created upload session instance. + */ + public BoxFileUploadSession.Info createUploadSession(long fileSize) { + URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL(), this.getID()); + + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); + request.addHeader("Content-Type", APPLICATION_JSON); + + JsonObject body = new JsonObject(); + body.add("file_size", fileSize); + request.setBody(body.toString()); + + try (BoxJSONResponse response = request.send()) { + JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); + + String sessionId = jsonObject.get("id").asString(); + BoxFileUploadSession session = new BoxFileUploadSession(this.getAPI(), sessionId); + return session.new Info(jsonObject); + } + } + + /** + * Creates a new version of a file. + * + * @param inputStream the stream instance that contains the data. + * @param fileSize the size of the file that will be uploaded. + * @return the created file instance. + * @throws InterruptedException when a thread execution is interrupted. + * @throws IOException when reading a stream throws exception. + */ + public BoxFile.Info uploadLargeFile(InputStream inputStream, long fileSize) + throws InterruptedException, IOException { + URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL(), this.getID()); + return new LargeFileUpload().upload(this.getAPI(), inputStream, url, fileSize); + } + + /** + * Creates a new version of a file. Also sets file attributes. + * + * @param inputStream the stream instance that contains the data. + * @param fileSize the size of the file that will be uploaded. + * @param fileAttributes file attributes to set + * @return the created file instance. + * @throws InterruptedException when a thread execution is interrupted. + * @throws IOException when reading a stream throws exception. + */ + public BoxFile.Info uploadLargeFile( + InputStream inputStream, long fileSize, Map fileAttributes) + throws InterruptedException, IOException { + URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL(), this.getID()); + return new LargeFileUpload().upload(this.getAPI(), inputStream, url, fileSize, fileAttributes); + } + + /** + * Creates a new version of a file using specified number of parallel http connections. + * + * @param inputStream the stream instance that contains the data. + * @param fileSize the size of the file that will be uploaded. + * @param nParallelConnections number of parallel http connections to use + * @param timeOut time to wait before killing the job + * @param unit time unit for the time wait value + * @return the created file instance. + * @throws InterruptedException when a thread execution is interrupted. + * @throws IOException when reading a stream throws exception. + */ + public BoxFile.Info uploadLargeFile( + InputStream inputStream, long fileSize, int nParallelConnections, long timeOut, TimeUnit unit) + throws InterruptedException, IOException { + URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL(), this.getID()); + return new LargeFileUpload(nParallelConnections, timeOut, unit) + .upload(this.getAPI(), inputStream, url, fileSize); + } + + /** + * Creates a new version of a file using specified number of parallel http connections. Also sets + * file attributes. + * + * @param inputStream the stream instance that contains the data. + * @param fileSize the size of the file that will be uploaded. + * @param nParallelConnections number of parallel http connections to use + * @param timeOut time to wait before killing the job + * @param unit time unit for the time wait value + * @param fileAttributes file attributes to set + * @return the created file instance. + * @throws InterruptedException when a thread execution is interrupted. + * @throws IOException when reading a stream throws exception. + */ + public BoxFile.Info uploadLargeFile( + InputStream inputStream, + long fileSize, + int nParallelConnections, + long timeOut, + TimeUnit unit, + Map fileAttributes) + throws InterruptedException, IOException { + URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL(), this.getID()); + return new LargeFileUpload(nParallelConnections, timeOut, unit) + .upload(this.getAPI(), inputStream, url, fileSize, fileAttributes); + } + + private BoxCollaboration.Info collaborate( + JsonObject accessibleByField, + BoxCollaboration.Role role, + Boolean notify, + Boolean canViewPath, + Date expiresAt, + Boolean isAccessOnly) { + + JsonObject itemField = new JsonObject(); + itemField.add("id", this.getID()); + itemField.add("type", "file"); + + return BoxCollaboration.create( + this.getAPI(), + accessibleByField, + itemField, + role, + notify, + canViewPath, + expiresAt, + isAccessOnly); + } + + /** + * Adds a collaborator to this file. + * + * @param collaborator the collaborator to add. + * @param role the role of the collaborator. + * @param notify determines if the user (or all the users in the group) will receive email + * notifications. + * @param canViewPath whether view path collaboration feature is enabled or not. + * @param expiresAt when the collaboration should expire. + * @param isAccessOnly whether the collaboration is access only or not. + * @return info about the new collaboration. + */ + public BoxCollaboration.Info collaborate( + BoxCollaborator collaborator, + BoxCollaboration.Role role, + Boolean notify, + Boolean canViewPath, + Date expiresAt, + Boolean isAccessOnly) { + JsonObject accessibleByField = new JsonObject(); + accessibleByField.add("id", collaborator.getID()); + + if (collaborator instanceof BoxUser) { + accessibleByField.add("type", "user"); + } else if (collaborator instanceof BoxGroup) { + accessibleByField.add("type", "group"); + } else { + throw new IllegalArgumentException("The given collaborator is of an unknown type."); + } + return this.collaborate(accessibleByField, role, notify, canViewPath, expiresAt, isAccessOnly); + } + + /** + * Adds a collaborator to this file. + * + * @param collaborator the collaborator to add. + * @param role the role of the collaborator. + * @param notify determines if the user (or all the users in the group) will receive email + * notifications. + * @param canViewPath whether view path collaboration feature is enabled or not. + * @return info about the new collaboration. + */ + public BoxCollaboration.Info collaborate( + BoxCollaborator collaborator, + BoxCollaboration.Role role, + Boolean notify, + Boolean canViewPath) { + return this.collaborate(collaborator, role, notify, canViewPath, null, null); + } + + /** + * Adds a collaborator to this folder. An email will be sent to the collaborator if they don't + * already have a Box account. + * + * @param email the email address of the collaborator to add. + * @param role the role of the collaborator. + * @param notify determines if the user (or all the users in the group) will receive email + * notifications. + * @param canViewPath whether view path collaboration feature is enabled or not. + * @param expiresAt when the collaboration should expire. + * @param isAccessOnly whether the collaboration is access only or not. + * @return info about the new collaboration. + */ + public BoxCollaboration.Info collaborate( + String email, + BoxCollaboration.Role role, + Boolean notify, + Boolean canViewPath, + Date expiresAt, + Boolean isAccessOnly) { + JsonObject accessibleByField = new JsonObject(); + accessibleByField.add("login", email); + accessibleByField.add("type", "user"); + + return this.collaborate(accessibleByField, role, notify, canViewPath, expiresAt, isAccessOnly); + } + + /** + * Adds a collaborator to this folder. An email will be sent to the collaborator if they don't + * already have a Box account. + * + * @param email the email address of the collaborator to add. + * @param role the role of the collaborator. + * @param notify determines if the user (or all the users in the group) will receive email + * notifications. + * @param canViewPath whether view path collaboration feature is enabled or not. + * @return info about the new collaboration. + */ + public BoxCollaboration.Info collaborate( + String email, BoxCollaboration.Role role, Boolean notify, Boolean canViewPath) { + return this.collaborate(email, role, notify, canViewPath, null, null); + } + + /** + * Used to retrieve all collaborations associated with the item. + * + * @param fields the optional fields to retrieve. + * @return An iterable of metadata instances associated with the item. + */ + public BoxResourceIterable getAllFileCollaborations(String... fields) { + return BoxCollaboration.getAllFileCollaborations( + this.getAPI(), this.getID(), GET_COLLABORATORS_PAGE_SIZE, fields); + } + + /** Used to specify what filetype to request for a file thumbnail. */ + public enum ThumbnailFileType { + /** PNG image format. */ + PNG, + + /** JPG image format. */ + JPG + } + + /** Enumerates the possible permissions that a user can have on a file. */ + public enum Permission { + /** The user can download the file. */ + CAN_DOWNLOAD("can_download"), + + /** The user can upload new versions of the file. */ + CAN_UPLOAD("can_upload"), + + /** The user can rename the file. */ + CAN_RENAME("can_rename"), + + /** The user can delete the file. */ + CAN_DELETE("can_delete"), + + /** The user can share the file. */ + CAN_SHARE("can_share"), + + /** The user can set the access level for shared links to the file. */ + CAN_SET_SHARE_ACCESS("can_set_share_access"), + + /** The user can preview the file. */ + CAN_PREVIEW("can_preview"), + + /** The user can comment on the file. */ + CAN_COMMENT("can_comment"), + + /** The user can place annotations on this file. */ + CAN_ANNOTATE("can_annotate"), + + /** + * The current user can invite new users to collaborate on this item, and the user can update + * the role of a user already collaborated on this item. + */ + CAN_INVITE_COLLABORATOR("can_invite_collaborator"), - URL url = ADD_COMMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); - request.setBody(requestJSON.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + /** The user can view all annotations placed on this file. */ + CAN_VIEW_ANNOTATIONS_ALL("can_view_annotations_all"), + + /** The user can view annotations placed by themselves on this file. */ + CAN_VIEW_ANNOTATIONS_SELF("can_view_annotations_self"); - BoxComment addedComment = new BoxComment(this.getAPI(), responseJSON.get("id").asString()); - return addedComment.new Info(responseJSON); - } - } + private final String jsonValue; - /** - * Adds a new task to this file. The task can have an optional message to include, and a due date. - * - * @param action the action the task assignee will be prompted to do. - * @param message an optional message to include with the task. - * @param dueAt the day at which this task is due. - * @return information about the newly added task. - */ - public BoxTask.Info addTask(BoxTask.Action action, String message, Date dueAt) { - return this.addTask(action, message, dueAt, null); + Permission(String jsonValue) { + this.jsonValue = jsonValue; } - /** - * Adds a new task to this file. The task can have an optional message to include, due date, - * and task completion rule. - * - * @param action the action the task assignee will be prompted to do. - * @param message an optional message to include with the task. - * @param dueAt the day at which this task is due. - * @param completionRule the rule for completing the task. - * @return information about the newly added task. - */ - public BoxTask.Info addTask(BoxTask.Action action, String message, Date dueAt, - BoxTask.CompletionRule completionRule) { - JsonObject itemJSON = new JsonObject(); - itemJSON.add("type", "file"); - itemJSON.add("id", this.getID()); - - JsonObject requestJSON = new JsonObject(); - requestJSON.add("item", itemJSON); - requestJSON.add("action", action.toJSONString()); - - if (message != null && !message.isEmpty()) { - requestJSON.add("message", message); - } - - if (dueAt != null) { - requestJSON.add("due_at", BoxDateFormat.format(dueAt)); - } - - if (completionRule != null) { - requestJSON.add("completion_rule", completionRule.toJSONString()); - } - - URL url = ADD_TASK_URL_TEMPLATE.build(this.getAPI().getBaseURL()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); - request.setBody(requestJSON.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - - BoxTask addedTask = new BoxTask(this.getAPI(), responseJSON.get("id").asString()); - return addedTask.new Info(responseJSON); - } + static Permission fromJSONValue(String jsonValue) { + return Permission.valueOf(jsonValue.toUpperCase(java.util.Locale.ROOT)); } - /** - * Gets an expiring URL for downloading a file directly from Box. This can be user, - * for example, for sending as a redirect to a browser to cause the browser - * to download the file directly from Box. - * - * @return the temporary download URL - */ - public URL getDownloadURL() { - URL url = getDownloadUrl(); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); - request.setFollowRedirects(false); + String toJSONValue() { + return this.jsonValue; + } + } - try (BoxAPIResponse response = request.send()) { - String location = response.getHeaderField("location"); + /** Contains information about a BoxFile. */ + public class Info extends BoxItem.Info { + private String sha1; + private String versionNumber; + private long commentCount; + private EnumSet permissions; + private String extension; + private boolean isPackage; + private BoxFileVersion version; + private URL previewLink; + private BoxLock lock; + private boolean isWatermarked; + private boolean isExternallyOwned; + private Map> metadataMap; + private List representations; + private List allowedInviteeRoles; + private Boolean hasCollaborations; + private String uploaderDisplayName; + private BoxClassification classification; + private Date dispositionAt; + private boolean isAccessibleViaSharedLink; - try { - return new URL(location); - } catch (MalformedURLException e) { - throw new RuntimeException(e); - } - } + /** Constructs an empty Info object. */ + public Info() { + super(); } /** - * Downloads the contents of this file to a given OutputStream. + * Constructs an Info object by parsing information from a JSON string. * - * @param output the stream to where the file will be written. + * @param json the JSON string to parse. */ - public void download(OutputStream output) { - this.download(output, null); + public Info(String json) { + super(json); } /** - * Downloads the contents of this file to a given OutputStream while reporting the progress to a ProgressListener. + * Constructs an Info object using an already parsed JSON object. * - * @param output the stream to where the file will be written. - * @param listener a listener for monitoring the download's progress. - */ - public void download(OutputStream output, ProgressListener listener) { - URL url = getDownloadUrl(); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); - BoxAPIResponse response = request.send(); - writeStream(response, output, listener); - } - - /** - * Downloads the content of the file to a given OutputStream using the provided shared link. - * @param api the API connection to be used to get download URL of the file. - * @param output the stream to where the file will be written. - * @param sharedLink the shared link of the file. - */ - public static void downloadFromSharedLink(BoxAPIConnection api, OutputStream output, String sharedLink) { - downloadFromSharedLink(api, output, sharedLink, null, null); - } - - /** - * Downloads the content of the file to a given OutputStream using the provided shared link. - * @param api the API connection to be used to get download URL of the file. - * @param output the stream to where the file will be written. - * @param sharedLink the shared link of the file. - * @param password the password for the shared link. - */ - public static void downloadFromSharedLink( - BoxAPIConnection api, OutputStream output, String sharedLink, String password - ) { - downloadFromSharedLink(api, output, sharedLink, password, null); - } - - /** - * Downloads the content of the file to a given OutputStream using the provided shared link. - * @param api the API connection to be used to get download URL of the file. - * @param output the stream to where the file will be written. - * @param sharedLink the shared link of the file. - * @param listener a listener for monitoring the download's progress. - */ - public static void downloadFromSharedLink( - BoxAPIConnection api, OutputStream output, String sharedLink, ProgressListener listener - ) { - downloadFromSharedLink(api, output, sharedLink, null, listener); - } - - /** - * Downloads the content of the file to a given OutputStream using the provided shared link. - * @param api the API connection to be used to get download URL of the file. - * @param output the stream to where the file will be written. - * @param sharedLink the shared link of the file. - * @param password the password for the shared link. - * @param listener a listener for monitoring the download's progress. + * @param jsonObject the parsed JSON object. */ - public static void downloadFromSharedLink( - BoxAPIConnection api, OutputStream output, String sharedLink, String password, ProgressListener listener - ) { - BoxItem.Info item = BoxItem.getSharedItem(api, sharedLink, password, "id"); - if (!(item instanceof BoxFile.Info)) { - throw new BoxAPIException("The shared link provided is not a shared link for a file."); - } - BoxFile sharedFile = new BoxFile(api, item.getID()); - URL url = sharedFile.getDownloadUrl(); - BoxAPIRequest request = new BoxAPIRequest(api, url, "GET"); - request.addHeader("BoxApi", BoxSharedLink.getSharedLinkHeaderValue(sharedLink, password)); - BoxAPIResponse response = request.send(); - writeStream(response, output, listener); + public Info(JsonObject jsonObject) { + super(jsonObject); } - /** - * Downloads a part of this file's contents, starting at specified byte offset. - * - * @param output the stream to where the file will be written. - * @param offset the byte offset at which to start the download. - */ - public void downloadRange(OutputStream output, long offset) { - this.downloadRange(output, offset, -1); + @Override + public BoxFile getResource() { + return BoxFile.this; } /** - * Downloads a part of this file's contents, starting at rangeStart and stopping at rangeEnd. + * Gets the SHA1 hash of the file. * - * @param output the stream to where the file will be written. - * @param rangeStart the byte offset at which to start the download. - * @param rangeEnd the byte offset at which to stop the download. + * @return the SHA1 hash of the file. */ - public void downloadRange(OutputStream output, long rangeStart, long rangeEnd) { - this.downloadRange(output, rangeStart, rangeEnd, null); + public String getSha1() { + return this.sha1; } /** - * Downloads a part of this file's contents, starting at rangeStart and stopping at rangeEnd, while reporting the - * progress to a ProgressListener. + * Gets the lock of the file. * - * @param output the stream to where the file will be written. - * @param rangeStart the byte offset at which to start the download. - * @param rangeEnd the byte offset at which to stop the download. - * @param listener a listener for monitoring the download's progress. + * @return the lock of the file. */ - public void downloadRange(OutputStream output, long rangeStart, long rangeEnd, ProgressListener listener) { - URL url = getDownloadUrl(); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); - if (rangeEnd > 0) { - request.addHeader("Range", String.format("bytes=%s-%s", rangeStart, rangeEnd)); - } else { - request.addHeader("Range", String.format("bytes=%s-", rangeStart)); - } - writeStream(request.send(), output, listener); + public BoxLock getLock() { + return this.lock; } /** - * Can be used to override the URL used for file download. + * Gets the current version number of the file. * - * @return URL for file downalod - */ - protected URL getDownloadUrl() { - return CONTENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - } - - @Override - public BoxFile.Info copy(BoxFolder destination) { - return this.copy(destination, null); - } - - @Override - public BoxFile.Info copy(BoxFolder destination, String newName) { - URL url = COPY_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - - JsonObject parent = new JsonObject(); - parent.add("id", destination.getID()); - - JsonObject copyInfo = new JsonObject(); - copyInfo.add("parent", parent); - if (newName != null) { - copyInfo.add("name", newName); - } - - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); - request.setBody(copyInfo.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - BoxFile copiedFile = new BoxFile(this.getAPI(), responseJSON.get("id").asString()); - return copiedFile.new Info(responseJSON); - } - } - - /** - * Deletes this file by moving it to the trash. + * @return the current version number of the file. */ - public void delete() { - URL url = FILE_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); - request.send().close(); - } - - @Override - public BoxItem.Info move(BoxFolder destination) { - return this.move(destination, null); - } - - @Override - public BoxItem.Info move(BoxFolder destination, String newName) { - URL url = FILE_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); - - JsonObject parent = new JsonObject(); - parent.add("id", destination.getID()); - - JsonObject updateInfo = new JsonObject(); - updateInfo.add("parent", parent); - if (newName != null) { - updateInfo.add("name", newName); - } - - request.setBody(updateInfo.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - BoxFile movedFile = new BoxFile(this.getAPI(), responseJSON.get("id").asString()); - return movedFile.new Info(responseJSON); - } + public String getVersionNumber() { + return this.versionNumber; } /** - * Renames this file. + * Gets the number of comments on the file. * - * @param newName the new name of the file. + * @return the number of comments on the file. */ - public void rename(String newName) { - URL url = FILE_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); - - JsonObject updateInfo = new JsonObject(); - updateInfo.add("name", newName); - - request.setBody(updateInfo.toString()); - try (BoxJSONResponse response = request.send()) { - response.getJSON(); - } - } - - @Override - public BoxFile.Info getInfo(String... fields) { - URL url = FILE_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - if (fields.length > 0) { - String queryString = new QueryStringBuilder().appendParam("fields", fields).toString(); - url = FILE_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID()); - } - - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); - try (BoxJSONResponse response = request.send()) { - return new Info(response.getJSON()); - } + public long getCommentCount() { + return this.commentCount; } /** - * Gets information about this item including a specified set of representations. + * Gets the permissions that the current user has on the file. * - * @param representationHints hints for representations to be retrieved - * @param fields the fields to retrieve. - * @return info about this item containing only the specified fields, including representations. - * @see X-Rep-Hints Header + * @return the permissions that the current user has on the file. */ - public BoxFile.Info getInfoWithRepresentations(String representationHints, String... fields) { - if (representationHints.matches(Representation.X_REP_HINTS_PATTERN)) { - //Since the user intends to get representations, add it to fields, even if user has missed it - Set fieldsSet = new HashSet<>(Arrays.asList(fields)); - fieldsSet.add("representations"); - String queryString = new QueryStringBuilder().appendParam("fields", - fieldsSet.toArray(new String[0])).toString(); - URL url = FILE_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID()); - - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); - request.addHeader("X-Rep-Hints", representationHints); - try (BoxJSONResponse response = request.send()) { - return new Info(response.getJSON()); - } - } else { - throw new BoxAPIException( - "Represention hints is not valid. Refer documention on how to construct X-Rep-Hints Header" - ); - } + public EnumSet getPermissions() { + return this.permissions; } /** - * Fetches the contents of a file representation and writes them to the provided output stream. + * Gets the extension suffix of the file, excluding the dot. * - * @param representationHint the X-Rep-Hints query for the representation to fetch. - * @param output the output stream to write the contents to. - * @see X-Rep-Hints Header + * @return the extension of the file. */ - public void getRepresentationContent(String representationHint, OutputStream output) { - - this.getRepresentationContent(representationHint, "", output); + public String getExtension() { + return this.extension; } /** - * Fetches the contents of a file representation with asset path and writes them to the provided output stream. + * Gets whether or not the file is an OSX package. * - * @param representationHint the X-Rep-Hints query for the representation to fetch. - * @param assetPath the path of the asset for representations containing multiple files. - * @param output the output stream to write the contents to. - * @see X-Rep-Hints Header + * @return true if the file is an OSX package; otherwise false. */ - public void getRepresentationContent(String representationHint, String assetPath, OutputStream output) { - this.getRepresentationContent(representationHint, assetPath, output, Integer.MAX_VALUE); + public boolean getIsPackage() { + return this.isPackage; } /** - * Fetches the contents of a file representation with asset path and writes them to the provided output stream. + * Gets the current version details of the file. * - * @param representationHint the X-Rep-Hints query for the representation to fetch. - * @param assetPath the path of the asset for representations containing multiple files. - * @param output the output stream to write the contents to. - * @param maxRetries the maximum number of attempts to call the request for retrieving status information - * indicating whether the representation has been generated and is ready to fetch. - * If the number of attempts is exceeded, the method will throw a BoxApiException. - * @see X-Rep-Hints Header + * @return the current version details of the file. */ - public void getRepresentationContent( - String representationHint, String assetPath, OutputStream output, int maxRetries - ) { - List reps = this.getInfoWithRepresentations(representationHint).getRepresentations(); - if (reps.size() < 1) { - throw new BoxAPIException("No matching representations found for requested '" + representationHint - + "' hint"); - } - Representation representation = reps.get(0); - String repState = representation.getStatus().getState(); - - switch (repState) { - case "viewable": - case "success": - this.makeRepresentationContentRequest(representation.getContent().getUrlTemplate(), assetPath, output); - break; - case "pending": - case "none": - - String repContentURLString = null; - int attemptNumber = 0; - while (repContentURLString == null && attemptNumber < maxRetries) { - repContentURLString = this.pollRepInfo(representation.getInfo().getUrl()); - try { - Thread.sleep(100); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - attemptNumber++; - } - - if (repContentURLString != null) { - this.makeRepresentationContentRequest(repContentURLString, assetPath, output); - } else { - throw new BoxAPIException( - "Representation did not have a success status allowing it to be retrieved after " - + maxRetries - + " attempts" - ); - } - - break; - case "error": - throw new BoxAPIException("Representation had error status"); - default: - throw new BoxAPIException("Representation had unknown status"); - } - - } - - private String pollRepInfo(URL infoURL) { - - BoxJSONRequest infoRequest = new BoxJSONRequest(this.getAPI(), infoURL, HttpMethod.GET); - try (BoxJSONResponse infoResponse = infoRequest.send()) { - JsonObject response = infoResponse.getJsonObject(); - - Representation rep = new Representation(response); - - String repState = rep.getStatus().getState(); - - switch (repState) { - case "viewable": - case "success": - return rep.getContent().getUrlTemplate(); - case "pending": - case "none": - return null; - case "error": - throw new BoxAPIException("Representation had error status"); - default: - throw new BoxAPIException("Representation had unknown status"); - } - } - } - - private void makeRepresentationContentRequest( - String representationURLTemplate, String assetPath, OutputStream output - ) { - try { - URL repURL = new URL(representationURLTemplate.replace("{+asset_path}", assetPath)); - BoxAPIRequest repContentReq = new BoxAPIRequest(this.getAPI(), repURL, HttpMethod.GET); - BoxAPIResponse response = repContentReq.send(); - writeStreamWithContentLength(response, output); - } catch (MalformedURLException ex) { - - throw new BoxAPIException("Could not generate representation content URL"); - } + public BoxFileVersion getVersion() { + return this.version; } /** - * Updates the information about this file with any info fields that have been modified locally. - * - *

The only fields that will be updated are the ones that have been modified locally. For example, the following - * code won't update any information (or even send a network request) since none of the info's fields were - * changed:

+ * Gets the current expiring preview link. * - *
BoxFile file = new File(api, id);
-     * BoxFile.Info info = file.getInfo();
-     * file.updateInfo(info);
- * - * @param info the updated info. + * @return the expiring preview link */ - public void updateInfo(BoxFile.Info info) { - URL url = FILE_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); - request.setBody(info.getPendingChanges()); - try (BoxJSONResponse response = request.send()) { - JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - info.update(jsonObject); - } + public URL getPreviewLink() { + return this.previewLink; } /** - * Retrieve a specific file version. + * Gets flag indicating whether this file is Watermarked. * - * @param fileVersionID the ID of the file version to retrieve. - * @param fields the optional fields to retrieve. - * @return a specific file version. + * @return whether the file is watermarked or not */ - public BoxFileVersion getVersionByID(String fileVersionID, String... fields) { - URL url = BoxFileVersion.VERSION_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), fileVersionID); - if (fields.length > 0) { - String queryString = new QueryStringBuilder().appendParam("fields", fields).toString(); - url = BoxFileVersion.VERSION_URL_TEMPLATE.buildWithQuery( - this.getAPI().getBaseURL(), - queryString, - this.getID(), - fileVersionID - ); - } - - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); - try (BoxJSONResponse response = request.send()) { - JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - return new BoxFileVersion(this.getAPI(), jsonObject, this.getID()); - } + public boolean getIsWatermarked() { + return this.isWatermarked; } /** - * Gets up to 1000 versions of this file. Note that only users with premium accounts will be able to retrieve - * previous versions of their files. `fields` parameter is optional, if specified only requested fields will - * be returned: - *
-     * {@code
-     * new BoxFile(api, file_id).getVersions()       // will return all default fields
-     * new BoxFile(api, file_id).getVersions("name") // will return only specified fields
-     * }
-     * 
+ * Returns the allowed invitee roles for this file item. * - * @param fields the fields to retrieve. If nothing provided default fields will be returned. - * You can find list of available fields at {@link BoxFile#ALL_VERSION_FIELDS} - * @return a list of previous file versions. + * @return the list of roles allowed for invited collaborators. */ - public Collection getVersions(String... fields) { - return getVersionsRange(0, BoxFileVersion.DEFAULT_LIMIT, fields); + public List getAllowedInviteeRoles() { + return this.allowedInviteeRoles; } - /** - * Retrieves a specific range of versions of this file. + * Returns the indicator for whether this file item has collaborations. * - * @param offset the index of the first version of this file to retrieve. - * @param limit the maximum number of versions to retrieve after the offset. - * @param fields the fields to retrieve. - * @return a partial collection containing the specified range of versions of this file. + * @return indicator for whether this file item has collaborations. */ - public PartialCollection getVersionsRange(long offset, long limit, String... fields) { - QueryStringBuilder builder = new QueryStringBuilder() - .appendParam("limit", limit) - .appendParam("offset", offset); - - if (fields.length > 0) { - builder.appendParam("fields", fields); - } - - URL url = VERSIONS_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), builder.toString(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); - try (BoxJSONResponse response = request.send()) { - - JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - String totalCountString = jsonObject.get("total_count").toString(); - long fullSize = Double.valueOf(totalCountString).longValue(); - PartialCollection versions = new PartialCollection<>(offset, limit, fullSize); - JsonArray entries = jsonObject.get("entries").asArray(); - for (JsonValue entry : entries) { - versions.add(new BoxFileVersion(this.getAPI(), entry.asObject(), this.getID())); - } - - return versions; - } + public Boolean getHasCollaborations() { + return this.hasCollaborations; } /** - * Checks if a new version of the file can be uploaded with the specified name. + * Gets the metadata on this file associated with a specified scope and template. Makes an + * attempt to get metadata that was retrieved using getInfo(String ...) method. * - * @param name the new name for the file. - * @return whether or not the file version can be uploaded. + * @param templateName the metadata template type name. + * @param scope the scope of the template (usually "global" or "enterprise"). + * @return the metadata returned from the server. */ - public boolean canUploadVersion(String name) { - return this.canUploadVersion(name, 0); + public Metadata getMetadata(String templateName, String scope) { + try { + return this.metadataMap.get(scope).get(templateName); + } catch (NullPointerException e) { + return null; + } } /** - * Checks if a new version of the file can be uploaded with the specified name and size. + * Returns the field for indicating whether a file is owned by a user outside the enterprise. * - * @param name the new name for the file. - * @param fileSize the size of the new version content in bytes. - * @return whether the file version can be uploaded. + * @return indicator for whether or not the file is owned by a user outside the enterprise. */ - public boolean canUploadVersion(String name, long fileSize) { - - URL url = getDownloadUrl(); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "OPTIONS"); - - JsonObject preflightInfo = new JsonObject(); - if (name != null) { - preflightInfo.add("name", name); - } - - preflightInfo.add("size", fileSize); - - request.setBody(preflightInfo.toString()); - try (BoxAPIResponse response = request.send()) { - return response.getResponseCode() == 200; - } catch (BoxAPIException ex) { - if (ex.getResponseCode() >= 400 && ex.getResponseCode() < 500) { - // This looks like an error response, meaning the upload would fail - return false; - } else { - // This looks like a network error or server error, rethrow exception - throw ex; - } - } + public boolean getIsExternallyOwned() { + return this.isExternallyOwned; } /** - * Uploads a new version of this file, replacing the current version. Note that only users with premium accounts - * will be able to view and recover previous versions of the file. + * Get file's representations. * - * @param fileContent a stream containing the new file contents. - * @return the uploaded file version. + * @return list of representations */ - public BoxFile.Info uploadNewVersion(InputStream fileContent) { - return this.uploadNewVersion(fileContent, null); + public List getRepresentations() { + return this.representations; } /** - * Uploads a new version of this file, replacing the current version. Note that only users with premium accounts - * will be able to view and recover previous versions of the file. + * Returns user's name at the time of upload. * - * @param fileContent a stream containing the new file contents. - * @param fileContentSHA1 a string containing the SHA1 hash of the new file contents. - * @return the uploaded file version. + * @return user's name at the time of upload */ - public BoxFile.Info uploadNewVersion(InputStream fileContent, String fileContentSHA1) { - return this.uploadNewVersion(fileContent, fileContentSHA1, null); + public String getUploaderDisplayName() { + return this.uploaderDisplayName; } /** - * Uploads a new version of this file, replacing the current version. Note that only users with premium accounts - * will be able to view and recover previous versions of the file. + * Gets the metadata classification type of this file. * - * @param fileContent a stream containing the new file contents. - * @param fileContentSHA1 a string containing the SHA1 hash of the new file contents. - * @param modified the date that the new version was modified. - * @return the uploaded file version. + * @return the metadata classification type of this file. */ - public BoxFile.Info uploadNewVersion(InputStream fileContent, String fileContentSHA1, Date modified) { - return this.uploadNewVersion(fileContent, fileContentSHA1, modified, 0, null); + public BoxClassification getClassification() { + return this.classification; } /** - * Uploads a new version of this file, replacing the current version. Note that only users with premium accounts - * will be able to view and recover previous versions of the file. + * Returns the retention expiration timestamp for the given file. * - * @param fileContent a stream containing the new file contents. - * @param fileContentSHA1 a string containing the SHA1 hash of the new file contents. - * @param modified the date that the new version was modified. - * @param name the new name for the file - * @return the uploaded file version. + * @return Date representing expiration timestamp */ - public BoxFile.Info uploadNewVersion(InputStream fileContent, String fileContentSHA1, Date modified, String name) { - return this.uploadNewVersion(fileContent, fileContentSHA1, modified, name, 0, null); + public Date getDispositionAt() { + return dispositionAt; } /** - * Uploads a new version of this file, replacing the current version, while reporting the progress to a - * ProgressListener. Note that only users with premium accounts will be able to view and recover previous versions - * of the file. + * Modifies the retention expiration timestamp for the given file. This date cannot be shortened + * once set on a file. * - * @param fileContent a stream containing the new file contents. - * @param modified the date that the new version was modified. - * @param fileSize the size of the file used for determining the progress of the upload. - * @param listener a listener for monitoring the upload's progress. - * @return the uploaded file version. + * @param dispositionAt Date representing expiration timestamp */ - public BoxFile.Info uploadNewVersion(InputStream fileContent, Date modified, long fileSize, - ProgressListener listener) { - return this.uploadNewVersion(fileContent, null, modified, fileSize, listener); + public void setDispositionAt(Date dispositionAt) { + this.dispositionAt = dispositionAt; + this.addPendingChange("disposition_at", BoxDateFormat.format(dispositionAt)); } /** - * Uploads a new version of this file, replacing the current version, while reporting the progress to a - * ProgressListener. Note that only users with premium accounts will be able to view and recover previous versions - * of the file. + * Returns the flag indicating whether the file is accessible via a shared link. * - * @param fileContent a stream containing the new file contents. - * @param fileContentSHA1 the SHA1 hash of the file contents. will be sent along in the Content-MD5 header - * @param modified the date that the new version was modified. - * @param fileSize the size of the file used for determining the progress of the upload. - * @param listener a listener for monitoring the upload's progress. - * @return the uploaded file version. + * @return boolean flag indicating whether the file is accessible via a shared link. */ - public BoxFile.Info uploadNewVersion(InputStream fileContent, String fileContentSHA1, Date modified, long fileSize, - ProgressListener listener) { - return this.uploadNewVersion(fileContent, fileContentSHA1, modified, null, fileSize, listener); + public boolean getIsAccessibleViaSharedLink() { + return this.isAccessibleViaSharedLink; } - /** - * Uploads a new version of this file, replacing the current version, while reporting the progress to a - * ProgressListener. Note that only users with premium accounts will be able to view and recover previous versions - * of the file. - * - * @param fileContent a stream containing the new file contents. - * @param fileContentSHA1 the SHA1 hash of the file contents. will be sent along in the Content-MD5 header - * @param modified the date that the new version was modified. - * @param name the new name for the file - * @param fileSize the size of the file used for determining the progress of the upload. - * @param listener a listener for monitoring the upload's progress. - * @return the uploaded file version. - */ - public BoxFile.Info uploadNewVersion(InputStream fileContent, String fileContentSHA1, Date modified, String name, - long fileSize, ProgressListener listener) { - URL uploadURL = CONTENT_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL(), this.getID()); - BoxMultipartRequest request = new BoxMultipartRequest(getAPI(), uploadURL); - - if (fileSize > 0) { - request.setFile(fileContent, "", fileSize); - } else { - request.setFile(fileContent, ""); - } - - if (fileContentSHA1 != null) { - request.setContentSHA1(fileContentSHA1); - } - - JsonObject attributesJSON = new JsonObject(); - if (modified != null) { - attributesJSON.add("content_modified_at", BoxDateFormat.format(modified)); - } - - if (name != null) { - attributesJSON.add("name", name); - } - - request.putField("attributes", attributesJSON.toString()); - - BoxJSONResponse response = null; - try { - if (listener == null) { - // upload is multipart request but response is JSON - response = (BoxJSONResponse) request.send(); + @Override + protected void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + + String memberName = member.getName(); + JsonValue value = member.getValue(); + try { + switch (memberName) { + case "sha1": + this.sha1 = value.asString(); + break; + case "version_number": + this.versionNumber = value.asString(); + break; + case "comment_count": + this.commentCount = value.asLong(); + break; + case "permissions": + this.permissions = this.parsePermissions(value.asObject()); + break; + case "extension": + this.extension = value.asString(); + break; + case "is_package": + this.isPackage = value.asBoolean(); + break; + case "has_collaborations": + this.hasCollaborations = value.asBoolean(); + break; + case "is_externally_owned": + this.isExternallyOwned = value.asBoolean(); + break; + case "file_version": + this.version = this.parseFileVersion(value.asObject()); + break; + case "allowed_invitee_roles": + this.allowedInviteeRoles = this.parseAllowedInviteeRoles(value.asArray()); + break; + case "expiring_embed_link": + try { + String urlString = member.getValue().asObject().get("url").asString(); + this.previewLink = new URL(urlString); + } catch (MalformedURLException e) { + throw new BoxAPIException("Couldn't parse expiring_embed_link/url for file", e); + } + break; + case "lock": + if (value.isNull()) { + this.lock = null; } else { - // upload is multipart request but response is JSON - response = (BoxJSONResponse) request.send(listener); + this.lock = new BoxLock(value.asObject(), BoxFile.this.getAPI()); } - - String fileJSON = response.getJsonObject().get("entries").asArray().get(0).toString(); - - return new BoxFile.Info(fileJSON); - } finally { - Optional.ofNullable(response).ifPresent(BoxAPIResponse::close); - } - } - - /** - * Gets an expiring URL for creating an embedded preview session. The URL will expire after 60 seconds and the - * preview session will expire after 60 minutes. - * - * @return the expiring preview link - */ - public URL getPreviewLink() { - BoxFile.Info info = this.getInfo("expiring_embed_link"); - - return info.getPreviewLink(); - } - - /** - * Gets a list of any comments on this file. - * - * @return a list of comments on this file. - */ - public List getComments() { - URL url = GET_COMMENTS_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - - int totalCount = responseJSON.get("total_count").asInt(); - List comments = new ArrayList<>(totalCount); - JsonArray entries = responseJSON.get("entries").asArray(); - for (JsonValue value : entries) { - JsonObject commentJSON = value.asObject(); - BoxComment comment = new BoxComment(this.getAPI(), commentJSON.get("id").asString()); - BoxComment.Info info = comment.new Info(commentJSON); - comments.add(info); + break; + case "watermark_info": + this.isWatermarked = value.asObject().get("is_watermarked").asBoolean(); + break; + case "metadata": + this.metadataMap = Parsers.parseAndPopulateMetadataMap(value.asObject()); + break; + case "representations": + this.representations = Parsers.parseRepresentations(value.asObject()); + break; + case "uploader_display_name": + this.uploaderDisplayName = value.asString(); + break; + case "classification": + if (value.isNull()) { + this.classification = null; + } else { + this.classification = new BoxClassification(value.asObject()); } - - return comments; + break; + case "disposition_at": + this.dispositionAt = BoxDateFormat.parse(value.asString()); + break; + case "is_accessible_via_shared_link": + this.isAccessibleViaSharedLink = value.asBoolean(); + break; + default: + break; + } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); + } + } + + @SuppressWarnings("checkstyle:MissingSwitchDefault") + private EnumSet parsePermissions(JsonObject jsonObject) { + EnumSet permissions = EnumSet.noneOf(Permission.class); + for (JsonObject.Member member : jsonObject) { + JsonValue value = member.getValue(); + if (value.isNull() || !value.asBoolean()) { + continue; } - } - - /** - * Gets a list of any tasks on this file with requested fields. - * - * @param fields optional fields to retrieve for this task. - * @return a list of tasks on this file. - */ - public List getTasks(String... fields) { - QueryStringBuilder builder = new QueryStringBuilder(); - if (fields.length > 0) { - builder.appendParam("fields", fields); + try { + permissions.add(Permission.fromJSONValue(member.getName())); + } catch (IllegalArgumentException ignored) { + // If the permission is not recognized, we ignore it. } - URL url = GET_TASKS_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), builder.toString(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - - int totalCount = responseJSON.get("total_count").asInt(); - List tasks = new ArrayList<>(totalCount); - JsonArray entries = responseJSON.get("entries").asArray(); - for (JsonValue value : entries) { - JsonObject taskJSON = value.asObject(); - BoxTask task = new BoxTask(this.getAPI(), taskJSON.get("id").asString()); - BoxTask.Info info = task.new Info(taskJSON); - tasks.add(info); - } + } - return tasks; - } + return permissions; } - /** - * Creates metadata on this file in the global properties template. - * - * @param metadata The new metadata values. - * @return the metadata returned from the server. - */ - public Metadata createMetadata(Metadata metadata) { - return this.createMetadata(Metadata.DEFAULT_METADATA_TYPE, metadata); + private BoxFileVersion parseFileVersion(JsonObject jsonObject) { + return new BoxFileVersion(BoxFile.this.getAPI(), jsonObject, BoxFile.this.getID()); } - /** - * Creates metadata on this file in the specified template type. - * - * @param typeName the metadata template type name. - * @param metadata the new metadata values. - * @return the metadata returned from the server. - */ - public Metadata createMetadata(String typeName, Metadata metadata) { - String scope = Metadata.scopeBasedOnType(typeName); - return this.createMetadata(typeName, scope, metadata); - } + private List parseAllowedInviteeRoles(JsonArray jsonArray) { + List roles = new ArrayList<>(jsonArray.size()); + for (JsonValue value : jsonArray) { + roles.add(value.asString()); + } - /** - * Creates metadata on this file in the specified template type. - * - * @param typeName the metadata template type name. - * @param scope the metadata scope (global or enterprise). - * @param metadata the new metadata values. - * @return the metadata returned from the server. - */ - public Metadata createMetadata(String typeName, String scope, Metadata metadata) { - URL url = METADATA_URL_TEMPLATE.buildAlpha(this.getAPI().getBaseURL(), this.getID(), scope, typeName); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); - request.setBody(metadata.toString()); - try (BoxJSONResponse response = request.send()) { - return new Metadata(Json.parse(response.getJSON()).asObject()); - } + return roles; } - - /** - * Sets the provided metadata on the file. If metadata has already been created on this file, - * it overwrites metadata keys specified in the `metadata` param. - * - * @param templateName the name of the metadata template. - * @param scope the scope of the template (usually "global" or "enterprise"). - * @param metadata the new metadata values. - * @return the metadata returned from the server. - */ - public Metadata setMetadata(String templateName, String scope, Metadata metadata) { - try { - return this.createMetadata(templateName, scope, metadata); - } catch (BoxAPIException e) { - if (e.getResponseCode() == 409) { - if (metadata.getOperations().isEmpty()) { - return getMetadata(); - } else { - return updateExistingTemplate(templateName, scope, metadata); - } - } else { - throw e; - } - } - } - - private Metadata updateExistingTemplate(String templateName, String scope, Metadata metadata) { - Metadata metadataToUpdate = new Metadata(scope, templateName); - for (JsonValue value : metadata.getOperations()) { - if (value.asObject().get("value").isNumber()) { - metadataToUpdate.add(value.asObject().get("path").asString(), - value.asObject().get("value").asDouble()); - } else if (value.asObject().get("value").isString()) { - metadataToUpdate.add(value.asObject().get("path").asString(), - value.asObject().get("value").asString()); - } else if (value.asObject().get("value").isArray()) { - ArrayList list = new ArrayList<>(); - for (JsonValue jsonValue : value.asObject().get("value").asArray()) { - list.add(jsonValue.asString()); - } - metadataToUpdate.add(value.asObject().get("path").asString(), list); - } - } - return this.updateMetadata(metadataToUpdate); - } - - /** - * Adds a metadata classification to the specified file. - * - * @param classificationType the metadata classification type. - * @return the metadata classification type added to the file. - */ - public String addClassification(String classificationType) { - Metadata metadata = new Metadata().add(Metadata.CLASSIFICATION_KEY, classificationType); - Metadata classification = this.createMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, - "enterprise", metadata); - - return classification.getString(Metadata.CLASSIFICATION_KEY); - } - - /** - * Updates a metadata classification on the specified file. - * - * @param classificationType the metadata classification type. - * @return the new metadata classification type updated on the file. - */ - public String updateClassification(String classificationType) { - Metadata metadata = new Metadata("enterprise", Metadata.CLASSIFICATION_TEMPLATE_KEY); - metadata.add("/Box__Security__Classification__Key", classificationType); - Metadata classification = this.updateMetadata(metadata); - - return classification.getString(Metadata.CLASSIFICATION_KEY); - } - - /** - * Attempts to add classification to a file. If classification already exists then do update. - * - * @param classificationType the metadata classification type. - * @return the metadata classification type on the file. - */ - public String setClassification(String classificationType) { - Metadata metadata = new Metadata().add(Metadata.CLASSIFICATION_KEY, classificationType); - Metadata classification; - - try { - classification = this.createMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, "enterprise", metadata); - } catch (BoxAPIException e) { - if (e.getResponseCode() == 409) { - metadata = new Metadata("enterprise", Metadata.CLASSIFICATION_TEMPLATE_KEY); - metadata.replace(Metadata.CLASSIFICATION_KEY, classificationType); - classification = this.updateMetadata(metadata); - } else { - throw e; - } - } - - return classification.getString(Metadata.CLASSIFICATION_KEY); - } - - /** - * Gets the classification type for the specified file. - * - * @return the metadata classification type on the file. - */ - public String getClassification() { - Metadata metadata; - try { - metadata = this.getMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY); - - } catch (BoxAPIException e) { - JsonObject responseObject = Json.parse(e.getResponse()).asObject(); - String code = responseObject.get("code").asString(); - - if (e.getResponseCode() == 404 && code.equals("instance_not_found")) { - return null; - } else { - throw e; - } - } - - return metadata.getString(Metadata.CLASSIFICATION_KEY); - } - - /** - * Deletes the classification on the file. - */ - public void deleteClassification() { - this.deleteMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, "enterprise"); - } - - /** - * Locks a file. - * - * @return the lock returned from the server. - */ - public BoxLock lock() { - return this.lock(null, false); - } - - /** - * Locks a file. - * - * @param isDownloadPrevented is downloading of file prevented when locked. - * @return the lock returned from the server. - */ - public BoxLock lock(boolean isDownloadPrevented) { - return this.lock(null, isDownloadPrevented); - } - - /** - * Locks a file. - * - * @param expiresAt expiration date of the lock. - * @return the lock returned from the server. - */ - public BoxLock lock(Date expiresAt) { - return this.lock(expiresAt, false); - } - - /** - * Locks a file. - * - * @param expiresAt expiration date of the lock. - * @param isDownloadPrevented is downloading of file prevented when locked. - * @return the lock returned from the server. - */ - public BoxLock lock(Date expiresAt, boolean isDownloadPrevented) { - String queryString = new QueryStringBuilder().appendParam("fields", "lock").toString(); - URL url = FILE_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); - - JsonObject lockConfig = new JsonObject(); - lockConfig.add("type", "lock"); - if (expiresAt != null) { - lockConfig.add("expires_at", BoxDateFormat.format(expiresAt)); - } - lockConfig.add("is_download_prevented", isDownloadPrevented); - - JsonObject requestJSON = new JsonObject(); - requestJSON.add("lock", lockConfig); - request.setBody(requestJSON.toString()); - - try (BoxJSONResponse response = request.send()) { - - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - JsonValue lockValue = responseJSON.get("lock"); - JsonObject lockJSON = Json.parse(lockValue.toString()).asObject(); - - return new BoxLock(lockJSON, this.getAPI()); - } - } - - /** - * Unlocks a file. - */ - public void unlock() { - String queryString = new QueryStringBuilder().appendParam("fields", "lock").toString(); - URL url = FILE_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID()); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "PUT"); - - JsonObject lockObject = new JsonObject(); - lockObject.add("lock", NULL); - - request.setBody(lockObject.toString()); - request.send().close(); - } - - /** - * Used to retrieve all metadata associated with the file. - * - * @param fields the optional fields to retrieve. - * @return An iterable of metadata instances associated with the file. - */ - public Iterable getAllMetadata(String... fields) { - return Metadata.getAllMetadata(this, fields); - } - - /** - * Gets the file properties metadata. - * - * @return the metadata returned from the server. - */ - public Metadata getMetadata() { - return this.getMetadata(Metadata.DEFAULT_METADATA_TYPE); - } - - /** - * Gets the file metadata of specified template type. - * - * @param typeName the metadata template type name. - * @return the metadata returned from the server. - */ - public Metadata getMetadata(String typeName) { - String scope = Metadata.scopeBasedOnType(typeName); - return this.getMetadata(typeName, scope); - } - - /** - * Gets the file metadata of specified template type. - * - * @param typeName the metadata template type name. - * @param scope the metadata scope (global or enterprise). - * @return the metadata returned from the server. - */ - public Metadata getMetadata(String typeName, String scope) { - URL url = METADATA_URL_TEMPLATE.buildAlpha(this.getAPI().getBaseURL(), this.getID(), scope, typeName); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); - try (BoxJSONResponse response = request.send()) { - return new Metadata(Json.parse(response.getJSON()).asObject()); - } - } - - /** - * Updates the file metadata. - * - * @param metadata the new metadata values. - * @return the metadata returned from the server. - */ - public Metadata updateMetadata(Metadata metadata) { - String scope; - if (metadata.getScope().equals(Metadata.GLOBAL_METADATA_SCOPE)) { - scope = Metadata.GLOBAL_METADATA_SCOPE; - } else if (metadata.getScope().startsWith(Metadata.ENTERPRISE_METADATA_SCOPE)) { - scope = metadata.getScope(); - } else { - scope = Metadata.ENTERPRISE_METADATA_SCOPE; - } - - URL url = METADATA_URL_TEMPLATE.buildAlpha(this.getAPI().getBaseURL(), this.getID(), - scope, metadata.getTemplateName()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT", APPLICATION_JSON_PATCH); - request.setBody(metadata.getPatch()); - try (BoxJSONResponse response = request.send()) { - return new Metadata(Json.parse(response.getJSON()).asObject()); - } - } - - /** - * Deletes the file properties metadata. - */ - public void deleteMetadata() { - this.deleteMetadata(Metadata.DEFAULT_METADATA_TYPE); - } - - /** - * Deletes the file metadata of specified template type. - * - * @param typeName the metadata template type name. - */ - public void deleteMetadata(String typeName) { - String scope = Metadata.scopeBasedOnType(typeName); - this.deleteMetadata(typeName, scope); - } - - /** - * Deletes the file metadata of specified template type. - * - * @param typeName the metadata template type name. - * @param scope the metadata scope (global or enterprise). - */ - public void deleteMetadata(String typeName, String scope) { - URL url = METADATA_URL_TEMPLATE.buildAlpha(this.getAPI().getBaseURL(), this.getID(), scope, typeName); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); - request.send().close(); - } - - /** - * Used to retrieve the watermark for the file. - * If the file does not have a watermark applied to it, a 404 Not Found will be returned by API. - * - * @param fields the fields to retrieve. - * @return the watermark associated with the file. - */ - public BoxWatermark getWatermark(String... fields) { - return this.getWatermark(FILE_URL_TEMPLATE, fields); - } - - /** - * Used to apply or update the watermark for the file. - * - * @return the watermark associated with the file. - */ - public BoxWatermark applyWatermark() { - return this.applyWatermark(FILE_URL_TEMPLATE, BoxWatermark.WATERMARK_DEFAULT_IMPRINT); - } - - /** - * Removes a watermark from the file. - * If the file did not have a watermark applied to it, a 404 Not Found will be returned by API. - */ - public void removeWatermark() { - this.removeWatermark(FILE_URL_TEMPLATE); - } - - /** - * {@inheritDoc} - */ - @Override - public BoxFile.Info setCollections(BoxCollection... collections) { - JsonArray jsonArray = new JsonArray(); - for (BoxCollection collection : collections) { - JsonObject collectionJSON = new JsonObject(); - collectionJSON.add("id", collection.getID()); - jsonArray.add(collectionJSON); - } - JsonObject infoJSON = new JsonObject(); - infoJSON.add("collections", jsonArray); - - String queryString = new QueryStringBuilder().appendParam("fields", ALL_FIELDS).toString(); - URL url = FILE_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); - request.setBody(infoJSON.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - return new Info(jsonObject); - } - } - - /** - * Creates an upload session to create a new version of a file in chunks. - * This will first verify that the version can be created and then open a session for uploading pieces of the file. - * - * @param fileSize the size of the file that will be uploaded. - * @return the created upload session instance. - */ - public BoxFileUploadSession.Info createUploadSession(long fileSize) { - URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL(), this.getID()); - - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); - request.addHeader("Content-Type", APPLICATION_JSON); - - JsonObject body = new JsonObject(); - body.add("file_size", fileSize); - request.setBody(body.toString()); - - try (BoxJSONResponse response = request.send()) { - JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - - String sessionId = jsonObject.get("id").asString(); - BoxFileUploadSession session = new BoxFileUploadSession(this.getAPI(), sessionId); - return session.new Info(jsonObject); - } - } - - /** - * Creates a new version of a file. - * - * @param inputStream the stream instance that contains the data. - * @param fileSize the size of the file that will be uploaded. - * @return the created file instance. - * @throws InterruptedException when a thread execution is interrupted. - * @throws IOException when reading a stream throws exception. - */ - public BoxFile.Info uploadLargeFile(InputStream inputStream, long fileSize) - throws InterruptedException, IOException { - URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL(), this.getID()); - return new LargeFileUpload().upload(this.getAPI(), inputStream, url, fileSize); - } - - /** - * Creates a new version of a file. Also sets file attributes. - * - * @param inputStream the stream instance that contains the data. - * @param fileSize the size of the file that will be uploaded. - * @param fileAttributes file attributes to set - * @return the created file instance. - * @throws InterruptedException when a thread execution is interrupted. - * @throws IOException when reading a stream throws exception. - */ - public BoxFile.Info uploadLargeFile(InputStream inputStream, long fileSize, Map fileAttributes) - throws InterruptedException, IOException { - URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL(), this.getID()); - return new LargeFileUpload().upload(this.getAPI(), inputStream, url, fileSize, fileAttributes); - } - - /** - * Creates a new version of a file using specified number of parallel http connections. - * - * @param inputStream the stream instance that contains the data. - * @param fileSize the size of the file that will be uploaded. - * @param nParallelConnections number of parallel http connections to use - * @param timeOut time to wait before killing the job - * @param unit time unit for the time wait value - * @return the created file instance. - * @throws InterruptedException when a thread execution is interrupted. - * @throws IOException when reading a stream throws exception. - */ - public BoxFile.Info uploadLargeFile(InputStream inputStream, long fileSize, - int nParallelConnections, long timeOut, TimeUnit unit) - throws InterruptedException, IOException { - URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL(), this.getID()); - return new LargeFileUpload(nParallelConnections, timeOut, unit) - .upload(this.getAPI(), inputStream, url, fileSize); - } - - /** - * Creates a new version of a file using specified number of parallel http connections. Also sets file attributes. - * - * @param inputStream the stream instance that contains the data. - * @param fileSize the size of the file that will be uploaded. - * @param nParallelConnections number of parallel http connections to use - * @param timeOut time to wait before killing the job - * @param unit time unit for the time wait value - * @param fileAttributes file attributes to set - * @return the created file instance. - * @throws InterruptedException when a thread execution is interrupted. - * @throws IOException when reading a stream throws exception. - */ - public BoxFile.Info uploadLargeFile(InputStream inputStream, long fileSize, - int nParallelConnections, long timeOut, TimeUnit unit, - Map fileAttributes) - throws InterruptedException, IOException { - URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL(), this.getID()); - return new LargeFileUpload(nParallelConnections, timeOut, unit) - .upload(this.getAPI(), inputStream, url, fileSize, fileAttributes); - } - - private BoxCollaboration.Info collaborate(JsonObject accessibleByField, BoxCollaboration.Role role, - Boolean notify, Boolean canViewPath, Date expiresAt, - Boolean isAccessOnly) { - - JsonObject itemField = new JsonObject(); - itemField.add("id", this.getID()); - itemField.add("type", "file"); - - return BoxCollaboration.create(this.getAPI(), accessibleByField, itemField, role, notify, canViewPath, - expiresAt, isAccessOnly); - } - - /** - * Adds a collaborator to this file. - * - * @param collaborator the collaborator to add. - * @param role the role of the collaborator. - * @param notify determines if the user (or all the users in the group) will receive email notifications. - * @param canViewPath whether view path collaboration feature is enabled or not. - * @param expiresAt when the collaboration should expire. - * @param isAccessOnly whether the collaboration is access only or not. - * @return info about the new collaboration. - */ - public BoxCollaboration.Info collaborate(BoxCollaborator collaborator, BoxCollaboration.Role role, - Boolean notify, Boolean canViewPath, - Date expiresAt, Boolean isAccessOnly) { - JsonObject accessibleByField = new JsonObject(); - accessibleByField.add("id", collaborator.getID()); - - if (collaborator instanceof BoxUser) { - accessibleByField.add("type", "user"); - } else if (collaborator instanceof BoxGroup) { - accessibleByField.add("type", "group"); - } else { - throw new IllegalArgumentException("The given collaborator is of an unknown type."); - } - return this.collaborate(accessibleByField, role, notify, canViewPath, expiresAt, isAccessOnly); - } - - /** - * Adds a collaborator to this file. - * - * @param collaborator the collaborator to add. - * @param role the role of the collaborator. - * @param notify determines if the user (or all the users in the group) will receive email notifications. - * @param canViewPath whether view path collaboration feature is enabled or not. - * @return info about the new collaboration. - */ - public BoxCollaboration.Info collaborate(BoxCollaborator collaborator, BoxCollaboration.Role role, - Boolean notify, Boolean canViewPath) { - return this.collaborate(collaborator, role, notify, canViewPath, null, null); - } - - /** - * Adds a collaborator to this folder. An email will be sent to the collaborator if they don't already have a Box - * account. - * - * @param email the email address of the collaborator to add. - * @param role the role of the collaborator. - * @param notify determines if the user (or all the users in the group) will receive email notifications. - * @param canViewPath whether view path collaboration feature is enabled or not. - * @param expiresAt when the collaboration should expire. - * @param isAccessOnly whether the collaboration is access only or not. - * @return info about the new collaboration. - */ - public BoxCollaboration.Info collaborate(String email, BoxCollaboration.Role role, - Boolean notify, Boolean canViewPath, - Date expiresAt, Boolean isAccessOnly) { - JsonObject accessibleByField = new JsonObject(); - accessibleByField.add("login", email); - accessibleByField.add("type", "user"); - - return this.collaborate(accessibleByField, role, notify, canViewPath, expiresAt, isAccessOnly); - } - - /** - * Adds a collaborator to this folder. An email will be sent to the collaborator if they don't already have a Box - * account. - * - * @param email the email address of the collaborator to add. - * @param role the role of the collaborator. - * @param notify determines if the user (or all the users in the group) will receive email notifications. - * @param canViewPath whether view path collaboration feature is enabled or not. - * @return info about the new collaboration. - */ - public BoxCollaboration.Info collaborate(String email, BoxCollaboration.Role role, - Boolean notify, Boolean canViewPath) { - return this.collaborate(email, role, notify, canViewPath, null, null); - } - - /** - * Used to retrieve all collaborations associated with the item. - * - * @param fields the optional fields to retrieve. - * @return An iterable of metadata instances associated with the item. - */ - public BoxResourceIterable getAllFileCollaborations(String... fields) { - return BoxCollaboration.getAllFileCollaborations(this.getAPI(), this.getID(), - GET_COLLABORATORS_PAGE_SIZE, fields); - - } - - /** - * Used to specify what filetype to request for a file thumbnail. - */ - public enum ThumbnailFileType { - /** - * PNG image format. - */ - PNG, - - /** - * JPG image format. - */ - JPG - } - - /** - * Enumerates the possible permissions that a user can have on a file. - */ - public enum Permission { - /** - * The user can download the file. - */ - CAN_DOWNLOAD("can_download"), - - /** - * The user can upload new versions of the file. - */ - CAN_UPLOAD("can_upload"), - - /** - * The user can rename the file. - */ - CAN_RENAME("can_rename"), - - /** - * The user can delete the file. - */ - CAN_DELETE("can_delete"), - - /** - * The user can share the file. - */ - CAN_SHARE("can_share"), - - /** - * The user can set the access level for shared links to the file. - */ - CAN_SET_SHARE_ACCESS("can_set_share_access"), - - /** - * The user can preview the file. - */ - CAN_PREVIEW("can_preview"), - - /** - * The user can comment on the file. - */ - CAN_COMMENT("can_comment"), - - /** - * The user can place annotations on this file. - */ - CAN_ANNOTATE("can_annotate"), - - /** - * The current user can invite new users to collaborate on this item, and the user can update the role of a - * user already collaborated on this item. - */ - CAN_INVITE_COLLABORATOR("can_invite_collaborator"), - - /** - * The user can view all annotations placed on this file. - */ - CAN_VIEW_ANNOTATIONS_ALL("can_view_annotations_all"), - - /** - * The user can view annotations placed by themselves on this file. - */ - CAN_VIEW_ANNOTATIONS_SELF("can_view_annotations_self"); - - private final String jsonValue; - - Permission(String jsonValue) { - this.jsonValue = jsonValue; - } - - static Permission fromJSONValue(String jsonValue) { - return Permission.valueOf(jsonValue.toUpperCase(java.util.Locale.ROOT)); - } - - String toJSONValue() { - return this.jsonValue; - } - } - - /** - * Contains information about a BoxFile. - */ - public class Info extends BoxItem.Info { - private String sha1; - private String versionNumber; - private long commentCount; - private EnumSet permissions; - private String extension; - private boolean isPackage; - private BoxFileVersion version; - private URL previewLink; - private BoxLock lock; - private boolean isWatermarked; - private boolean isExternallyOwned; - private Map> metadataMap; - private List representations; - private List allowedInviteeRoles; - private Boolean hasCollaborations; - private String uploaderDisplayName; - private BoxClassification classification; - private Date dispositionAt; - private boolean isAccessibleViaSharedLink; - - /** - * Constructs an empty Info object. - */ - public Info() { - super(); - } - - /** - * Constructs an Info object by parsing information from a JSON string. - * - * @param json the JSON string to parse. - */ - public Info(String json) { - super(json); - } - - /** - * Constructs an Info object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - public Info(JsonObject jsonObject) { - super(jsonObject); - } - - @Override - public BoxFile getResource() { - return BoxFile.this; - } - - /** - * Gets the SHA1 hash of the file. - * - * @return the SHA1 hash of the file. - */ - public String getSha1() { - return this.sha1; - } - - /** - * Gets the lock of the file. - * - * @return the lock of the file. - */ - public BoxLock getLock() { - return this.lock; - } - - /** - * Gets the current version number of the file. - * - * @return the current version number of the file. - */ - public String getVersionNumber() { - return this.versionNumber; - } - - /** - * Gets the number of comments on the file. - * - * @return the number of comments on the file. - */ - public long getCommentCount() { - return this.commentCount; - } - - /** - * Gets the permissions that the current user has on the file. - * - * @return the permissions that the current user has on the file. - */ - public EnumSet getPermissions() { - return this.permissions; - } - - /** - * Gets the extension suffix of the file, excluding the dot. - * - * @return the extension of the file. - */ - public String getExtension() { - return this.extension; - } - - /** - * Gets whether or not the file is an OSX package. - * - * @return true if the file is an OSX package; otherwise false. - */ - public boolean getIsPackage() { - return this.isPackage; - } - - /** - * Gets the current version details of the file. - * - * @return the current version details of the file. - */ - public BoxFileVersion getVersion() { - return this.version; - } - - /** - * Gets the current expiring preview link. - * - * @return the expiring preview link - */ - public URL getPreviewLink() { - return this.previewLink; - } - - /** - * Gets flag indicating whether this file is Watermarked. - * - * @return whether the file is watermarked or not - */ - public boolean getIsWatermarked() { - return this.isWatermarked; - } - - /** - * Returns the allowed invitee roles for this file item. - * - * @return the list of roles allowed for invited collaborators. - */ - public List getAllowedInviteeRoles() { - return this.allowedInviteeRoles; - } - - /** - * Returns the indicator for whether this file item has collaborations. - * - * @return indicator for whether this file item has collaborations. - */ - public Boolean getHasCollaborations() { - return this.hasCollaborations; - } - - /** - * Gets the metadata on this file associated with a specified scope and template. - * Makes an attempt to get metadata that was retrieved using getInfo(String ...) method. - * - * @param templateName the metadata template type name. - * @param scope the scope of the template (usually "global" or "enterprise"). - * @return the metadata returned from the server. - */ - public Metadata getMetadata(String templateName, String scope) { - try { - return this.metadataMap.get(scope).get(templateName); - } catch (NullPointerException e) { - return null; - } - } - - /** - * Returns the field for indicating whether a file is owned by a user outside the enterprise. - * - * @return indicator for whether or not the file is owned by a user outside the enterprise. - */ - public boolean getIsExternallyOwned() { - return this.isExternallyOwned; - } - - /** - * Get file's representations. - * - * @return list of representations - */ - public List getRepresentations() { - return this.representations; - } - - /** - * Returns user's name at the time of upload. - * - * @return user's name at the time of upload - */ - public String getUploaderDisplayName() { - return this.uploaderDisplayName; - } - - /** - * Gets the metadata classification type of this file. - * - * @return the metadata classification type of this file. - */ - public BoxClassification getClassification() { - return this.classification; - } - - /** - * Returns the retention expiration timestamp for the given file. - * - * @return Date representing expiration timestamp - */ - public Date getDispositionAt() { - return dispositionAt; - } - - /** - * Modifies the retention expiration timestamp for the given file. - * This date cannot be shortened once set on a file. - * - * @param dispositionAt Date representing expiration timestamp - */ - public void setDispositionAt(Date dispositionAt) { - this.dispositionAt = dispositionAt; - this.addPendingChange("disposition_at", BoxDateFormat.format(dispositionAt)); - } - - /** - * Returns the flag indicating whether the file is accessible via a shared link. - * - * @return boolean flag indicating whether the file is accessible via a shared link. - */ - public boolean getIsAccessibleViaSharedLink() { - return this.isAccessibleViaSharedLink; - } - - @Override - protected void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - - String memberName = member.getName(); - JsonValue value = member.getValue(); - try { - switch (memberName) { - case "sha1": - this.sha1 = value.asString(); - break; - case "version_number": - this.versionNumber = value.asString(); - break; - case "comment_count": - this.commentCount = value.asLong(); - break; - case "permissions": - this.permissions = this.parsePermissions(value.asObject()); - break; - case "extension": - this.extension = value.asString(); - break; - case "is_package": - this.isPackage = value.asBoolean(); - break; - case "has_collaborations": - this.hasCollaborations = value.asBoolean(); - break; - case "is_externally_owned": - this.isExternallyOwned = value.asBoolean(); - break; - case "file_version": - this.version = this.parseFileVersion(value.asObject()); - break; - case "allowed_invitee_roles": - this.allowedInviteeRoles = this.parseAllowedInviteeRoles(value.asArray()); - break; - case "expiring_embed_link": - try { - String urlString = member.getValue().asObject().get("url").asString(); - this.previewLink = new URL(urlString); - } catch (MalformedURLException e) { - throw new BoxAPIException("Couldn't parse expiring_embed_link/url for file", e); - } - break; - case "lock": - if (value.isNull()) { - this.lock = null; - } else { - this.lock = new BoxLock(value.asObject(), BoxFile.this.getAPI()); - } - break; - case "watermark_info": - this.isWatermarked = value.asObject().get("is_watermarked").asBoolean(); - break; - case "metadata": - this.metadataMap = Parsers.parseAndPopulateMetadataMap(value.asObject()); - break; - case "representations": - this.representations = Parsers.parseRepresentations(value.asObject()); - break; - case "uploader_display_name": - this.uploaderDisplayName = value.asString(); - break; - case "classification": - if (value.isNull()) { - this.classification = null; - } else { - this.classification = new BoxClassification(value.asObject()); - } - break; - case "disposition_at": - this.dispositionAt = BoxDateFormat.parse(value.asString()); - break; - case "is_accessible_via_shared_link": - this.isAccessibleViaSharedLink = value.asBoolean(); - break; - default: - break; - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); - } - } - - @SuppressWarnings("checkstyle:MissingSwitchDefault") - private EnumSet parsePermissions(JsonObject jsonObject) { - EnumSet permissions = EnumSet.noneOf(Permission.class); - for (JsonObject.Member member : jsonObject) { - JsonValue value = member.getValue(); - if (value.isNull() || !value.asBoolean()) { - continue; - } - try { - permissions.add(Permission.fromJSONValue(member.getName())); - } catch (IllegalArgumentException ignored) { - // If the permission is not recognized, we ignore it. - } - } - - return permissions; - } - - private BoxFileVersion parseFileVersion(JsonObject jsonObject) { - return new BoxFileVersion(BoxFile.this.getAPI(), jsonObject, BoxFile.this.getID()); - } - - private List parseAllowedInviteeRoles(JsonArray jsonArray) { - List roles = new ArrayList<>(jsonArray.size()); - for (JsonValue value : jsonArray) { - roles.add(value.asString()); - } - - return roles; - } - } - + } } diff --git a/src/main/java/com/box/sdk/BoxFileRequest.java b/src/main/java/com/box/sdk/BoxFileRequest.java index d37d59368..8c2099607 100644 --- a/src/main/java/com/box/sdk/BoxFileRequest.java +++ b/src/main/java/com/box/sdk/BoxFileRequest.java @@ -7,485 +7,476 @@ import java.net.URL; import java.util.Date; -/** - * Represents a file request on Box. - */ +/** Represents a file request on Box. */ @BoxResourceType("file_request") public class BoxFileRequest extends BoxResource { + /** File Request URL Template. */ + public static final URLTemplate FILE_REQUEST_URL_TEMPLATE = new URLTemplate("file_requests/%s"); + /** Copy File Request URL Template. */ + public static final URLTemplate COPY_FILE_REQUEST_URL_TEMPLATE = + new URLTemplate("file_requests/%s/copy"); + + /** + * Constructs a BoxFileRequest for a file request with a given ID. + * + * @param api the API connection to be used by the file request. + * @param id the ID of the file request. + */ + public BoxFileRequest(BoxAPIConnection api, String id) { + super(api, id); + } + + /** + * Gets information about this file request. + * + * @return info about this file request. + */ + public BoxFileRequest.Info getInfo() { + URL url = FILE_REQUEST_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + return new Info(responseJSON, this.getAPI().getBaseAppUrl()); + } + } + + /** + * Copies this file request that is already present on one folder, and applies it to another + * folder. + * + * @param folderId the ID of the folder for the file request. + * @return info about the newly copied file request. + */ + public BoxFileRequest.Info copyInfo(String folderId) { + URL url = COPY_FILE_REQUEST_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); + JsonObject body = new JsonObject(); + JsonObject folderBody = new JsonObject(); + folderBody.add("id", folderId); + folderBody.add("type", "folder"); + body.add("folder", folderBody); + request.setBody(body.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); + String id = jsonObject.get("id").asString(); + return new BoxFileRequest(this.getAPI(), id) + .new Info(jsonObject, this.getAPI().getBaseAppUrl()); + } + } + + /** + * Copies this file request that is already present on one folder, and applies it to another + * folder. + * + *

Info fields that have been modified locally will overwrite the values in the original file + * request. + * + * @param info the info. + * @param folderId the ID of the folder for the file request. + * @return info about the newly copied file request. + */ + public BoxFileRequest.Info copyInfo(BoxFileRequest.Info info, String folderId) { + URL url = COPY_FILE_REQUEST_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); + JsonObject body = new JsonObject(); + JsonObject pendingChanges = info.getPendingChangesAsJsonObject(); + if (pendingChanges != null) { + body = pendingChanges; + } + JsonObject folderBody = new JsonObject(); + folderBody.add("id", folderId); + folderBody.add("type", "folder"); + body.add("folder", folderBody); + request.setBody(body.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); + String id = jsonObject.get("id").asString(); + return new BoxFileRequest(this.getAPI(), id) + .new Info(jsonObject, this.getAPI().getBaseAppUrl()); + } + } + + /** + * Updates the information about this file request with any info fields that have been modified + * locally. + * + *

The only fields that will be updated are the ones that have been modified locally. For + * example, the following code won't update any information (or even send a network request) since + * none of the info's fields were changed: + * + *

BoxFileRequest fileRequest = new BoxFileRequest(api, id);
+   * BoxFileRequest.Info info = fileRequest.getInfo();
+   * info.updateInfo(info);
+ * + * @param info the updated info. + * @return info about the updated file request. + */ + public BoxFileRequest.Info updateInfo(BoxFileRequest.Info info) { + URL url = FILE_REQUEST_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); + request.setBody(info.getPendingChanges()); + try (BoxJSONResponse response = request.send()) { + JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); + info.update(jsonObject); + return info; + } + } + + /** Delete this file request. */ + public void delete() { + URL url = FILE_REQUEST_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); + request.send().close(); + } + + /** The status of the file request. */ + public enum Status { + /** The file request can accept new submissions. */ + ACTIVE("active"), + + /** The file request can't accept new submissions. */ + INACTIVE("inactive"); + + private final String jsonValue; + + Status(String jsonValue) { + this.jsonValue = jsonValue; + } + + static Status fromJSONString(String jsonValue) { + return Status.valueOf(jsonValue.toUpperCase(java.util.Locale.ROOT)); + } + + String toJSONString() { + return this.jsonValue; + } + } + + /** Contains information about a BoxFileRequest. */ + public class Info extends BoxResource.Info { + private String type; + private Date createdAt; + private BoxUser.Info createdBy; + private String description; + private String etag; + private Date expiresAt; + private BoxFolder.Info folder; + private boolean isDescriptionRequired; + private boolean isEmailRequired; + private Status status; + private String title; + private Date updatedAt; + private BoxUser.Info updatedBy; + private URL url; + private String path; + private String baseUrl; + + /** Constructs an empty Info object. */ + public Info() { + super(); + } + /** - * File Request URL Template. + * Constructs an Info object by parsing information from a JSON string. + * + * @param json the JSON string to parse. */ - public static final URLTemplate FILE_REQUEST_URL_TEMPLATE = new URLTemplate("file_requests/%s"); + public Info(String json) { + super(json); + } + /** - * Copy File Request URL Template. + * Constructs an Info object using an already parsed JSON object. + * + * @param jsonObject the parsed JSON object. + * @param fileRequestBaseUrl Request base URL */ - public static final URLTemplate COPY_FILE_REQUEST_URL_TEMPLATE = new URLTemplate("file_requests/%s/copy"); + Info(JsonObject jsonObject, String fileRequestBaseUrl) { + super(jsonObject); + try { + this.baseUrl = fileRequestBaseUrl; + this.url = new URL(this.baseUrl + this.path); + } catch (MalformedURLException e) { + throw new BoxAPIException("Couldn't construct url for file request", e); + } + } + + @Override + public BoxFileRequest getResource() { + return BoxFileRequest.this; + } /** - * Constructs a BoxFileRequest for a file request with a given ID. + * Gets the file request type. * - * @param api the API connection to be used by the file request. - * @param id the ID of the file request. + * @return the file request type. */ - public BoxFileRequest(BoxAPIConnection api, String id) { - super(api, id); + public String getType() { + return this.type; } /** - * Gets information about this file request. + * Gets the date when the file request was created. * - * @return info about this file request. + * @return the date when the file request was created. */ - public BoxFileRequest.Info getInfo() { - URL url = FILE_REQUEST_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - return new Info(responseJSON, this.getAPI().getBaseAppUrl()); - } + public Date getCreatedAt() { + return this.createdAt; } /** - * Copies this file request that is already present on one folder, and applies it to another folder. + * Gets the user who created this file request. * - * @param folderId the ID of the folder for the file request. - * @return info about the newly copied file request. + * @return the user who created this file request. */ - public BoxFileRequest.Info copyInfo(String folderId) { - URL url = COPY_FILE_REQUEST_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); - JsonObject body = new JsonObject(); - JsonObject folderBody = new JsonObject(); - folderBody.add("id", folderId); - folderBody.add("type", "folder"); - body.add("folder", folderBody); - request.setBody(body.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - String id = jsonObject.get("id").asString(); - return new BoxFileRequest(this.getAPI(), id).new Info(jsonObject, this.getAPI().getBaseAppUrl()); - } + public BoxUser.Info getCreatedBy() { + return this.createdBy; } /** - * Copies this file request that is already present on one folder, and applies it to another folder. + * Gets the description of this file request. * - *

Info fields that have been modified locally will overwrite the values in the original file request. - * - * @param info the info. - * @param folderId the ID of the folder for the file request. - * @return info about the newly copied file request. + * @return the description of this file request. */ - public BoxFileRequest.Info copyInfo(BoxFileRequest.Info info, String folderId) { - URL url = COPY_FILE_REQUEST_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); - JsonObject body = new JsonObject(); - JsonObject pendingChanges = info.getPendingChangesAsJsonObject(); - if (pendingChanges != null) { - body = pendingChanges; - } - JsonObject folderBody = new JsonObject(); - folderBody.add("id", folderId); - folderBody.add("type", "folder"); - body.add("folder", folderBody); - request.setBody(body.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - String id = jsonObject.get("id").asString(); - return new BoxFileRequest(this.getAPI(), id).new Info(jsonObject, this.getAPI().getBaseAppUrl()); - } + public String getDescription() { + return this.description; } /** - * Updates the information about this file request with any info fields that have been modified locally. - * - *

The only fields that will be updated are the ones that have been modified locally. For example, the following - * code won't update any information (or even send a network request) since none of the info's fields were - * changed:

- * - *
BoxFileRequest fileRequest = new BoxFileRequest(api, id);
-     * BoxFileRequest.Info info = fileRequest.getInfo();
-     * info.updateInfo(info);
+ * Sets the description of this file request. * - * @param info the updated info. - * @return info about the updated file request. + * @param description the file request's new description. */ - public BoxFileRequest.Info updateInfo(BoxFileRequest.Info info) { - URL url = FILE_REQUEST_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); - request.setBody(info.getPendingChanges()); - try (BoxJSONResponse response = request.send()) { - JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - info.update(jsonObject); - return info; - } + public void setDescription(String description) { + this.description = description; + this.addPendingChange("description", description); } /** - * Delete this file request. + * Gets a unique string identifying the version of the item. + * + * @return a unique string identifying the version of the item. */ - public void delete() { - URL url = FILE_REQUEST_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); - request.send().close(); + public String getEtag() { + return this.etag; } /** - * The status of the file request. + * Gets the date after which a file request will no longer accept new submissions. + * + * @return the date after which a file request will no longer accept new submissions. */ - public enum Status { - /** - * The file request can accept new submissions. - */ - ACTIVE("active"), - - /** - * The file request can't accept new submissions. - */ - INACTIVE("inactive"); - - private final String jsonValue; - - Status(String jsonValue) { - this.jsonValue = jsonValue; - } - - static Status fromJSONString(String jsonValue) { - return Status.valueOf(jsonValue.toUpperCase(java.util.Locale.ROOT)); - } - - String toJSONString() { - return this.jsonValue; - } + public Date getExpiresAt() { + return this.expiresAt; } /** - * Contains information about a BoxFileRequest. + * Sets the date after which a file request will no longer accept new submissions. + * + * @param expiresAt the date after which a file request will no longer accept new submissions. */ - public class Info extends BoxResource.Info { - private String type; - private Date createdAt; - private BoxUser.Info createdBy; - private String description; - private String etag; - private Date expiresAt; - private BoxFolder.Info folder; - private boolean isDescriptionRequired; - private boolean isEmailRequired; - private Status status; - private String title; - private Date updatedAt; - private BoxUser.Info updatedBy; - private URL url; - private String path; - private String baseUrl; - - /** - * Constructs an empty Info object. - */ - public Info() { - super(); - } - - /** - * Constructs an Info object by parsing information from a JSON string. - * - * @param json the JSON string to parse. - */ - public Info(String json) { - super(json); - } - - /** - * Constructs an Info object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - * @param fileRequestBaseUrl Request base URL - */ - Info(JsonObject jsonObject, String fileRequestBaseUrl) { - super(jsonObject); - try { - this.baseUrl = fileRequestBaseUrl; - this.url = new URL(this.baseUrl + this.path); - } catch (MalformedURLException e) { - throw new BoxAPIException("Couldn't construct url for file request", e); - } - } - - @Override - public BoxFileRequest getResource() { - return BoxFileRequest.this; - } - - /** - * Gets the file request type. - * - * @return the file request type. - */ - public String getType() { - return this.type; - } - - /** - * Gets the date when the file request was created. - * - * @return the date when the file request was created. - */ - public Date getCreatedAt() { - return this.createdAt; - } - - /** - * Gets the user who created this file request. - * - * @return the user who created this file request. - */ - public BoxUser.Info getCreatedBy() { - return this.createdBy; - } - - /** - * Gets the description of this file request. - * - * @return the description of this file request. - */ - public String getDescription() { - return this.description; - } - - /** - * Sets the description of this file request. - * - * @param description the file request's new description. - */ - public void setDescription(String description) { - this.description = description; - this.addPendingChange("description", description); - } - - /** - * Gets a unique string identifying the version of the item. - * - * @return a unique string identifying the version of the item. - */ - public String getEtag() { - return this.etag; - } - - /** - * Gets the date after which a file request will no longer accept new submissions. - * - * @return the date after which a file request will no longer accept new submissions. - */ - public Date getExpiresAt() { - return this.expiresAt; - } - - - /** - * Sets the date after which a file request will no longer accept new submissions. - * - * @param expiresAt the date after which a file request will no longer accept new submissions. - */ - public void setExpiresAt(Date expiresAt) { - this.expiresAt = expiresAt; - this.addPendingChange("expires_at", BoxDateFormat.format(expiresAt)); - } - - /** - * Gets the folder that this file request is associated with. - * - * @return the folder that this file request is associated with. - */ - public BoxFolder.Info getFolder() { - return this.folder; - } + public void setExpiresAt(Date expiresAt) { + this.expiresAt = expiresAt; + this.addPendingChange("expires_at", BoxDateFormat.format(expiresAt)); + } - /** - * Gets whether a file request submitter is required to provide a description of the files they are submitting. - * - * @return whether a file request submitter is required to provide a description of the files they - * are submitting. - */ - public Boolean getIsDescriptionRequired() { - return this.isDescriptionRequired; - } + /** + * Gets the folder that this file request is associated with. + * + * @return the folder that this file request is associated with. + */ + public BoxFolder.Info getFolder() { + return this.folder; + } - /** - * Sets whether a file request submitter is required to provide a description of the files they are submitting. - * - * @param isDescriptionRequired whether a file request submitter is required to provide a description of the - * files they are submitting. - */ - public void setIsDescriptionRequired(Boolean isDescriptionRequired) { - this.isDescriptionRequired = isDescriptionRequired; - this.addPendingChange("is_description_required", isDescriptionRequired); - } + /** + * Gets whether a file request submitter is required to provide a description of the files they + * are submitting. + * + * @return whether a file request submitter is required to provide a description of the files + * they are submitting. + */ + public Boolean getIsDescriptionRequired() { + return this.isDescriptionRequired; + } - /** - * Gets whether a file request submitter is required to provide their email address. - * - * @return whether a file request submitter is required to provide their email address. - */ - public Boolean getIsEmailRequired() { - return this.isEmailRequired; - } + /** + * Sets whether a file request submitter is required to provide a description of the files they + * are submitting. + * + * @param isDescriptionRequired whether a file request submitter is required to provide a + * description of the files they are submitting. + */ + public void setIsDescriptionRequired(Boolean isDescriptionRequired) { + this.isDescriptionRequired = isDescriptionRequired; + this.addPendingChange("is_description_required", isDescriptionRequired); + } - /** - * Sets whether a file request submitter is required to provide their email address. - * - * @param isEmailRequired whether a file request submitter is required to provide their email address. - */ - public void setIsEmailRequired(Boolean isEmailRequired) { - this.isEmailRequired = isEmailRequired; - this.addPendingChange("is_email_required", isEmailRequired); - } + /** + * Gets whether a file request submitter is required to provide their email address. + * + * @return whether a file request submitter is required to provide their email address. + */ + public Boolean getIsEmailRequired() { + return this.isEmailRequired; + } - /** - * Gets the status of the file request. - * - * @return the status of the file request - */ - public Status getStatus() { - return this.status; - } + /** + * Sets whether a file request submitter is required to provide their email address. + * + * @param isEmailRequired whether a file request submitter is required to provide their email + * address. + */ + public void setIsEmailRequired(Boolean isEmailRequired) { + this.isEmailRequired = isEmailRequired; + this.addPendingChange("is_email_required", isEmailRequired); + } + /** + * Gets the status of the file request. + * + * @return the status of the file request + */ + public Status getStatus() { + return this.status; + } - /** - * Sets the status of the file request. - * - * @param status the status of the file request - */ - public void setStatus(Status status) { - this.status = status; - this.addPendingChange("status", status.toJSONString()); - } + /** + * Sets the status of the file request. + * + * @param status the status of the file request + */ + public void setStatus(Status status) { + this.status = status; + this.addPendingChange("status", status.toJSONString()); + } - /** - * Gets the title of file request. - * - * @return the title of file request. - */ - public String getTitle() { - return this.title; - } + /** + * Gets the title of file request. + * + * @return the title of file request. + */ + public String getTitle() { + return this.title; + } - /** - * Sets the title of file request. - * - * @param title the title of file request. - */ - public void setTitle(String title) { - this.title = title; - this.addPendingChange("title", title); - } + /** + * Sets the title of file request. + * + * @param title the title of file request. + */ + public void setTitle(String title) { + this.title = title; + this.addPendingChange("title", title); + } - /** - * Gets the date when the file request was last updated. - * - * @return the date when the file request was last updated. - */ - public Date getUpdatedAt() { - return this.updatedAt; - } + /** + * Gets the date when the file request was last updated. + * + * @return the date when the file request was last updated. + */ + public Date getUpdatedAt() { + return this.updatedAt; + } - /** - * Gets the user who last modified this file request. - * - * @return the user who last modified this file request. - */ - public BoxUser.Info getUpdatedBy() { - return this.updatedBy; - } + /** + * Gets the user who last modified this file request. + * + * @return the user who last modified this file request. + */ + public BoxUser.Info getUpdatedBy() { + return this.updatedBy; + } - /** - * Gets the URL can be shared with users to let them upload files to the associated folder. - * - * @return the URL for files upload. - */ - public URL getUrl() { - return this.url; - } + /** + * Gets the URL can be shared with users to let them upload files to the associated folder. + * + * @return the URL for files upload. + */ + public URL getUrl() { + return this.url; + } - /** - * Gets the base URL for the upload files link. - * - * @return the base url including protocol and hostname. - */ - public String getBaseUrl() { - return this.baseUrl; - } + /** + * Gets the base URL for the upload files link. + * + * @return the base url including protocol and hostname. + */ + public String getBaseUrl() { + return this.baseUrl; + } - /** - * Sets the base URL for the upload files link. Can throw an exception if format of the URL is invalid. - * - * @param baseUrl the base url including protocol and hostname. - * @throws MalformedURLException when baseUrl format is invalid. - */ - public void setBaseUrl(String baseUrl) throws MalformedURLException { - this.baseUrl = baseUrl; - this.url = new URL(this.baseUrl + this.path); - } + /** + * Sets the base URL for the upload files link. Can throw an exception if format of the URL is + * invalid. + * + * @param baseUrl the base url including protocol and hostname. + * @throws MalformedURLException when baseUrl format is invalid. + */ + public void setBaseUrl(String baseUrl) throws MalformedURLException { + this.baseUrl = baseUrl; + this.url = new URL(this.baseUrl + this.path); + } - /** - * Gets the URL containing only the path (e.g. "/f/123456789") shared with users to let - * them upload files to the associated folder. - * - * @return the path of the URL for files upload. - */ - public String getPath() { - return this.path; - } + /** + * Gets the URL containing only the path (e.g. "/f/123456789") shared with users to let them + * upload files to the associated folder. + * + * @return the path of the URL for files upload. + */ + public String getPath() { + return this.path; + } - @Override - void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - - String memberName = member.getName(); - JsonValue value = member.getValue(); - try { - if (memberName.equals("type")) { - this.type = value.asString(); - } else if (memberName.equals("created_at")) { - this.createdAt = BoxDateFormat.parse(value.asString()); - } else if (memberName.equals("created_by")) { - JsonObject userJSON = value.asObject(); - String userID = userJSON.get("id").asString(); - BoxUser user = new BoxUser(getAPI(), userID); - this.createdBy = user.new Info(userJSON); - } else if (memberName.equals("description")) { - this.description = value.asString(); - } else if (memberName.equals("etag")) { - this.etag = value.asString(); - } else if (memberName.equals("expires_at")) { - this.expiresAt = BoxDateFormat.parse(value.asString()); - } else if (memberName.equals("folder")) { - JsonObject folderJSON = value.asObject(); - String folderID = folderJSON.get("id").asString(); - BoxFolder folder = new BoxFolder(getAPI(), folderID); - this.folder = folder.new Info(folderJSON); - } else if (memberName.equals("is_description_required")) { - this.isDescriptionRequired = value.asBoolean(); - } else if (memberName.equals("is_email_required")) { - this.isEmailRequired = value.asBoolean(); - } else if (memberName.equals("status")) { - this.status = Status.fromJSONString(value.asString()); - } else if (memberName.equals("title")) { - this.title = value.asString(); - } else if (memberName.equals("updated_at")) { - this.updatedAt = BoxDateFormat.parse(value.asString()); - } else if (memberName.equals("updated_by")) { - JsonObject userJSON = value.asObject(); - String userID = userJSON.get("id").asString(); - BoxUser user = new BoxUser(getAPI(), userID); - this.createdBy = user.new Info(userJSON); - } else if (memberName.equals("url")) { - this.path = value.asString(); - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); - } - } + @Override + void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + + String memberName = member.getName(); + JsonValue value = member.getValue(); + try { + if (memberName.equals("type")) { + this.type = value.asString(); + } else if (memberName.equals("created_at")) { + this.createdAt = BoxDateFormat.parse(value.asString()); + } else if (memberName.equals("created_by")) { + JsonObject userJSON = value.asObject(); + String userID = userJSON.get("id").asString(); + BoxUser user = new BoxUser(getAPI(), userID); + this.createdBy = user.new Info(userJSON); + } else if (memberName.equals("description")) { + this.description = value.asString(); + } else if (memberName.equals("etag")) { + this.etag = value.asString(); + } else if (memberName.equals("expires_at")) { + this.expiresAt = BoxDateFormat.parse(value.asString()); + } else if (memberName.equals("folder")) { + JsonObject folderJSON = value.asObject(); + String folderID = folderJSON.get("id").asString(); + BoxFolder folder = new BoxFolder(getAPI(), folderID); + this.folder = folder.new Info(folderJSON); + } else if (memberName.equals("is_description_required")) { + this.isDescriptionRequired = value.asBoolean(); + } else if (memberName.equals("is_email_required")) { + this.isEmailRequired = value.asBoolean(); + } else if (memberName.equals("status")) { + this.status = Status.fromJSONString(value.asString()); + } else if (memberName.equals("title")) { + this.title = value.asString(); + } else if (memberName.equals("updated_at")) { + this.updatedAt = BoxDateFormat.parse(value.asString()); + } else if (memberName.equals("updated_by")) { + JsonObject userJSON = value.asObject(); + String userID = userJSON.get("id").asString(); + BoxUser user = new BoxUser(getAPI(), userID); + this.createdBy = user.new Info(userJSON); + } else if (memberName.equals("url")) { + this.path = value.asString(); + } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); + } } + } } diff --git a/src/main/java/com/box/sdk/BoxFileUploadSession.java b/src/main/java/com/box/sdk/BoxFileUploadSession.java index dce882aa5..a12972e27 100644 --- a/src/main/java/com/box/sdk/BoxFileUploadSession.java +++ b/src/main/java/com/box/sdk/BoxFileUploadSession.java @@ -20,468 +20,475 @@ import java.util.Map; /** - * This API provides a way to reliably upload larger files to Box by chunking them into a sequence of parts. - * When using this APIinstead of the single file upload API, a request failure means a client only needs to - * retry upload of a single part instead of the entire file. Parts can also be uploaded in parallel allowing - * for potential performance improvement. + * This API provides a way to reliably upload larger files to Box by chunking them into a sequence + * of parts. When using this APIinstead of the single file upload API, a request failure means a + * client only needs to retry upload of a single part instead of the entire file. Parts can also be + * uploaded in parallel allowing for potential performance improvement. */ @BoxResourceType("upload_session") public class BoxFileUploadSession extends BoxResource { - private static final String DIGEST_HEADER_PREFIX_SHA = "sha="; - private static final String DIGEST_ALGORITHM_SHA1 = "SHA1"; + private static final String DIGEST_HEADER_PREFIX_SHA = "sha="; + private static final String DIGEST_ALGORITHM_SHA1 = "SHA1"; + + private static final String OFFSET_QUERY_STRING = "offset"; + private static final String LIMIT_QUERY_STRING = "limit"; + + private Info sessionInfo; + + /** + * Constructs a BoxFileUploadSession for a file with a given ID. + * + * @param api the API connection to be used by the upload session. + * @param id the ID of the upload session. + */ + BoxFileUploadSession(BoxAPIConnection api, String id) { + super(api, id); + } + + /** + * Uploads chunk of a stream to an open upload session. + * + * @param stream the stream that is used to read the chunck using the offset and part size. + * @param offset the byte position where the chunk begins in the file. + * @param partSize the part size returned as part of the upload session instance creation. Only + * the last chunk can have a lesser value. + * @param totalSizeOfFile The total size of the file being uploaded. + * @return the part instance that contains the part id, offset and part size. + */ + public BoxFileUploadSessionPart uploadPart( + InputStream stream, long offset, int partSize, long totalSizeOfFile) { + + URL uploadPartURL = this.sessionInfo.getSessionEndpoints().getUploadPartEndpoint(); + + BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), uploadPartURL, HttpMethod.PUT); + request.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_OCTET_STREAM); + + // Read the partSize bytes from the stream + byte[] bytes = new byte[partSize]; + try { + stream.read(bytes); + } catch (IOException ioe) { + throw new BoxAPIException("Reading data from stream failed.", ioe); + } - private static final String OFFSET_QUERY_STRING = "offset"; - private static final String LIMIT_QUERY_STRING = "limit"; + return this.uploadPart(bytes, offset, partSize, totalSizeOfFile); + } + + /** + * Uploads bytes to an open upload session. + * + * @param data data + * @param offset the byte position where the chunk begins in the file. + * @param partSize the part size returned as part of the upload session instance creation. Only + * the last chunk can have a lesser value. + * @param totalSizeOfFile The total size of the file being uploaded. + * @return the part instance that contains the part id, offset and part size. + */ + public BoxFileUploadSessionPart uploadPart( + byte[] data, long offset, int partSize, long totalSizeOfFile) { + URL uploadPartURL = this.sessionInfo.getSessionEndpoints().getUploadPartEndpoint(); + + BoxAPIRequest request = + new BoxAPIRequest( + this.getAPI(), + uploadPartURL, + HttpMethod.PUT.name(), + ContentType.APPLICATION_OCTET_STREAM); + + MessageDigest digestInstance; + try { + digestInstance = MessageDigest.getInstance(DIGEST_ALGORITHM_SHA1); + } catch (NoSuchAlgorithmException ae) { + throw new BoxAPIException("Digest algorithm not found", ae); + } - private Info sessionInfo; + // Creates the digest using SHA1 algorithm. Then encodes the bytes using Base64. + byte[] digestBytes = digestInstance.digest(data); + String digest = Base64.encode(digestBytes); + request.addHeader(HttpHeaders.DIGEST, DIGEST_HEADER_PREFIX_SHA + digest); + // Content-Range: bytes offset-part/totalSize + request.addHeader( + HttpHeaders.CONTENT_RANGE, + "bytes " + offset + "-" + (offset + partSize - 1) + "/" + totalSizeOfFile); + + // Creates the body + request.setBody(new ByteArrayInputStream(data)); + return request.sendForUploadPart(this, offset); + } + + /** + * Returns a list of all parts that have been uploaded to an upload session. + * + * @param offset paging marker for the list of parts. + * @param limit maximum number of parts to return. + * @return the list of parts. + */ + public BoxFileUploadSessionPartList listParts(int offset, int limit) { + URL listPartsURL = this.sessionInfo.getSessionEndpoints().getListPartsEndpoint(); + URLTemplate template = new URLTemplate(listPartsURL.toString()); + + QueryStringBuilder builder = new QueryStringBuilder(); + builder.appendParam(OFFSET_QUERY_STRING, offset); + String queryString = builder.appendParam(LIMIT_QUERY_STRING, limit).toString(); + + // Template is initalized with the full URL. So empty string for the path. + URL url = template.buildWithQuery("", queryString); + + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, HttpMethod.GET); + try (BoxJSONResponse response = request.send()) { + JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); + + return new BoxFileUploadSessionPartList(jsonObject); + } + } + + /** + * Returns a list of all parts that have been uploaded to an upload session. + * + * @return the list of parts. + */ + protected Iterable listParts() { + URL listPartsURL = this.sessionInfo.getSessionEndpoints().getListPartsEndpoint(); + int limit = 100; + return new BoxResourceIterable(this.getAPI(), listPartsURL, limit) { + + @Override + protected BoxFileUploadSessionPart factory(JsonObject jsonObject) { + return new BoxFileUploadSessionPart(jsonObject); + } + }; + } + + /** + * Commit an upload session after all parts have been uploaded, creating the new file or the + * version. + * + * @param digest the base64-encoded SHA-1 hash of the file being uploaded. + * @param parts the list of uploaded parts to be committed. + * @param attributes the key value pairs of attributes from the file instance. + * @param ifMatch ensures that your app only alters files/folders on Box if you have the current + * version. + * @param ifNoneMatch ensure that it retrieve unnecessary data if the most current version of file + * is on-hand. + * @return the created file instance. + */ + public BoxFile.Info commit( + String digest, + List parts, + Map attributes, + String ifMatch, + String ifNoneMatch) { + + URL commitURL = this.sessionInfo.getSessionEndpoints().getCommitEndpoint(); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), commitURL, HttpMethod.POST); + request.addHeader(HttpHeaders.DIGEST, DIGEST_HEADER_PREFIX_SHA + digest); + request.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON); + + if (ifMatch != null) { + request.addHeader(HttpHeaders.IF_MATCH, ifMatch); + } - /** - * Constructs a BoxFileUploadSession for a file with a given ID. - * - * @param api the API connection to be used by the upload session. - * @param id the ID of the upload session. - */ - BoxFileUploadSession(BoxAPIConnection api, String id) { - super(api, id); + if (ifNoneMatch != null) { + request.addHeader(HttpHeaders.IF_NONE_MATCH, ifNoneMatch); } - /** - * Uploads chunk of a stream to an open upload session. - * - * @param stream the stream that is used to read the chunck using the offset and part size. - * @param offset the byte position where the chunk begins in the file. - * @param partSize the part size returned as part of the upload session instance creation. - * Only the last chunk can have a lesser value. - * @param totalSizeOfFile The total size of the file being uploaded. - * @return the part instance that contains the part id, offset and part size. - */ - public BoxFileUploadSessionPart uploadPart(InputStream stream, long offset, int partSize, - long totalSizeOfFile) { + // Creates the body of the request + String body = this.getCommitBody(parts, attributes); + request.setBody(body); + + try (BoxJSONResponse response = request.send()) { + // Retry the commit operation after the given number of seconds if the HTTP response code is + // 202. + if (response.getResponseCode() == 202) { + String retryInterval = response.getHeaderField("retry-after"); + if (retryInterval != null) { + try { + Thread.sleep(new Integer(retryInterval) * 1000); + } catch (InterruptedException ie) { + throw new BoxAPIException("Commit retry failed. ", ie); + } + + return this.commit(digest, parts, attributes, ifMatch, ifNoneMatch); + } + } - URL uploadPartURL = this.sessionInfo.getSessionEndpoints().getUploadPartEndpoint(); + // Create the file instance from the response + return this.getFile(response); + } + } - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), uploadPartURL, HttpMethod.PUT); - request.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_OCTET_STREAM); + /* + * Creates the file isntance from the JSON body of the response. + */ + private BoxFile.Info getFile(BoxJSONResponse response) { + JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - //Read the partSize bytes from the stream - byte[] bytes = new byte[partSize]; - try { - stream.read(bytes); - } catch (IOException ioe) { - throw new BoxAPIException("Reading data from stream failed.", ioe); - } + JsonArray array = (JsonArray) jsonObject.get("entries"); + JsonObject fileObj = (JsonObject) array.get(0); - return this.uploadPart(bytes, offset, partSize, totalSizeOfFile); - } + BoxFile file = new BoxFile(this.getAPI(), fileObj.get("id").asString()); - /** - * Uploads bytes to an open upload session. - * - * @param data data - * @param offset the byte position where the chunk begins in the file. - * @param partSize the part size returned as part of the upload session instance creation. - * Only the last chunk can have a lesser value. - * @param totalSizeOfFile The total size of the file being uploaded. - * @return the part instance that contains the part id, offset and part size. - */ - public BoxFileUploadSessionPart uploadPart(byte[] data, long offset, int partSize, - long totalSizeOfFile) { - URL uploadPartURL = this.sessionInfo.getSessionEndpoints().getUploadPartEndpoint(); + return file.new Info(fileObj); + } - BoxAPIRequest request = new BoxAPIRequest( - this.getAPI(), uploadPartURL, HttpMethod.PUT.name(), ContentType.APPLICATION_OCTET_STREAM - ); + /* + * Creates the JSON body for the commit request. + */ + private String getCommitBody( + List parts, Map attributes) { + JsonObject jsonObject = new JsonObject(); - MessageDigest digestInstance; - try { - digestInstance = MessageDigest.getInstance(DIGEST_ALGORITHM_SHA1); - } catch (NoSuchAlgorithmException ae) { - throw new BoxAPIException("Digest algorithm not found", ae); - } + JsonArray array = new JsonArray(); + for (BoxFileUploadSessionPart part : parts) { + JsonObject partObj = new JsonObject(); + partObj.add("part_id", part.getPartId()); + partObj.add("offset", part.getOffset()); + partObj.add("size", part.getSize()); - //Creates the digest using SHA1 algorithm. Then encodes the bytes using Base64. - byte[] digestBytes = digestInstance.digest(data); - String digest = Base64.encode(digestBytes); - request.addHeader(HttpHeaders.DIGEST, DIGEST_HEADER_PREFIX_SHA + digest); - //Content-Range: bytes offset-part/totalSize - request.addHeader(HttpHeaders.CONTENT_RANGE, - "bytes " + offset + "-" + (offset + partSize - 1) + "/" + totalSizeOfFile); - - //Creates the body - request.setBody(new ByteArrayInputStream(data)); - return request.sendForUploadPart(this, offset); + array.add(partObj); + } + jsonObject.add("parts", array); + + if (attributes != null) { + JsonObject attrObj = new JsonObject(); + for (String key : attributes.keySet()) { + attrObj.add(key, attributes.get(key)); + } + jsonObject.add("attributes", attrObj); } - /** - * Returns a list of all parts that have been uploaded to an upload session. - * - * @param offset paging marker for the list of parts. - * @param limit maximum number of parts to return. - * @return the list of parts. - */ - public BoxFileUploadSessionPartList listParts(int offset, int limit) { - URL listPartsURL = this.sessionInfo.getSessionEndpoints().getListPartsEndpoint(); - URLTemplate template = new URLTemplate(listPartsURL.toString()); + return jsonObject.toString(); + } + + /** + * Get the status of the upload session. It contains the number of parts that are processed so + * far, the total number of parts required for the commit and expiration date and time of the + * upload session. + * + * @return the status. + */ + public BoxFileUploadSession.Info getStatus() { + URL statusURL = this.sessionInfo.getSessionEndpoints().getStatusEndpoint(); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), statusURL, HttpMethod.GET); + try (BoxJSONResponse response = request.send()) { + JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); + + this.sessionInfo.update(jsonObject); + + return this.sessionInfo; + } + } - QueryStringBuilder builder = new QueryStringBuilder(); - builder.appendParam(OFFSET_QUERY_STRING, offset); - String queryString = builder.appendParam(LIMIT_QUERY_STRING, limit).toString(); + /** Abort an upload session, discarding any chunks that were uploaded to it. */ + public void abort() { + URL abortURL = this.sessionInfo.getSessionEndpoints().getAbortEndpoint(); + BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), abortURL, HttpMethod.DELETE); + request.send().close(); + } - //Template is initalized with the full URL. So empty string for the path. - URL url = template.buildWithQuery("", queryString); + /** Model contains the upload session information. */ + public class Info extends BoxResource.Info { - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, HttpMethod.GET); - try (BoxJSONResponse response = request.send()) { - JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); + private Date sessionExpiresAt; + private String uploadSessionId; + private Endpoints sessionEndpoints; + private int partSize; + private int totalParts; + private int partsProcessed; - return new BoxFileUploadSessionPartList(jsonObject); - } + /** + * Constructs an Info object by parsing information from a JSON string. + * + * @param json the JSON string to parse. + */ + public Info(String json) { + this(Json.parse(json).asObject()); } /** - * Returns a list of all parts that have been uploaded to an upload session. + * Constructs an Info object using an already parsed JSON object. * - * @return the list of parts. + * @param jsonObject the parsed JSON object. */ - protected Iterable listParts() { - URL listPartsURL = this.sessionInfo.getSessionEndpoints().getListPartsEndpoint(); - int limit = 100; - return new BoxResourceIterable( - this.getAPI(), - listPartsURL, - limit) { - - @Override - protected BoxFileUploadSessionPart factory(JsonObject jsonObject) { - return new BoxFileUploadSessionPart(jsonObject); - } - }; + Info(JsonObject jsonObject) { + super(jsonObject); + BoxFileUploadSession.this.sessionInfo = this; } /** - * Commit an upload session after all parts have been uploaded, creating the new file or the version. + * Returns the BoxFileUploadSession isntance to which this object belongs to. * - * @param digest the base64-encoded SHA-1 hash of the file being uploaded. - * @param parts the list of uploaded parts to be committed. - * @param attributes the key value pairs of attributes from the file instance. - * @param ifMatch ensures that your app only alters files/folders on Box if you have the current version. - * @param ifNoneMatch ensure that it retrieve unnecessary data if the most current version of file is on-hand. - * @return the created file instance. + * @return the instance of upload session. */ - public BoxFile.Info commit(String digest, List parts, - Map attributes, String ifMatch, String ifNoneMatch) { - - URL commitURL = this.sessionInfo.getSessionEndpoints().getCommitEndpoint(); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), commitURL, HttpMethod.POST); - request.addHeader(HttpHeaders.DIGEST, DIGEST_HEADER_PREFIX_SHA + digest); - request.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON); - - if (ifMatch != null) { - request.addHeader(HttpHeaders.IF_MATCH, ifMatch); - } - - if (ifNoneMatch != null) { - request.addHeader(HttpHeaders.IF_NONE_MATCH, ifNoneMatch); - } - - //Creates the body of the request - String body = this.getCommitBody(parts, attributes); - request.setBody(body); - - try (BoxJSONResponse response = request.send()) { - //Retry the commit operation after the given number of seconds if the HTTP response code is 202. - if (response.getResponseCode() == 202) { - String retryInterval = response.getHeaderField("retry-after"); - if (retryInterval != null) { - try { - Thread.sleep(new Integer(retryInterval) * 1000); - } catch (InterruptedException ie) { - throw new BoxAPIException("Commit retry failed. ", ie); - } - - return this.commit(digest, parts, attributes, ifMatch, ifNoneMatch); - } - } - - //Create the file instance from the response - return this.getFile(response); - } + public BoxFileUploadSession getResource() { + return BoxFileUploadSession.this; } - /* - * Creates the file isntance from the JSON body of the response. + /** + * Returns the total parts of the file that is uploaded in the upload session. + * + * @return the total number of parts. */ - private BoxFile.Info getFile(BoxJSONResponse response) { - JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - - JsonArray array = (JsonArray) jsonObject.get("entries"); - JsonObject fileObj = (JsonObject) array.get(0); - - BoxFile file = new BoxFile(this.getAPI(), fileObj.get("id").asString()); - - return file.new Info(fileObj); + public int getTotalParts() { + return this.totalParts; } - /* - * Creates the JSON body for the commit request. + /** + * Returns the parts that are processed so for. + * + * @return the number of the processed parts. */ - private String getCommitBody(List parts, Map attributes) { - JsonObject jsonObject = new JsonObject(); - - JsonArray array = new JsonArray(); - for (BoxFileUploadSessionPart part : parts) { - JsonObject partObj = new JsonObject(); - partObj.add("part_id", part.getPartId()); - partObj.add("offset", part.getOffset()); - partObj.add("size", part.getSize()); - - array.add(partObj); - } - jsonObject.add("parts", array); - - if (attributes != null) { - JsonObject attrObj = new JsonObject(); - for (String key : attributes.keySet()) { - attrObj.add(key, attributes.get(key)); - } - jsonObject.add("attributes", attrObj); - } - - return jsonObject.toString(); + public int getPartsProcessed() { + return this.partsProcessed; } /** - * Get the status of the upload session. It contains the number of parts that are processed so far, - * the total number of parts required for the commit and expiration date and time of the upload session. + * Returns the date and time at which the upload session expires. * - * @return the status. + * @return the date and time in UTC format. */ - public BoxFileUploadSession.Info getStatus() { - URL statusURL = this.sessionInfo.getSessionEndpoints().getStatusEndpoint(); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), statusURL, HttpMethod.GET); - try (BoxJSONResponse response = request.send()) { - JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - - this.sessionInfo.update(jsonObject); - - return this.sessionInfo; - } + public Date getSessionExpiresAt() { + return this.sessionExpiresAt; } /** - * Abort an upload session, discarding any chunks that were uploaded to it. + * Returns the upload session id. + * + * @return the id string. */ - public void abort() { - URL abortURL = this.sessionInfo.getSessionEndpoints().getAbortEndpoint(); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), abortURL, HttpMethod.DELETE); - request.send().close(); + public String getUploadSessionId() { + return this.uploadSessionId; } /** - * Model contains the upload session information. + * Returns the session endpoints that can be called for this upload session. + * + * @return the Endpoints instance. */ - public class Info extends BoxResource.Info { - - private Date sessionExpiresAt; - private String uploadSessionId; - private Endpoints sessionEndpoints; - private int partSize; - private int totalParts; - private int partsProcessed; - - /** - * Constructs an Info object by parsing information from a JSON string. - * - * @param json the JSON string to parse. - */ - public Info(String json) { - this(Json.parse(json).asObject()); - } - - /** - * Constructs an Info object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - Info(JsonObject jsonObject) { - super(jsonObject); - BoxFileUploadSession.this.sessionInfo = this; - } - - /** - * Returns the BoxFileUploadSession isntance to which this object belongs to. - * - * @return the instance of upload session. - */ - public BoxFileUploadSession getResource() { - return BoxFileUploadSession.this; - } - - /** - * Returns the total parts of the file that is uploaded in the upload session. - * - * @return the total number of parts. - */ - public int getTotalParts() { - return this.totalParts; - } - - /** - * Returns the parts that are processed so for. - * - * @return the number of the processed parts. - */ - public int getPartsProcessed() { - return this.partsProcessed; - } + public Endpoints getSessionEndpoints() { + return this.sessionEndpoints; + } - /** - * Returns the date and time at which the upload session expires. - * - * @return the date and time in UTC format. - */ - public Date getSessionExpiresAt() { - return this.sessionExpiresAt; - } + /** + * Returns the size of the each part. Only the last part of the file can be lessor than this + * value. + * + * @return the part size. + */ + public int getPartSize() { + return this.partSize; + } - /** - * Returns the upload session id. - * - * @return the id string. - */ - public String getUploadSessionId() { - return this.uploadSessionId; - } + @Override + protected void parseJSONMember(JsonObject.Member member) { - /** - * Returns the session endpoints that can be called for this upload session. - * - * @return the Endpoints instance. - */ - public Endpoints getSessionEndpoints() { - return this.sessionEndpoints; + String memberName = member.getName(); + JsonValue value = member.getValue(); + if (memberName.equals("session_expires_at")) { + try { + String dateStr = value.asString(); + this.sessionExpiresAt = + BoxDateFormat.parse(dateStr.substring(0, dateStr.length() - 1) + "-00:00"); + } catch (ParseException pe) { + assert false : "A ParseException indicates a bug in the SDK."; } + } else if (memberName.equals("id")) { + this.uploadSessionId = value.asString(); + } else if (memberName.equals("part_size")) { + this.partSize = Integer.parseInt(value.toString()); + } else if (memberName.equals("session_endpoints")) { + this.sessionEndpoints = new Endpoints(value.asObject()); + } else if (memberName.equals("total_parts")) { + this.totalParts = value.asInt(); + } else if (memberName.equals("num_parts_processed")) { + this.partsProcessed = value.asInt(); + } + } + } - /** - * Returns the size of the each part. Only the last part of the file can be lessor than this value. - * - * @return the part size. - */ - public int getPartSize() { - return this.partSize; - } + /** Represents the end points specific to an upload session. */ + public static class Endpoints extends BoxJSONObject { + private URL listPartsEndpoint; + private URL commitEndpoint; + private URL uploadPartEndpoint; + private URL statusEndpoint; + private URL abortEndpoint; - @Override - protected void parseJSONMember(JsonObject.Member member) { - - String memberName = member.getName(); - JsonValue value = member.getValue(); - if (memberName.equals("session_expires_at")) { - try { - String dateStr = value.asString(); - this.sessionExpiresAt = BoxDateFormat.parse(dateStr.substring(0, dateStr.length() - 1) + "-00:00"); - } catch (ParseException pe) { - assert false : "A ParseException indicates a bug in the SDK."; - } - } else if (memberName.equals("id")) { - this.uploadSessionId = value.asString(); - } else if (memberName.equals("part_size")) { - this.partSize = Integer.parseInt(value.toString()); - } else if (memberName.equals("session_endpoints")) { - this.sessionEndpoints = new Endpoints(value.asObject()); - } else if (memberName.equals("total_parts")) { - this.totalParts = value.asInt(); - } else if (memberName.equals("num_parts_processed")) { - this.partsProcessed = value.asInt(); - } - } + /** + * Constructs an Endpoints object using an already parsed JSON object. + * + * @param jsonObject the parsed JSON object. + */ + Endpoints(JsonObject jsonObject) { + super(jsonObject); } /** - * Represents the end points specific to an upload session. + * Returns the list parts end point. + * + * @return the url of the list parts end point. */ - public static class Endpoints extends BoxJSONObject { - private URL listPartsEndpoint; - private URL commitEndpoint; - private URL uploadPartEndpoint; - private URL statusEndpoint; - private URL abortEndpoint; - - /** - * Constructs an Endpoints object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - Endpoints(JsonObject jsonObject) { - super(jsonObject); - } - - /** - * Returns the list parts end point. - * - * @return the url of the list parts end point. - */ - public URL getListPartsEndpoint() { - return this.listPartsEndpoint; - } + public URL getListPartsEndpoint() { + return this.listPartsEndpoint; + } - /** - * Returns the commit end point. - * - * @return the url of the commit end point. - */ - public URL getCommitEndpoint() { - return this.commitEndpoint; - } + /** + * Returns the commit end point. + * + * @return the url of the commit end point. + */ + public URL getCommitEndpoint() { + return this.commitEndpoint; + } - /** - * Returns the upload part end point. - * - * @return the url of the upload part end point. - */ - public URL getUploadPartEndpoint() { - return this.uploadPartEndpoint; - } + /** + * Returns the upload part end point. + * + * @return the url of the upload part end point. + */ + public URL getUploadPartEndpoint() { + return this.uploadPartEndpoint; + } - /** - * Returns the upload session status end point. - * - * @return the url of the session end point. - */ - public URL getStatusEndpoint() { - return this.statusEndpoint; - } + /** + * Returns the upload session status end point. + * + * @return the url of the session end point. + */ + public URL getStatusEndpoint() { + return this.statusEndpoint; + } - /** - * Returns the abort upload session end point. - * - * @return the url of the abort end point. - */ - public URL getAbortEndpoint() { - return this.abortEndpoint; - } + /** + * Returns the abort upload session end point. + * + * @return the url of the abort end point. + */ + public URL getAbortEndpoint() { + return this.abortEndpoint; + } - @Override - protected void parseJSONMember(JsonObject.Member member) { - - String memberName = member.getName(); - JsonValue value = member.getValue(); - try { - if (memberName.equals("list_parts")) { - this.listPartsEndpoint = new URL(value.asString()); - } else if (memberName.equals("commit")) { - this.commitEndpoint = new URL(value.asString()); - } else if (memberName.equals("upload_part")) { - this.uploadPartEndpoint = new URL(value.asString()); - } else if (memberName.equals("status")) { - this.statusEndpoint = new URL(value.asString()); - } else if (memberName.equals("abort")) { - this.abortEndpoint = new URL(value.asString()); - } - } catch (MalformedURLException mue) { - assert false : "A ParseException indicates a bug in the SDK."; - } + @Override + protected void parseJSONMember(JsonObject.Member member) { + + String memberName = member.getName(); + JsonValue value = member.getValue(); + try { + if (memberName.equals("list_parts")) { + this.listPartsEndpoint = new URL(value.asString()); + } else if (memberName.equals("commit")) { + this.commitEndpoint = new URL(value.asString()); + } else if (memberName.equals("upload_part")) { + this.uploadPartEndpoint = new URL(value.asString()); + } else if (memberName.equals("status")) { + this.statusEndpoint = new URL(value.asString()); + } else if (memberName.equals("abort")) { + this.abortEndpoint = new URL(value.asString()); } + } catch (MalformedURLException mue) { + assert false : "A ParseException indicates a bug in the SDK."; + } } + } } diff --git a/src/main/java/com/box/sdk/BoxFileUploadSessionPart.java b/src/main/java/com/box/sdk/BoxFileUploadSessionPart.java index b0ae14a0a..d2ee846b9 100644 --- a/src/main/java/com/box/sdk/BoxFileUploadSessionPart.java +++ b/src/main/java/com/box/sdk/BoxFileUploadSessionPart.java @@ -3,116 +3,112 @@ import com.eclipsesource.json.JsonObject; import com.eclipsesource.json.JsonValue; -/** - * Represents a part of the file that is uploaded. - */ +/** Represents a part of the file that is uploaded. */ public class BoxFileUploadSessionPart extends BoxJSONObject { - private String partId; - private long offset; - private long size; - private String sha1; + private String partId; + private long offset; + private long size; + private String sha1; - /** - * Constructs an BoxFileUploadSessionPart object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - BoxFileUploadSessionPart(JsonObject jsonObject) { - super(jsonObject); - } + /** + * Constructs an BoxFileUploadSessionPart object using an already parsed JSON object. + * + * @param jsonObject the parsed JSON object. + */ + BoxFileUploadSessionPart(JsonObject jsonObject) { + super(jsonObject); + } - /** - * Constructs an empty BoxFileUploadSessionPart object. - */ - BoxFileUploadSessionPart() { - super(); - } + /** Constructs an empty BoxFileUploadSessionPart object. */ + BoxFileUploadSessionPart() { + super(); + } - /** - * Gets the sha1 digest of the part. - * - * @return the sh1 digest - */ - public String getSha1() { - return this.sha1; - } + /** + * Gets the sha1 digest of the part. + * + * @return the sh1 digest + */ + public String getSha1() { + return this.sha1; + } - /** - * Sets the sh1 digest of the part. - * - * @param sha1 the sh1 digest of the part - */ - public void setSha1(String sha1) { - this.sha1 = sha1; - } + /** + * Sets the sh1 digest of the part. + * + * @param sha1 the sh1 digest of the part + */ + public void setSha1(String sha1) { + this.sha1 = sha1; + } - /** - * Gets the part id. - * - * @return the id of the part. - */ - public String getPartId() { - return this.partId; - } + /** + * Gets the part id. + * + * @return the id of the part. + */ + public String getPartId() { + return this.partId; + } - /** - * Sets the part id. - * - * @param partId the id of the part. - */ - public void setPartId(String partId) { - this.partId = partId; - } + /** + * Sets the part id. + * + * @param partId the id of the part. + */ + public void setPartId(String partId) { + this.partId = partId; + } - /** - * Gets the offset byte. - * - * @return the offset of the part. - */ - public long getOffset() { - return this.offset; - } + /** + * Gets the offset byte. + * + * @return the offset of the part. + */ + public long getOffset() { + return this.offset; + } - /** - * Sets the offset. - * - * @param offset the offset byte of the part. - */ - public void setOffset(long offset) { - this.offset = offset; - } + /** + * Sets the offset. + * + * @param offset the offset byte of the part. + */ + public void setOffset(long offset) { + this.offset = offset; + } - /** - * Gets the size of the part. - * - * @return the size of the part. - */ - public long getSize() { - return this.size; - } + /** + * Gets the size of the part. + * + * @return the size of the part. + */ + public long getSize() { + return this.size; + } - /** - * Sets the size of the part. - * - * @param size the size of the part. - */ - public void setSize(long size) { - this.size = size; - } + /** + * Sets the size of the part. + * + * @param size the size of the part. + */ + public void setSize(long size) { + this.size = size; + } - @Override - protected void parseJSONMember(JsonObject.Member member) { - String memberName = member.getName(); - JsonValue value = member.getValue(); - if (memberName.equals("part_id")) { - this.partId = value.asString(); - } else if (memberName.equals("offset")) { - this.offset = Double.valueOf(value.toString()).longValue(); - } else if (memberName.equals("size")) { - this.size = Double.valueOf(value.toString()).longValue(); - } else if (memberName.equals("sha1")) { - this.sha1 = value.asString(); - } + @Override + protected void parseJSONMember(JsonObject.Member member) { + String memberName = member.getName(); + JsonValue value = member.getValue(); + if (memberName.equals("part_id")) { + this.partId = value.asString(); + } else if (memberName.equals("offset")) { + this.offset = Double.valueOf(value.toString()).longValue(); + } else if (memberName.equals("size")) { + this.size = Double.valueOf(value.toString()).longValue(); + } else if (memberName.equals("sha1")) { + this.sha1 = value.asString(); } + } } diff --git a/src/main/java/com/box/sdk/BoxFileUploadSessionPartList.java b/src/main/java/com/box/sdk/BoxFileUploadSessionPartList.java index bf479e396..dc502427b 100644 --- a/src/main/java/com/box/sdk/BoxFileUploadSessionPartList.java +++ b/src/main/java/com/box/sdk/BoxFileUploadSessionPartList.java @@ -7,89 +7,89 @@ import java.util.List; /** - * Contains the list of parts of a large file that are already uploaded. - * It also contains a offset to represent the paging. + * Contains the list of parts of a large file that are already uploaded. It also contains a offset + * to represent the paging. */ public class BoxFileUploadSessionPartList extends BoxJSONObject { - private List entries; - private int offset; - private int limit; - private int totalCount; + private List entries; + private int offset; + private int limit; + private int totalCount; - /** - * Constructs an BoxFileUploadSessionPart object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - BoxFileUploadSessionPartList(JsonObject jsonObject) { - super(jsonObject); - } + /** + * Constructs an BoxFileUploadSessionPart object using an already parsed JSON object. + * + * @param jsonObject the parsed JSON object. + */ + BoxFileUploadSessionPartList(JsonObject jsonObject) { + super(jsonObject); + } - /** - * Returns the list of parts that are already uploaded. - * - * @return the list of parts. - */ - public List getEntries() { - return this.entries; - } + /** + * Returns the list of parts that are already uploaded. + * + * @return the list of parts. + */ + public List getEntries() { + return this.entries; + } - /** - * Returns the paging offset for the list of parts. - * - * @return the paging offset. - */ - public int getOffset() { - return this.offset; - } + /** + * Returns the paging offset for the list of parts. + * + * @return the paging offset. + */ + public int getOffset() { + return this.offset; + } - /** - * Returns the limit on number of entires in a response. - * - * @return the limit - */ - public int getLimit() { - return this.limit; - } + /** + * Returns the limit on number of entires in a response. + * + * @return the limit + */ + public int getLimit() { + return this.limit; + } - /** - * Returns the total count of entries. - * - * @return the toal count of entries - */ - public int getTotalCount() { - return this.totalCount; - } + /** + * Returns the total count of entries. + * + * @return the toal count of entries + */ + public int getTotalCount() { + return this.totalCount; + } - @Override - protected void parseJSONMember(JsonObject.Member member) { - String memberName = member.getName(); - JsonValue value = member.getValue(); - if (memberName.equals("entries")) { - JsonArray array = (JsonArray) value; + @Override + protected void parseJSONMember(JsonObject.Member member) { + String memberName = member.getName(); + JsonValue value = member.getValue(); + if (memberName.equals("entries")) { + JsonArray array = (JsonArray) value; - if (array.size() > 0) { - this.entries = this.getParts(array); - } - } else if (memberName.equals("offset")) { - this.offset = Double.valueOf(value.toString()).intValue(); - } else if (memberName.equals("limit")) { - this.limit = Double.valueOf(value.toString()).intValue(); - } else if (memberName.equals("total_count")) { - this.totalCount = Double.valueOf(value.toString()).intValue(); - } + if (array.size() > 0) { + this.entries = this.getParts(array); + } + } else if (memberName.equals("offset")) { + this.offset = Double.valueOf(value.toString()).intValue(); + } else if (memberName.equals("limit")) { + this.limit = Double.valueOf(value.toString()).intValue(); + } else if (memberName.equals("total_count")) { + this.totalCount = Double.valueOf(value.toString()).intValue(); } + } - /* - * Creates List of parts from the JSON array - */ - private List getParts(JsonArray partsArray) { - List parts = new ArrayList(); - for (JsonValue value : partsArray) { - BoxFileUploadSessionPart part = new BoxFileUploadSessionPart((JsonObject) value); - parts.add(part); - } - return parts; + /* + * Creates List of parts from the JSON array + */ + private List getParts(JsonArray partsArray) { + List parts = new ArrayList(); + for (JsonValue value : partsArray) { + BoxFileUploadSessionPart part = new BoxFileUploadSessionPart((JsonObject) value); + parts.add(part); } + return parts; + } } diff --git a/src/main/java/com/box/sdk/BoxFileVersion.java b/src/main/java/com/box/sdk/BoxFileVersion.java index 91d630829..9fb410385 100644 --- a/src/main/java/com/box/sdk/BoxFileVersion.java +++ b/src/main/java/com/box/sdk/BoxFileVersion.java @@ -10,304 +10,292 @@ import java.text.ParseException; import java.util.Date; -/** - * Represents a particular version of a file on Box. - */ +/** Represents a particular version of a file on Box. */ @BoxResourceType("file_version") public class BoxFileVersion extends BoxResource { - /** - * Content URL Template. - */ - public static final URLTemplate CONTENT_URL_TEMPLATE = new URLTemplate("files/%s/content?version=%s"); - /** - * Version URL Template. - */ - public static final URLTemplate VERSION_URL_TEMPLATE = new URLTemplate("files/%s/versions/%s"); - - /** - * The default limit of entries per response. - */ - public static final long DEFAULT_LIMIT = 1000; - - private String fileID; - - private String versionID; - private String sha1; - private String name; - private long size; - private String uploaderDisplayName; - private Date createdAt; - private Date modifiedAt; - private BoxUser.Info modifiedBy; - private Date trashedAt; - private BoxUser.Info trashedBy; - private Date restoredAt; - private BoxUser.Info restoredBy; - private Date purgedAt; - private Long versionNumber; - - /** - * Constructs a BoxFileVersion from a JSON string. - * - * @param api the API connection to be used by the file. - * @param json the JSON encoded file version. - * @param fileID the ID of the file. - */ - public BoxFileVersion(BoxAPIConnection api, String json, String fileID) { - this(api, Json.parse(json).asObject(), fileID); - } - - BoxFileVersion(BoxAPIConnection api, JsonObject jsonObject, String fileID) { - super(api, jsonObject.get("id").asString()); - - this.fileID = fileID; - this.parseJSON(jsonObject); - } - - /** - * Method used to update fields with values received from API. - * - * @param jsonObject JSON-encoded info about File Version object. - */ - private void parseJSON(JsonObject jsonObject) { - for (JsonObject.Member member : jsonObject) { - JsonValue value = member.getValue(); - if (value.isNull()) { - continue; - } - - try { - String memberName = member.getName(); - if (memberName.equals("id")) { - this.versionID = value.asString(); - } else if (memberName.equals("sha1")) { - this.sha1 = value.asString(); - } else if (memberName.equals("name")) { - this.name = value.asString(); - } else if (memberName.equals("size")) { - this.size = Double.valueOf(value.toString()).longValue(); - } else if (memberName.equals("uploader_display_name")) { - this.uploaderDisplayName = value.asString(); - } else if (memberName.equals("created_at")) { - this.createdAt = BoxDateFormat.parse(value.asString()); - } else if (memberName.equals("modified_at")) { - this.modifiedAt = BoxDateFormat.parse(value.asString()); - } else if (memberName.equals("trashed_at")) { - this.trashedAt = BoxDateFormat.parse(value.asString()); - } else if (memberName.equals("trashed_by")) { - JsonObject userJSON = value.asObject(); - String userID = userJSON.get("id").asString(); - BoxUser user = new BoxUser(getAPI(), userID); - this.trashedBy = user.new Info(userJSON); - } else if (memberName.equals("modified_by")) { - JsonObject userJSON = value.asObject(); - String userID = userJSON.get("id").asString(); - BoxUser user = new BoxUser(getAPI(), userID); - this.modifiedBy = user.new Info(userJSON); - } else if (memberName.equals("restored_at")) { - this.restoredAt = BoxDateFormat.parse(value.asString()); - } else if (memberName.equals("restored_by")) { - JsonObject userJSON = value.asObject(); - String userID = userJSON.get("id").asString(); - BoxUser user = new BoxUser(getAPI(), userID); - this.restoredBy = user.new Info(userJSON); - } else if (memberName.equals("purged_at")) { - this.purgedAt = BoxDateFormat.parse(value.asString()); - } else if (memberName.equals("version_number")) { - this.versionNumber = Long.parseLong(value.asString()); - } - } catch (ParseException e) { - assert false : "A ParseException indicates a bug in the SDK."; - } + /** Content URL Template. */ + public static final URLTemplate CONTENT_URL_TEMPLATE = + new URLTemplate("files/%s/content?version=%s"); + /** Version URL Template. */ + public static final URLTemplate VERSION_URL_TEMPLATE = new URLTemplate("files/%s/versions/%s"); + + /** The default limit of entries per response. */ + public static final long DEFAULT_LIMIT = 1000; + + private String fileID; + + private String versionID; + private String sha1; + private String name; + private long size; + private String uploaderDisplayName; + private Date createdAt; + private Date modifiedAt; + private BoxUser.Info modifiedBy; + private Date trashedAt; + private BoxUser.Info trashedBy; + private Date restoredAt; + private BoxUser.Info restoredBy; + private Date purgedAt; + private Long versionNumber; + + /** + * Constructs a BoxFileVersion from a JSON string. + * + * @param api the API connection to be used by the file. + * @param json the JSON encoded file version. + * @param fileID the ID of the file. + */ + public BoxFileVersion(BoxAPIConnection api, String json, String fileID) { + this(api, Json.parse(json).asObject(), fileID); + } + + BoxFileVersion(BoxAPIConnection api, JsonObject jsonObject, String fileID) { + super(api, jsonObject.get("id").asString()); + + this.fileID = fileID; + this.parseJSON(jsonObject); + } + + /** + * Method used to update fields with values received from API. + * + * @param jsonObject JSON-encoded info about File Version object. + */ + private void parseJSON(JsonObject jsonObject) { + for (JsonObject.Member member : jsonObject) { + JsonValue value = member.getValue(); + if (value.isNull()) { + continue; + } + + try { + String memberName = member.getName(); + if (memberName.equals("id")) { + this.versionID = value.asString(); + } else if (memberName.equals("sha1")) { + this.sha1 = value.asString(); + } else if (memberName.equals("name")) { + this.name = value.asString(); + } else if (memberName.equals("size")) { + this.size = Double.valueOf(value.toString()).longValue(); + } else if (memberName.equals("uploader_display_name")) { + this.uploaderDisplayName = value.asString(); + } else if (memberName.equals("created_at")) { + this.createdAt = BoxDateFormat.parse(value.asString()); + } else if (memberName.equals("modified_at")) { + this.modifiedAt = BoxDateFormat.parse(value.asString()); + } else if (memberName.equals("trashed_at")) { + this.trashedAt = BoxDateFormat.parse(value.asString()); + } else if (memberName.equals("trashed_by")) { + JsonObject userJSON = value.asObject(); + String userID = userJSON.get("id").asString(); + BoxUser user = new BoxUser(getAPI(), userID); + this.trashedBy = user.new Info(userJSON); + } else if (memberName.equals("modified_by")) { + JsonObject userJSON = value.asObject(); + String userID = userJSON.get("id").asString(); + BoxUser user = new BoxUser(getAPI(), userID); + this.modifiedBy = user.new Info(userJSON); + } else if (memberName.equals("restored_at")) { + this.restoredAt = BoxDateFormat.parse(value.asString()); + } else if (memberName.equals("restored_by")) { + JsonObject userJSON = value.asObject(); + String userID = userJSON.get("id").asString(); + BoxUser user = new BoxUser(getAPI(), userID); + this.restoredBy = user.new Info(userJSON); + } else if (memberName.equals("purged_at")) { + this.purgedAt = BoxDateFormat.parse(value.asString()); + } else if (memberName.equals("version_number")) { + this.versionNumber = Long.parseLong(value.asString()); } + } catch (ParseException e) { + assert false : "A ParseException indicates a bug in the SDK."; + } } - - /** - * @return the file id this file version belongs to. - */ - public String getFileID() { - return this.fileID; - } - - /** - * Used if no or wrong file id was set with constructor. - * - * @param fileID the file id this file version belongs to. - */ - public void setFileID(String fileID) { - this.fileID = fileID; - } - - /** - * Gets the version ID of this version of the file. - * - * @return the version ID of this version of the file. - */ - public String getVersionID() { - return this.versionID; - } - - /** - * Gets the SHA1 hash of this version of the file. - * - * @return the SHA1 hash of this version of the file. - */ - public String getSha1() { - return this.sha1; - } - - /** - * Gets the name of this version of the file. - * - * @return the name of this version of the file. - */ - public String getName() { - return this.name; - } - - /** - * Gets the size of this version of the file. - * - * @return the size of this version of the file. - */ - public long getSize() { - return this.size; - } - - /** - * Gets the time that this version of the file was created. - * - * @return the time that this version of the file was created. - */ - public Date getCreatedAt() { - return this.createdAt; - } - - /** - * Gets the user's name at the time of upload. - * - * @return the time user's name at the time of upload. - */ - public String getUploaderDisplayName() { - return this.uploaderDisplayName; - } - - /** - * Gets the time that this version of the file was modified. - * - * @return the time that this version of the file was modified. - */ - public Date getModifiedAt() { - return this.modifiedAt; - } - - /** - * Gets the time that this version of the file was deleted. - * - * @return the time that this version of the file was deleted. - */ - public Date getTrashedAt() { - return this.trashedAt; - } - - /** - * Gets information about the user who trashed this version of the file. - * - * @return info about the user who trashed this version of the file. - */ - public BoxUser.Info getTrashedBy() { - return this.trashedBy; - } - - /** - * Gets information about the user who last modified this version of the file. - * - * @return info about the user who last modified this version of the file. - */ - public BoxUser.Info getModifiedBy() { - return this.modifiedBy; - } - - /** - * Gets the time that this version of the file was restored. - * - * @return the time that this version of the file was restored. - */ - public Date getRestoredAt() { - return this.restoredAt; - } - - /** - * Gets information about the user who restored this version of the file. - * - * @return info about the user who restored this version of the file. - */ - public BoxUser.Info getRestoredBy() { - return this.restoredBy; - } - - /** - * Gets the time that this version of the file was purged. - * - * @return the time that this version of the file was purged. - */ - public Date getPurgedAt() { - return this.purgedAt; - } - - /** - * Returns version number. - * - * @return version number - */ - public Long getVersionNumber() { - return versionNumber; - } - - /** - * Deletes this version of the file. - */ - public void delete() { - URL url = VERSION_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.fileID, this.getID()); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); - request.send().close(); - } - - /** - * Downloads this version of the file to a given OutputStream. - * - * @param output the stream to where the file will be written. - */ - public void download(OutputStream output) { - this.download(output, null); - } - - /** - * Downloads this version of the file to a given OutputStream while reporting the progress to a ProgressListener. - * - * @param output the stream to where the file will be written. - * @param listener a listener for monitoring the download's progress. - */ - public void download(OutputStream output, ProgressListener listener) { - URL url = CONTENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.fileID, this.getID()); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); - writeStream(request.send(), output, listener); - } - - /** - * Promotes this version of the file to be the latest version. - */ - public void promote() { - URL url = VERSION_URL_TEMPLATE.buildAlpha(this.getAPI().getBaseURL(), this.fileID, "current"); - - JsonObject jsonObject = new JsonObject(); - jsonObject.add("type", "file_version"); - jsonObject.add("id", this.getID()); - - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); - request.setBody(jsonObject.toString()); - try (BoxJSONResponse response = request.send()) { - this.parseJSON(Json.parse(response.getJSON()).asObject()); - } + } + + /** @return the file id this file version belongs to. */ + public String getFileID() { + return this.fileID; + } + + /** + * Used if no or wrong file id was set with constructor. + * + * @param fileID the file id this file version belongs to. + */ + public void setFileID(String fileID) { + this.fileID = fileID; + } + + /** + * Gets the version ID of this version of the file. + * + * @return the version ID of this version of the file. + */ + public String getVersionID() { + return this.versionID; + } + + /** + * Gets the SHA1 hash of this version of the file. + * + * @return the SHA1 hash of this version of the file. + */ + public String getSha1() { + return this.sha1; + } + + /** + * Gets the name of this version of the file. + * + * @return the name of this version of the file. + */ + public String getName() { + return this.name; + } + + /** + * Gets the size of this version of the file. + * + * @return the size of this version of the file. + */ + public long getSize() { + return this.size; + } + + /** + * Gets the time that this version of the file was created. + * + * @return the time that this version of the file was created. + */ + public Date getCreatedAt() { + return this.createdAt; + } + + /** + * Gets the user's name at the time of upload. + * + * @return the time user's name at the time of upload. + */ + public String getUploaderDisplayName() { + return this.uploaderDisplayName; + } + + /** + * Gets the time that this version of the file was modified. + * + * @return the time that this version of the file was modified. + */ + public Date getModifiedAt() { + return this.modifiedAt; + } + + /** + * Gets the time that this version of the file was deleted. + * + * @return the time that this version of the file was deleted. + */ + public Date getTrashedAt() { + return this.trashedAt; + } + + /** + * Gets information about the user who trashed this version of the file. + * + * @return info about the user who trashed this version of the file. + */ + public BoxUser.Info getTrashedBy() { + return this.trashedBy; + } + + /** + * Gets information about the user who last modified this version of the file. + * + * @return info about the user who last modified this version of the file. + */ + public BoxUser.Info getModifiedBy() { + return this.modifiedBy; + } + + /** + * Gets the time that this version of the file was restored. + * + * @return the time that this version of the file was restored. + */ + public Date getRestoredAt() { + return this.restoredAt; + } + + /** + * Gets information about the user who restored this version of the file. + * + * @return info about the user who restored this version of the file. + */ + public BoxUser.Info getRestoredBy() { + return this.restoredBy; + } + + /** + * Gets the time that this version of the file was purged. + * + * @return the time that this version of the file was purged. + */ + public Date getPurgedAt() { + return this.purgedAt; + } + + /** + * Returns version number. + * + * @return version number + */ + public Long getVersionNumber() { + return versionNumber; + } + + /** Deletes this version of the file. */ + public void delete() { + URL url = VERSION_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.fileID, this.getID()); + BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); + request.send().close(); + } + + /** + * Downloads this version of the file to a given OutputStream. + * + * @param output the stream to where the file will be written. + */ + public void download(OutputStream output) { + this.download(output, null); + } + + /** + * Downloads this version of the file to a given OutputStream while reporting the progress to a + * ProgressListener. + * + * @param output the stream to where the file will be written. + * @param listener a listener for monitoring the download's progress. + */ + public void download(OutputStream output, ProgressListener listener) { + URL url = CONTENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.fileID, this.getID()); + BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); + writeStream(request.send(), output, listener); + } + + /** Promotes this version of the file to be the latest version. */ + public void promote() { + URL url = VERSION_URL_TEMPLATE.buildAlpha(this.getAPI().getBaseURL(), this.fileID, "current"); + + JsonObject jsonObject = new JsonObject(); + jsonObject.add("type", "file_version"); + jsonObject.add("id", this.getID()); + + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); + request.setBody(jsonObject.toString()); + try (BoxJSONResponse response = request.send()) { + this.parseJSON(Json.parse(response.getJSON()).asObject()); } + } } diff --git a/src/main/java/com/box/sdk/BoxFileVersionLegalHold.java b/src/main/java/com/box/sdk/BoxFileVersionLegalHold.java index 65ee97405..88890a40b 100644 --- a/src/main/java/com/box/sdk/BoxFileVersionLegalHold.java +++ b/src/main/java/com/box/sdk/BoxFileVersionLegalHold.java @@ -10,179 +10,156 @@ import java.util.List; /** - * Representing all holds on a file version. - * Note that every file version can have a maximum of one file version legal hold. + * Representing all holds on a file version. Note that every file version can have a maximum of one + * file version legal hold. */ @BoxResourceType("file_version_legal_hold") public class BoxFileVersionLegalHold extends BoxResource { + /** + * The URL template used for operation with file version legal hold with given ID. + * + * @see #getInfo(String...) + */ + public static final URLTemplate FILE_VERSION_HOLD_URL_TEMPLATE = + new URLTemplate("file_version_legal_holds/%s"); + + /** + * Constructs a file version legal hold with a given ID. + * + * @param api the API connection to be used by the resource. + * @param id the ID of the resource. + */ + public BoxFileVersionLegalHold(BoxAPIConnection api, String id) { + super(api, id); + } + + /** + * @param fields the fields to retrieve. + * @return information about this file version legal hold. + */ + public BoxFileVersionLegalHold.Info getInfo(String... fields) { + QueryStringBuilder builder = new QueryStringBuilder(); + if (fields.length > 0) { + builder.appendParam("fields", fields); + } + URL url = + FILE_VERSION_HOLD_URL_TEMPLATE.buildWithQuery( + this.getAPI().getBaseURL(), builder.toString(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + return new Info(responseJSON); + } + } + + /** Contains information about the file version legal hold. */ + public class Info extends BoxResource.Info { + + /** Used for file version in case it was retrieved separately from file. */ + private static final String DEFAULT_FILE_ID = "0"; + + /** @see #getFileVersion() */ + private BoxFileVersion fileVersion; + + /** @see #getFile() */ + private BoxFile.Info file; + + /** @see #getAssignments() */ + private List assignments; + + /** @see #getDeletedAt() */ + private Date deletedAt; + + /** Constructs an empty Info object. */ + public Info() { + super(); + } + /** - * The URL template used for operation with file version legal hold with given ID. + * Constructs an Info object by parsing information from a JSON string. * - * @see #getInfo(String...) + * @param json the JSON string to parse. */ - public static final URLTemplate FILE_VERSION_HOLD_URL_TEMPLATE = new URLTemplate("file_version_legal_holds/%s"); + public Info(String json) { + super(json); + } /** - * Constructs a file version legal hold with a given ID. + * Constructs an Info object using an already parsed JSON object. * - * @param api the API connection to be used by the resource. - * @param id the ID of the resource. + * @param jsonObject the parsed JSON object. */ - public BoxFileVersionLegalHold(BoxAPIConnection api, String id) { - super(api, id); + Info(JsonObject jsonObject) { + super(jsonObject); } - /** - * @param fields the fields to retrieve. - * @return information about this file version legal hold. - */ - public BoxFileVersionLegalHold.Info getInfo(String... fields) { - QueryStringBuilder builder = new QueryStringBuilder(); - if (fields.length > 0) { - builder.appendParam("fields", fields); - } - URL url = FILE_VERSION_HOLD_URL_TEMPLATE.buildWithQuery( - this.getAPI().getBaseURL(), builder.toString(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - return new Info(responseJSON); - } + /** {@inheritDoc} */ + @Override + public BoxResource getResource() { + return BoxFileVersionLegalHold.this; + } + + /** @return the file version that is held. */ + public BoxFileVersion getFileVersion() { + return this.fileVersion; } /** - * Contains information about the file version legal hold. + * @return the parent file of the file version that is held. Note that there is no guarantee + * that the current version of this file is held. */ - public class Info extends BoxResource.Info { - - /** - * Used for file version in case it was retrieved separately from file. - */ - private static final String DEFAULT_FILE_ID = "0"; - - /** - * @see #getFileVersion() - */ - private BoxFileVersion fileVersion; - - /** - * @see #getFile() - */ - private BoxFile.Info file; - - /** - * @see #getAssignments() - */ - private List assignments; - - /** - * @see #getDeletedAt() - */ - private Date deletedAt; - - /** - * Constructs an empty Info object. - */ - public Info() { - super(); - } - - /** - * Constructs an Info object by parsing information from a JSON string. - * - * @param json the JSON string to parse. - */ - public Info(String json) { - super(json); - } - - /** - * Constructs an Info object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - Info(JsonObject jsonObject) { - super(jsonObject); - } - - /** - * {@inheritDoc} - */ - @Override - public BoxResource getResource() { - return BoxFileVersionLegalHold.this; - } - - /** - * @return the file version that is held. - */ - public BoxFileVersion getFileVersion() { - return this.fileVersion; - } - - /** - * @return the parent file of the file version that is held. - * Note that there is no guarantee that the current version of this file is held. - */ - public BoxFile.Info getFile() { - return this.file; - } + public BoxFile.Info getFile() { + return this.file; + } - /** - * @return iterable with the assignments contributing to this file version legal hold. - */ - public Iterable getAssignments() { - return this.assignments; - } + /** @return iterable with the assignments contributing to this file version legal hold. */ + public Iterable getAssignments() { + return this.assignments; + } - /** - * @return time that this file version legal hold was deleted. - */ - public Date getDeletedAt() { - return this.deletedAt; - } + /** @return time that this file version legal hold was deleted. */ + public Date getDeletedAt() { + return this.deletedAt; + } - /** - * {@inheritDoc} - */ - @Override - void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - String memberName = member.getName(); - JsonValue value = member.getValue(); - try { - if (memberName.equals("file")) { - JsonObject fileJSON = value.asObject(); - if (this.file == null) { - String fileID = fileJSON.get("id").asString(); - BoxFile file = new BoxFile(getAPI(), fileID); - this.file = file.new Info(fileJSON); - } else { - this.file.update(fileJSON); - } - if (this.fileVersion != null) { - this.fileVersion.setFileID(this.file.getID()); - } - } else if (memberName.equals("file_version")) { - JsonObject versionJSON = value.asObject(); - String fileID = this.file != null ? this.file.getID() : DEFAULT_FILE_ID; - this.fileVersion = new BoxFileVersion(getAPI(), versionJSON, fileID); - } else if (memberName.equals("legal_hold_policy_assignments")) { - JsonArray array = value.asArray(); - this.assignments = new ArrayList<>(); - for (JsonValue assignmentJSON : array) { - String assignmentID = ((JsonObject) assignmentJSON).get("id").asString(); - BoxLegalHoldAssignment assignment = new BoxLegalHoldAssignment(getAPI(), assignmentID); - this.assignments.add(assignment.new Info((JsonObject) assignmentJSON)); - } - } else if (memberName.equals("deleted_at")) { - this.deletedAt = BoxDateFormat.parse(value.asString()); - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); - } + /** {@inheritDoc} */ + @Override + void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + String memberName = member.getName(); + JsonValue value = member.getValue(); + try { + if (memberName.equals("file")) { + JsonObject fileJSON = value.asObject(); + if (this.file == null) { + String fileID = fileJSON.get("id").asString(); + BoxFile file = new BoxFile(getAPI(), fileID); + this.file = file.new Info(fileJSON); + } else { + this.file.update(fileJSON); + } + if (this.fileVersion != null) { + this.fileVersion.setFileID(this.file.getID()); + } + } else if (memberName.equals("file_version")) { + JsonObject versionJSON = value.asObject(); + String fileID = this.file != null ? this.file.getID() : DEFAULT_FILE_ID; + this.fileVersion = new BoxFileVersion(getAPI(), versionJSON, fileID); + } else if (memberName.equals("legal_hold_policy_assignments")) { + JsonArray array = value.asArray(); + this.assignments = new ArrayList<>(); + for (JsonValue assignmentJSON : array) { + String assignmentID = ((JsonObject) assignmentJSON).get("id").asString(); + BoxLegalHoldAssignment assignment = new BoxLegalHoldAssignment(getAPI(), assignmentID); + this.assignments.add(assignment.new Info((JsonObject) assignmentJSON)); + } + } else if (memberName.equals("deleted_at")) { + this.deletedAt = BoxDateFormat.parse(value.asString()); } - + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); + } } + } } diff --git a/src/main/java/com/box/sdk/BoxFileVersionRetention.java b/src/main/java/com/box/sdk/BoxFileVersionRetention.java index 9c9c40fed..24254f75f 100644 --- a/src/main/java/com/box/sdk/BoxFileVersionRetention.java +++ b/src/main/java/com/box/sdk/BoxFileVersionRetention.java @@ -7,356 +7,312 @@ import java.util.Date; /** - * Represents a file version retention. - * A retention policy blocks permanent deletion of content for a specified amount of time. - * Admins can apply policies to specified folders, or an entire enterprise. - * A file version retention is a record for a retained file version. + * Represents a file version retention. A retention policy blocks permanent deletion of content for + * a specified amount of time. Admins can apply policies to specified folders, or an entire + * enterprise. A file version retention is a record for a retained file version. * - * @see Box file version retention - * - *

Unless otherwise noted, the methods in this class can throw an unchecked {@link BoxAPIException} (unchecked - * meaning that the compiler won't force you to handle it) if an error occurs. If you wish to implement custom error - * handling for errors related to the Box REST API, you should capture this exception explicitly.

+ * @see Box file + * version retention + *

Unless otherwise noted, the methods in this class can throw an unchecked {@link + * BoxAPIException} (unchecked meaning that the compiler won't force you to handle it) if an + * error occurs. If you wish to implement custom error handling for errors related to the Box + * REST API, you should capture this exception explicitly. */ @BoxResourceType("file_version_retention") public class BoxFileVersionRetention extends BoxResource { + /** @see #getInfo(String...) */ + public static final URLTemplate RETENTION_URL_TEMPLATE = + new URLTemplate("file_version_retentions/%s"); + + /** The URL template used for operation with file version retentions. */ + public static final URLTemplate ALL_RETENTIONS_URL_TEMPLATE = + new URLTemplate("file_version_retentions"); + + /** The default limit of entries per response. */ + private static final int DEFAULT_LIMIT = 100; + + /** + * Constructs a BoxFileVersionRetention for a resource with a given ID. + * + * @param api the API connection to be used by the resource. + * @param id the ID of the resource. + */ + public BoxFileVersionRetention(BoxAPIConnection api, String id) { + super(api, id); + } + + /** + * Retrieves all file version retentions. + * + * @param api the API connection to be used by the resource. + * @param fields the fields to retrieve. + * @return an iterable contains information about all file version retentions. + */ + public static Iterable getAll( + BoxAPIConnection api, String... fields) { + return getRetentions(api, new QueryFilter(), fields); + } + + /** + * Retrieves all file version retentions matching given filters as an Iterable. + * + * @param api the API connection to be used by the resource. + * @param filter filters for the query stored in QueryFilter object. + * @param fields the fields to retrieve. + * @return an iterable contains information about all file version retentions matching given + * filter. + */ + public static Iterable getRetentions( + final BoxAPIConnection api, QueryFilter filter, String... fields) { + filter.addFields(fields); + return new BoxResourceIterable( + api, + ALL_RETENTIONS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), filter.toString()), + DEFAULT_LIMIT) { + + @Override + protected BoxFileVersionRetention.Info factory(JsonObject jsonObject) { + BoxFileVersionRetention retention = + new BoxFileVersionRetention(api, jsonObject.get("id").asString()); + return retention.new Info(jsonObject); + } + }; + } + + /** + * @param fields the fields to retrieve. + * @return information about this retention policy. + */ + public BoxFileVersionRetention.Info getInfo(String... fields) { + QueryStringBuilder builder = new QueryStringBuilder(); + if (fields.length > 0) { + builder.appendParam("fields", fields); + } + URL url = + RETENTION_URL_TEMPLATE.buildWithQuery( + this.getAPI().getBaseURL(), builder.toString(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + return new Info(responseJSON); + } + } + + /** Represents possible query filters for "Get File Version Retentions" function. */ + public static class QueryFilter extends QueryStringBuilder { + + /** Param name for the file id to filter the file version retentions by. */ + private static final String PARAM_FILE_ID = "file_id"; + + /** Param name for the file version id to filter the file version retentions by. */ + private static final String PARAM_FILE_VERSION_ID = "file_version_id"; + + /** Param name for the policy id to filter the file version retentions by. */ + private static final String PARAM_POLICY_ID = "policy_id"; + + /** Param name for the disposition action of the retention policy. */ + private static final String PARAM_DISPOSITION_ACTION = "disposition_action"; + + /** Param name for the datetime to filter file version retentions. */ + private static final String PARAM_DISPOSITION_BEFORE = "disposition_before"; + + /** Param name for the datetime to filter file version retentions. */ + private static final String PARAM_DISPOSITION_AFTER = "disposition_after"; + + /** Param name for the the fields to retrieve. */ + private static final String PARAM_FIELDS = "fields"; + + /** Constructs empty query filter. */ + public QueryFilter() { + super(); + } + /** - * @see #getInfo(String...) + * @param id a file id to filter the file version retentions by. + * @return modified query filter. */ - public static final URLTemplate RETENTION_URL_TEMPLATE = new URLTemplate("file_version_retentions/%s"); + public QueryFilter addFileID(String id) { + this.appendParam(PARAM_FILE_ID, id); + return this; + } /** - * The URL template used for operation with file version retentions. + * @param id a file version id to filter the file version retentions by. + * @return modified query filter. */ - public static final URLTemplate ALL_RETENTIONS_URL_TEMPLATE = new URLTemplate("file_version_retentions"); + public QueryFilter addFileVersionID(String id) { + this.appendParam(PARAM_FILE_VERSION_ID, id); + return this; + } /** - * The default limit of entries per response. + * @param id a policy id to filter the file version retentions by. + * @return modified query filter. */ - private static final int DEFAULT_LIMIT = 100; + public QueryFilter addPolicyID(String id) { + this.appendParam(PARAM_POLICY_ID, id); + return this; + } /** - * Constructs a BoxFileVersionRetention for a resource with a given ID. + * The action can be "permanently_delete" or "remove_retention". * - * @param api the API connection to be used by the resource. - * @param id the ID of the resource. + * @param action the disposition action of the retention policy. + * @return modified query filter. */ - public BoxFileVersionRetention(BoxAPIConnection api, String id) { - super(api, id); + public QueryFilter addDispositionAction(String action) { + this.appendParam(PARAM_DISPOSITION_ACTION, action); + return this; } /** - * Retrieves all file version retentions. - * - * @param api the API connection to be used by the resource. - * @param fields the fields to retrieve. - * @return an iterable contains information about all file version retentions. + * @param date the datetime to filter file version retentions. + * @return modified query filter. */ - public static Iterable getAll(BoxAPIConnection api, String... fields) { - return getRetentions(api, new QueryFilter(), fields); + public QueryFilter addDispositionBefore(Date date) { + this.appendParam(PARAM_DISPOSITION_BEFORE, BoxDateFormat.format(date)); + return this; } /** - * Retrieves all file version retentions matching given filters as an Iterable. - * - * @param api the API connection to be used by the resource. - * @param filter filters for the query stored in QueryFilter object. - * @param fields the fields to retrieve. - * @return an iterable contains information about all file version retentions matching given filter. + * @param date the datetime to filter file version retentions. + * @return modified query filter. */ - public static Iterable getRetentions( - final BoxAPIConnection api, QueryFilter filter, String... fields) { - filter.addFields(fields); - return new BoxResourceIterable(api, - ALL_RETENTIONS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), filter.toString()), - DEFAULT_LIMIT) { - - @Override - protected BoxFileVersionRetention.Info factory(JsonObject jsonObject) { - BoxFileVersionRetention retention = new BoxFileVersionRetention(api, jsonObject.get("id").asString()); - return retention.new Info(jsonObject); - } - }; + public QueryFilter addDispositionAfter(Date date) { + this.appendParam(PARAM_DISPOSITION_AFTER, BoxDateFormat.format(date)); + return this; } /** * @param fields the fields to retrieve. - * @return information about this retention policy. + * @return modified query filter. */ - public BoxFileVersionRetention.Info getInfo(String... fields) { - QueryStringBuilder builder = new QueryStringBuilder(); - if (fields.length > 0) { - builder.appendParam("fields", fields); - } - URL url = RETENTION_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), builder.toString(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - return new Info(responseJSON); - } + public QueryFilter addFields(String... fields) { + if (fields.length > 0) { + this.appendParam(PARAM_FIELDS, fields); + } + return this; } + } - /** - * Represents possible query filters for "Get File Version Retentions" function. - */ - public static class QueryFilter extends QueryStringBuilder { - - /** - * Param name for the file id to filter the file version retentions by. - */ - private static final String PARAM_FILE_ID = "file_id"; - - /** - * Param name for the file version id to filter the file version retentions by. - */ - private static final String PARAM_FILE_VERSION_ID = "file_version_id"; - - /** - * Param name for the policy id to filter the file version retentions by. - */ - private static final String PARAM_POLICY_ID = "policy_id"; - - /** - * Param name for the disposition action of the retention policy. - */ - private static final String PARAM_DISPOSITION_ACTION = "disposition_action"; - - /** - * Param name for the datetime to filter file version retentions. - */ - private static final String PARAM_DISPOSITION_BEFORE = "disposition_before"; - - /** - * Param name for the datetime to filter file version retentions. - */ - private static final String PARAM_DISPOSITION_AFTER = "disposition_after"; - - /** - * Param name for the the fields to retrieve. - */ - private static final String PARAM_FIELDS = "fields"; - - /** - * Constructs empty query filter. - */ - public QueryFilter() { - super(); - } + /** Contains information about the retention policy. */ + public class Info extends BoxResource.Info { - /** - * @param id a file id to filter the file version retentions by. - * @return modified query filter. - */ - public QueryFilter addFileID(String id) { - this.appendParam(PARAM_FILE_ID, id); - return this; - } + /** @see #getFileVersion() */ + private BoxFileVersion fileVersion; - /** - * @param id a file version id to filter the file version retentions by. - * @return modified query filter. - */ - public QueryFilter addFileVersionID(String id) { - this.appendParam(PARAM_FILE_VERSION_ID, id); - return this; - } + /** @see #getFile() */ + private BoxFile.Info file; - /** - * @param id a policy id to filter the file version retentions by. - * @return modified query filter. - */ - public QueryFilter addPolicyID(String id) { - this.appendParam(PARAM_POLICY_ID, id); - return this; - } + /** @see #getAppliedAt() */ + private Date appliedAt; - /** - * The action can be "permanently_delete" or "remove_retention". - * - * @param action the disposition action of the retention policy. - * @return modified query filter. - */ - public QueryFilter addDispositionAction(String action) { - this.appendParam(PARAM_DISPOSITION_ACTION, action); - return this; - } - - /** - * @param date the datetime to filter file version retentions. - * @return modified query filter. - */ - public QueryFilter addDispositionBefore(Date date) { - this.appendParam(PARAM_DISPOSITION_BEFORE, BoxDateFormat.format(date)); - return this; - } + /** @see #getDispositionAt() */ + private Date dispositionAt; - /** - * @param date the datetime to filter file version retentions. - * @return modified query filter. - */ - public QueryFilter addDispositionAfter(Date date) { - this.appendParam(PARAM_DISPOSITION_AFTER, BoxDateFormat.format(date)); - return this; - } + /** @see #getWinningPolicy() */ + private BoxRetentionPolicy.Info winningPolicy; - /** - * @param fields the fields to retrieve. - * @return modified query filter. - */ - public QueryFilter addFields(String... fields) { - if (fields.length > 0) { - this.appendParam(PARAM_FIELDS, fields); - } - return this; - } + /** Constructs an empty Info object. */ + public Info() { + super(); } /** - * Contains information about the retention policy. + * Constructs an Info object by parsing information from a JSON string. + * + * @param json the JSON string to parse. */ - public class Info extends BoxResource.Info { - - /** - * @see #getFileVersion() - */ - private BoxFileVersion fileVersion; - - /** - * @see #getFile() - */ - private BoxFile.Info file; - - /** - * @see #getAppliedAt() - */ - private Date appliedAt; - - /** - * @see #getDispositionAt() - */ - private Date dispositionAt; - - /** - * @see #getWinningPolicy() - */ - private BoxRetentionPolicy.Info winningPolicy; - - /** - * Constructs an empty Info object. - */ - public Info() { - super(); - } - - /** - * Constructs an Info object by parsing information from a JSON string. - * - * @param json the JSON string to parse. - */ - public Info(String json) { - super(json); - } + public Info(String json) { + super(json); + } - /** - * Constructs an Info object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - Info(JsonObject jsonObject) { - super(jsonObject); - } + /** + * Constructs an Info object using an already parsed JSON object. + * + * @param jsonObject the parsed JSON object. + */ + Info(JsonObject jsonObject) { + super(jsonObject); + } - /** - * {@inheritDoc} - */ - @Override - public BoxResource getResource() { - return BoxFileVersionRetention.this; - } + /** {@inheritDoc} */ + @Override + public BoxResource getResource() { + return BoxFileVersionRetention.this; + } - /** - * @return the file version this file version retention was applied to. - */ - public BoxFileVersion getFileVersion() { - return this.fileVersion; - } + /** @return the file version this file version retention was applied to. */ + public BoxFileVersion getFileVersion() { + return this.fileVersion; + } - /** - * @return the file this file version retention was applied to. - */ - public BoxFile.Info getFile() { - return this.file; - } + /** @return the file this file version retention was applied to. */ + public BoxFile.Info getFile() { + return this.file; + } - /** - * @return the time that this file version retention was created. - */ - public Date getAppliedAt() { - return this.appliedAt; - } + /** @return the time that this file version retention was created. */ + public Date getAppliedAt() { + return this.appliedAt; + } - /** - * @return the time that the retention period expires on this file version retention. - */ - public Date getDispositionAt() { - return this.dispositionAt; - } + /** @return the time that the retention period expires on this file version retention. */ + public Date getDispositionAt() { + return this.dispositionAt; + } - /** - * @return the winning retention policy applied to this file version retention. - */ - public BoxRetentionPolicy.Info getWinningPolicy() { - return this.winningPolicy; - } + /** @return the winning retention policy applied to this file version retention. */ + public BoxRetentionPolicy.Info getWinningPolicy() { + return this.winningPolicy; + } - /** - * {@inheritDoc} - */ - @Override - void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - String memberName = member.getName(); - JsonValue value = member.getValue(); - try { - switch (memberName) { - case "winning_retention_policy": - JsonObject policyJSON = value.asObject(); - if (this.winningPolicy == null) { - String policyID = policyJSON.get("id").asString(); - BoxRetentionPolicy policy = new BoxRetentionPolicy(getAPI(), policyID); - this.winningPolicy = policy.new Info(policyJSON); - } else { - this.winningPolicy.update(policyJSON); - } - break; - case "file": - JsonObject fileJSON = value.asObject(); - if (this.file == null) { - String fileID = fileJSON.get("id").asString(); - BoxFile file = new BoxFile(getAPI(), fileID); - this.file = file.new Info(fileJSON); - } else { - this.file.update(fileJSON); - } - break; - case "file_version": - JsonObject versionJSON = value.asObject(); - String fileVersionID = versionJSON.get("id").asString(); - this.fileVersion = new BoxFileVersion(getAPI(), versionJSON, fileVersionID); - break; - case "applied_at": - this.appliedAt = BoxDateFormat.parse(value.asString()); - break; - case "disposition_at": - this.dispositionAt = BoxDateFormat.parse(value.asString()); - break; - default: - break; - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); + /** {@inheritDoc} */ + @Override + void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + String memberName = member.getName(); + JsonValue value = member.getValue(); + try { + switch (memberName) { + case "winning_retention_policy": + JsonObject policyJSON = value.asObject(); + if (this.winningPolicy == null) { + String policyID = policyJSON.get("id").asString(); + BoxRetentionPolicy policy = new BoxRetentionPolicy(getAPI(), policyID); + this.winningPolicy = policy.new Info(policyJSON); + } else { + this.winningPolicy.update(policyJSON); + } + break; + case "file": + JsonObject fileJSON = value.asObject(); + if (this.file == null) { + String fileID = fileJSON.get("id").asString(); + BoxFile file = new BoxFile(getAPI(), fileID); + this.file = file.new Info(fileJSON); + } else { + this.file.update(fileJSON); } + break; + case "file_version": + JsonObject versionJSON = value.asObject(); + String fileVersionID = versionJSON.get("id").asString(); + this.fileVersion = new BoxFileVersion(getAPI(), versionJSON, fileVersionID); + break; + case "applied_at": + this.appliedAt = BoxDateFormat.parse(value.asString()); + break; + case "disposition_at": + this.dispositionAt = BoxDateFormat.parse(value.asString()); + break; + default: + break; } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); + } } + } } diff --git a/src/main/java/com/box/sdk/BoxFolder.java b/src/main/java/com/box/sdk/BoxFolder.java index 0632b591b..f194ec8b2 100644 --- a/src/main/java/com/box/sdk/BoxFolder.java +++ b/src/main/java/com/box/sdk/BoxFolder.java @@ -25,1779 +25,1803 @@ import java.util.concurrent.TimeUnit; /** - *

Represents a folder on Box. This class can be used to iterate through a folder's contents, collaborate a folder with - * another user or group, and perform other common folder operations (move, copy, delete, etc.). - *

- *

Unless otherwise noted, the methods in this class can throw an unchecked {@link BoxAPIException} (unchecked - * meaning that the compiler won't force you to handle it) if an error occurs. If you wish to implement custom error - * handling for errors related to the Box REST API, you should capture this exception explicitly.

+ * Represents a folder on Box. This class can be used to iterate through a folder's contents, + * collaborate a folder with another user or group, and perform other common folder operations + * (move, copy, delete, etc.). + * + *

Unless otherwise noted, the methods in this class can throw an unchecked {@link + * BoxAPIException} (unchecked meaning that the compiler won't force you to handle it) if an error + * occurs. If you wish to implement custom error handling for errors related to the Box REST API, + * you should capture this exception explicitly. */ @BoxResourceType("folder") public class BoxFolder extends BoxItem implements Iterable { - /** - * An array of all possible folder fields that can be requested when calling {@link #getInfo(String...)}. - */ - public static final String[] ALL_FIELDS = {"type", "id", "sequence_id", "etag", "name", "created_at", "modified_at", - "description", "size", "path_collection", "created_by", "modified_by", "trashed_at", "purged_at", - "content_created_at", "content_modified_at", "owned_by", "shared_link", "folder_upload_email", "parent", - "item_status", "item_collection", "sync_state", "has_collaborations", "permissions", "tags", - "can_non_owners_invite", "collections", "watermark_info", "metadata", "is_externally_owned", - "is_collaboration_restricted_to_enterprise", "allowed_shared_link_access_levels", "allowed_invitee_roles", - "is_accessible_via_shared_link", "can_non_owners_view_collaborators" + /** + * An array of all possible folder fields that can be requested when calling {@link + * #getInfo(String...)}. + */ + public static final String[] ALL_FIELDS = { + "type", + "id", + "sequence_id", + "etag", + "name", + "created_at", + "modified_at", + "description", + "size", + "path_collection", + "created_by", + "modified_by", + "trashed_at", + "purged_at", + "content_created_at", + "content_modified_at", + "owned_by", + "shared_link", + "folder_upload_email", + "parent", + "item_status", + "item_collection", + "sync_state", + "has_collaborations", + "permissions", + "tags", + "can_non_owners_invite", + "collections", + "watermark_info", + "metadata", + "is_externally_owned", + "is_collaboration_restricted_to_enterprise", + "allowed_shared_link_access_levels", + "allowed_invitee_roles", + "is_accessible_via_shared_link", + "can_non_owners_view_collaborators" + }; + /** Create Folder URL Template. */ + public static final URLTemplate CREATE_FOLDER_URL = new URLTemplate("folders"); + /** Create Web Link URL Template. */ + public static final URLTemplate CREATE_WEB_LINK_URL = new URLTemplate("web_links"); + /** Copy Folder URL Template. */ + public static final URLTemplate COPY_FOLDER_URL = new URLTemplate("folders/%s/copy"); + /** Delete Folder URL Template. */ + public static final URLTemplate DELETE_FOLDER_URL = new URLTemplate("folders/%s?recursive=%b"); + /** Folder Info URL Template. */ + public static final URLTemplate FOLDER_INFO_URL_TEMPLATE = new URLTemplate("folders/%s"); + /** Upload File URL Template. */ + public static final URLTemplate UPLOAD_FILE_URL = new URLTemplate("files/content"); + /** Add Collaboration URL Template. */ + public static final URLTemplate ADD_COLLABORATION_URL = new URLTemplate("collaborations"); + /** Get Collaborations URL Template. */ + public static final URLTemplate GET_COLLABORATIONS_URL = + new URLTemplate("folders/%s/collaborations"); + /** Get Items URL Template. */ + public static final URLTemplate GET_ITEMS_URL = new URLTemplate("folders/%s/items/"); + /** Search URL Template. */ + public static final URLTemplate SEARCH_URL_TEMPLATE = new URLTemplate("search"); + /** Metadata URL Template. */ + public static final URLTemplate METADATA_URL_TEMPLATE = + new URLTemplate("folders/%s/metadata/%s/%s"); + /** Upload Session URL Template. */ + public static final URLTemplate UPLOAD_SESSION_URL_TEMPLATE = + new URLTemplate("files/upload_sessions"); + /** Folder Locks URL Template. */ + public static final URLTemplate FOLDER_LOCK_URL_TEMPLATE = new URLTemplate("folder_locks"); + /** Describes folder item type. */ + static final String TYPE = "folder"; + + /** + * Constructs a BoxFolder for a folder with a given ID. + * + * @param api the API connection to be used by the folder. + * @param id the ID of the folder. + */ + public BoxFolder(BoxAPIConnection api, String id) { + super(api, id); + } + + /** + * Gets the current user's root folder. + * + * @param api the API connection to be used by the folder. + * @return the user's root folder. + */ + public static BoxFolder getRootFolder(BoxAPIConnection api) { + return new BoxFolder(api, "0"); + } + + /** {@inheritDoc} */ + @Override + protected URL getItemURL() { + return FOLDER_INFO_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + } + + /** + * Adds a collaborator to this folder. + * + * @param collaborator the collaborator to add. + * @param role the role of the collaborator. + * @return info about the new collaboration. + */ + public BoxCollaboration.Info collaborate( + BoxCollaborator collaborator, BoxCollaboration.Role role) { + JsonObject accessibleByField = new JsonObject(); + accessibleByField.add("id", collaborator.getID()); + + if (collaborator instanceof BoxUser) { + accessibleByField.add("type", "user"); + } else if (collaborator instanceof BoxGroup) { + accessibleByField.add("type", "group"); + } else { + throw new IllegalArgumentException("The given collaborator is of an unknown type."); + } + + return this.collaborate(accessibleByField, role, null, null, null, null); + } + + /** + * Adds a collaborator to this folder. An email will be sent to the collaborator if they don't + * already have a Box account. + * + * @param email the email address of the collaborator to add. + * @param role the role of the collaborator. + * @return info about the new collaboration. + */ + public BoxCollaboration.Info collaborate(String email, BoxCollaboration.Role role) { + JsonObject accessibleByField = new JsonObject(); + accessibleByField.add("login", email); + accessibleByField.add("type", "user"); + + return this.collaborate(accessibleByField, role, null, null, null, null); + } + + /** + * Adds a collaborator to this folder. + * + * @param collaborator the collaborator to add. + * @param role the role of the collaborator. + * @param notify the user/group should receive email notification of the collaboration or not. + * @param canViewPath the view path collaboration feature is enabled or not. View path + * collaborations allow the invitee to see the entire ancestral path to the associated folder. + * The user will not gain privileges in any ancestral folder. + * @param expiresAt when the collaboration should expire. + * @param isAccessOnly whether the collaboration is access only or not. + * @return info about the new collaboration. + */ + public BoxCollaboration.Info collaborate( + BoxCollaborator collaborator, + BoxCollaboration.Role role, + Boolean notify, + Boolean canViewPath, + Date expiresAt, + Boolean isAccessOnly) { + JsonObject accessibleByField = new JsonObject(); + accessibleByField.add("id", collaborator.getID()); + + if (collaborator instanceof BoxUser) { + accessibleByField.add("type", "user"); + } else if (collaborator instanceof BoxGroup) { + accessibleByField.add("type", "group"); + } else { + throw new IllegalArgumentException("The given collaborator is of an unknown type."); + } + + return this.collaborate(accessibleByField, role, notify, canViewPath, expiresAt, isAccessOnly); + } + + /** + * Adds a collaborator to this folder. + * + * @param collaborator the collaborator to add. + * @param role the role of the collaborator. + * @param notify the user/group should receive email notification of the collaboration or not. + * @param canViewPath the view path collaboration feature is enabled or not. View path + * collaborations allow the invitee to see the entire ancestral path to the associated folder. + * The user will not gain privileges in any ancestral folder. + * @return info about the new collaboration. + */ + public BoxCollaboration.Info collaborate( + BoxCollaborator collaborator, + BoxCollaboration.Role role, + Boolean notify, + Boolean canViewPath) { + return this.collaborate(collaborator, role, notify, canViewPath, null, null); + } + + /** + * Adds a collaborator to this folder. An email will be sent to the collaborator if they don't + * already have a Box account. + * + * @param email the email address of the collaborator to add. + * @param role the role of the collaborator. + * @param notify the user/group should receive email notification of the collaboration or not. + * @param canViewPath the view path collaboration feature is enabled or not. View path + * collaborations allow the invitee to see the entire ancestral path to the associated folder. + * The user will not gain privileges in any ancestral folder. + * @param expiresAt when the collaboration should expire. + * @param isAccessOnly whether the collaboration is access only or not. + * @return info about the new collaboration. + */ + public BoxCollaboration.Info collaborate( + String email, + BoxCollaboration.Role role, + Boolean notify, + Boolean canViewPath, + Date expiresAt, + Boolean isAccessOnly) { + JsonObject accessibleByField = new JsonObject(); + accessibleByField.add("login", email); + accessibleByField.add("type", "user"); + + return this.collaborate(accessibleByField, role, notify, canViewPath, expiresAt, isAccessOnly); + } + + /** + * Adds a collaborator to this folder. An email will be sent to the collaborator if they don't + * already have a Box account. + * + * @param email the email address of the collaborator to add. + * @param role the role of the collaborator. + * @param notify the user/group should receive email notification of the collaboration or not. + * @param canViewPath the view path collaboration feature is enabled or not. View path + * collaborations allow the invitee to see the entire ancestral path to the associated folder. + * The user will not gain privileges in any ancestral folder. + * @return info about the new collaboration. + */ + public BoxCollaboration.Info collaborate( + String email, BoxCollaboration.Role role, Boolean notify, Boolean canViewPath) { + return this.collaborate(email, role, notify, canViewPath, null, null); + } + + private BoxCollaboration.Info collaborate( + JsonObject accessibleByField, + BoxCollaboration.Role role, + Boolean notify, + Boolean canViewPath, + Date expiresAt, + Boolean isAccessOnly) { + + JsonObject itemField = new JsonObject(); + itemField.add("id", this.getID()); + itemField.add("type", "folder"); + + return BoxCollaboration.create( + this.getAPI(), + accessibleByField, + itemField, + role, + notify, + canViewPath, + expiresAt, + isAccessOnly); + } + + /** + * Creates a shared link. + * + * @param sharedLinkRequest Shared link to create + * @return Created shared link. + */ + public BoxSharedLink createSharedLink(BoxSharedLinkRequest sharedLinkRequest) { + return createSharedLink(sharedLinkRequest.asSharedLink()); + } + + private BoxSharedLink createSharedLink(BoxSharedLink sharedLink) { + BoxFolder.Info info = new BoxFolder.Info(); + info.setSharedLink(removeCanEditPermissionIfSet(sharedLink)); + + this.updateInfo(info); + return info.getSharedLink(); + } + + private BoxSharedLink removeCanEditPermissionIfSet(BoxSharedLink sharedLink) { + if (sharedLink.getPermissions() != null && sharedLink.getPermissions().getCanEdit()) { + BoxSharedLink.Permissions permissions = sharedLink.getPermissions(); + sharedLink.setPermissions( + new BoxSharedLink.Permissions( + permissions.getCanPreview(), permissions.getCanDownload(), false)); + } + return sharedLink; + } + + /** + * Gets information about all of the collaborations for this folder. + * + * @return a collection of information about the collaborations for this folder. + */ + public Collection getCollaborations(String... fields) { + BoxAPIConnection api = this.getAPI(); + QueryStringBuilder queryBuilder = new QueryStringBuilder(); + if (fields.length > 0) { + queryBuilder.appendParam("fields", fields); + } + URL url = + GET_COLLABORATIONS_URL.buildWithQuery( + api.getBaseURL(), queryBuilder.toString(), this.getID()); + + BoxJSONRequest request = new BoxJSONRequest(api, url, "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + + int entriesCount = responseJSON.get("total_count").asInt(); + Collection collaborations = new ArrayList<>(entriesCount); + JsonArray entries = responseJSON.get("entries").asArray(); + for (JsonValue entry : entries) { + JsonObject entryObject = entry.asObject(); + BoxCollaboration collaboration = + new BoxCollaboration(api, entryObject.get("id").asString()); + BoxCollaboration.Info info = collaboration.new Info(entryObject); + collaborations.add(info); + } + + return collaborations; + } + } + + @Override + public BoxFolder.Info getInfo(String... fields) { + URL url = FOLDER_INFO_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + if (fields.length > 0) { + String queryString = new QueryStringBuilder().appendParam("fields", fields).toString(); + url = + FOLDER_INFO_URL_TEMPLATE.buildWithQuery( + this.getAPI().getBaseURL(), queryString, this.getID()); + } + + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); + try (BoxJSONResponse response = request.send()) { + return new Info(response.getJSON()); + } + } + + /** + * Updates the information about this folder with any info fields that have been modified locally. + * + * @param info the updated info. + */ + public void updateInfo(BoxFolder.Info info) { + URL url = FOLDER_INFO_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); + request.setBody(info.getPendingChanges()); + try (BoxJSONResponse response = request.send()) { + JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); + info.update(jsonObject); + } + } + + @Override + public BoxFolder.Info copy(BoxFolder destination) { + return this.copy(destination, null); + } + + @Override + public BoxFolder.Info copy(BoxFolder destination, String newName) { + URL url = COPY_FOLDER_URL.build(this.getAPI().getBaseURL(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); + + JsonObject parent = new JsonObject(); + parent.add("id", destination.getID()); + + JsonObject copyInfo = new JsonObject(); + copyInfo.add("parent", parent); + if (newName != null) { + copyInfo.add("name", newName); + } + + request.setBody(copyInfo.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + BoxFolder copiedFolder = new BoxFolder(this.getAPI(), responseJSON.get("id").asString()); + return copiedFolder.new Info(responseJSON); + } + } + + /** + * Creates a new child folder inside this folder. + * + * @param name the new folder's name. + * @return the created folder's info. + */ + public BoxFolder.Info createFolder(String name) { + JsonObject parent = new JsonObject(); + parent.add("id", this.getID()); + + JsonObject newFolder = new JsonObject(); + newFolder.add("name", name); + newFolder.add("parent", parent); + + BoxJSONRequest request = + new BoxJSONRequest( + this.getAPI(), CREATE_FOLDER_URL.build(this.getAPI().getBaseURL()), "POST"); + request.setBody(newFolder.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + + BoxFolder createdFolder = new BoxFolder(this.getAPI(), responseJSON.get("id").asString()); + return createdFolder.new Info(responseJSON); + } + } + + /** + * Deletes this folder, optionally recursively deleting all of its contents. + * + * @param recursive true to recursively delete this folder's contents; otherwise false. + */ + public void delete(boolean recursive) { + URL url = DELETE_FOLDER_URL.buildAlpha(this.getAPI().getBaseURL(), this.getID(), recursive); + BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); + request.send().close(); + } + + @Override + public BoxItem.Info move(BoxFolder destination) { + return this.move(destination, null); + } + + @Override + public BoxItem.Info move(BoxFolder destination, String newName) { + URL url = FOLDER_INFO_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); + + JsonObject parent = new JsonObject(); + parent.add("id", destination.getID()); + + JsonObject updateInfo = new JsonObject(); + updateInfo.add("parent", parent); + if (newName != null) { + updateInfo.add("name", newName); + } + + request.setBody(updateInfo.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + BoxFolder movedFolder = new BoxFolder(this.getAPI(), responseJSON.get("id").asString()); + return movedFolder.new Info(responseJSON); + } + } + + /** + * Renames this folder. + * + * @param newName the new name of the folder. + */ + public void rename(String newName) { + URL url = FOLDER_INFO_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); + + JsonObject updateInfo = new JsonObject(); + updateInfo.add("name", newName); + + request.setBody(updateInfo.toString()); + try (BoxJSONResponse response = request.send()) { + response.getJSON(); + } + } + + /** + * Checks if the file can be successfully uploaded by using the preflight check. + * + * @param name the name to give the uploaded file. + * @param fileSize the size of the file used for account capacity calculations. + */ + public void canUpload(String name, long fileSize) { + URL url = UPLOAD_FILE_URL.build(this.getAPI().getBaseURL()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "OPTIONS"); + + JsonObject parent = new JsonObject(); + parent.add("id", this.getID()); + + JsonObject preflightInfo = new JsonObject(); + preflightInfo.add("parent", parent); + preflightInfo.add("name", name); + + preflightInfo.add("size", fileSize); + + request.setBody(preflightInfo.toString()); + try (BoxJSONResponse response = request.send()) { + response.getJSON(); + } + } + + /** + * Uploads a new file to this folder. + * + * @param fileContent a stream containing the contents of the file to upload. + * @param name the name to give the uploaded file. + * @return the uploaded file's info. + */ + public BoxFile.Info uploadFile(InputStream fileContent, String name) { + FileUploadParams uploadInfo = new FileUploadParams().setContent(fileContent).setName(name); + return this.uploadFile(uploadInfo); + } + + /** + * Uploads a new file to this folder. + * + * @param callback the callback which allows file content to be written on output stream. + * @param name the name to give the uploaded file. + * @return the uploaded file's info. + */ + public BoxFile.Info uploadFile(UploadFileCallback callback, String name) { + FileUploadParams uploadInfo = + new FileUploadParams().setUploadFileCallback(callback).setName(name); + return this.uploadFile(uploadInfo); + } + + /** + * Uploads a new file to this folder while reporting the progress to a ProgressListener. + * + * @param fileContent a stream containing the contents of the file to upload. + * @param name the name to give the uploaded file. + * @param fileSize the size of the file used for determining the progress of the upload. + * @param listener a listener for monitoring the upload's progress. + * @return the uploaded file's info. + */ + public BoxFile.Info uploadFile( + InputStream fileContent, String name, long fileSize, ProgressListener listener) { + FileUploadParams uploadInfo = + new FileUploadParams() + .setContent(fileContent) + .setName(name) + .setSize(fileSize) + .setProgressListener(listener); + return this.uploadFile(uploadInfo); + } + + /** + * Uploads a new file to this folder with a specified file description. + * + * @param fileContent a stream containing the contents of the file to upload. + * @param name the name to give the uploaded file. + * @param description the description to give the uploaded file. + * @return the uploaded file's info. + */ + public BoxFile.Info uploadFile(InputStream fileContent, String name, String description) { + FileUploadParams uploadInfo = + new FileUploadParams().setContent(fileContent).setName(name).setDescription(description); + return this.uploadFile(uploadInfo); + } + + /** + * Uploads a new file to this folder with custom upload parameters. + * + * @param uploadParams the custom upload parameters. + * @return the uploaded file's info. + */ + public BoxFile.Info uploadFile(FileUploadParams uploadParams) { + URL uploadURL = UPLOAD_FILE_URL.build(this.getAPI().getBaseUploadURL()); + BoxMultipartRequest request = new BoxMultipartRequest(getAPI(), uploadURL); + + JsonObject fieldJSON = new JsonObject(); + JsonObject parentIdJSON = new JsonObject(); + parentIdJSON.add("id", getID()); + fieldJSON.add("name", uploadParams.getName()); + fieldJSON.add("parent", parentIdJSON); + + if (uploadParams.getCreated() != null) { + fieldJSON.add("content_created_at", BoxDateFormat.format(uploadParams.getCreated())); + } + + if (uploadParams.getModified() != null) { + fieldJSON.add("content_modified_at", BoxDateFormat.format(uploadParams.getModified())); + } + + if (uploadParams.getSHA1() != null && !uploadParams.getSHA1().isEmpty()) { + request.setContentSHA1(uploadParams.getSHA1()); + } + + if (uploadParams.getDescription() != null) { + fieldJSON.add("description", uploadParams.getDescription()); + } + + request.putField("attributes", fieldJSON.toString()); + + if (uploadParams.getSize() > 0) { + request.setFile(uploadParams.getContent(), uploadParams.getName(), uploadParams.getSize()); + } else if (uploadParams.getContent() != null) { + request.setFile(uploadParams.getContent(), uploadParams.getName()); + } else { + request.setUploadFileCallback(uploadParams.getUploadFileCallback(), uploadParams.getName()); + } + + BoxJSONResponse response = null; + try { + if (uploadParams.getProgressListener() == null) { + // upload files sends multipart request but response is JSON + response = (BoxJSONResponse) request.send(); + } else { + // upload files sends multipart request but response is JSON + response = (BoxJSONResponse) request.send(uploadParams.getProgressListener()); + } + JsonObject collection = Json.parse(response.getJSON()).asObject(); + JsonArray entries = collection.get("entries").asArray(); + JsonObject fileInfoJSON = entries.get(0).asObject(); + String uploadedFileID = fileInfoJSON.get("id").asString(); + + BoxFile uploadedFile = new BoxFile(getAPI(), uploadedFileID); + return uploadedFile.new Info(fileInfoJSON); + } finally { + Optional.ofNullable(response).ifPresent(BoxAPIResponse::close); + } + } + + /** + * Uploads a new weblink to this folder. + * + * @param linkURL the URL the weblink points to. + * @return the uploaded weblink's info. + */ + public BoxWebLink.Info createWebLink(URL linkURL) { + return this.createWebLink(null, linkURL, null); + } + + /** + * Uploads a new weblink to this folder. + * + * @param name the filename for the weblink. + * @param linkURL the URL the weblink points to. + * @return the uploaded weblink's info. + */ + public BoxWebLink.Info createWebLink(String name, URL linkURL) { + return this.createWebLink(name, linkURL, null); + } + + /** + * Uploads a new weblink to this folder. + * + * @param linkURL the URL the weblink points to. + * @param description the weblink's description. + * @return the uploaded weblink's info. + */ + public BoxWebLink.Info createWebLink(URL linkURL, String description) { + return this.createWebLink(null, linkURL, description); + } + + /** + * Uploads a new weblink to this folder. + * + * @param name the filename for the weblink. + * @param linkURL the URL the weblink points to. + * @param description the weblink's description. + * @return the uploaded weblink's info. + */ + public BoxWebLink.Info createWebLink(String name, URL linkURL, String description) { + JsonObject parent = new JsonObject(); + parent.add("id", this.getID()); + + JsonObject newWebLink = new JsonObject(); + newWebLink.add("name", name); + newWebLink.add("parent", parent); + newWebLink.add("url", linkURL.toString()); + + if (description != null) { + newWebLink.add("description", description); + } + + BoxJSONRequest request = + new BoxJSONRequest( + this.getAPI(), CREATE_WEB_LINK_URL.build(this.getAPI().getBaseURL()), "POST"); + request.setBody(newWebLink.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + + BoxWebLink createdWebLink = new BoxWebLink(this.getAPI(), responseJSON.get("id").asString()); + return createdWebLink.new Info(responseJSON); + } + } + + /** + * Returns an iterable containing the items in this folder. Iterating over the iterable returned + * by this method is equivalent to iterating over this BoxFolder directly. + * + * @return an iterable containing the items in this folder. + */ + public Iterable getChildren() { + return this; + } + + /** + * Returns an iterable containing the items in this folder and specifies which child fields to + * retrieve from the API. + * + * @param fields the fields to retrieve. + * @return an iterable containing the items in this folder. + */ + public Iterable getChildren(final String... fields) { + return () -> { + String queryString = new QueryStringBuilder().appendParam("fields", fields).toString(); + URL url = GET_ITEMS_URL.buildWithQuery(getAPI().getBaseURL(), queryString, getID()); + return new BoxItemIterator(getAPI(), url, marker(DEFAULT_LIMIT)); }; - /** - * Create Folder URL Template. - */ - public static final URLTemplate CREATE_FOLDER_URL = new URLTemplate("folders"); - /** - * Create Web Link URL Template. - */ - public static final URLTemplate CREATE_WEB_LINK_URL = new URLTemplate("web_links"); - /** - * Copy Folder URL Template. - */ - public static final URLTemplate COPY_FOLDER_URL = new URLTemplate("folders/%s/copy"); - /** - * Delete Folder URL Template. - */ - public static final URLTemplate DELETE_FOLDER_URL = new URLTemplate("folders/%s?recursive=%b"); - /** - * Folder Info URL Template. - */ - public static final URLTemplate FOLDER_INFO_URL_TEMPLATE = new URLTemplate("folders/%s"); - /** - * Upload File URL Template. - */ - public static final URLTemplate UPLOAD_FILE_URL = new URLTemplate("files/content"); - /** - * Add Collaboration URL Template. - */ - public static final URLTemplate ADD_COLLABORATION_URL = new URLTemplate("collaborations"); - /** - * Get Collaborations URL Template. - */ - public static final URLTemplate GET_COLLABORATIONS_URL = new URLTemplate("folders/%s/collaborations"); - /** - * Get Items URL Template. - */ - public static final URLTemplate GET_ITEMS_URL = new URLTemplate("folders/%s/items/"); - /** - * Search URL Template. - */ - public static final URLTemplate SEARCH_URL_TEMPLATE = new URLTemplate("search"); - /** - * Metadata URL Template. - */ - public static final URLTemplate METADATA_URL_TEMPLATE = new URLTemplate("folders/%s/metadata/%s/%s"); - /** - * Upload Session URL Template. - */ - public static final URLTemplate UPLOAD_SESSION_URL_TEMPLATE = new URLTemplate("files/upload_sessions"); - /** - * Folder Locks URL Template. - */ - public static final URLTemplate FOLDER_LOCK_URL_TEMPLATE = new URLTemplate("folder_locks"); - /** - * Describes folder item type. - */ - static final String TYPE = "folder"; - - /** - * Constructs a BoxFolder for a folder with a given ID. - * - * @param api the API connection to be used by the folder. - * @param id the ID of the folder. - */ - public BoxFolder(BoxAPIConnection api, String id) { - super(api, id); - } + } + + /** + * Returns an iterable containing the items in this folder sorted by name and direction. + * + * @param sort the field to sort by, can be set as `name`, `id`, and `date`. + * @param direction the direction to display the item results. + * @param fields the fields to retrieve. + * @return an iterable containing the items in this folder. + */ + public Iterable getChildren( + String sort, SortDirection direction, final String... fields) { + QueryStringBuilder builder = + new QueryStringBuilder() + .appendParam("sort", sort) + .appendParam("direction", direction.toString()); - /** - * Gets the current user's root folder. - * - * @param api the API connection to be used by the folder. - * @return the user's root folder. - */ - public static BoxFolder getRootFolder(BoxAPIConnection api) { - return new BoxFolder(api, "0"); + if (fields.length > 0) { + builder.appendParam("fields", fields); } + final String query = builder.toString(); + return () -> { + URL url = GET_ITEMS_URL.buildWithQuery(getAPI().getBaseURL(), query, getID()); + return new BoxItemIterator(getAPI(), url, offset(0, DEFAULT_LIMIT)); + }; + } + + /** + * Returns an iterable containing the items in this folder sorted by name and direction. + * + * @param sort the field to sort by, can be set as `name`, `id`, and `date`. + * @param direction the direction to display the item results. + * @param offset the index of the first child item to retrieve. + * @param limit the maximum number of children to retrieve after the offset. + * @param fields the fields to retrieve. + * @return an iterable containing the items in this folder. + */ + public Iterable getChildren( + String sort, + SortDirection direction, + final long offset, + final long limit, + final String... fields) { + QueryStringBuilder builder = + new QueryStringBuilder() + .appendParam("sort", sort) + .appendParam("direction", direction.toString()); - /** - * {@inheritDoc} - */ - @Override - protected URL getItemURL() { - return FOLDER_INFO_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + if (fields.length > 0) { + builder.appendParam("fields", fields); } - - /** - * Adds a collaborator to this folder. - * - * @param collaborator the collaborator to add. - * @param role the role of the collaborator. - * @return info about the new collaboration. - */ - public BoxCollaboration.Info collaborate(BoxCollaborator collaborator, BoxCollaboration.Role role) { - JsonObject accessibleByField = new JsonObject(); - accessibleByField.add("id", collaborator.getID()); - - if (collaborator instanceof BoxUser) { - accessibleByField.add("type", "user"); - } else if (collaborator instanceof BoxGroup) { - accessibleByField.add("type", "group"); + final String query = builder.toString(); + return () -> { + URL url = GET_ITEMS_URL.buildWithQuery(getAPI().getBaseURL(), query, getID()); + return new BoxItemIterator(getAPI(), url, limit, offset); + }; + } + + /** + * Retrieves a specific range of child items in this folder. + * + * @param offset the index of the first child item to retrieve. + * @param limit the maximum number of children to retrieve after the offset. + * @param fields the fields to retrieve. + * @return a partial collection containing the specified range of child items. + */ + public PartialCollection getChildrenRange( + long offset, long limit, String... fields) { + QueryStringBuilder builder = + new QueryStringBuilder().appendParam("limit", limit).appendParam("offset", offset); + + if (fields.length > 0) { + builder.appendParam("fields", fields); + } + + URL url = GET_ITEMS_URL.buildWithQuery(getAPI().getBaseURL(), builder.toString(), getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + + String totalCountString = responseJSON.get("total_count").toString(); + long fullSize = Double.valueOf(totalCountString).longValue(); + PartialCollection children = new PartialCollection<>(offset, limit, fullSize); + JsonArray jsonArray = responseJSON.get("entries").asArray(); + for (JsonValue value : jsonArray) { + JsonObject jsonObject = value.asObject(); + BoxItem.Info parsedItemInfo = + (BoxItem.Info) BoxResource.parseInfo(this.getAPI(), jsonObject); + if (parsedItemInfo != null) { + children.add(parsedItemInfo); + } + } + return children; + } + } + + /** + * Returns an iterable containing the items in this folder sorted by name and direction. + * + * @param sortParameters describes sorting parameters. Sort parameters are supported only with + * offset based pagination. Use {@link SortParameters#none()} to ignore sorting. + * @param pagingParameters describes paging parameters. + * @param fields the fields to retrieve. + * @return an iterable containing the items in this folder. + */ + public Iterable getChildren( + final SortParameters sortParameters, + final PagingParameters pagingParameters, + String... fields) { + QueryStringBuilder builder = sortParameters.asQueryStringBuilder(); + validateSortIsSelectedWithOffsetPaginationOnly(pagingParameters, builder); + + if (fields.length > 0) { + builder.appendParam("fields", fields); + } + final String query = builder.toString(); + return () -> { + URL url = GET_ITEMS_URL.buildWithQuery(getAPI().getBaseURL(), query, getID()); + return new BoxItemIterator(getAPI(), url, pagingParameters); + }; + } + + /** + * Returns an iterator over the items in this folder. + * + * @return an iterator over the items in this folder. + */ + @Override + public Iterator iterator() { + URL url = GET_ITEMS_URL.build(this.getAPI().getBaseURL(), BoxFolder.this.getID()); + return new BoxItemIterator(BoxFolder.this.getAPI(), url, marker(DEFAULT_LIMIT)); + } + + /** + * Adds new {@link BoxWebHook} to this {@link BoxFolder}. + * + * @param address {@link BoxWebHook.Info#getAddress()} + * @param triggers {@link BoxWebHook.Info#getTriggers()} + * @return created {@link BoxWebHook.Info} + */ + public BoxWebHook.Info addWebHook(URL address, BoxWebHook.Trigger... triggers) { + return BoxWebHook.create(this, address, triggers); + } + + /** + * Used to retrieve the watermark for the folder. If the folder does not have a watermark applied + * to it, a 404 Not Found will be returned by API. + * + * @param fields the fields to retrieve. + * @return the watermark associated with the folder. + */ + public BoxWatermark getWatermark(String... fields) { + return this.getWatermark(FOLDER_INFO_URL_TEMPLATE, fields); + } + + /** + * Used to apply or update the watermark for the folder. + * + * @return the watermark associated with the folder. + */ + public BoxWatermark applyWatermark() { + return this.applyWatermark(FOLDER_INFO_URL_TEMPLATE, BoxWatermark.WATERMARK_DEFAULT_IMPRINT); + } + + /** + * Removes a watermark from the folder. If the folder did not have a watermark applied to it, a + * 404 Not Found will be returned by API. + */ + public void removeWatermark() { + this.removeWatermark(FOLDER_INFO_URL_TEMPLATE); + } + + /** + * Used to retrieve all metadata associated with the folder. + * + * @param fields the optional fields to retrieve. + * @return An iterable of metadata instances associated with the folder + */ + public Iterable getAllMetadata(String... fields) { + return Metadata.getAllMetadata(this, fields); + } + + @Override + public BoxFolder.Info setCollections(BoxCollection... collections) { + JsonArray jsonArray = new JsonArray(); + for (BoxCollection collection : collections) { + JsonObject collectionJSON = new JsonObject(); + collectionJSON.add("id", collection.getID()); + jsonArray.add(collectionJSON); + } + JsonObject infoJSON = new JsonObject(); + infoJSON.add("collections", jsonArray); + + String queryString = new QueryStringBuilder().appendParam("fields", ALL_FIELDS).toString(); + URL url = + FOLDER_INFO_URL_TEMPLATE.buildWithQuery( + this.getAPI().getBaseURL(), queryString, this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); + request.setBody(infoJSON.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); + return new Info(jsonObject); + } + } + + /** + * Creates global property metadata on this folder. + * + * @param metadata the new metadata values. + * @return the metadata returned from the server. + */ + public Metadata createMetadata(Metadata metadata) { + return this.createMetadata(Metadata.DEFAULT_METADATA_TYPE, metadata); + } + + /** + * Creates metadata on this folder using a specified template. + * + * @param templateName the name of the metadata template. + * @param metadata the new metadata values. + * @return the metadata returned from the server. + */ + public Metadata createMetadata(String templateName, Metadata metadata) { + String scope = Metadata.scopeBasedOnType(templateName); + return this.createMetadata(templateName, scope, metadata); + } + + /** + * Creates metadata on this folder using a specified scope and template. + * + * @param templateName the name of the metadata template. + * @param scope the scope of the template (usually "global" or "enterprise"). + * @param metadata the new metadata values. + * @return the metadata returned from the server. + */ + public Metadata createMetadata(String templateName, String scope, Metadata metadata) { + URL url = + METADATA_URL_TEMPLATE.buildAlpha( + this.getAPI().getBaseURL(), this.getID(), scope, templateName); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); + request.setBody(metadata.toString()); + try (BoxJSONResponse response = request.send()) { + return new Metadata(Json.parse(response.getJSON()).asObject()); + } + } + + /** + * Sets the provided metadata on the folder. If metadata has already been created on this folder, + * it overwrites metadata keys specified in the `metadata` param. + * + * @param templateName the name of the metadata template. + * @param scope the scope of the template (usually "global" or "enterprise"). + * @param metadata the new metadata values. + * @return the metadata returned from the server. + */ + public Metadata setMetadata(String templateName, String scope, Metadata metadata) { + try { + return this.createMetadata(templateName, scope, metadata); + } catch (BoxAPIException e) { + if (e.getResponseCode() == 409) { + if (metadata.getOperations().isEmpty()) { + return getMetadata(); } else { - throw new IllegalArgumentException("The given collaborator is of an unknown type."); - } - - return this.collaborate(accessibleByField, role, null, null, null, null); - } + return updateExistingTemplate(templateName, scope, metadata); + } + } else { + throw e; + } + } + } + + /** + * Throws IllegalArgumentException exception when sorting and marker pagination is selected. + * + * @param pagingParameters paging definition to check + * @param sortQuery builder containing sort query + */ + private void validateSortIsSelectedWithOffsetPaginationOnly( + PagingParameters pagingParameters, QueryStringBuilder sortQuery) { + if (pagingParameters != null + && pagingParameters.isMarkerBasedPaging() + && sortQuery.toString().length() > 0) { + throw new IllegalArgumentException( + "Sorting is not supported when using marker based pagination."); + } + } + + private Metadata updateExistingTemplate(String templateName, String scope, Metadata metadata) { + Metadata metadataToUpdate = new Metadata(scope, templateName); + for (JsonValue value : metadata.getOperations()) { + if (value.asObject().get("value").isNumber()) { + metadataToUpdate.add( + value.asObject().get("path").asString(), value.asObject().get("value").asDouble()); + } else if (value.asObject().get("value").isString()) { + metadataToUpdate.add( + value.asObject().get("path").asString(), value.asObject().get("value").asString()); + } else if (value.asObject().get("value").isArray()) { + ArrayList list = new ArrayList<>(); + for (JsonValue jsonValue : value.asObject().get("value").asArray()) { + list.add(jsonValue.asString()); + } + metadataToUpdate.add(value.asObject().get("path").asString(), list); + } + } + return this.updateMetadata(metadataToUpdate); + } + + /** + * Gets the global properties metadata on this folder. + * + * @return the metadata returned from the server. + */ + public Metadata getMetadata() { + return this.getMetadata(Metadata.DEFAULT_METADATA_TYPE); + } + + /** + * Gets the metadata on this folder associated with a specified template. + * + * @param templateName the metadata template type name. + * @return the metadata returned from the server. + */ + public Metadata getMetadata(String templateName) { + String scope = Metadata.scopeBasedOnType(templateName); + return this.getMetadata(templateName, scope); + } + + /** + * Gets the metadata on this folder associated with a specified scope and template. + * + * @param templateName the metadata template type name. + * @param scope the scope of the template (usually "global" or "enterprise"). + * @return the metadata returned from the server. + */ + public Metadata getMetadata(String templateName, String scope) { + URL url = + METADATA_URL_TEMPLATE.buildAlpha( + this.getAPI().getBaseURL(), this.getID(), scope, templateName); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); + try (BoxJSONResponse response = request.send()) { + return new Metadata(Json.parse(response.getJSON()).asObject()); + } + } + + /** + * Updates the folder metadata. + * + * @param metadata the new metadata values. + * @return the metadata returned from the server. + */ + public Metadata updateMetadata(Metadata metadata) { + URL url = + METADATA_URL_TEMPLATE.buildAlpha( + this.getAPI().getBaseURL(), + this.getID(), + metadata.getScope(), + metadata.getTemplateName()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT", APPLICATION_JSON_PATCH); + request.setBody(metadata.getPatch()); + try (BoxJSONResponse response = request.send()) { + return new Metadata(Json.parse(response.getJSON()).asObject()); + } + } + + /** Deletes the global properties metadata on this folder. */ + public void deleteMetadata() { + this.deleteMetadata(Metadata.DEFAULT_METADATA_TYPE); + } + + /** + * Deletes the metadata on this folder associated with a specified template. + * + * @param templateName the metadata template type name. + */ + public void deleteMetadata(String templateName) { + String scope = Metadata.scopeBasedOnType(templateName); + this.deleteMetadata(templateName, scope); + } + + /** + * Deletes the metadata on this folder associated with a specified scope and template. + * + * @param templateName the metadata template type name. + * @param scope the scope of the template (usually "global" or "enterprise"). + */ + public void deleteMetadata(String templateName, String scope) { + URL url = + METADATA_URL_TEMPLATE.buildAlpha( + this.getAPI().getBaseURL(), this.getID(), scope, templateName); + BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); + request.send().close(); + } + + /** + * Adds a metadata classification to the specified file. + * + * @param classificationType the metadata classification type. + * @return the metadata classification type added to the file. + */ + public String addClassification(String classificationType) { + Metadata metadata = new Metadata().add(Metadata.CLASSIFICATION_KEY, classificationType); + Metadata classification = + this.createMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, "enterprise", metadata); + + return classification.getString(Metadata.CLASSIFICATION_KEY); + } + + /** + * Updates a metadata classification on the specified file. + * + * @param classificationType the metadata classification type. + * @return the new metadata classification type updated on the file. + */ + public String updateClassification(String classificationType) { + Metadata metadata = new Metadata("enterprise", Metadata.CLASSIFICATION_TEMPLATE_KEY); + metadata.replace(Metadata.CLASSIFICATION_KEY, classificationType); + Metadata classification = this.updateMetadata(metadata); + + return classification.getString(Metadata.CLASSIFICATION_KEY); + } + + /** + * Attempts to add classification to a file. If classification already exists then do update. + * + * @param classificationType the metadata classification type. + * @return the metadata classification type on the file. + */ + public String setClassification(String classificationType) { + Metadata metadata = new Metadata().add(Metadata.CLASSIFICATION_KEY, classificationType); + Metadata classification; + + try { + classification = + this.createMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, "enterprise", metadata); + } catch (BoxAPIException e) { + if (e.getResponseCode() == 409) { + metadata = new Metadata("enterprise", Metadata.CLASSIFICATION_TEMPLATE_KEY); + metadata.replace(Metadata.CLASSIFICATION_KEY, classificationType); + classification = this.updateMetadata(metadata); + } else { + throw e; + } + } + + return classification.getString("/Box__Security__Classification__Key"); + } + + /** + * Gets the classification type for the specified file. + * + * @return the metadata classification type on the file. + */ + public String getClassification() { + Metadata metadata = this.getMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY); + return metadata.getString(Metadata.CLASSIFICATION_KEY); + } + + /** Deletes the classification on the file. */ + public void deleteClassification() { + this.deleteMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, "enterprise"); + } + + /** + * Creates an upload session to create a new file in chunks. This will first verify that the file + * can be created and then open a session for uploading pieces of the file. + * + * @param fileName the name of the file to be created + * @param fileSize the size of the file that will be uploaded + * @return the created upload session instance + */ + public BoxFileUploadSession.Info createUploadSession(String fileName, long fileSize) { + + URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); + + JsonObject body = new JsonObject(); + body.add("folder_id", this.getID()); + body.add("file_name", fileName); + body.add("file_size", fileSize); + request.setBody(body.toString()); + + try (BoxJSONResponse response = request.send()) { + JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); + + String sessionId = jsonObject.get("id").asString(); + BoxFileUploadSession session = new BoxFileUploadSession(this.getAPI(), sessionId); + + return session.new Info(jsonObject); + } + } + + /** + * Creates a new file. + * + * @param inputStream the stream instance that contains the data. + * @param fileName the name of the file to be created. + * @param fileSize the size of the file that will be uploaded. + * @return the created file instance. + * @throws InterruptedException when a thread execution is interrupted. + * @throws IOException when reading a stream throws exception. + */ + public BoxFile.Info uploadLargeFile(InputStream inputStream, String fileName, long fileSize) + throws InterruptedException, IOException { + URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL()); + this.canUpload(fileName, fileSize); + return new LargeFileUpload() + .upload(this.getAPI(), this.getID(), inputStream, url, fileName, fileSize); + } + + /** + * Creates a new file. Also sets file attributes. + * + * @param inputStream the stream instance that contains the data. + * @param fileName the name of the file to be created. + * @param fileSize the size of the file that will be uploaded. + * @param fileAttributes file attributes to set + * @return the created file instance. + * @throws InterruptedException when a thread execution is interrupted. + * @throws IOException when reading a stream throws exception. + */ + public BoxFile.Info uploadLargeFile( + InputStream inputStream, String fileName, long fileSize, Map fileAttributes) + throws InterruptedException, IOException { + URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL()); + this.canUpload(fileName, fileSize); + return new LargeFileUpload() + .upload(this.getAPI(), this.getID(), inputStream, url, fileName, fileSize, fileAttributes); + } + + /** + * Creates a new file using specified number of parallel http connections. + * + * @param inputStream the stream instance that contains the data. + * @param fileName the name of the file to be created. + * @param fileSize the size of the file that will be uploaded. + * @param nParallelConnections number of parallel http connections to use + * @param timeOut time to wait before killing the job + * @param unit time unit for the time wait value + * @return the created file instance. + * @throws InterruptedException when a thread execution is interrupted. + * @throws IOException when reading a stream throws exception. + */ + public BoxFile.Info uploadLargeFile( + InputStream inputStream, + String fileName, + long fileSize, + int nParallelConnections, + long timeOut, + TimeUnit unit) + throws InterruptedException, IOException { + URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL()); + this.canUpload(fileName, fileSize); + return new LargeFileUpload(nParallelConnections, timeOut, unit) + .upload(this.getAPI(), this.getID(), inputStream, url, fileName, fileSize); + } + + /** + * Creates a new file using specified number of parallel http connections. Also sets file + * attributes. + * + * @param inputStream the stream instance that contains the data. + * @param fileName the name of the file to be created. + * @param fileSize the size of the file that will be uploaded. + * @param nParallelConnections number of parallel http connections to use + * @param timeOut time to wait before killing the job + * @param unit time unit for the time wait value + * @param fileAttributes file attributes to set + * @return the created file instance. + * @throws InterruptedException when a thread execution is interrupted. + * @throws IOException when reading a stream throws exception. + */ + public BoxFile.Info uploadLargeFile( + InputStream inputStream, + String fileName, + long fileSize, + int nParallelConnections, + long timeOut, + TimeUnit unit, + Map fileAttributes) + throws InterruptedException, IOException { + URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL()); + this.canUpload(fileName, fileSize); + return new LargeFileUpload(nParallelConnections, timeOut, unit) + .upload(this.getAPI(), this.getID(), inputStream, url, fileName, fileSize, fileAttributes); + } + + /** + * Creates a new Metadata Cascade Policy on a folder. + * + * @param scope the scope of the metadata cascade policy. + * @param templateKey the key of the template. + * @return information about the Metadata Cascade Policy. + */ + public BoxMetadataCascadePolicy.Info addMetadataCascadePolicy(String scope, String templateKey) { + + return BoxMetadataCascadePolicy.create(this.getAPI(), this.getID(), scope, templateKey); + } + + /** + * Retrieves all Metadata Cascade Policies on a folder. + * + * @param fields optional fields to retrieve for cascade policies. + * @return the Iterable of Box Metadata Cascade Policies in your enterprise. + */ + public Iterable getMetadataCascadePolicies(String... fields) { + return BoxMetadataCascadePolicy.getAll(this.getAPI(), this.getID(), fields); + } + + /** + * Retrieves all Metadata Cascade Policies on a folder. + * + * @param enterpriseID the ID of the enterprise to retrieve cascade policies for. + * @param limit the number of entries of cascade policies to retrieve. + * @param fields optional fields to retrieve for cascade policies. + * @return the Iterable of Box Metadata Cascade Policies in your enterprise. + */ + public Iterable getMetadataCascadePolicies( + String enterpriseID, int limit, String... fields) { + + return BoxMetadataCascadePolicy.getAll( + this.getAPI(), this.getID(), enterpriseID, limit, fields); + } + + /** + * Lock this folder. + * + * @return a created folder lock object. + */ + public BoxFolderLock.Info lock() { + JsonObject folderObject = new JsonObject(); + folderObject.add("type", "folder"); + folderObject.add("id", this.getID()); + + JsonObject lockedOperations = new JsonObject(); + lockedOperations.add("move", true); + lockedOperations.add("delete", true); + + JsonObject body = new JsonObject(); + body.add("folder", folderObject); + body.add("locked_operations", lockedOperations); + + BoxJSONRequest request = + new BoxJSONRequest( + this.getAPI(), FOLDER_LOCK_URL_TEMPLATE.build(this.getAPI().getBaseURL()), "POST"); + request.setBody(body.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + + BoxFolderLock createdFolderLock = + new BoxFolderLock(this.getAPI(), responseJSON.get("id").asString()); + return createdFolderLock.new Info(responseJSON); + } + } + + /** + * Get the lock on this folder. + * + * @return a folder lock object. + */ + public Iterable getLocks() { + String queryString = new QueryStringBuilder().appendParam("folder_id", this.getID()).toString(); + final BoxAPIConnection api = this.getAPI(); + return new BoxResourceIterable( + api, FOLDER_LOCK_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), queryString), 100) { + @Override + protected BoxFolderLock.Info factory(JsonObject jsonObject) { + BoxFolderLock folderLock = new BoxFolderLock(api, jsonObject.get("id").asString()); + return folderLock.new Info(jsonObject); + } + }; + } - /** - * Adds a collaborator to this folder. An email will be sent to the collaborator if they don't already have a Box - * account. - * - * @param email the email address of the collaborator to add. - * @param role the role of the collaborator. - * @return info about the new collaboration. - */ - public BoxCollaboration.Info collaborate(String email, BoxCollaboration.Role role) { - JsonObject accessibleByField = new JsonObject(); - accessibleByField.add("login", email); - accessibleByField.add("type", "user"); + /** Used to specify what direction to sort and display results. */ + public enum SortDirection { + /** ASC for ascending order. */ + ASC, - return this.collaborate(accessibleByField, role, null, null, null, null); - } + /** DESC for descending order. */ + DESC + } - /** - * Adds a collaborator to this folder. - * - * @param collaborator the collaborator to add. - * @param role the role of the collaborator. - * @param notify the user/group should receive email notification of the collaboration or not. - * @param canViewPath the view path collaboration feature is enabled or not. - * View path collaborations allow the invitee to see the entire ancestral path to the associated - * folder. The user will not gain privileges in any ancestral folder. - * @param expiresAt when the collaboration should expire. - * @param isAccessOnly whether the collaboration is access only or not. - * @return info about the new collaboration. - */ - public BoxCollaboration.Info collaborate(BoxCollaborator collaborator, BoxCollaboration.Role role, - Boolean notify, Boolean canViewPath, - Date expiresAt, Boolean isAccessOnly) { - JsonObject accessibleByField = new JsonObject(); - accessibleByField.add("id", collaborator.getID()); - - if (collaborator instanceof BoxUser) { - accessibleByField.add("type", "user"); - } else if (collaborator instanceof BoxGroup) { - accessibleByField.add("type", "group"); - } else { - throw new IllegalArgumentException("The given collaborator is of an unknown type."); - } + /** Enumerates the possible sync states that a folder can have. */ + public enum SyncState { + /** The folder is synced. */ + SYNCED("synced"), - return this.collaborate(accessibleByField, role, notify, canViewPath, expiresAt, isAccessOnly); - } + /** The folder is not synced. */ + NOT_SYNCED("not_synced"), - /** - * Adds a collaborator to this folder. - * - * @param collaborator the collaborator to add. - * @param role the role of the collaborator. - * @param notify the user/group should receive email notification of the collaboration or not. - * @param canViewPath the view path collaboration feature is enabled or not. - * View path collaborations allow the invitee to see the entire ancestral path to the associated - * folder. The user will not gain privileges in any ancestral folder. - * @return info about the new collaboration. - */ - public BoxCollaboration.Info collaborate(BoxCollaborator collaborator, BoxCollaboration.Role role, - Boolean notify, Boolean canViewPath) { - return this.collaborate(collaborator, role, notify, canViewPath, null, null); - } + /** The folder is partially synced. */ + PARTIALLY_SYNCED("partially_synced"); - /** - * Adds a collaborator to this folder. An email will be sent to the collaborator if they don't already have a Box - * account. - * - * @param email the email address of the collaborator to add. - * @param role the role of the collaborator. - * @param notify the user/group should receive email notification of the collaboration or not. - * @param canViewPath the view path collaboration feature is enabled or not. - * View path collaborations allow the invitee to see the entire ancestral path to the associated - * folder. The user will not gain privileges in any ancestral folder. - * @param expiresAt when the collaboration should expire. - * @param isAccessOnly whether the collaboration is access only or not. - * @return info about the new collaboration. - */ - public BoxCollaboration.Info collaborate(String email, BoxCollaboration.Role role, - Boolean notify, Boolean canViewPath, - Date expiresAt, Boolean isAccessOnly) { - JsonObject accessibleByField = new JsonObject(); - accessibleByField.add("login", email); - accessibleByField.add("type", "user"); + private final String jsonValue; - return this.collaborate(accessibleByField, role, notify, canViewPath, expiresAt, isAccessOnly); + SyncState(String jsonValue) { + this.jsonValue = jsonValue; } - /** - * Adds a collaborator to this folder. An email will be sent to the collaborator if they don't already have a Box - * account. - * - * @param email the email address of the collaborator to add. - * @param role the role of the collaborator. - * @param notify the user/group should receive email notification of the collaboration or not. - * @param canViewPath the view path collaboration feature is enabled or not. - * View path collaborations allow the invitee to see the entire ancestral path to the associated - * folder. The user will not gain privileges in any ancestral folder. - * @return info about the new collaboration. - */ - public BoxCollaboration.Info collaborate(String email, BoxCollaboration.Role role, - Boolean notify, Boolean canViewPath) { - return this.collaborate(email, role, notify, canViewPath, null, null); + static SyncState fromJSONValue(String jsonValue) { + return SyncState.valueOf(jsonValue.toUpperCase(java.util.Locale.ROOT)); } - private BoxCollaboration.Info collaborate(JsonObject accessibleByField, BoxCollaboration.Role role, - Boolean notify, Boolean canViewPath, - Date expiresAt, Boolean isAccessOnly) { - - JsonObject itemField = new JsonObject(); - itemField.add("id", this.getID()); - itemField.add("type", "folder"); - - return BoxCollaboration.create(this.getAPI(), accessibleByField, itemField, role, notify, canViewPath, - expiresAt, isAccessOnly); + String toJSONValue() { + return this.jsonValue; } + } - /** - * Creates a shared link. - * - * @param sharedLinkRequest Shared link to create - * @return Created shared link. - */ - public BoxSharedLink createSharedLink(BoxSharedLinkRequest sharedLinkRequest) { - return createSharedLink(sharedLinkRequest.asSharedLink()); - } - - private BoxSharedLink createSharedLink(BoxSharedLink sharedLink) { - BoxFolder.Info info = new BoxFolder.Info(); - info.setSharedLink(removeCanEditPermissionIfSet(sharedLink)); + /** Enumerates the possible permissions that a user can have on a folder. */ + public enum Permission { + /** The user can download the folder. */ + CAN_DOWNLOAD("can_download"), - this.updateInfo(info); - return info.getSharedLink(); - } + /** The user can upload to the folder. */ + CAN_UPLOAD("can_upload"), - private BoxSharedLink removeCanEditPermissionIfSet(BoxSharedLink sharedLink) { - if (sharedLink.getPermissions() != null && sharedLink.getPermissions().getCanEdit()) { - BoxSharedLink.Permissions permissions = sharedLink.getPermissions(); - sharedLink.setPermissions( - new BoxSharedLink.Permissions(permissions.getCanPreview(), permissions.getCanDownload(), false) - ); - } - return sharedLink; - } - - /** - * Gets information about all of the collaborations for this folder. - * - * @return a collection of information about the collaborations for this folder. - */ - public Collection getCollaborations(String... fields) { - BoxAPIConnection api = this.getAPI(); - QueryStringBuilder queryBuilder = new QueryStringBuilder(); - if (fields.length > 0) { - queryBuilder.appendParam("fields", fields); - } - URL url = GET_COLLABORATIONS_URL.buildWithQuery(api.getBaseURL(), queryBuilder.toString(), this.getID()); + /** The user can rename the folder. */ + CAN_RENAME("can_rename"), + /** The user can delete the folder. */ + CAN_DELETE("can_delete"), - BoxJSONRequest request = new BoxJSONRequest(api, url, "GET"); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + /** The user can share the folder. */ + CAN_SHARE("can_share"), - int entriesCount = responseJSON.get("total_count").asInt(); - Collection collaborations = new ArrayList<>(entriesCount); - JsonArray entries = responseJSON.get("entries").asArray(); - for (JsonValue entry : entries) { - JsonObject entryObject = entry.asObject(); - BoxCollaboration collaboration = new BoxCollaboration(api, entryObject.get("id").asString()); - BoxCollaboration.Info info = collaboration.new Info(entryObject); - collaborations.add(info); - } + /** The user can invite collaborators to the folder. */ + CAN_INVITE_COLLABORATOR("can_invite_collaborator"), - return collaborations; - } - } + /** The user can set the access level for shared links to the folder. */ + CAN_SET_SHARE_ACCESS("can_set_share_access"); - @Override - public BoxFolder.Info getInfo(String... fields) { - URL url = FOLDER_INFO_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - if (fields.length > 0) { - String queryString = new QueryStringBuilder().appendParam("fields", fields).toString(); - url = FOLDER_INFO_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID()); - } + private final String jsonValue; - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); - try (BoxJSONResponse response = request.send()) { - return new Info(response.getJSON()); - } + Permission(String jsonValue) { + this.jsonValue = jsonValue; } - /** - * Updates the information about this folder with any info fields that have been modified locally. - * - * @param info the updated info. - */ - public void updateInfo(BoxFolder.Info info) { - URL url = FOLDER_INFO_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); - request.setBody(info.getPendingChanges()); - try (BoxJSONResponse response = request.send()) { - JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - info.update(jsonObject); - } + static Permission fromJSONValue(String jsonValue) { + return Permission.valueOf(jsonValue.toUpperCase(java.util.Locale.ROOT)); } - @Override - public BoxFolder.Info copy(BoxFolder destination) { - return this.copy(destination, null); + String toJSONValue() { + return this.jsonValue; } + } - @Override - public BoxFolder.Info copy(BoxFolder destination, String newName) { - URL url = COPY_FOLDER_URL.build(this.getAPI().getBaseURL(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); - - JsonObject parent = new JsonObject(); - parent.add("id", destination.getID()); + /** Contains information about a BoxFolder. */ + public class Info extends BoxItem.Info { + private BoxUploadEmail uploadEmail; + private boolean hasCollaborations; + private SyncState syncState; + private EnumSet permissions; + private boolean canNonOwnersInvite; + private boolean isWatermarked; + private boolean isCollaborationRestrictedToEnterprise; + private boolean isExternallyOwned; + private Map> metadataMap; + private List allowedSharedLinkAccessLevels; + private List allowedInviteeRoles; + private BoxClassification classification; - JsonObject copyInfo = new JsonObject(); - copyInfo.add("parent", parent); - if (newName != null) { - copyInfo.add("name", newName); - } + private boolean isAccessibleViaSharedLink; + private boolean canNonOwnersViewCollaborators; - request.setBody(copyInfo.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - BoxFolder copiedFolder = new BoxFolder(this.getAPI(), responseJSON.get("id").asString()); - return copiedFolder.new Info(responseJSON); - } + /** Constructs an empty Info object. */ + public Info() { + super(); } /** - * Creates a new child folder inside this folder. + * Constructs an Info object by parsing information from a JSON string. * - * @param name the new folder's name. - * @return the created folder's info. + * @param json the JSON string to parse. */ - public BoxFolder.Info createFolder(String name) { - JsonObject parent = new JsonObject(); - parent.add("id", this.getID()); - - JsonObject newFolder = new JsonObject(); - newFolder.add("name", name); - newFolder.add("parent", parent); - - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), CREATE_FOLDER_URL.build(this.getAPI().getBaseURL()), - "POST"); - request.setBody(newFolder.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - - BoxFolder createdFolder = new BoxFolder(this.getAPI(), responseJSON.get("id").asString()); - return createdFolder.new Info(responseJSON); - } + public Info(String json) { + super(json); } /** - * Deletes this folder, optionally recursively deleting all of its contents. + * Constructs an Info object using an already parsed JSON object. * - * @param recursive true to recursively delete this folder's contents; otherwise false. + * @param jsonObject the parsed JSON object. */ - public void delete(boolean recursive) { - URL url = DELETE_FOLDER_URL.buildAlpha(this.getAPI().getBaseURL(), this.getID(), recursive); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); - request.send().close(); - } - - @Override - public BoxItem.Info move(BoxFolder destination) { - return this.move(destination, null); - } - - @Override - public BoxItem.Info move(BoxFolder destination, String newName) { - URL url = FOLDER_INFO_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); - - JsonObject parent = new JsonObject(); - parent.add("id", destination.getID()); - - JsonObject updateInfo = new JsonObject(); - updateInfo.add("parent", parent); - if (newName != null) { - updateInfo.add("name", newName); - } - - request.setBody(updateInfo.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - BoxFolder movedFolder = new BoxFolder(this.getAPI(), responseJSON.get("id").asString()); - return movedFolder.new Info(responseJSON); - } + public Info(JsonObject jsonObject) { + super(jsonObject); } /** - * Renames this folder. + * Gets the upload email for the folder. * - * @param newName the new name of the folder. + * @return the upload email for the folder. */ - public void rename(String newName) { - URL url = FOLDER_INFO_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); - - JsonObject updateInfo = new JsonObject(); - updateInfo.add("name", newName); - - request.setBody(updateInfo.toString()); - try (BoxJSONResponse response = request.send()) { - response.getJSON(); - } + public BoxUploadEmail getUploadEmail() { + return this.uploadEmail; } /** - * Checks if the file can be successfully uploaded by using the preflight check. + * Sets the upload email for the folder. * - * @param name the name to give the uploaded file. - * @param fileSize the size of the file used for account capacity calculations. + * @param uploadEmail the upload email for the folder. */ - public void canUpload(String name, long fileSize) { - URL url = UPLOAD_FILE_URL.build(this.getAPI().getBaseURL()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "OPTIONS"); + public void setUploadEmail(BoxUploadEmail uploadEmail) { + if (this.uploadEmail == uploadEmail) { + return; + } - JsonObject parent = new JsonObject(); - parent.add("id", this.getID()); + this.removeChildObject("folder_upload_email"); + this.uploadEmail = uploadEmail; - JsonObject preflightInfo = new JsonObject(); - preflightInfo.add("parent", parent); - preflightInfo.add("name", name); - - preflightInfo.add("size", fileSize); - - request.setBody(preflightInfo.toString()); - try (BoxJSONResponse response = request.send()) { - response.getJSON(); - } + if (uploadEmail == null) { + this.addPendingChange("folder_upload_email", (String) null); + } else { + this.addChildObject("folder_upload_email", uploadEmail); + } } /** - * Uploads a new file to this folder. + * Gets whether or not the folder has any collaborations. * - * @param fileContent a stream containing the contents of the file to upload. - * @param name the name to give the uploaded file. - * @return the uploaded file's info. + * @return true if the folder has collaborations; otherwise false. */ - public BoxFile.Info uploadFile(InputStream fileContent, String name) { - FileUploadParams uploadInfo = new FileUploadParams() - .setContent(fileContent) - .setName(name); - return this.uploadFile(uploadInfo); + public boolean getHasCollaborations() { + return this.hasCollaborations; } /** - * Uploads a new file to this folder. + * Gets the sync state of the folder. * - * @param callback the callback which allows file content to be written on output stream. - * @param name the name to give the uploaded file. - * @return the uploaded file's info. + * @return the sync state of the folder. */ - public BoxFile.Info uploadFile(UploadFileCallback callback, String name) { - FileUploadParams uploadInfo = new FileUploadParams() - .setUploadFileCallback(callback) - .setName(name); - return this.uploadFile(uploadInfo); + public SyncState getSyncState() { + return this.syncState; } /** - * Uploads a new file to this folder while reporting the progress to a ProgressListener. + * Sets the sync state of the folder. * - * @param fileContent a stream containing the contents of the file to upload. - * @param name the name to give the uploaded file. - * @param fileSize the size of the file used for determining the progress of the upload. - * @param listener a listener for monitoring the upload's progress. - * @return the uploaded file's info. + * @param syncState the sync state of the folder. */ - public BoxFile.Info uploadFile(InputStream fileContent, String name, long fileSize, ProgressListener listener) { - FileUploadParams uploadInfo = new FileUploadParams() - .setContent(fileContent) - .setName(name) - .setSize(fileSize) - .setProgressListener(listener); - return this.uploadFile(uploadInfo); + public void setSyncState(SyncState syncState) { + this.syncState = syncState; + this.addPendingChange("sync_state", syncState.toJSONValue()); } /** - * Uploads a new file to this folder with a specified file description. + * Gets the permissions that the current user has on the folder. * - * @param fileContent a stream containing the contents of the file to upload. - * @param name the name to give the uploaded file. - * @param description the description to give the uploaded file. - * @return the uploaded file's info. + * @return the permissions that the current user has on the folder. */ - public BoxFile.Info uploadFile(InputStream fileContent, String name, String description) { - FileUploadParams uploadInfo = new FileUploadParams() - .setContent(fileContent) - .setName(name) - .setDescription(description); - return this.uploadFile(uploadInfo); + public EnumSet getPermissions() { + return this.permissions; } /** - * Uploads a new file to this folder with custom upload parameters. + * Gets whether or not the non-owners can invite collaborators to the folder. * - * @param uploadParams the custom upload parameters. - * @return the uploaded file's info. + * @return [description] */ - public BoxFile.Info uploadFile(FileUploadParams uploadParams) { - URL uploadURL = UPLOAD_FILE_URL.build(this.getAPI().getBaseUploadURL()); - BoxMultipartRequest request = new BoxMultipartRequest(getAPI(), uploadURL); - - JsonObject fieldJSON = new JsonObject(); - JsonObject parentIdJSON = new JsonObject(); - parentIdJSON.add("id", getID()); - fieldJSON.add("name", uploadParams.getName()); - fieldJSON.add("parent", parentIdJSON); - - if (uploadParams.getCreated() != null) { - fieldJSON.add("content_created_at", BoxDateFormat.format(uploadParams.getCreated())); - } - - if (uploadParams.getModified() != null) { - fieldJSON.add("content_modified_at", BoxDateFormat.format(uploadParams.getModified())); - } - - if (uploadParams.getSHA1() != null && !uploadParams.getSHA1().isEmpty()) { - request.setContentSHA1(uploadParams.getSHA1()); - } - - if (uploadParams.getDescription() != null) { - fieldJSON.add("description", uploadParams.getDescription()); - } - - request.putField("attributes", fieldJSON.toString()); - - if (uploadParams.getSize() > 0) { - request.setFile(uploadParams.getContent(), uploadParams.getName(), uploadParams.getSize()); - } else if (uploadParams.getContent() != null) { - request.setFile(uploadParams.getContent(), uploadParams.getName()); - } else { - request.setUploadFileCallback(uploadParams.getUploadFileCallback(), uploadParams.getName()); - } - - BoxJSONResponse response = null; - try { - if (uploadParams.getProgressListener() == null) { - // upload files sends multipart request but response is JSON - response = (BoxJSONResponse) request.send(); - } else { - // upload files sends multipart request but response is JSON - response = (BoxJSONResponse) request.send(uploadParams.getProgressListener()); - } - JsonObject collection = Json.parse(response.getJSON()).asObject(); - JsonArray entries = collection.get("entries").asArray(); - JsonObject fileInfoJSON = entries.get(0).asObject(); - String uploadedFileID = fileInfoJSON.get("id").asString(); - - BoxFile uploadedFile = new BoxFile(getAPI(), uploadedFileID); - return uploadedFile.new Info(fileInfoJSON); - } finally { - Optional.ofNullable(response).ifPresent(BoxAPIResponse::close); - } - } - - /** - * Uploads a new weblink to this folder. - * - * @param linkURL the URL the weblink points to. - * @return the uploaded weblink's info. - */ - public BoxWebLink.Info createWebLink(URL linkURL) { - return this.createWebLink(null, linkURL, - null); + public boolean getCanNonOwnersInvite() { + return this.canNonOwnersInvite; } /** - * Uploads a new weblink to this folder. + * Sets whether or not non-owners can invite collaborators to the folder. * - * @param name the filename for the weblink. - * @param linkURL the URL the weblink points to. - * @return the uploaded weblink's info. + * @param canNonOwnersInvite indicates non-owners can invite collaborators to the folder. */ - public BoxWebLink.Info createWebLink(String name, URL linkURL) { - return this.createWebLink(name, linkURL, - null); - } - - /** - * Uploads a new weblink to this folder. - * - * @param linkURL the URL the weblink points to. - * @param description the weblink's description. - * @return the uploaded weblink's info. - */ - public BoxWebLink.Info createWebLink(URL linkURL, String description) { - return this.createWebLink(null, linkURL, description); - } - - /** - * Uploads a new weblink to this folder. - * - * @param name the filename for the weblink. - * @param linkURL the URL the weblink points to. - * @param description the weblink's description. - * @return the uploaded weblink's info. - */ - public BoxWebLink.Info createWebLink(String name, URL linkURL, String description) { - JsonObject parent = new JsonObject(); - parent.add("id", this.getID()); - - JsonObject newWebLink = new JsonObject(); - newWebLink.add("name", name); - newWebLink.add("parent", parent); - newWebLink.add("url", linkURL.toString()); - - if (description != null) { - newWebLink.add("description", description); - } - - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), - CREATE_WEB_LINK_URL.build(this.getAPI().getBaseURL()), "POST"); - request.setBody(newWebLink.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - - BoxWebLink createdWebLink = new BoxWebLink(this.getAPI(), responseJSON.get("id").asString()); - return createdWebLink.new Info(responseJSON); - } + public void setCanNonOwnersInvite(boolean canNonOwnersInvite) { + this.canNonOwnersInvite = canNonOwnersInvite; + this.addPendingChange("can_non_owners_invite", canNonOwnersInvite); } /** - * Returns an iterable containing the items in this folder. Iterating over the iterable returned by this method is - * equivalent to iterating over this BoxFolder directly. + * Gets whether future collaborations should be restricted to within the enterprise only. * - * @return an iterable containing the items in this folder. + * @return indicates whether collaboration is restricted to enterprise only. */ - public Iterable getChildren() { - return this; + public boolean getIsCollaborationRestrictedToEnterprise() { + return this.isCollaborationRestrictedToEnterprise; } /** - * Returns an iterable containing the items in this folder and specifies which child fields to retrieve from the - * API. + * Sets whether future collaborations should be restricted to within the enterprise only. * - * @param fields the fields to retrieve. - * @return an iterable containing the items in this folder. + * @param isRestricted indicates whether there is collaboration restriction within enterprise. */ - public Iterable getChildren(final String... fields) { - return () -> { - String queryString = new QueryStringBuilder().appendParam("fields", fields).toString(); - URL url = GET_ITEMS_URL.buildWithQuery(getAPI().getBaseURL(), queryString, getID()); - return new BoxItemIterator(getAPI(), url, marker(DEFAULT_LIMIT)); - }; + public void setIsCollaborationRestrictedToEnterprise(boolean isRestricted) { + this.isCollaborationRestrictedToEnterprise = isRestricted; + this.addPendingChange("is_collaboration_restricted_to_enterprise", isRestricted); } /** - * Returns an iterable containing the items in this folder sorted by name and direction. + * Retrieves the allowed roles for collaborations. * - * @param sort the field to sort by, can be set as `name`, `id`, and `date`. - * @param direction the direction to display the item results. - * @param fields the fields to retrieve. - * @return an iterable containing the items in this folder. + * @return the roles allowed for collaboration. */ - public Iterable getChildren(String sort, SortDirection direction, final String... fields) { - QueryStringBuilder builder = new QueryStringBuilder() - .appendParam("sort", sort) - .appendParam("direction", direction.toString()); - - if (fields.length > 0) { - builder.appendParam("fields", fields); - } - final String query = builder.toString(); - return () -> { - URL url = GET_ITEMS_URL.buildWithQuery(getAPI().getBaseURL(), query, getID()); - return new BoxItemIterator(getAPI(), url, offset(0, DEFAULT_LIMIT)); - }; + public List getAllowedInviteeRoles() { + return this.allowedInviteeRoles; } /** - * Returns an iterable containing the items in this folder sorted by name and direction. + * Retrieves the allowed access levels for a shared link. * - * @param sort the field to sort by, can be set as `name`, `id`, and `date`. - * @param direction the direction to display the item results. - * @param offset the index of the first child item to retrieve. - * @param limit the maximum number of children to retrieve after the offset. - * @param fields the fields to retrieve. - * @return an iterable containing the items in this folder. + * @return the allowed access levels for a shared link. */ - public Iterable getChildren(String sort, SortDirection direction, final long offset, final long limit, - final String... fields) { - QueryStringBuilder builder = new QueryStringBuilder() - .appendParam("sort", sort) - .appendParam("direction", direction.toString()); - - if (fields.length > 0) { - builder.appendParam("fields", fields); - } - final String query = builder.toString(); - return () -> { - URL url = GET_ITEMS_URL.buildWithQuery(getAPI().getBaseURL(), query, getID()); - return new BoxItemIterator(getAPI(), url, limit, offset); - }; + public List getAllowedSharedLinkAccessLevels() { + return this.allowedSharedLinkAccessLevels; } /** - * Retrieves a specific range of child items in this folder. + * Gets flag indicating whether this file is Watermarked. * - * @param offset the index of the first child item to retrieve. - * @param limit the maximum number of children to retrieve after the offset. - * @param fields the fields to retrieve. - * @return a partial collection containing the specified range of child items. + * @return whether the file is watermarked or not */ - public PartialCollection getChildrenRange(long offset, long limit, String... fields) { - QueryStringBuilder builder = new QueryStringBuilder() - .appendParam("limit", limit) - .appendParam("offset", offset); - - if (fields.length > 0) { - builder.appendParam("fields", fields); - } - - URL url = GET_ITEMS_URL.buildWithQuery(getAPI().getBaseURL(), builder.toString(), getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - - String totalCountString = responseJSON.get("total_count").toString(); - long fullSize = Double.valueOf(totalCountString).longValue(); - PartialCollection children = new PartialCollection<>(offset, limit, fullSize); - JsonArray jsonArray = responseJSON.get("entries").asArray(); - for (JsonValue value : jsonArray) { - JsonObject jsonObject = value.asObject(); - BoxItem.Info parsedItemInfo = (BoxItem.Info) BoxResource.parseInfo(this.getAPI(), jsonObject); - if (parsedItemInfo != null) { - children.add(parsedItemInfo); - } - } - return children; - } + public boolean getIsWatermarked() { + return this.isWatermarked; } /** - * Returns an iterable containing the items in this folder sorted by name and direction. + * Gets the metadata on this folder associated with a specified scope and template. Makes an + * attempt to get metadata that was retrieved using getInfo(String ...) method. * - * @param sortParameters describes sorting parameters. - * Sort parameters are supported only with offset based pagination. - * Use {@link SortParameters#none()} to ignore sorting. - * @param pagingParameters describes paging parameters. - * @param fields the fields to retrieve. - * @return an iterable containing the items in this folder. + * @param templateName the metadata template type name. + * @param scope the scope of the template (usually "global" or "enterprise"). + * @return the metadata returned from the server. */ - public Iterable getChildren( - final SortParameters sortParameters, final PagingParameters pagingParameters, String... fields - ) { - QueryStringBuilder builder = sortParameters.asQueryStringBuilder(); - validateSortIsSelectedWithOffsetPaginationOnly(pagingParameters, builder); - - if (fields.length > 0) { - builder.appendParam("fields", fields); - } - final String query = builder.toString(); - return () -> { - URL url = GET_ITEMS_URL.buildWithQuery(getAPI().getBaseURL(), query, getID()); - return new BoxItemIterator(getAPI(), url, pagingParameters); - }; + public Metadata getMetadata(String templateName, String scope) { + try { + return this.metadataMap.get(scope).get(templateName); + } catch (NullPointerException e) { + return null; + } } /** - * Returns an iterator over the items in this folder. + * Get the field is_externally_owned determining whether this folder is owned by a user outside + * of the enterprise. * - * @return an iterator over the items in this folder. + * @return a boolean indicating whether this folder is owned by a user outside the enterprise. */ - @Override - public Iterator iterator() { - URL url = GET_ITEMS_URL.build(this.getAPI().getBaseURL(), BoxFolder.this.getID()); - return new BoxItemIterator(BoxFolder.this.getAPI(), url, marker(DEFAULT_LIMIT)); + public boolean getIsExternallyOwned() { + return this.isExternallyOwned; } /** - * Adds new {@link BoxWebHook} to this {@link BoxFolder}. + * Gets the metadata classification type of this folder. * - * @param address {@link BoxWebHook.Info#getAddress()} - * @param triggers {@link BoxWebHook.Info#getTriggers()} - * @return created {@link BoxWebHook.Info} + * @return the metadata classification type of this folder. */ - public BoxWebHook.Info addWebHook(URL address, BoxWebHook.Trigger... triggers) { - return BoxWebHook.create(this, address, triggers); + public BoxClassification getClassification() { + return this.classification; } /** - * Used to retrieve the watermark for the folder. - * If the folder does not have a watermark applied to it, a 404 Not Found will be returned by API. + * Returns the flag indicating whether the folder is accessible via a shared link. * - * @param fields the fields to retrieve. - * @return the watermark associated with the folder. + * @return boolean flag indicating whether the folder is accessible via a shared link. */ - public BoxWatermark getWatermark(String... fields) { - return this.getWatermark(FOLDER_INFO_URL_TEMPLATE, fields); + public boolean getIsAccessibleViaSharedLink() { + return this.isAccessibleViaSharedLink; } /** - * Used to apply or update the watermark for the folder. + * Returns the flag indicating if collaborators who are not owners of this folder are restricted + * from viewing other collaborations on this folder. * - * @return the watermark associated with the folder. - */ - public BoxWatermark applyWatermark() { - return this.applyWatermark(FOLDER_INFO_URL_TEMPLATE, BoxWatermark.WATERMARK_DEFAULT_IMPRINT); - } - - /** - * Removes a watermark from the folder. - * If the folder did not have a watermark applied to it, a 404 Not Found will be returned by API. + * @return boolean flag indicating if collaborators who are not owners of this folder are + * restricted from viewing other collaborations on this folder. */ - public void removeWatermark() { - this.removeWatermark(FOLDER_INFO_URL_TEMPLATE); + public boolean getCanNonOwnersViewCollaborators() { + return this.canNonOwnersViewCollaborators; } /** - * Used to retrieve all metadata associated with the folder. + * Sets whether collaborators who are not owners of this folder are restricted from viewing + * other collaborations on this folder. * - * @param fields the optional fields to retrieve. - * @return An iterable of metadata instances associated with the folder + * @param canNonOwnersViewCollaborators indicates if collaborators who are not owners of this + * folder are restricted from viewing other collaborations on this folderr. */ - public Iterable getAllMetadata(String... fields) { - return Metadata.getAllMetadata(this, fields); + public void setCanNonOwnersViewCollaborators(boolean canNonOwnersViewCollaborators) { + this.canNonOwnersViewCollaborators = canNonOwnersViewCollaborators; + this.addPendingChange("can_non_owners_view_collaborators", canNonOwnersViewCollaborators); } @Override - public BoxFolder.Info setCollections(BoxCollection... collections) { - JsonArray jsonArray = new JsonArray(); - for (BoxCollection collection : collections) { - JsonObject collectionJSON = new JsonObject(); - collectionJSON.add("id", collection.getID()); - jsonArray.add(collectionJSON); - } - JsonObject infoJSON = new JsonObject(); - infoJSON.add("collections", jsonArray); - - String queryString = new QueryStringBuilder().appendParam("fields", ALL_FIELDS).toString(); - URL url = FOLDER_INFO_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); - request.setBody(infoJSON.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - return new Info(jsonObject); - } + public BoxFolder getResource() { + return BoxFolder.this; } - /** - * Creates global property metadata on this folder. - * - * @param metadata the new metadata values. - * @return the metadata returned from the server. - */ - public Metadata createMetadata(Metadata metadata) { - return this.createMetadata(Metadata.DEFAULT_METADATA_TYPE, metadata); - } - - /** - * Creates metadata on this folder using a specified template. - * - * @param templateName the name of the metadata template. - * @param metadata the new metadata values. - * @return the metadata returned from the server. - */ - public Metadata createMetadata(String templateName, Metadata metadata) { - String scope = Metadata.scopeBasedOnType(templateName); - return this.createMetadata(templateName, scope, metadata); - } - - /** - * Creates metadata on this folder using a specified scope and template. - * - * @param templateName the name of the metadata template. - * @param scope the scope of the template (usually "global" or "enterprise"). - * @param metadata the new metadata values. - * @return the metadata returned from the server. - */ - public Metadata createMetadata(String templateName, String scope, Metadata metadata) { - URL url = METADATA_URL_TEMPLATE.buildAlpha(this.getAPI().getBaseURL(), this.getID(), scope, templateName); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); - request.setBody(metadata.toString()); - try (BoxJSONResponse response = request.send()) { - return new Metadata(Json.parse(response.getJSON()).asObject()); - } - } - - /** - * Sets the provided metadata on the folder. If metadata has already been created on this folder, - * it overwrites metadata keys specified in the `metadata` param. - * - * @param templateName the name of the metadata template. - * @param scope the scope of the template (usually "global" or "enterprise"). - * @param metadata the new metadata values. - * @return the metadata returned from the server. - */ - public Metadata setMetadata(String templateName, String scope, Metadata metadata) { - try { - return this.createMetadata(templateName, scope, metadata); - } catch (BoxAPIException e) { - if (e.getResponseCode() == 409) { - if (metadata.getOperations().isEmpty()) { - return getMetadata(); - } else { - return updateExistingTemplate(templateName, scope, metadata); - } + @Override + protected void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + + String memberName = member.getName(); + JsonValue value = member.getValue(); + try { + switch (memberName) { + case "folder_upload_email": + if (this.uploadEmail == null) { + this.uploadEmail = new BoxUploadEmail(value.asObject()); } else { - throw e; - } - } - } - - /** - * Throws IllegalArgumentException exception when sorting and marker pagination is selected. - * - * @param pagingParameters paging definition to check - * @param sortQuery builder containing sort query - */ - private void validateSortIsSelectedWithOffsetPaginationOnly( - PagingParameters pagingParameters, - QueryStringBuilder sortQuery - ) { - if (pagingParameters != null && pagingParameters.isMarkerBasedPaging() && sortQuery.toString().length() > 0) { - throw new IllegalArgumentException("Sorting is not supported when using marker based pagination."); - } - } - - private Metadata updateExistingTemplate(String templateName, String scope, Metadata metadata) { - Metadata metadataToUpdate = new Metadata(scope, templateName); - for (JsonValue value : metadata.getOperations()) { - if (value.asObject().get("value").isNumber()) { - metadataToUpdate.add(value.asObject().get("path").asString(), - value.asObject().get("value").asDouble()); - } else if (value.asObject().get("value").isString()) { - metadataToUpdate.add(value.asObject().get("path").asString(), - value.asObject().get("value").asString()); - } else if (value.asObject().get("value").isArray()) { - ArrayList list = new ArrayList<>(); - for (JsonValue jsonValue : value.asObject().get("value").asArray()) { - list.add(jsonValue.asString()); - } - metadataToUpdate.add(value.asObject().get("path").asString(), list); + this.uploadEmail.update(value.asObject()); } - } - return this.updateMetadata(metadataToUpdate); - } - - /** - * Gets the global properties metadata on this folder. - * - * @return the metadata returned from the server. - */ - public Metadata getMetadata() { - return this.getMetadata(Metadata.DEFAULT_METADATA_TYPE); - } - - /** - * Gets the metadata on this folder associated with a specified template. - * - * @param templateName the metadata template type name. - * @return the metadata returned from the server. - */ - public Metadata getMetadata(String templateName) { - String scope = Metadata.scopeBasedOnType(templateName); - return this.getMetadata(templateName, scope); - } - - /** - * Gets the metadata on this folder associated with a specified scope and template. - * - * @param templateName the metadata template type name. - * @param scope the scope of the template (usually "global" or "enterprise"). - * @return the metadata returned from the server. - */ - public Metadata getMetadata(String templateName, String scope) { - URL url = METADATA_URL_TEMPLATE.buildAlpha(this.getAPI().getBaseURL(), this.getID(), scope, templateName); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); - try (BoxJSONResponse response = request.send()) { - return new Metadata(Json.parse(response.getJSON()).asObject()); - } - } - - /** - * Updates the folder metadata. - * - * @param metadata the new metadata values. - * @return the metadata returned from the server. - */ - public Metadata updateMetadata(Metadata metadata) { - URL url = METADATA_URL_TEMPLATE.buildAlpha(this.getAPI().getBaseURL(), this.getID(), metadata.getScope(), - metadata.getTemplateName()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT", APPLICATION_JSON_PATCH); - request.setBody(metadata.getPatch()); - try (BoxJSONResponse response = request.send()) { - return new Metadata(Json.parse(response.getJSON()).asObject()); - } - } - - /** - * Deletes the global properties metadata on this folder. - */ - public void deleteMetadata() { - this.deleteMetadata(Metadata.DEFAULT_METADATA_TYPE); - } - - /** - * Deletes the metadata on this folder associated with a specified template. - * - * @param templateName the metadata template type name. - */ - public void deleteMetadata(String templateName) { - String scope = Metadata.scopeBasedOnType(templateName); - this.deleteMetadata(templateName, scope); - } - - /** - * Deletes the metadata on this folder associated with a specified scope and template. - * - * @param templateName the metadata template type name. - * @param scope the scope of the template (usually "global" or "enterprise"). - */ - public void deleteMetadata(String templateName, String scope) { - URL url = METADATA_URL_TEMPLATE.buildAlpha(this.getAPI().getBaseURL(), this.getID(), scope, templateName); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); - request.send().close(); - } - - /** - * Adds a metadata classification to the specified file. - * - * @param classificationType the metadata classification type. - * @return the metadata classification type added to the file. - */ - public String addClassification(String classificationType) { - Metadata metadata = new Metadata().add(Metadata.CLASSIFICATION_KEY, classificationType); - Metadata classification = this.createMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, - "enterprise", metadata); - - return classification.getString(Metadata.CLASSIFICATION_KEY); - } - - /** - * Updates a metadata classification on the specified file. - * - * @param classificationType the metadata classification type. - * @return the new metadata classification type updated on the file. - */ - public String updateClassification(String classificationType) { - Metadata metadata = new Metadata("enterprise", Metadata.CLASSIFICATION_TEMPLATE_KEY); - metadata.replace(Metadata.CLASSIFICATION_KEY, classificationType); - Metadata classification = this.updateMetadata(metadata); - - return classification.getString(Metadata.CLASSIFICATION_KEY); - } - - /** - * Attempts to add classification to a file. If classification already exists then do update. - * - * @param classificationType the metadata classification type. - * @return the metadata classification type on the file. - */ - public String setClassification(String classificationType) { - Metadata metadata = new Metadata().add(Metadata.CLASSIFICATION_KEY, classificationType); - Metadata classification; - - try { - classification = this.createMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, "enterprise", metadata); - } catch (BoxAPIException e) { - if (e.getResponseCode() == 409) { - metadata = new Metadata("enterprise", Metadata.CLASSIFICATION_TEMPLATE_KEY); - metadata.replace(Metadata.CLASSIFICATION_KEY, classificationType); - classification = this.updateMetadata(metadata); + break; + case "has_collaborations": + this.hasCollaborations = value.asBoolean(); + break; + case "sync_state": + this.syncState = SyncState.fromJSONValue(value.asString()); + break; + case "permissions": + this.permissions = this.parsePermissions(value.asObject()); + break; + case "can_non_owners_invite": + this.canNonOwnersInvite = value.asBoolean(); + break; + case "allowed_shared_link_access_levels": + this.allowedSharedLinkAccessLevels = this.parseSharedLinkAccessLevels(value.asArray()); + break; + case "allowed_invitee_roles": + this.allowedInviteeRoles = this.parseAllowedInviteeRoles(value.asArray()); + break; + case "is_collaboration_restricted_to_enterprise": + this.isCollaborationRestrictedToEnterprise = value.asBoolean(); + break; + case "is_externally_owned": + this.isExternallyOwned = value.asBoolean(); + break; + case "watermark_info": + this.isWatermarked = value.asObject().get("is_watermarked").asBoolean(); + break; + case "metadata": + this.metadataMap = Parsers.parseAndPopulateMetadataMap(value.asObject()); + break; + case "classification": + if (value.isNull()) { + this.classification = null; } else { - throw e; + this.classification = new BoxClassification(value.asObject()); } + break; + case "is_accessible_via_shared_link": + this.isAccessibleViaSharedLink = value.asBoolean(); + break; + case "can_non_owners_view_collaborators": + this.canNonOwnersViewCollaborators = value.asBoolean(); + break; + default: + break; } - - return classification.getString("/Box__Security__Classification__Key"); + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); + } } - /** - * Gets the classification type for the specified file. - * - * @return the metadata classification type on the file. - */ - public String getClassification() { - Metadata metadata = this.getMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY); - return metadata.getString(Metadata.CLASSIFICATION_KEY); - } - - /** - * Deletes the classification on the file. - */ - public void deleteClassification() { - this.deleteMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, "enterprise"); - } - - /** - * Creates an upload session to create a new file in chunks. - * This will first verify that the file can be created and then open a session for uploading pieces of the file. - * - * @param fileName the name of the file to be created - * @param fileSize the size of the file that will be uploaded - * @return the created upload session instance - */ - public BoxFileUploadSession.Info createUploadSession(String fileName, long fileSize) { - - URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); - - JsonObject body = new JsonObject(); - body.add("folder_id", this.getID()); - body.add("file_name", fileName); - body.add("file_size", fileSize); - request.setBody(body.toString()); - - try (BoxJSONResponse response = request.send()) { - JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - - String sessionId = jsonObject.get("id").asString(); - BoxFileUploadSession session = new BoxFileUploadSession(this.getAPI(), sessionId); - - return session.new Info(jsonObject); + private EnumSet parsePermissions(JsonObject jsonObject) { + EnumSet permissions = EnumSet.noneOf(Permission.class); + for (JsonObject.Member member : jsonObject) { + JsonValue value = member.getValue(); + if (value.isNull() || !value.asBoolean()) { + continue; } - } - - /** - * Creates a new file. - * - * @param inputStream the stream instance that contains the data. - * @param fileName the name of the file to be created. - * @param fileSize the size of the file that will be uploaded. - * @return the created file instance. - * @throws InterruptedException when a thread execution is interrupted. - * @throws IOException when reading a stream throws exception. - */ - public BoxFile.Info uploadLargeFile(InputStream inputStream, String fileName, long fileSize) - throws InterruptedException, IOException { - URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL()); - this.canUpload(fileName, fileSize); - return new LargeFileUpload(). - upload(this.getAPI(), this.getID(), inputStream, url, fileName, fileSize); - } - - /** - * Creates a new file. Also sets file attributes. - * - * @param inputStream the stream instance that contains the data. - * @param fileName the name of the file to be created. - * @param fileSize the size of the file that will be uploaded. - * @param fileAttributes file attributes to set - * @return the created file instance. - * @throws InterruptedException when a thread execution is interrupted. - * @throws IOException when reading a stream throws exception. - */ - public BoxFile.Info uploadLargeFile(InputStream inputStream, String fileName, long fileSize, - Map fileAttributes) - throws InterruptedException, IOException { - URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL()); - this.canUpload(fileName, fileSize); - return new LargeFileUpload(). - upload(this.getAPI(), this.getID(), inputStream, url, fileName, fileSize, fileAttributes); - } - - /** - * Creates a new file using specified number of parallel http connections. - * - * @param inputStream the stream instance that contains the data. - * @param fileName the name of the file to be created. - * @param fileSize the size of the file that will be uploaded. - * @param nParallelConnections number of parallel http connections to use - * @param timeOut time to wait before killing the job - * @param unit time unit for the time wait value - * @return the created file instance. - * @throws InterruptedException when a thread execution is interrupted. - * @throws IOException when reading a stream throws exception. - */ - public BoxFile.Info uploadLargeFile(InputStream inputStream, String fileName, long fileSize, - int nParallelConnections, long timeOut, TimeUnit unit) - throws InterruptedException, IOException { - URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL()); - this.canUpload(fileName, fileSize); - return new LargeFileUpload(nParallelConnections, timeOut, unit). - upload(this.getAPI(), this.getID(), inputStream, url, fileName, fileSize); - } - - /** - * Creates a new file using specified number of parallel http connections. Also sets file attributes. - * - * @param inputStream the stream instance that contains the data. - * @param fileName the name of the file to be created. - * @param fileSize the size of the file that will be uploaded. - * @param nParallelConnections number of parallel http connections to use - * @param timeOut time to wait before killing the job - * @param unit time unit for the time wait value - * @param fileAttributes file attributes to set - * @return the created file instance. - * @throws InterruptedException when a thread execution is interrupted. - * @throws IOException when reading a stream throws exception. - */ - public BoxFile.Info uploadLargeFile(InputStream inputStream, String fileName, long fileSize, - int nParallelConnections, long timeOut, TimeUnit unit, - Map fileAttributes) - throws InterruptedException, IOException { - URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL()); - this.canUpload(fileName, fileSize); - return new LargeFileUpload(nParallelConnections, timeOut, unit). - upload(this.getAPI(), this.getID(), inputStream, url, fileName, fileSize, fileAttributes); - } - /** - * Creates a new Metadata Cascade Policy on a folder. - * - * @param scope the scope of the metadata cascade policy. - * @param templateKey the key of the template. - * @return information about the Metadata Cascade Policy. - */ - public BoxMetadataCascadePolicy.Info addMetadataCascadePolicy(String scope, String templateKey) { - - return BoxMetadataCascadePolicy.create(this.getAPI(), this.getID(), scope, templateKey); - } - - /** - * Retrieves all Metadata Cascade Policies on a folder. - * - * @param fields optional fields to retrieve for cascade policies. - * @return the Iterable of Box Metadata Cascade Policies in your enterprise. - */ - public Iterable getMetadataCascadePolicies(String... fields) { - return BoxMetadataCascadePolicy.getAll(this.getAPI(), this.getID(), fields); - } - - /** - * Retrieves all Metadata Cascade Policies on a folder. - * - * @param enterpriseID the ID of the enterprise to retrieve cascade policies for. - * @param limit the number of entries of cascade policies to retrieve. - * @param fields optional fields to retrieve for cascade policies. - * @return the Iterable of Box Metadata Cascade Policies in your enterprise. - */ - public Iterable getMetadataCascadePolicies(String enterpriseID, - int limit, String... fields) { - - return BoxMetadataCascadePolicy.getAll(this.getAPI(), this.getID(), enterpriseID, limit, fields); - } - - /** - * Lock this folder. - * - * @return a created folder lock object. - */ - public BoxFolderLock.Info lock() { - JsonObject folderObject = new JsonObject(); - folderObject.add("type", "folder"); - folderObject.add("id", this.getID()); - - JsonObject lockedOperations = new JsonObject(); - lockedOperations.add("move", true); - lockedOperations.add("delete", true); - - - JsonObject body = new JsonObject(); - body.add("folder", folderObject); - body.add("locked_operations", lockedOperations); - - BoxJSONRequest request = - new BoxJSONRequest(this.getAPI(), FOLDER_LOCK_URL_TEMPLATE.build(this.getAPI().getBaseURL()), - "POST"); - request.setBody(body.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - - BoxFolderLock createdFolderLock = new BoxFolderLock(this.getAPI(), responseJSON.get("id").asString()); - return createdFolderLock.new Info(responseJSON); - } - } - - /** - * Get the lock on this folder. - * - * @return a folder lock object. - */ - public Iterable getLocks() { - String queryString = new QueryStringBuilder().appendParam("folder_id", this.getID()).toString(); - final BoxAPIConnection api = this.getAPI(); - return new BoxResourceIterable(api, - FOLDER_LOCK_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), queryString), 100) { - @Override - protected BoxFolderLock.Info factory(JsonObject jsonObject) { - BoxFolderLock folderLock = - new BoxFolderLock(api, jsonObject.get("id").asString()); - return folderLock.new Info(jsonObject); - } - }; - } - - /** - * Used to specify what direction to sort and display results. - */ - public enum SortDirection { - /** - * ASC for ascending order. - */ - ASC, - - /** - * DESC for descending order. - */ - DESC - } - - /** - * Enumerates the possible sync states that a folder can have. - */ - public enum SyncState { - /** - * The folder is synced. - */ - SYNCED("synced"), - - /** - * The folder is not synced. - */ - NOT_SYNCED("not_synced"), - - /** - * The folder is partially synced. - */ - PARTIALLY_SYNCED("partially_synced"); - - private final String jsonValue; - - SyncState(String jsonValue) { - this.jsonValue = jsonValue; - } - - static SyncState fromJSONValue(String jsonValue) { - return SyncState.valueOf(jsonValue.toUpperCase(java.util.Locale.ROOT)); + try { + permissions.add(BoxFolder.Permission.fromJSONValue(member.getName())); + } catch (IllegalArgumentException ignored) { + // If the permission is not recognized, we ignore it. } + } - String toJSONValue() { - return this.jsonValue; - } + return permissions; } - /** - * Enumerates the possible permissions that a user can have on a folder. - */ - public enum Permission { - /** - * The user can download the folder. - */ - CAN_DOWNLOAD("can_download"), - - /** - * The user can upload to the folder. - */ - CAN_UPLOAD("can_upload"), - - /** - * The user can rename the folder. - */ - CAN_RENAME("can_rename"), - - /** - * The user can delete the folder. - */ - CAN_DELETE("can_delete"), - - /** - * The user can share the folder. - */ - CAN_SHARE("can_share"), - - /** - * The user can invite collaborators to the folder. - */ - CAN_INVITE_COLLABORATOR("can_invite_collaborator"), - - /** - * The user can set the access level for shared links to the folder. - */ - CAN_SET_SHARE_ACCESS("can_set_share_access"); - - private final String jsonValue; - - Permission(String jsonValue) { - this.jsonValue = jsonValue; - } - - static Permission fromJSONValue(String jsonValue) { - return Permission.valueOf(jsonValue.toUpperCase(java.util.Locale.ROOT)); - } + private List parseSharedLinkAccessLevels(JsonArray jsonArray) { + List accessLevels = new ArrayList<>(jsonArray.size()); + for (JsonValue value : jsonArray) { + accessLevels.add(value.asString()); + } - String toJSONValue() { - return this.jsonValue; - } + return accessLevels; } - /** - * Contains information about a BoxFolder. - */ - public class Info extends BoxItem.Info { - private BoxUploadEmail uploadEmail; - private boolean hasCollaborations; - private SyncState syncState; - private EnumSet permissions; - private boolean canNonOwnersInvite; - private boolean isWatermarked; - private boolean isCollaborationRestrictedToEnterprise; - private boolean isExternallyOwned; - private Map> metadataMap; - private List allowedSharedLinkAccessLevels; - private List allowedInviteeRoles; - private BoxClassification classification; - - private boolean isAccessibleViaSharedLink; - private boolean canNonOwnersViewCollaborators; - - /** - * Constructs an empty Info object. - */ - public Info() { - super(); - } - - /** - * Constructs an Info object by parsing information from a JSON string. - * - * @param json the JSON string to parse. - */ - public Info(String json) { - super(json); - } - - /** - * Constructs an Info object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - public Info(JsonObject jsonObject) { - super(jsonObject); - } - - /** - * Gets the upload email for the folder. - * - * @return the upload email for the folder. - */ - public BoxUploadEmail getUploadEmail() { - return this.uploadEmail; - } - - /** - * Sets the upload email for the folder. - * - * @param uploadEmail the upload email for the folder. - */ - public void setUploadEmail(BoxUploadEmail uploadEmail) { - if (this.uploadEmail == uploadEmail) { - return; - } - - this.removeChildObject("folder_upload_email"); - this.uploadEmail = uploadEmail; - - if (uploadEmail == null) { - this.addPendingChange("folder_upload_email", (String) null); - } else { - this.addChildObject("folder_upload_email", uploadEmail); - } - } - - /** - * Gets whether or not the folder has any collaborations. - * - * @return true if the folder has collaborations; otherwise false. - */ - public boolean getHasCollaborations() { - return this.hasCollaborations; - } - - /** - * Gets the sync state of the folder. - * - * @return the sync state of the folder. - */ - public SyncState getSyncState() { - return this.syncState; - } - - /** - * Sets the sync state of the folder. - * - * @param syncState the sync state of the folder. - */ - public void setSyncState(SyncState syncState) { - this.syncState = syncState; - this.addPendingChange("sync_state", syncState.toJSONValue()); - } - - /** - * Gets the permissions that the current user has on the folder. - * - * @return the permissions that the current user has on the folder. - */ - public EnumSet getPermissions() { - return this.permissions; - } - - /** - * Gets whether or not the non-owners can invite collaborators to the folder. - * - * @return [description] - */ - public boolean getCanNonOwnersInvite() { - return this.canNonOwnersInvite; - } + private List parseAllowedInviteeRoles(JsonArray jsonArray) { + List roles = new ArrayList<>(jsonArray.size()); + for (JsonValue value : jsonArray) { + roles.add(value.asString()); + } - /** - * Sets whether or not non-owners can invite collaborators to the folder. - * - * @param canNonOwnersInvite indicates non-owners can invite collaborators to the folder. - */ - public void setCanNonOwnersInvite(boolean canNonOwnersInvite) { - this.canNonOwnersInvite = canNonOwnersInvite; - this.addPendingChange("can_non_owners_invite", canNonOwnersInvite); - } - - /** - * Gets whether future collaborations should be restricted to within the enterprise only. - * - * @return indicates whether collaboration is restricted to enterprise only. - */ - public boolean getIsCollaborationRestrictedToEnterprise() { - return this.isCollaborationRestrictedToEnterprise; - } - - /** - * Sets whether future collaborations should be restricted to within the enterprise only. - * - * @param isRestricted indicates whether there is collaboration restriction within enterprise. - */ - public void setIsCollaborationRestrictedToEnterprise(boolean isRestricted) { - this.isCollaborationRestrictedToEnterprise = isRestricted; - this.addPendingChange("is_collaboration_restricted_to_enterprise", isRestricted); - } - - /** - * Retrieves the allowed roles for collaborations. - * - * @return the roles allowed for collaboration. - */ - public List getAllowedInviteeRoles() { - return this.allowedInviteeRoles; - } - - /** - * Retrieves the allowed access levels for a shared link. - * - * @return the allowed access levels for a shared link. - */ - public List getAllowedSharedLinkAccessLevels() { - return this.allowedSharedLinkAccessLevels; - } - - /** - * Gets flag indicating whether this file is Watermarked. - * - * @return whether the file is watermarked or not - */ - public boolean getIsWatermarked() { - return this.isWatermarked; - } - - /** - * Gets the metadata on this folder associated with a specified scope and template. - * Makes an attempt to get metadata that was retrieved using getInfo(String ...) method. - * - * @param templateName the metadata template type name. - * @param scope the scope of the template (usually "global" or "enterprise"). - * @return the metadata returned from the server. - */ - public Metadata getMetadata(String templateName, String scope) { - try { - return this.metadataMap.get(scope).get(templateName); - } catch (NullPointerException e) { - return null; - } - } - - /** - * Get the field is_externally_owned determining whether this folder is owned by a user outside of the - * enterprise. - * - * @return a boolean indicating whether this folder is owned by a user outside the enterprise. - */ - public boolean getIsExternallyOwned() { - return this.isExternallyOwned; - } - - /** - * Gets the metadata classification type of this folder. - * - * @return the metadata classification type of this folder. - */ - public BoxClassification getClassification() { - return this.classification; - } - - /** - * Returns the flag indicating whether the folder is accessible via a shared link. - * - * @return boolean flag indicating whether the folder is accessible via a shared link. - */ - public boolean getIsAccessibleViaSharedLink() { - return this.isAccessibleViaSharedLink; - } - - /** - * Returns the flag indicating if collaborators who are not owners of this folder - * are restricted from viewing other collaborations on this folder. - * - * @return boolean flag indicating if collaborators who are not owners of this folder - * are restricted from viewing other collaborations on this folder. - */ - public boolean getCanNonOwnersViewCollaborators() { - return this.canNonOwnersViewCollaborators; - } - - /** - * Sets whether collaborators who are not owners of this folder - * are restricted from viewing other collaborations on this folder. - * - * @param canNonOwnersViewCollaborators indicates if collaborators who are not owners of this folder - * are restricted from viewing other collaborations on this folderr. - */ - public void setCanNonOwnersViewCollaborators(boolean canNonOwnersViewCollaborators) { - this.canNonOwnersViewCollaborators = canNonOwnersViewCollaborators; - this.addPendingChange("can_non_owners_view_collaborators", canNonOwnersViewCollaborators); - } - - - @Override - public BoxFolder getResource() { - return BoxFolder.this; - } - - @Override - protected void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - - String memberName = member.getName(); - JsonValue value = member.getValue(); - try { - switch (memberName) { - case "folder_upload_email": - if (this.uploadEmail == null) { - this.uploadEmail = new BoxUploadEmail(value.asObject()); - } else { - this.uploadEmail.update(value.asObject()); - } - break; - case "has_collaborations": - this.hasCollaborations = value.asBoolean(); - break; - case "sync_state": - this.syncState = SyncState.fromJSONValue(value.asString()); - break; - case "permissions": - this.permissions = this.parsePermissions(value.asObject()); - break; - case "can_non_owners_invite": - this.canNonOwnersInvite = value.asBoolean(); - break; - case "allowed_shared_link_access_levels": - this.allowedSharedLinkAccessLevels = this.parseSharedLinkAccessLevels(value.asArray()); - break; - case "allowed_invitee_roles": - this.allowedInviteeRoles = this.parseAllowedInviteeRoles(value.asArray()); - break; - case "is_collaboration_restricted_to_enterprise": - this.isCollaborationRestrictedToEnterprise = value.asBoolean(); - break; - case "is_externally_owned": - this.isExternallyOwned = value.asBoolean(); - break; - case "watermark_info": - this.isWatermarked = value.asObject().get("is_watermarked").asBoolean(); - break; - case "metadata": - this.metadataMap = Parsers.parseAndPopulateMetadataMap(value.asObject()); - break; - case "classification": - if (value.isNull()) { - this.classification = null; - } else { - this.classification = new BoxClassification(value.asObject()); - } - break; - case "is_accessible_via_shared_link": - this.isAccessibleViaSharedLink = value.asBoolean(); - break; - case "can_non_owners_view_collaborators": - this.canNonOwnersViewCollaborators = value.asBoolean(); - break; - default: - break; - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); - } - } - - private EnumSet parsePermissions(JsonObject jsonObject) { - EnumSet permissions = EnumSet.noneOf(Permission.class); - for (JsonObject.Member member : jsonObject) { - JsonValue value = member.getValue(); - if (value.isNull() || !value.asBoolean()) { - continue; - } - - try { - permissions.add(BoxFolder.Permission.fromJSONValue(member.getName())); - } catch (IllegalArgumentException ignored) { - // If the permission is not recognized, we ignore it. - } - } - - return permissions; - } - - private List parseSharedLinkAccessLevels(JsonArray jsonArray) { - List accessLevels = new ArrayList<>(jsonArray.size()); - for (JsonValue value : jsonArray) { - accessLevels.add(value.asString()); - } - - return accessLevels; - } - - private List parseAllowedInviteeRoles(JsonArray jsonArray) { - List roles = new ArrayList<>(jsonArray.size()); - for (JsonValue value : jsonArray) { - roles.add(value.asString()); - } - - return roles; - } + return roles; } + } } diff --git a/src/main/java/com/box/sdk/BoxFolderLock.java b/src/main/java/com/box/sdk/BoxFolderLock.java index 8900968c6..c49ccbfa4 100644 --- a/src/main/java/com/box/sdk/BoxFolderLock.java +++ b/src/main/java/com/box/sdk/BoxFolderLock.java @@ -10,165 +10,157 @@ /** * Represents a lock on a folder. * - *

Unless otherwise noted, the methods in this class can throw an unchecked {@link BoxAPIException} (unchecked - * meaning that the compiler won't force you to handle it) if an error occurs. If you wish to implement custom error - * handling for errors related to the Box REST API, you should capture this exception explicitly.

+ *

Unless otherwise noted, the methods in this class can throw an unchecked {@link + * BoxAPIException} (unchecked meaning that the compiler won't force you to handle it) if an error + * occurs. If you wish to implement custom error handling for errors related to the Box REST API, + * you should capture this exception explicitly. */ @BoxResourceType("folder_lock") public class BoxFolderLock extends BoxResource { + /** Delete Folder Locks URL Template. */ + public static final URLTemplate DELETE_FOLDER_LOCK_URL_TEMPLATE = + new URLTemplate("folder_locks/%s"); + + /** + * Constructs a BoxFolderLock with a given ID. + * + * @param api the API connection to be used by the folder lock. + * @param id the ID of the folder lock. + */ + public BoxFolderLock(BoxAPIConnection api, String id) { + super(api, id); + } + + /** Delete the lock on this folder. */ + public void delete() { + URL url = DELETE_FOLDER_LOCK_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); + request.send().close(); + } + + /** Contains information about a BoxFolderLock. */ + public class Info extends BoxResource.Info { + private BoxFolder.Info folder; + private BoxUser.Info createdBy; + private Date createdAt; + private String lockType; + private Map lockedOperations; + + /** Constructs an empty Info object. */ + public Info() { + super(); + } + /** - * Delete Folder Locks URL Template. + * Constructs an Info object by parsing information from a JSON string. + * + * @param json the JSON string to parse. */ - public static final URLTemplate DELETE_FOLDER_LOCK_URL_TEMPLATE = new URLTemplate("folder_locks/%s"); + public Info(String json) { + super(json); + } /** - * Constructs a BoxFolderLock with a given ID. + * Constructs an Info object using an already parsed JSON object. * - * @param api the API connection to be used by the folder lock. - * @param id the ID of the folder lock. + * @param jsonObject the parsed JSON object. */ - public BoxFolderLock(BoxAPIConnection api, String id) { - super(api, id); + Info(JsonObject jsonObject) { + super(jsonObject); + } + + @Override + public BoxResource getResource() { + return BoxFolderLock.this; } /** - * Delete the lock on this folder. + * Gets the folder that the lock applies to. + * + * @return The folder that the lock applies to. */ - public void delete() { - URL url = DELETE_FOLDER_LOCK_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); - request.send().close(); + public BoxFolder.Info getFolder() { + return this.folder; } /** - * Contains information about a BoxFolderLock. + * Gets the user or group that created the lock. + * + * @return the user or group that created the lock. */ - public class Info extends BoxResource.Info { - private BoxFolder.Info folder; - private BoxUser.Info createdBy; - private Date createdAt; - private String lockType; - private Map lockedOperations; - - /** - * Constructs an empty Info object. - */ - public Info() { - super(); - } - - /** - * Constructs an Info object by parsing information from a JSON string. - * - * @param json the JSON string to parse. - */ - public Info(String json) { - super(json); - } - - /** - * Constructs an Info object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - Info(JsonObject jsonObject) { - super(jsonObject); - } - - @Override - public BoxResource getResource() { - return BoxFolderLock.this; - } - - /** - * Gets the folder that the lock applies to. - * - * @return The folder that the lock applies to. - */ - public BoxFolder.Info getFolder() { - return this.folder; - } - - /** - * Gets the user or group that created the lock. - * - * @return the user or group that created the lock. - */ - public BoxUser.Info getCreatedBy() { - return this.createdBy; - } + public BoxUser.Info getCreatedBy() { + return this.createdBy; + } - /** - * Gets the date the folder lock object was created. - * - * @return the date the folder lock object was created. - */ - public Date getCreatedAt() { - return this.createdAt; - } + /** + * Gets the date the folder lock object was created. + * + * @return the date the folder lock object was created. + */ + public Date getCreatedAt() { + return this.createdAt; + } - /** - * Gets the lock type, always freeze. - * - * @return the lock type, always freeze. - */ - public String getLockType() { - return this.lockType; - } + /** + * Gets the lock type, always freeze. + * + * @return the lock type, always freeze. + */ + public String getLockType() { + return this.lockType; + } - /** - * Gets the operations that have been locked. - * - * @return the operations that have been locked. - */ - public Map getLockedOperations() { - return this.lockedOperations; - } + /** + * Gets the operations that have been locked. + * + * @return the operations that have been locked. + */ + public Map getLockedOperations() { + return this.lockedOperations; + } - /** - * {@inheritDoc} - */ - @Override - protected void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - - String memberName = member.getName(); - JsonValue value = member.getValue(); - - try { - if (memberName.equals("folder")) { - JsonObject folderJSON = value.asObject(); - String folderID = folderJSON.get("id").asString(); - BoxFolder folder = new BoxFolder(getAPI(), folderID); - this.folder = folder.new Info(folderJSON); - } else if (memberName.equals("created_by")) { - JsonObject userJSON = value.asObject(); - if (this.createdBy == null) { - String userID = userJSON.get("id").asString(); - BoxUser user = new BoxUser(getAPI(), userID); - this.createdBy = user.new Info(userJSON); - } else { - this.createdBy.update(userJSON); - } - } else if (memberName.equals("created_at")) { - this.createdAt = BoxDateFormat.parse(value.asString()); - - } else if (memberName.equals("lock_type")) { - this.lockType = value.asString(); - - } else if (memberName.equals("locked_operations")) { - JsonObject lockedOperationsJSON = value.asObject(); - Map operationsMap = new HashMap<>(); - for (JsonObject.Member operationMember : lockedOperationsJSON) { - String operation = operationMember.getName(); - Boolean operationBoolean = operationMember.getValue().asBoolean(); - operationsMap.put(operation, operationBoolean); - } - this.lockedOperations = operationsMap; - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); - } + /** {@inheritDoc} */ + @Override + protected void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + + String memberName = member.getName(); + JsonValue value = member.getValue(); + + try { + if (memberName.equals("folder")) { + JsonObject folderJSON = value.asObject(); + String folderID = folderJSON.get("id").asString(); + BoxFolder folder = new BoxFolder(getAPI(), folderID); + this.folder = folder.new Info(folderJSON); + } else if (memberName.equals("created_by")) { + JsonObject userJSON = value.asObject(); + if (this.createdBy == null) { + String userID = userJSON.get("id").asString(); + BoxUser user = new BoxUser(getAPI(), userID); + this.createdBy = user.new Info(userJSON); + } else { + this.createdBy.update(userJSON); + } + } else if (memberName.equals("created_at")) { + this.createdAt = BoxDateFormat.parse(value.asString()); + + } else if (memberName.equals("lock_type")) { + this.lockType = value.asString(); + + } else if (memberName.equals("locked_operations")) { + JsonObject lockedOperationsJSON = value.asObject(); + Map operationsMap = new HashMap<>(); + for (JsonObject.Member operationMember : lockedOperationsJSON) { + String operation = operationMember.getName(); + Boolean operationBoolean = operationMember.getValue().asBoolean(); + operationsMap.put(operation, operationBoolean); + } + this.lockedOperations = operationsMap; } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); + } } + } } diff --git a/src/main/java/com/box/sdk/BoxGlobalSettings.java b/src/main/java/com/box/sdk/BoxGlobalSettings.java index 3ddc03346..479b12060 100644 --- a/src/main/java/com/box/sdk/BoxGlobalSettings.java +++ b/src/main/java/com/box/sdk/BoxGlobalSettings.java @@ -1,87 +1,83 @@ package com.box.sdk; -/** - * Global settings to apply to all API requests. - */ +/** Global settings to apply to all API requests. */ public final class BoxGlobalSettings { - private static int connectTimeout = 0; - private static int readTimeout = 0; - private static int maxRetryAttempts = BoxAPIConnection.DEFAULT_MAX_RETRIES; - private static boolean useZstdCompression = true; + private static int connectTimeout = 0; + private static int readTimeout = 0; + private static int maxRetryAttempts = BoxAPIConnection.DEFAULT_MAX_RETRIES; + private static boolean useZstdCompression = true; - private BoxGlobalSettings() { - } + private BoxGlobalSettings() {} - /** - * Returns the current global connect timeout. - * - * @return connect timeout - */ - public static int getConnectTimeout() { - return connectTimeout; - } + /** + * Returns the current global connect timeout. + * + * @return connect timeout + */ + public static int getConnectTimeout() { + return connectTimeout; + } - /** - * Sets the global connect timeout. - * - * @param connectTimeout timeout in milliseconds - */ - public static void setConnectTimeout(int connectTimeout) { - BoxGlobalSettings.connectTimeout = connectTimeout; - } + /** + * Sets the global connect timeout. + * + * @param connectTimeout timeout in milliseconds + */ + public static void setConnectTimeout(int connectTimeout) { + BoxGlobalSettings.connectTimeout = connectTimeout; + } - /** - * Returns the current global read timeout. - * - * @return read timeout - */ - public static int getReadTimeout() { - return readTimeout; - } + /** + * Returns the current global read timeout. + * + * @return read timeout + */ + public static int getReadTimeout() { + return readTimeout; + } - /** - * Sets the global read timeout. - * - * @param readTimeout timeout in milliseconds - */ - public static void setReadTimeout(int readTimeout) { - BoxGlobalSettings.readTimeout = readTimeout; - } + /** + * Sets the global read timeout. + * + * @param readTimeout timeout in milliseconds + */ + public static void setReadTimeout(int readTimeout) { + BoxGlobalSettings.readTimeout = readTimeout; + } + /** + * Returns the global maximum number of times an API request will be retried after an error + * response is received. + * + * @return max number of request attempts + */ + public static int getMaxRetryAttempts() { + return maxRetryAttempts; + } - /** - * Returns the global maximum number of times an API request will be retried after an error response - * is received. - * - * @return max number of request attempts - */ - public static int getMaxRetryAttempts() { - return maxRetryAttempts; - } + /** + * Sets the global maximum number of times an API request will be retried after an error response + * is received. + * + * @param attempts maximum number of request attempts + */ + public static void setMaxRetryAttempts(int attempts) { + BoxGlobalSettings.maxRetryAttempts = attempts; + } - /** - * Sets the global maximum number of times an API request will be retried after an error response - * is received. - * - * @param attempts maximum number of request attempts - */ - public static void setMaxRetryAttempts(int attempts) { - BoxGlobalSettings.maxRetryAttempts = attempts; - } + /* + * Returns the global settings for using Zstd compression. + * @return true if Zstd compression is enabled, false otherwise + */ + public static boolean getUseZstdCompression() { + return useZstdCompression; + } - /* - * Returns the global settings for using Zstd compression. - * @return true if Zstd compression is enabled, false otherwise - */ - public static boolean getUseZstdCompression() { - return useZstdCompression; - } - - /* - * Sets the global settings for using Zstd compression. - * @param useZstdCompression true to enable Zstd compression, false otherwise - */ - public static void setUseZstdCompression(boolean useZstdCompression) { - BoxGlobalSettings.useZstdCompression = useZstdCompression; - } + /* + * Sets the global settings for using Zstd compression. + * @param useZstdCompression true to enable Zstd compression, false otherwise + */ + public static void setUseZstdCompression(boolean useZstdCompression) { + BoxGlobalSettings.useZstdCompression = useZstdCompression; + } } diff --git a/src/main/java/com/box/sdk/BoxGroup.java b/src/main/java/com/box/sdk/BoxGroup.java index 5b38413f4..e034d8480 100644 --- a/src/main/java/com/box/sdk/BoxGroup.java +++ b/src/main/java/com/box/sdk/BoxGroup.java @@ -13,544 +13,533 @@ /** * Represents a set of Box users. * - *

Unless otherwise noted, the methods in this class can throw an unchecked {@link BoxAPIException} (unchecked - * meaning that the compiler won't force you to handle it) if an error occurs. If you wish to implement custom error - * handling for errors related to the Box REST API, you should capture this exception explicitly.

+ *

Unless otherwise noted, the methods in this class can throw an unchecked {@link + * BoxAPIException} (unchecked meaning that the compiler won't force you to handle it) if an error + * occurs. If you wish to implement custom error handling for errors related to the Box REST API, + * you should capture this exception explicitly. */ @BoxResourceType("group") public class BoxGroup extends BoxCollaborator { - /** - * @see #getAllGroups(BoxAPIConnection, String...) - */ - public static final URLTemplate GROUPS_URL_TEMPLATE = new URLTemplate("groups"); + /** @see #getAllGroups(BoxAPIConnection, String...) */ + public static final URLTemplate GROUPS_URL_TEMPLATE = new URLTemplate("groups"); + + /** @see #getInfo(String...) */ + public static final URLTemplate GROUP_URL_TEMPLATE = new URLTemplate("groups/%s"); + + /** @see #getMemberships() */ + public static final URLTemplate MEMBERSHIPS_URL_TEMPLATE = + new URLTemplate("groups/%s/memberships"); + + /** @see #addMembership(BoxUser) */ + public static final URLTemplate ADD_MEMBERSHIP_URL_TEMPLATE = + new URLTemplate("group_memberships"); + + /** @see #getCollaborations() */ + public static final URLTemplate COLLABORATIONS_URL_TEMPLATE = + new URLTemplate("groups/%s/collaborations"); + + /** + * Constructs a BoxGroup for a group with a given ID. + * + * @param api the API connection to be used by the group. + * @param id the ID of the group. + */ + public BoxGroup(BoxAPIConnection api, String id) { + super(api, id); + } + + /** + * Creates a new group with a specified name. + * + * @param api the API connection to be used by the group. + * @param name the name of the new group. + * @return info about the created group. + */ + public static BoxGroup.Info createGroup(BoxAPIConnection api, String name) { + return createGroup(api, name, null, null, null, null, null); + } + + /** + * Creates a new group with a specified name. + * + * @param api the API connection to be used by the group. + * @param name the name of the new group. + * @param provenance the provenance of the new group + * @param externalSyncIdentifier the external_sync_identifier of the new group + * @param description the description of the new group + * @param invitabilityLevel the invitibility_level of the new group + * @param memberViewabilityLevel the member_viewability_level of the new group + * @return info about the created group. + */ + public static BoxGroup.Info createGroup( + BoxAPIConnection api, + String name, + String provenance, + String externalSyncIdentifier, + String description, + String invitabilityLevel, + String memberViewabilityLevel) { + JsonObject requestJSON = new JsonObject(); + requestJSON.add("name", name); + + if (provenance != null) { + requestJSON.add("provenance", provenance); + } + if (externalSyncIdentifier != null) { + requestJSON.add("external_sync_identifier", externalSyncIdentifier); + } + if (description != null) { + requestJSON.add("description", description); + } + if (invitabilityLevel != null) { + requestJSON.add("invitability_level", invitabilityLevel); + } + if (memberViewabilityLevel != null) { + requestJSON.add("member_viewability_level", memberViewabilityLevel); + } - /** - * @see #getInfo(String...) - */ - public static final URLTemplate GROUP_URL_TEMPLATE = new URLTemplate("groups/%s"); + URL url = GROUPS_URL_TEMPLATE.build(api.getBaseURL()); + BoxJSONRequest request = new BoxJSONRequest(api, url, "POST"); + request.setBody(requestJSON.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - /** - * @see #getMemberships() - */ - public static final URLTemplate MEMBERSHIPS_URL_TEMPLATE = new URLTemplate("groups/%s/memberships"); + BoxGroup group = new BoxGroup(api, responseJSON.get("id").asString()); + return group.new Info(responseJSON); + } + } + + /** + * Gets an iterable of all the groups in the enterprise. + * + * @param api the API connection to be used when retrieving the groups. + * @return an iterable containing info about all the groups. + */ + public static Iterable getAllGroups(final BoxAPIConnection api) { + return () -> { + URL url = GROUPS_URL_TEMPLATE.build(api.getBaseURL()); + return new BoxGroupIterator(api, url); + }; + } + + /** + * Gets an iterable of all the groups in the enterprise. + * + * @param api the API connection to be used when retrieving the groups. + * @param fields the fields to retrieve. + * @return an iterable containing info about all the groups. + */ + public static Iterable getAllGroups(final BoxAPIConnection api, String... fields) { + final QueryStringBuilder builder = new QueryStringBuilder(); + if (fields.length > 0) { + builder.appendParam("fields", fields); + } + return () -> { + URL url = GROUPS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString()); + return new BoxGroupIterator(api, url); + }; + } + + /** + * Gets an iterable of all the groups in the enterprise that are starting with the given name + * string. + * + * @param api the API connection to be used when retrieving the groups. + * @param name the name prefix of the groups. If the groups need to searched by full name that has + * spaces, then the parameter string should have been wrapped with "". + * @param fields the fields to retrieve. + * @return an iterable containing info about all the groups. + */ + public static Iterable getAllGroupsByName( + final BoxAPIConnection api, String name, String... fields) { + final QueryStringBuilder builder = new QueryStringBuilder(); + if (name == null || name.trim().isEmpty()) { + throw new BoxAPIException("Searching groups by name requires a non NULL or non empty name"); + } else { + builder.appendParam("filter_term", name); + if (fields != null && fields.length > 0) { + builder.appendParam("fields", fields); + } + } - /** - * @see #addMembership(BoxUser) - */ - public static final URLTemplate ADD_MEMBERSHIP_URL_TEMPLATE = new URLTemplate("group_memberships"); + return () -> { + URL url = GROUPS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString()); + return new BoxGroupIterator(api, url); + }; + } + + /** + * Gets information about this group. + * + * @param fields the fields to retrieve. + * @return info about this group. + */ + public Info getInfo(String... fields) { + URL url = GROUP_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + if (fields.length > 0) { + QueryStringBuilder builder = new QueryStringBuilder().appendParam("fields", fields); + url = + GROUP_URL_TEMPLATE.buildWithQuery( + this.getAPI().getBaseURL(), builder.toString(), this.getID()); + } + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + return new Info(responseJSON); + } + } + + /** + * Gets information about all of the group memberships for this group. Does not support paging. + * + * @return a collection of information about the group memberships for this group. + */ + public Collection getMemberships() { + final BoxAPIConnection api = this.getAPI(); + final String groupID = this.getID(); + + Iterable iter = + () -> { + URL url = MEMBERSHIPS_URL_TEMPLATE.build(api.getBaseURL(), groupID); + return new BoxGroupMembershipIterator(api, url); + }; - /** - * @see #getCollaborations() - */ - public static final URLTemplate COLLABORATIONS_URL_TEMPLATE = new URLTemplate("groups/%s/collaborations"); + // We need to iterate all results because this method must return a Collection. This logic + // should be removed in + // the next major version, and instead return the Iterable directly. + Collection memberships = new ArrayList<>(); + for (BoxGroupMembership.Info membership : iter) { + memberships.add(membership); + } + return memberships; + } + + /** + * Gets information about all of the group memberships for this group as iterable with paging + * support. + * + * @param fields the fields to retrieve. + * @return an iterable with information about the group memberships for this group. + */ + public Iterable getAllMemberships(String... fields) { + final QueryStringBuilder builder = new QueryStringBuilder(); + if (fields.length > 0) { + builder.appendParam("fields", fields); + } + return () -> { + URL url = + MEMBERSHIPS_URL_TEMPLATE.buildWithQuery( + BoxGroup.this.getAPI().getBaseURL(), builder.toString(), BoxGroup.this.getID()); + return new BoxGroupMembershipIterator(BoxGroup.this.getAPI(), url); + }; + } + + /** + * Adds a member to this group with the default role. + * + * @param user the member to be added to this group. + * @return info about the new group membership. + */ + public BoxGroupMembership.Info addMembership(BoxUser user) { + return this.addMembership(user, null, null); + } + + /** + * Adds a member to this group with the specified role. + * + * @param user the member to be added to this group. + * @param role the role of the user in this group. Can be null to assign the default role. + * @return info about the new group membership. + */ + public BoxGroupMembership.Info addMembership(BoxUser user, BoxGroupMembership.GroupRole role) { + return this.addMembership(user, role, null); + } + + /** + * Adds a member to this group with the specified role. + * + * @param user the member to be added to this group. + * @param role the role of the user in this group. Can be null to assign the default role. + * @param configurablePermissions the configurable permission of the user as a group admin. Can be + * null to give all group admin permissions. + * @return info about the new group membership. + */ + public BoxGroupMembership.Info addMembership( + BoxUser user, + BoxGroupMembership.GroupRole role, + Map configurablePermissions) { + BoxAPIConnection api = this.getAPI(); + + JsonObject requestJSON = new JsonObject(); + requestJSON.add("user", new JsonObject().add("id", user.getID())); + requestJSON.add("group", new JsonObject().add("id", this.getID())); + if (role != null) { + requestJSON.add("role", role.toJSONString()); + } - /** - * Constructs a BoxGroup for a group with a given ID. - * - * @param api the API connection to be used by the group. - * @param id the ID of the group. - */ - public BoxGroup(BoxAPIConnection api, String id) { - super(api, id); + if (configurablePermissions != null) { + JsonObject configurablePermissionJson = new JsonObject(); + for (Permission attrKey : configurablePermissions.keySet()) { + configurablePermissionJson.set(attrKey.toJSONValue(), configurablePermissions.get(attrKey)); + } + requestJSON.add("configurable_permissions", configurablePermissionJson); } - /** - * Creates a new group with a specified name. - * - * @param api the API connection to be used by the group. - * @param name the name of the new group. - * @return info about the created group. - */ - public static BoxGroup.Info createGroup(BoxAPIConnection api, String name) { - return createGroup(api, name, null, null, null, null, null); + URL url = ADD_MEMBERSHIP_URL_TEMPLATE.build(api.getBaseURL()); + BoxJSONRequest request = new BoxJSONRequest(api, url, "POST"); + request.setBody(requestJSON.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + + BoxGroupMembership membership = + new BoxGroupMembership(api, responseJSON.get("id").asString()); + return membership.new Info(responseJSON); + } + } + + /** + * Gets information about all of the collaborations for this group. + * + * @return a collection of information about the collaborations for this group. + */ + public Collection getCollaborations() { + BoxAPIConnection api = this.getAPI(); + URL url = COLLABORATIONS_URL_TEMPLATE.build(api.getBaseURL(), this.getID()); + + BoxJSONRequest request = new BoxJSONRequest(api, url, "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + + int entriesCount = responseJSON.get("total_count").asInt(); + Collection collaborations = new ArrayList<>(entriesCount); + JsonArray entries = responseJSON.get("entries").asArray(); + for (JsonValue entry : entries) { + JsonObject entryObject = entry.asObject(); + BoxCollaboration collaboration = + new BoxCollaboration(api, entryObject.get("id").asString()); + BoxCollaboration.Info info = collaboration.new Info(entryObject); + collaborations.add(info); + } + + return collaborations; + } + } + + /** + * Gets information about all of the collaborations for this group. + * + * @param fields the optional fields to retrieve. + * @return An iterable of BoxCollaboration.Info instances associated with the item. + */ + public Iterable getAllCollaborations(String... fields) { + final BoxAPIConnection api = this.getAPI(); + final QueryStringBuilder builder = new QueryStringBuilder(); + if (fields.length > 0) { + builder.appendParam("fields", fields); + } + return () -> { + URL url = + COLLABORATIONS_URL_TEMPLATE.buildWithQuery( + api.getBaseURL(), builder.toString(), BoxGroup.this.getID()); + return new BoxCollaborationIterator(api, url); + }; + } + + /** Deletes this group. */ + public void delete() { + URL url = GROUP_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); + request.send().close(); + } + + /** + * Updates the information about this group with any info fields that have been modified locally. + * + * @param info the updated info. + */ + public void updateInfo(BoxGroup.Info info) { + URL url = GROUP_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); + request.setBody(info.getPendingChanges()); + try (BoxJSONResponse response = request.send()) { + JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); + info.update(jsonObject); } + } - /** - * Creates a new group with a specified name. - * - * @param api the API connection to be used by the group. - * @param name the name of the new group. - * @param provenance the provenance of the new group - * @param externalSyncIdentifier the external_sync_identifier of the new group - * @param description the description of the new group - * @param invitabilityLevel the invitibility_level of the new group - * @param memberViewabilityLevel the member_viewability_level of the new group - * @return info about the created group. - */ - public static BoxGroup.Info createGroup(BoxAPIConnection api, String name, String provenance, - String externalSyncIdentifier, String description, - String invitabilityLevel, String memberViewabilityLevel) { - JsonObject requestJSON = new JsonObject(); - requestJSON.add("name", name); - - if (provenance != null) { - requestJSON.add("provenance", provenance); - } - if (externalSyncIdentifier != null) { - requestJSON.add("external_sync_identifier", externalSyncIdentifier); - } - if (description != null) { - requestJSON.add("description", description); - } - if (invitabilityLevel != null) { - requestJSON.add("invitability_level", invitabilityLevel); - } - if (memberViewabilityLevel != null) { - requestJSON.add("member_viewability_level", memberViewabilityLevel); - } + /** Contains information about a BoxGroup. */ + public class Info extends BoxCollaborator.Info { - URL url = GROUPS_URL_TEMPLATE.build(api.getBaseURL()); - BoxJSONRequest request = new BoxJSONRequest(api, url, "POST"); - request.setBody(requestJSON.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + /** @see #getProvenance() */ + private String provenance; - BoxGroup group = new BoxGroup(api, responseJSON.get("id").asString()); - return group.new Info(responseJSON); - } - } + /** @see #getExternalSyncIdentifier() */ + private String externalSyncIdentifier; - /** - * Gets an iterable of all the groups in the enterprise. - * - * @param api the API connection to be used when retrieving the groups. - * @return an iterable containing info about all the groups. - */ - public static Iterable getAllGroups(final BoxAPIConnection api) { - return () -> { - URL url = GROUPS_URL_TEMPLATE.build(api.getBaseURL()); - return new BoxGroupIterator(api, url); - }; + /** @see #getDescription() */ + private String description; + + /** @see #getInvitabilityLevel() */ + private String invitabilityLevel; + + /** @see #getMemberViewabilityLevel() */ + private String memberViewabilityLevel; + + /** Constructs an empty Info object. */ + public Info() { + super(); } /** - * Gets an iterable of all the groups in the enterprise. + * Constructs an Info object by parsing information from a JSON string. * - * @param api the API connection to be used when retrieving the groups. - * @param fields the fields to retrieve. - * @return an iterable containing info about all the groups. + * @param json the JSON string to parse. */ - public static Iterable getAllGroups(final BoxAPIConnection api, String... fields) { - final QueryStringBuilder builder = new QueryStringBuilder(); - if (fields.length > 0) { - builder.appendParam("fields", fields); - } - return () -> { - URL url = GROUPS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString()); - return new BoxGroupIterator(api, url); - }; + public Info(String json) { + super(json); } /** - * Gets an iterable of all the groups in the enterprise that are starting with the given name string. + * Constructs an Info object using an already parsed JSON object. * - * @param api the API connection to be used when retrieving the groups. - * @param name the name prefix of the groups. If the groups need to searched by full name that has spaces, - * then the parameter string should have been wrapped with "". - * @param fields the fields to retrieve. - * @return an iterable containing info about all the groups. + * @param jsonObject the parsed JSON object. */ - public static Iterable getAllGroupsByName( - final BoxAPIConnection api, String name, String... fields - ) { - final QueryStringBuilder builder = new QueryStringBuilder(); - if (name == null || name.trim().isEmpty()) { - throw new BoxAPIException("Searching groups by name requires a non NULL or non empty name"); - } else { - builder.appendParam("filter_term", name); - if (fields != null && fields.length > 0) { - builder.appendParam("fields", fields); - } - } + Info(JsonObject jsonObject) { + super(jsonObject); + } - return () -> { - URL url = GROUPS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString()); - return new BoxGroupIterator(api, url); - }; + /** {@inheritDoc} */ + @Override + public BoxGroup getResource() { + return BoxGroup.this; } - /** - * Gets information about this group. - * - * @param fields the fields to retrieve. - * @return info about this group. - */ - public Info getInfo(String... fields) { - URL url = GROUP_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - if (fields.length > 0) { - QueryStringBuilder builder = new QueryStringBuilder().appendParam("fields", fields); - url = GROUP_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), builder.toString(), this.getID()); - } - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - return new Info(responseJSON); - } + /** {@inheritDoc} */ + @Override + protected void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + + String memberName = member.getName(); + JsonValue value = member.getValue(); + try { + switch (memberName) { + case "description": + this.description = value.asString(); + break; + case "external_sync_identifier": + this.externalSyncIdentifier = value.asString(); + break; + case "invitability_level": + this.invitabilityLevel = value.asString(); + break; + case "member_viewability_level": + this.memberViewabilityLevel = value.asString(); + break; + case "provenance": + this.provenance = value.asString(); + break; + default: + break; + } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); + } } /** - * Gets information about all of the group memberships for this group. - * Does not support paging. + * Gets the description for the group. * - * @return a collection of information about the group memberships for this group. + * @return the description for the group. */ - public Collection getMemberships() { - final BoxAPIConnection api = this.getAPI(); - final String groupID = this.getID(); - - Iterable iter = () -> { - URL url = MEMBERSHIPS_URL_TEMPLATE.build(api.getBaseURL(), groupID); - return new BoxGroupMembershipIterator(api, url); - }; - - // We need to iterate all results because this method must return a Collection. This logic should be removed in - // the next major version, and instead return the Iterable directly. - Collection memberships = new ArrayList<>(); - for (BoxGroupMembership.Info membership : iter) { - memberships.add(membership); - } - return memberships; + public String getDescription() { + return this.description; } /** - * Gets information about all of the group memberships for this group as iterable with paging support. + * Sets the description for the group. * - * @param fields the fields to retrieve. - * @return an iterable with information about the group memberships for this group. + * @param description the description for the group. */ - public Iterable getAllMemberships(String... fields) { - final QueryStringBuilder builder = new QueryStringBuilder(); - if (fields.length > 0) { - builder.appendParam("fields", fields); - } - return () -> { - URL url = MEMBERSHIPS_URL_TEMPLATE.buildWithQuery( - BoxGroup.this.getAPI().getBaseURL(), builder.toString(), BoxGroup.this.getID()); - return new BoxGroupMembershipIterator(BoxGroup.this.getAPI(), url); - }; + public void setDescription(String description) { + this.description = description; + addPendingChange("description", description); } /** - * Adds a member to this group with the default role. + * Gets the external_sync_identifier for the group. * - * @param user the member to be added to this group. - * @return info about the new group membership. + * @return the external_sync_identifier for the group. */ - public BoxGroupMembership.Info addMembership(BoxUser user) { - return this.addMembership(user, null, null); + public String getExternalSyncIdentifier() { + return this.externalSyncIdentifier; } /** - * Adds a member to this group with the specified role. + * Sets the external_sync_identifier for the group. * - * @param user the member to be added to this group. - * @param role the role of the user in this group. Can be null to assign the default role. - * @return info about the new group membership. + * @param externalSyncIdentifier the external_sync_identifier for the group. */ - public BoxGroupMembership.Info addMembership(BoxUser user, BoxGroupMembership.GroupRole role) { - return this.addMembership(user, role, null); + public void setExternalSyncIdentifier(String externalSyncIdentifier) { + this.externalSyncIdentifier = externalSyncIdentifier; + addPendingChange("external_sync_identifier", externalSyncIdentifier); } /** - * Adds a member to this group with the specified role. + * Gets the invitability_level for the group. * - * @param user the member to be added to this group. - * @param role the role of the user in this group. Can be null to assign the default role. - * @param configurablePermissions the configurable permission of the user as a group admin. - * Can be null to give all group admin permissions. - * @return info about the new group membership. + * @return the invitability_level for the group. */ - public BoxGroupMembership.Info addMembership(BoxUser user, BoxGroupMembership.GroupRole role, - Map configurablePermissions) { - BoxAPIConnection api = this.getAPI(); - - JsonObject requestJSON = new JsonObject(); - requestJSON.add("user", new JsonObject().add("id", user.getID())); - requestJSON.add("group", new JsonObject().add("id", this.getID())); - if (role != null) { - requestJSON.add("role", role.toJSONString()); - } - - if (configurablePermissions != null) { - JsonObject configurablePermissionJson = new JsonObject(); - for (Permission attrKey : configurablePermissions.keySet()) { - configurablePermissionJson.set(attrKey.toJSONValue(), configurablePermissions.get(attrKey)); - } - requestJSON.add("configurable_permissions", configurablePermissionJson); - } - - URL url = ADD_MEMBERSHIP_URL_TEMPLATE.build(api.getBaseURL()); - BoxJSONRequest request = new BoxJSONRequest(api, url, "POST"); - request.setBody(requestJSON.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - - BoxGroupMembership membership = new BoxGroupMembership(api, responseJSON.get("id").asString()); - return membership.new Info(responseJSON); - } + public String getInvitabilityLevel() { + return this.invitabilityLevel; } /** - * Gets information about all of the collaborations for this group. + * Sets the invitability_level for the group. * - * @return a collection of information about the collaborations for this group. + * @param invitabilityLevel the invitability_level for the group. */ - public Collection getCollaborations() { - BoxAPIConnection api = this.getAPI(); - URL url = COLLABORATIONS_URL_TEMPLATE.build(api.getBaseURL(), this.getID()); - - BoxJSONRequest request = new BoxJSONRequest(api, url, "GET"); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - - int entriesCount = responseJSON.get("total_count").asInt(); - Collection collaborations = new ArrayList<>(entriesCount); - JsonArray entries = responseJSON.get("entries").asArray(); - for (JsonValue entry : entries) { - JsonObject entryObject = entry.asObject(); - BoxCollaboration collaboration = new BoxCollaboration(api, entryObject.get("id").asString()); - BoxCollaboration.Info info = collaboration.new Info(entryObject); - collaborations.add(info); - } - - return collaborations; - } + public void setInvitabilityLevel(String invitabilityLevel) { + this.invitabilityLevel = invitabilityLevel; + addPendingChange("invitability_level", invitabilityLevel); } /** - * Gets information about all of the collaborations for this group. + * Gets the member_viewability_level for the group. * - * @param fields the optional fields to retrieve. - * @return An iterable of BoxCollaboration.Info instances associated with the item. + * @return the member_viewability_level for the group. */ - public Iterable getAllCollaborations(String... fields) { - final BoxAPIConnection api = this.getAPI(); - final QueryStringBuilder builder = new QueryStringBuilder(); - if (fields.length > 0) { - builder.appendParam("fields", fields); - } - return () -> { - URL url = COLLABORATIONS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString(), - BoxGroup.this.getID()); - return new BoxCollaborationIterator(api, url); - }; + public String getMemberViewabilityLevel() { + return this.memberViewabilityLevel; } /** - * Deletes this group. + * Sets the member_viewability_level for the group. + * + * @param memberViewabilityLevel the member_viewability_level for the group. */ - public void delete() { - URL url = GROUP_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); - request.send().close(); + public void setMemberViewabilityLevel(String memberViewabilityLevel) { + this.memberViewabilityLevel = memberViewabilityLevel; + addPendingChange("member_viewability_level", memberViewabilityLevel); } /** - * Updates the information about this group with any info fields that have been modified locally. + * Gets the provenance for the group. * - * @param info the updated info. + * @return the provenance for the group. */ - public void updateInfo(BoxGroup.Info info) { - URL url = GROUP_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); - request.setBody(info.getPendingChanges()); - try (BoxJSONResponse response = request.send()) { - JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - info.update(jsonObject); - } + public String getProvenance() { + return this.provenance; } /** - * Contains information about a BoxGroup. + * Sets the provenance for the group. + * + * @param provenance the provenance for the group. */ - public class Info extends BoxCollaborator.Info { - - /** - * @see #getProvenance() - */ - private String provenance; - - /** - * @see #getExternalSyncIdentifier() - */ - private String externalSyncIdentifier; - - /** - * @see #getDescription() - */ - private String description; - - /** - * @see #getInvitabilityLevel() - */ - private String invitabilityLevel; - - /** - * @see #getMemberViewabilityLevel() - */ - private String memberViewabilityLevel; - - /** - * Constructs an empty Info object. - */ - public Info() { - super(); - } - - /** - * Constructs an Info object by parsing information from a JSON string. - * - * @param json the JSON string to parse. - */ - public Info(String json) { - super(json); - } - - /** - * Constructs an Info object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - Info(JsonObject jsonObject) { - super(jsonObject); - } - - /** - * {@inheritDoc} - */ - @Override - public BoxGroup getResource() { - return BoxGroup.this; - } - - /** - * {@inheritDoc} - */ - @Override - protected void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - - String memberName = member.getName(); - JsonValue value = member.getValue(); - try { - switch (memberName) { - case "description": - this.description = value.asString(); - break; - case "external_sync_identifier": - this.externalSyncIdentifier = value.asString(); - break; - case "invitability_level": - this.invitabilityLevel = value.asString(); - break; - case "member_viewability_level": - this.memberViewabilityLevel = value.asString(); - break; - case "provenance": - this.provenance = value.asString(); - break; - default: - break; - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); - } - } - - /** - * Gets the description for the group. - * - * @return the description for the group. - */ - public String getDescription() { - return this.description; - } - - /** - * Sets the description for the group. - * - * @param description the description for the group. - */ - public void setDescription(String description) { - this.description = description; - addPendingChange("description", description); - } - - /** - * Gets the external_sync_identifier for the group. - * - * @return the external_sync_identifier for the group. - */ - public String getExternalSyncIdentifier() { - return this.externalSyncIdentifier; - } - - /** - * Sets the external_sync_identifier for the group. - * - * @param externalSyncIdentifier the external_sync_identifier for the group. - */ - public void setExternalSyncIdentifier(String externalSyncIdentifier) { - this.externalSyncIdentifier = externalSyncIdentifier; - addPendingChange("external_sync_identifier", externalSyncIdentifier); - } - - /** - * Gets the invitability_level for the group. - * - * @return the invitability_level for the group. - */ - public String getInvitabilityLevel() { - return this.invitabilityLevel; - } - - /** - * Sets the invitability_level for the group. - * - * @param invitabilityLevel the invitability_level for the group. - */ - public void setInvitabilityLevel(String invitabilityLevel) { - this.invitabilityLevel = invitabilityLevel; - addPendingChange("invitability_level", invitabilityLevel); - } - - /** - * Gets the member_viewability_level for the group. - * - * @return the member_viewability_level for the group. - */ - public String getMemberViewabilityLevel() { - return this.memberViewabilityLevel; - } - - /** - * Sets the member_viewability_level for the group. - * - * @param memberViewabilityLevel the member_viewability_level for the group. - */ - public void setMemberViewabilityLevel(String memberViewabilityLevel) { - this.memberViewabilityLevel = memberViewabilityLevel; - addPendingChange("member_viewability_level", memberViewabilityLevel); - } - - /** - * Gets the provenance for the group. - * - * @return the provenance for the group. - */ - public String getProvenance() { - return this.provenance; - } - - /** - * Sets the provenance for the group. - * - * @param provenance the provenance for the group. - */ - public void setProvenance(String provenance) { - this.provenance = provenance; - addPendingChange("provenance", provenance); - } + public void setProvenance(String provenance) { + this.provenance = provenance; + addPendingChange("provenance", provenance); } + } } diff --git a/src/main/java/com/box/sdk/BoxGroupIterator.java b/src/main/java/com/box/sdk/BoxGroupIterator.java index 12be2f595..e5a9e5521 100644 --- a/src/main/java/com/box/sdk/BoxGroupIterator.java +++ b/src/main/java/com/box/sdk/BoxGroupIterator.java @@ -7,29 +7,29 @@ import java.util.Iterator; class BoxGroupIterator implements Iterator { - private static final long LIMIT = 1000; + private static final long LIMIT = 1000; - private final BoxAPIConnection api; - private final JsonIterator jsonIterator; + private final BoxAPIConnection api; + private final JsonIterator jsonIterator; - BoxGroupIterator(BoxAPIConnection api, URL url) { - this.api = api; - this.jsonIterator = new JsonIterator(api, url, offset(0, LIMIT)); - } + BoxGroupIterator(BoxAPIConnection api, URL url) { + this.api = api; + this.jsonIterator = new JsonIterator(api, url, offset(0, LIMIT)); + } - public boolean hasNext() { - return this.jsonIterator.hasNext(); - } + public boolean hasNext() { + return this.jsonIterator.hasNext(); + } - public BoxGroup.Info next() { - JsonObject nextJSONObject = this.jsonIterator.next(); - String id = nextJSONObject.get("id").asString(); + public BoxGroup.Info next() { + JsonObject nextJSONObject = this.jsonIterator.next(); + String id = nextJSONObject.get("id").asString(); - BoxGroup group = new BoxGroup(this.api, id); - return group.new Info(nextJSONObject); - } + BoxGroup group = new BoxGroup(this.api, id); + return group.new Info(nextJSONObject); + } - public void remove() { - throw new UnsupportedOperationException(); - } + public void remove() { + throw new UnsupportedOperationException(); + } } diff --git a/src/main/java/com/box/sdk/BoxGroupMembership.java b/src/main/java/com/box/sdk/BoxGroupMembership.java index 2c598df8a..c66eb627e 100644 --- a/src/main/java/com/box/sdk/BoxGroupMembership.java +++ b/src/main/java/com/box/sdk/BoxGroupMembership.java @@ -11,414 +11,377 @@ /** * Represents a relationship between a user and a group. * - *

Unless otherwise noted, the methods in this class can throw an unchecked {@link BoxAPIException} (unchecked - * meaning that the compiler won't force you to handle it) if an error occurs. If you wish to implement custom error - * handling for errors related to the Box REST API, you should capture this exception explicitly.

+ *

Unless otherwise noted, the methods in this class can throw an unchecked {@link + * BoxAPIException} (unchecked meaning that the compiler won't force you to handle it) if an error + * occurs. If you wish to implement custom error handling for errors related to the Box REST API, + * you should capture this exception explicitly. */ @BoxResourceType("group_membership") public class BoxGroupMembership extends BoxResource { + /** + * The URL template for all group membership requests. + * + * @see #getInfo() + */ + public static final URLTemplate MEMBERSHIP_URL_TEMPLATE = new URLTemplate("group_memberships/%s"); + + /** + * Constructs a BoxGroupMembership for a group membership with a given ID. + * + * @param api the API connection to be used by the group membership. + * @param id the ID of the group membership. + */ + public BoxGroupMembership(BoxAPIConnection api, String id) { + super(api, id); + } + + /** + * Gets information about this group membership. + * + * @return info about this group membership. + */ + public Info getInfo() { + BoxAPIConnection api = this.getAPI(); + URL url = MEMBERSHIP_URL_TEMPLATE.build(api.getBaseURL(), this.getID()); + + BoxJSONRequest request = new BoxJSONRequest(api, url, "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); + return new Info(jsonObject); + } + } + + /** + * Updates the information about this group membership with any info fields that have been + * modified locally. + * + * @param info the updated info. + */ + public void updateInfo(Info info) { + BoxAPIConnection api = this.getAPI(); + URL url = MEMBERSHIP_URL_TEMPLATE.build(api.getBaseURL(), this.getID()); + + BoxJSONRequest request = new BoxJSONRequest(api, url, "PUT"); + request.setBody(info.getPendingChanges()); + try (BoxJSONResponse response = request.send()) { + JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); + info.update(jsonObject); + } + } + + /** Deletes this group membership. */ + public void delete() { + BoxAPIConnection api = this.getAPI(); + URL url = MEMBERSHIP_URL_TEMPLATE.build(api.getBaseURL(), this.getID()); + + BoxAPIRequest request = new BoxAPIRequest(api, url, "DELETE"); + request.send().close(); + } + + /** Enumerates the possible roles that a user can have within a group. */ + public enum GroupRole { + /** The user is an administrator in the group. */ + ADMIN("admin"), + + /** The user is a regular member in the group. */ + MEMBER("member"); + + /** String representation of the groupRole. */ + private final String jsonValue; + /** - * The URL template for all group membership requests. + * Constructor. * - * @see #getInfo() + * @param jsonValue string representation of the role. */ - public static final URLTemplate MEMBERSHIP_URL_TEMPLATE = new URLTemplate("group_memberships/%s"); + GroupRole(String jsonValue) { + this.jsonValue = jsonValue; + } /** - * Constructs a BoxGroupMembership for a group membership with a given ID. + * Creates the groupRole from given string. * - * @param api the API connection to be used by the group membership. - * @param id the ID of the group membership. + * @param jsonValue string to be converted to role. + * @return the role, created from string value. */ - public BoxGroupMembership(BoxAPIConnection api, String id) { - super(api, id); + static GroupRole fromJSONString(String jsonValue) { + for (GroupRole role : GroupRole.values()) { + if (role.jsonValue.equalsIgnoreCase(jsonValue)) { + return role; + } + } + throw new IllegalArgumentException("Invalid value for enum GroupRole: " + jsonValue); + } + + /** @return string representation of the groupRole. */ + String toJSONString() { + return this.jsonValue; + } + } + + /** Enumerates the possible permissions that a user can have as a group admin. */ + public enum Permission { + /** The user can create accounts. */ + CAN_CREATE_ACCOUNTS("can_create_accounts"), + + /** The user can edit accounts. */ + CAN_EDIT_ACCOUNTS("can_edit_accounts"), + + /** The user can instant login as another user. */ + CAN_INSTANT_LOGIN("can_instant_login"), + + /** The user can run reports. */ + CAN_RUN_REPORTS("can_run_reports"); + + private final String jsonValue; + + Permission(String jsonValue) { + this.jsonValue = jsonValue; + } + + static Permission fromJSONValue(String jsonValue) { + return Permission.valueOf(jsonValue.toUpperCase(java.util.Locale.ROOT)); + } + + String toJSONValue() { + return this.jsonValue; + } + } + + /** Contains information about a BoxGroupMembership. */ + public class Info extends BoxResource.Info { + + /** @see #getUser() */ + private BoxUser.Info user; + + /** @see #getGroup() */ + private BoxGroup.Info group; + + /** @see #getGroupRole() */ + private GroupRole groupRole; + + /** @see #getCreatedAt() */ + private Date createdAt; + + /** @see #getModifiedAt() */ + private Date modifiedAt; + + /** @see #getConfigurablePermissions() */ + private Map configurablePermissions; + + /** Constructs an empty Info object. */ + public Info() { + super(); } /** - * Gets information about this group membership. + * Constructs an Info object by parsing information from a JSON string. * - * @return info about this group membership. + * @param json the JSON string to parse. */ - public Info getInfo() { - BoxAPIConnection api = this.getAPI(); - URL url = MEMBERSHIP_URL_TEMPLATE.build(api.getBaseURL(), this.getID()); - - BoxJSONRequest request = new BoxJSONRequest(api, url, "GET"); - try (BoxJSONResponse response = request.send()) { - JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - return new Info(jsonObject); - } + public Info(String json) { + super(json); } /** - * Updates the information about this group membership with any info fields that have been modified locally. + * Constructs an Info object using an already parsed JSON object. * - * @param info the updated info. + * @param jsonObject the parsed JSON object. */ - public void updateInfo(Info info) { - BoxAPIConnection api = this.getAPI(); - URL url = MEMBERSHIP_URL_TEMPLATE.build(api.getBaseURL(), this.getID()); - - BoxJSONRequest request = new BoxJSONRequest(api, url, "PUT"); - request.setBody(info.getPendingChanges()); - try (BoxJSONResponse response = request.send()) { - JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - info.update(jsonObject); - } + Info(JsonObject jsonObject) { + super(jsonObject); } /** - * Deletes this group membership. + * Gets the user belonging to the group. + * + *

Note: the BoxUser.Info returned by this method will only have the ID, name, and login + * fields populated. + * + * @return the user belonging to the group. */ - public void delete() { - BoxAPIConnection api = this.getAPI(); - URL url = MEMBERSHIP_URL_TEMPLATE.build(api.getBaseURL(), this.getID()); - - BoxAPIRequest request = new BoxAPIRequest(api, url, "DELETE"); - request.send().close(); + public BoxUser.Info getUser() { + return this.user; } /** - * Enumerates the possible roles that a user can have within a group. + * Gets the group the user belongs to. + * + *

Note: the BoxGroup.Info returned by this method will only have the ID and name fields + * populated. + * + * @return the group the user belongs to. */ - public enum GroupRole { - /** - * The user is an administrator in the group. - */ - ADMIN("admin"), - - /** - * The user is a regular member in the group. - */ - MEMBER("member"); - - /** - * String representation of the groupRole. - */ - private final String jsonValue; - - /** - * Constructor. - * - * @param jsonValue string representation of the role. - */ - GroupRole(String jsonValue) { - this.jsonValue = jsonValue; - } - - /** - * Creates the groupRole from given string. - * - * @param jsonValue string to be converted to role. - * @return the role, created from string value. - */ - static GroupRole fromJSONString(String jsonValue) { - for (GroupRole role : GroupRole.values()) { - if (role.jsonValue.equalsIgnoreCase(jsonValue)) { - return role; - } - } - throw new IllegalArgumentException("Invalid value for enum GroupRole: " + jsonValue); - } - - /** - * @return string representation of the groupRole. - */ - String toJSONString() { - return this.jsonValue; - } + public BoxGroup.Info getGroup() { + return this.group; } /** - * Enumerates the possible permissions that a user can have as a group admin. + * Gets the level of access the user has. + * + * @return the level of access the user has. */ - public enum Permission { - /** - * The user can create accounts. - */ - CAN_CREATE_ACCOUNTS("can_create_accounts"), - - /** - * The user can edit accounts. - */ - CAN_EDIT_ACCOUNTS("can_edit_accounts"), - - /** - * The user can instant login as another user. - */ - CAN_INSTANT_LOGIN("can_instant_login"), - - /** - * The user can run reports. - */ - CAN_RUN_REPORTS("can_run_reports"); - - private final String jsonValue; - - Permission(String jsonValue) { - this.jsonValue = jsonValue; - } - - static Permission fromJSONValue(String jsonValue) { - return Permission.valueOf(jsonValue.toUpperCase(java.util.Locale.ROOT)); - } - - String toJSONValue() { - return this.jsonValue; - } + public GroupRole getGroupRole() { + return this.groupRole; } /** - * Contains information about a BoxGroupMembership. + * Sets the level of access the user has. + * + * @param role the new level of access to give the user. */ - public class Info extends BoxResource.Info { - - /** - * @see #getUser() - */ - private BoxUser.Info user; - - /** - * @see #getGroup() - */ - private BoxGroup.Info group; - - /** - * @see #getGroupRole() - */ - private GroupRole groupRole; - - /** - * @see #getCreatedAt() - */ - private Date createdAt; - - /** - * @see #getModifiedAt() - */ - private Date modifiedAt; - - /** - * @see #getConfigurablePermissions() - */ - private Map configurablePermissions; - - /** - * Constructs an empty Info object. - */ - public Info() { - super(); - } + public void setGroupRole(GroupRole role) { + this.groupRole = role; + this.addPendingChange("role", role.toJSONString()); + } - /** - * Constructs an Info object by parsing information from a JSON string. - * - * @param json the JSON string to parse. - */ - public Info(String json) { - super(json); - } + /** + * Gets the time the group membership was created. + * + * @return the time the group membership was created. + */ + public Date getCreatedAt() { + return this.createdAt; + } - /** - * Constructs an Info object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - Info(JsonObject jsonObject) { - super(jsonObject); - } + /** + * Gets the time the group membership was last modified. + * + * @return the time the group membership was last modified. + */ + public Date getModifiedAt() { + return this.modifiedAt; + } - /** - * Gets the user belonging to the group. - * - *

Note: the BoxUser.Info returned by this method will only have the ID, name, and login fields - * populated.

- * - * @return the user belonging to the group. - */ - public BoxUser.Info getUser() { - return this.user; - } + /** + * Gets the configurablePermissions that the current user has on the group as group admin. + * + * @return the configurablePermissions that the current user has on the group as group admin. + */ + public Map getConfigurablePermissions() { + return this.configurablePermissions; + } - /** - * Gets the group the user belongs to. - * - *

Note: the BoxGroup.Info returned by this method will only have the ID and name fields populated.

- * - * @return the group the user belongs to. - */ - public BoxGroup.Info getGroup() { - return this.group; - } + /** + * Sets the configurablePermissions that the current user has on the group as group admin. + * + * @param configurablePermissions a Map representing the group admin configurable permissions + */ + public void setConfigurablePermissions(Map configurablePermissions) { + this.configurablePermissions = configurablePermissions; + this.addPendingChange("configurable_permissions", this.configurablePermissionJson()); + } - /** - * Gets the level of access the user has. - * - * @return the level of access the user has. - */ - public GroupRole getGroupRole() { - return this.groupRole; - } + /** + * append new configurable permissions to the previous existing list. + * + * @param permission the group admin permission one wants to enable or disable of the user on + * the group. + * @param value the true/false value of the attribute to set. + */ + public void appendConfigurablePermissions(Permission permission, Boolean value) { + this.configurablePermissions.put(permission, value); + this.addPendingChange("configurable_permissions", this.configurablePermissionJson()); + } - /** - * Sets the level of access the user has. - * - * @param role the new level of access to give the user. - */ - public void setGroupRole(GroupRole role) { - this.groupRole = role; - this.addPendingChange("role", role.toJSONString()); - } + private JsonObject configurablePermissionJson() { + JsonObject configurablePermissionJson = new JsonObject(); + for (Permission attrKey : this.configurablePermissions.keySet()) { + configurablePermissionJson.set( + attrKey.toJSONValue(), this.configurablePermissions.get(attrKey)); + } + return configurablePermissionJson; + } - /** - * Gets the time the group membership was created. - * - * @return the time the group membership was created. - */ - public Date getCreatedAt() { - return this.createdAt; - } + /** {@inheritDoc} */ + @Override + public BoxGroupMembership getResource() { + return BoxGroupMembership.this; + } - /** - * Gets the time the group membership was last modified. - * - * @return the time the group membership was last modified. - */ - public Date getModifiedAt() { - return this.modifiedAt; + private Map parseConfigurablePermissions(JsonObject jsonObject) { + if (jsonObject == null) { + return null; + } + Map permissions = new HashMap<>(); + for (JsonObject.Member member : jsonObject) { + String memberName = member.getName(); + boolean memberValue = member.getValue().asBoolean(); + switch (memberName) { + case "can_create_accounts": + permissions.put(Permission.CAN_CREATE_ACCOUNTS, memberValue); + break; + case "can_edit_accounts": + permissions.put(Permission.CAN_EDIT_ACCOUNTS, memberValue); + break; + case "can_instant_login": + permissions.put(Permission.CAN_INSTANT_LOGIN, memberValue); + break; + case "can_run_reports": + permissions.put(Permission.CAN_RUN_REPORTS, memberValue); + break; + default: + break; } + } + return permissions; + } - /** - * Gets the configurablePermissions that the current user has on the group as group admin. - * - * @return the configurablePermissions that the current user has on the group as group admin. - */ - public Map getConfigurablePermissions() { - return this.configurablePermissions; - } + /** {@inheritDoc} */ + @Override + protected void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + + String memberName = member.getName(); + JsonValue value = member.getValue(); + + try { + switch (memberName) { + case "user": + JsonObject userJSON = value.asObject(); + if (this.user == null) { + String userID = userJSON.get("id").asString(); + BoxUser user = new BoxUser(getAPI(), userID); + this.user = user.new Info(userJSON); + } else { + this.user.update(userJSON); + } - /** - * Sets the configurablePermissions that the current user has on the group as group admin. - * - * @param configurablePermissions a Map representing the group admin configurable permissions - */ - public void setConfigurablePermissions(Map configurablePermissions) { - this.configurablePermissions = configurablePermissions; - this.addPendingChange("configurable_permissions", this.configurablePermissionJson()); - } + break; + case "group": + JsonObject groupJSON = value.asObject(); + if (this.group == null) { + String userID = groupJSON.get("id").asString(); + BoxGroup group = new BoxGroup(getAPI(), userID); + this.group = group.new Info(groupJSON); + } else { + this.group.update(groupJSON); + } - /** - * append new configurable permissions to the previous existing list. - * - * @param permission the group admin permission one wants to enable or disable of the user on the group. - * @param value the true/false value of the attribute to set. - */ - public void appendConfigurablePermissions(Permission permission, Boolean value) { - this.configurablePermissions.put(permission, value); - this.addPendingChange("configurable_permissions", this.configurablePermissionJson()); - } + break; + case "role": + this.groupRole = GroupRole.fromJSONString(value.asString()); - private JsonObject configurablePermissionJson() { - JsonObject configurablePermissionJson = new JsonObject(); - for (Permission attrKey : this.configurablePermissions.keySet()) { - configurablePermissionJson.set(attrKey.toJSONValue(), this.configurablePermissions.get(attrKey)); - } - return configurablePermissionJson; - } + break; + case "created_at": + this.createdAt = BoxDateFormat.parse(value.asString()); - /** - * {@inheritDoc} - */ - @Override - public BoxGroupMembership getResource() { - return BoxGroupMembership.this; - } + break; + case "modified_at": + this.modifiedAt = BoxDateFormat.parse(value.asString()); - private Map parseConfigurablePermissions(JsonObject jsonObject) { - if (jsonObject == null) { - return null; - } - Map permissions = new HashMap<>(); - for (JsonObject.Member member : jsonObject) { - String memberName = member.getName(); - boolean memberValue = member.getValue().asBoolean(); - switch (memberName) { - case "can_create_accounts": - permissions.put(Permission.CAN_CREATE_ACCOUNTS, memberValue); - break; - case "can_edit_accounts": - permissions.put(Permission.CAN_EDIT_ACCOUNTS, memberValue); - break; - case "can_instant_login": - permissions.put(Permission.CAN_INSTANT_LOGIN, memberValue); - break; - case "can_run_reports": - permissions.put(Permission.CAN_RUN_REPORTS, memberValue); - break; - default: - break; - } - } - return permissions; - } + break; + case "configurable_permissions": + this.configurablePermissions = this.parseConfigurablePermissions(value.asObject()); - /** - * {@inheritDoc} - */ - @Override - protected void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - - String memberName = member.getName(); - JsonValue value = member.getValue(); - - try { - switch (memberName) { - case "user": - JsonObject userJSON = value.asObject(); - if (this.user == null) { - String userID = userJSON.get("id").asString(); - BoxUser user = new BoxUser(getAPI(), userID); - this.user = user.new Info(userJSON); - } else { - this.user.update(userJSON); - } - - break; - case "group": - JsonObject groupJSON = value.asObject(); - if (this.group == null) { - String userID = groupJSON.get("id").asString(); - BoxGroup group = new BoxGroup(getAPI(), userID); - this.group = group.new Info(groupJSON); - } else { - this.group.update(groupJSON); - } - - break; - case "role": - this.groupRole = GroupRole.fromJSONString(value.asString()); - - break; - case "created_at": - this.createdAt = BoxDateFormat.parse(value.asString()); - - break; - case "modified_at": - this.modifiedAt = BoxDateFormat.parse(value.asString()); - - break; - case "configurable_permissions": - this.configurablePermissions = this.parseConfigurablePermissions(value.asObject()); - - break; - default: - break; - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); - } + break; + default: + break; } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); + } } + } } diff --git a/src/main/java/com/box/sdk/BoxGroupMembershipIterator.java b/src/main/java/com/box/sdk/BoxGroupMembershipIterator.java index 76b6e54f7..8f2a3c0f9 100644 --- a/src/main/java/com/box/sdk/BoxGroupMembershipIterator.java +++ b/src/main/java/com/box/sdk/BoxGroupMembershipIterator.java @@ -6,60 +6,45 @@ import java.net.URL; import java.util.Iterator; -/** - * An iterator object for {@link BoxGroupMembership} object. - * Supports offset-based paging. - */ +/** An iterator object for {@link BoxGroupMembership} object. Supports offset-based paging. */ class BoxGroupMembershipIterator implements Iterator { - /** - * The limit of entries per response. - */ - private static final long LIMIT = 1000; - - /** - * The API connection to be used. - */ - private final BoxAPIConnection api; - - /** - * Iterator object with paging support. - */ - private final JsonIterator jsonIterator; - - /** - * Creates new BoxGroupMembership iterator. - * - * @param api The API connection to be used by the iterator. - * @param url The endpoint url. - */ - BoxGroupMembershipIterator(BoxAPIConnection api, URL url) { - this.api = api; - this.jsonIterator = new JsonIterator(api, url, offset(0, LIMIT)); - } - - /** - * @return false if current element is the last. - */ - public boolean hasNext() { - return this.jsonIterator.hasNext(); - } - - /** - * @return next BoxGroupMembeship object in the list. - */ - public BoxGroupMembership.Info next() { - JsonObject nextJSONObject = this.jsonIterator.next(); - String id = nextJSONObject.get("id").asString(); - - BoxGroupMembership membership = new BoxGroupMembership(this.api, id); - return membership.new Info(nextJSONObject); - } - - /** - * Remove operation is not supported. - */ - public void remove() { - throw new UnsupportedOperationException(); - } + /** The limit of entries per response. */ + private static final long LIMIT = 1000; + + /** The API connection to be used. */ + private final BoxAPIConnection api; + + /** Iterator object with paging support. */ + private final JsonIterator jsonIterator; + + /** + * Creates new BoxGroupMembership iterator. + * + * @param api The API connection to be used by the iterator. + * @param url The endpoint url. + */ + BoxGroupMembershipIterator(BoxAPIConnection api, URL url) { + this.api = api; + this.jsonIterator = new JsonIterator(api, url, offset(0, LIMIT)); + } + + /** @return false if current element is the last. */ + public boolean hasNext() { + return this.jsonIterator.hasNext(); + } + + /** @return next BoxGroupMembeship object in the list. */ + public BoxGroupMembership.Info next() { + JsonObject nextJSONObject = this.jsonIterator.next(); + String id = nextJSONObject.get("id").asString(); + + BoxGroupMembership membership = new BoxGroupMembership(this.api, id); + return membership.new Info(nextJSONObject); + } + + /** Remove operation is not supported. */ + public void remove() { + throw new UnsupportedOperationException(); + } } diff --git a/src/main/java/com/box/sdk/BoxImageMultipartRequest.java b/src/main/java/com/box/sdk/BoxImageMultipartRequest.java index ac497b7af..557d6ad39 100644 --- a/src/main/java/com/box/sdk/BoxImageMultipartRequest.java +++ b/src/main/java/com/box/sdk/BoxImageMultipartRequest.java @@ -4,46 +4,47 @@ import okhttp3.MediaType; /** - * Used to make HTTP multipart requests to the Box API to upload an image. You can define part name that - * contains image binary data. Image type will be determined from the file name. + * Used to make HTTP multipart requests to the Box API to upload an image. You can define part name + * that contains image binary data. Image type will be determined from the file name. * - *

This class partially implements the HTTP multipart standard in order to upload files to Box. The body of this - * request type cannot be set directly. Instead, it can be modified by adding multipart fields and setting file - * contents. The body of multipart requests will not be logged since they are likely to contain binary data.

+ *

This class partially implements the HTTP multipart standard in order to upload files to Box. + * The body of this request type cannot be set directly. Instead, it can be modified by adding + * multipart fields and setting file contents. The body of multipart requests will not be logged + * since they are likely to contain binary data. */ class BoxImageMultipartRequest extends AbstractBoxMultipartRequest { - private final String partName; + private final String partName; - /** - * Constructs an authenticated BoxImageMultipartRequest using a provided BoxAPIConnection. - * You can define part name that contains image binary data. Image type will be determined from the file name. - * - * @param api an API connection for authenticating the request. - * @param url the URL of the request. - * @param partName the name of the part that will contain image - */ - BoxImageMultipartRequest(BoxAPIConnection api, URL url, String partName) { - super(api, url); - this.partName = partName; - } + /** + * Constructs an authenticated BoxImageMultipartRequest using a provided BoxAPIConnection. You can + * define part name that contains image binary data. Image type will be determined from the file + * name. + * + * @param api an API connection for authenticating the request. + * @param url the URL of the request. + * @param partName the name of the part that will contain image + */ + BoxImageMultipartRequest(BoxAPIConnection api, URL url, String partName) { + super(api, url); + this.partName = partName; + } - @Override - protected String getPartName() { - return partName; - } + @Override + protected String getPartName() { + return partName; + } - @Override - protected MediaType getPartContentType(String filename) { - return MediaType.parse(determineImageTypeFromFileName(filename)); - } + @Override + protected MediaType getPartContentType(String filename) { + return MediaType.parse(determineImageTypeFromFileName(filename)); + } - private String determineImageTypeFromFileName(String filename) { - String[] filenameAndExtension = filename.split("\\."); - if (filenameAndExtension.length > 1) { - return "image/" + filenameAndExtension[filenameAndExtension.length - 1]; - } - throw new IllegalArgumentException( - "Could not determine file extenstion for Avatar Upload. Filename: " + filename - ); + private String determineImageTypeFromFileName(String filename) { + String[] filenameAndExtension = filename.split("\\."); + if (filenameAndExtension.length > 1) { + return "image/" + filenameAndExtension[filenameAndExtension.length - 1]; } + throw new IllegalArgumentException( + "Could not determine file extenstion for Avatar Upload. Filename: " + filename); + } } diff --git a/src/main/java/com/box/sdk/BoxInvite.java b/src/main/java/com/box/sdk/BoxInvite.java index 592106bd1..c28d11647 100644 --- a/src/main/java/com/box/sdk/BoxInvite.java +++ b/src/main/java/com/box/sdk/BoxInvite.java @@ -9,256 +9,234 @@ /** * Represents an invitation for a user to join an enterprise. * - *

Unless otherwise noted, the methods in this class can throw an unchecked {@link BoxAPIException} (unchecked - * meaning that the compiler won't force you to handle it) if an error occurs. If you wish to implement custom error - * handling for errors related to the Box REST API, you should capture this exception explicitly.

+ *

Unless otherwise noted, the methods in this class can throw an unchecked {@link + * BoxAPIException} (unchecked meaning that the compiler won't force you to handle it) if an error + * occurs. If you wish to implement custom error handling for errors related to the Box REST API, + * you should capture this exception explicitly. */ @BoxResourceType("invite") public class BoxInvite extends BoxResource { + /** The URL template for invite creation requests. */ + public static final URLTemplate INVITE_CREATION_URL_TEMPLATE = new URLTemplate("invites"); + + /** + * The URL template for invite retrieval requests. + * + * @see #getInfo() + */ + public static final URLTemplate INVITE_URL_TEMPLATE = new URLTemplate("invites/%s"); + + /** + * Constructs a BoxInvitee for an invite with a given ID. + * + * @param api the API connection to be used by the invite. + * @param id the ID of the invite. + */ + public BoxInvite(BoxAPIConnection api, String id) { + super(api, id); + } + + /** + * Invite a user to an enterprise. + * + * @param api the API connection to use for the request. + * @param userLogin the login of the user to invite. + * @param enterpriseID the ID of the enterprise to invite the user to. + * @return the invite info. + */ + public static Info inviteUserToEnterprise( + BoxAPIConnection api, String userLogin, String enterpriseID) { + + URL url = INVITE_CREATION_URL_TEMPLATE.build(api.getBaseURL()); + BoxJSONRequest request = new BoxJSONRequest(api, url, "POST"); + + JsonObject body = new JsonObject(); + + JsonObject enterprise = new JsonObject(); + enterprise.add("id", enterpriseID); + body.add("enterprise", enterprise); + + JsonObject actionableBy = new JsonObject(); + actionableBy.add("login", userLogin); + body.add("actionable_by", actionableBy); + + request.setBody(body); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + + BoxInvite invite = new BoxInvite(api, responseJSON.get("id").asString()); + return invite.new Info(responseJSON); + } + } + + /** + * Gets information about this group membership. + * + * @return info about this group membership. + */ + public Info getInfo() { + BoxAPIConnection api = this.getAPI(); + URL url = INVITE_URL_TEMPLATE.build(api.getBaseURL(), this.getID()); + + BoxJSONRequest request = new BoxJSONRequest(api, url, "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); + return new Info(jsonObject); + } + } + + /** Contains information about a BoxInvite. */ + public class Info extends BoxResource.Info { + + /** @see #getInvitedTo() */ + private BoxEnterprise invitedTo; + + /** @see #getActionableBy() */ + private BoxUser.Info actionableBy; + + /** @see #getInvitedBy() */ + private BoxUser.Info invitedBy; + + /** @see #getCreatedAt() */ + private Date createdAt; + + /** @see #getModifiedAt() */ + private Date modifiedAt; + + /** @see #getStatus() */ + private String status; + + /** Constructs an empty Info object. */ + public Info() { + super(); + } + /** - * The URL template for invite creation requests. + * Constructs an Info object by parsing information from a JSON string. + * + * @param json the JSON string to parse. */ - public static final URLTemplate INVITE_CREATION_URL_TEMPLATE = new URLTemplate("invites"); + public Info(String json) { + super(json); + } /** - * The URL template for invite retrieval requests. + * Constructs an Info object using an already parsed JSON object. * - * @see #getInfo() + * @param jsonObject the parsed JSON object. */ - public static final URLTemplate INVITE_URL_TEMPLATE = new URLTemplate("invites/%s"); + Info(JsonObject jsonObject) { + super(jsonObject); + } /** - * Constructs a BoxInvitee for an invite with a given ID. + * Gets the enterprise the user was invited to. * - * @param api the API connection to be used by the invite. - * @param id the ID of the invite. + * @return the enterprise the user was invited to. */ - public BoxInvite(BoxAPIConnection api, String id) { - super(api, id); + public BoxEnterprise getInvitedTo() { + return this.invitedTo; } /** - * Invite a user to an enterprise. + * Gets the user that was invited to the enterprise. + * + *

Note: the BoxUser.Info returned by this method will only have the ID, name, and login + * fields populated. * - * @param api the API connection to use for the request. - * @param userLogin the login of the user to invite. - * @param enterpriseID the ID of the enterprise to invite the user to. - * @return the invite info. + * @return the invited user. */ - public static Info inviteUserToEnterprise(BoxAPIConnection api, String userLogin, String enterpriseID) { - - URL url = INVITE_CREATION_URL_TEMPLATE.build(api.getBaseURL()); - BoxJSONRequest request = new BoxJSONRequest(api, url, "POST"); - - JsonObject body = new JsonObject(); - - JsonObject enterprise = new JsonObject(); - enterprise.add("id", enterpriseID); - body.add("enterprise", enterprise); - - JsonObject actionableBy = new JsonObject(); - actionableBy.add("login", userLogin); - body.add("actionable_by", actionableBy); - - request.setBody(body); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - - BoxInvite invite = new BoxInvite(api, responseJSON.get("id").asString()); - return invite.new Info(responseJSON); - } + public BoxUser.Info getActionableBy() { + return this.actionableBy; } /** - * Gets information about this group membership. + * Gets the user that made the invitation. + * + *

Note: the BoxUser.Info returned by this method will only have the ID, name, and login + * fields populated. * - * @return info about this group membership. + * @return the user that created the invitation. */ - public Info getInfo() { - BoxAPIConnection api = this.getAPI(); - URL url = INVITE_URL_TEMPLATE.build(api.getBaseURL(), this.getID()); - - BoxJSONRequest request = new BoxJSONRequest(api, url, "GET"); - try (BoxJSONResponse response = request.send()) { - JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - return new Info(jsonObject); - } + public BoxUser.Info getInvitedBy() { + return this.invitedBy; } /** - * Contains information about a BoxInvite. + * Gets the status of the invitation. + * + * @return the invite status. */ - public class Info extends BoxResource.Info { - - /** - * @see #getInvitedTo() - */ - private BoxEnterprise invitedTo; - - /** - * @see #getActionableBy() - */ - private BoxUser.Info actionableBy; - - /** - * @see #getInvitedBy() - */ - private BoxUser.Info invitedBy; - - /** - * @see #getCreatedAt() - */ - private Date createdAt; - - /** - * @see #getModifiedAt() - */ - private Date modifiedAt; - - /** - * @see #getStatus() - */ - private String status; - - /** - * Constructs an empty Info object. - */ - public Info() { - super(); - } - - /** - * Constructs an Info object by parsing information from a JSON string. - * - * @param json the JSON string to parse. - */ - public Info(String json) { - super(json); - } - - /** - * Constructs an Info object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - Info(JsonObject jsonObject) { - super(jsonObject); - } - - /** - * Gets the enterprise the user was invited to. - * - * @return the enterprise the user was invited to. - */ - public BoxEnterprise getInvitedTo() { - return this.invitedTo; - } - - /** - * Gets the user that was invited to the enterprise. - * - *

Note: the BoxUser.Info returned by this method will only have the ID, name, and login fields - * populated.

- * - * @return the invited user. - */ - public BoxUser.Info getActionableBy() { - return this.actionableBy; - } - - /** - * Gets the user that made the invitation. - * - *

Note: the BoxUser.Info returned by this method will only have the ID, name, and login fields - * populated.

- * - * @return the user that created the invitation. - */ - public BoxUser.Info getInvitedBy() { - return this.invitedBy; - } - - /** - * Gets the status of the invitation. - * - * @return the invite status. - */ - public String getStatus() { - return this.status; - } + public String getStatus() { + return this.status; + } - /** - * Gets the time the invite was created. - * - * @return the time the invite was created. - */ - public Date getCreatedAt() { - return this.createdAt; - } + /** + * Gets the time the invite was created. + * + * @return the time the invite was created. + */ + public Date getCreatedAt() { + return this.createdAt; + } - /** - * Gets the time the invite was last modified. - * - * @return the time the invite was last modified. - */ - public Date getModifiedAt() { - return this.modifiedAt; - } + /** + * Gets the time the invite was last modified. + * + * @return the time the invite was last modified. + */ + public Date getModifiedAt() { + return this.modifiedAt; + } - /** - * {@inheritDoc} - */ - @Override - public BoxInvite getResource() { - return BoxInvite.this; - } + /** {@inheritDoc} */ + @Override + public BoxInvite getResource() { + return BoxInvite.this; + } - /** - * {@inheritDoc} - */ - @Override - protected void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - - String memberName = member.getName(); - JsonValue value = member.getValue(); - - try { - if (memberName.equals("invited_to")) { - JsonObject enterpriseJSON = value.asObject(); - this.invitedTo = new BoxEnterprise(enterpriseJSON); - } else if (memberName.equals("actionable_by")) { - JsonObject userJSON = value.asObject(); - if (this.actionableBy == null) { - String userID = userJSON.get("id").asString(); - BoxUser user = new BoxUser(getAPI(), userID); - this.actionableBy = user.new Info(userJSON); - } else { - this.actionableBy.update(userJSON); - } - } else if (memberName.equals("invited_by")) { - JsonObject userJSON = value.asObject(); - if (this.invitedBy == null) { - String userID = userJSON.get("id").asString(); - BoxUser user = new BoxUser(getAPI(), userID); - this.invitedBy = user.new Info(userJSON); - } else { - this.invitedBy.update(userJSON); - } - } else if (memberName.equals("status")) { - this.status = value.asString(); - } else if (memberName.equals("created_at")) { - this.createdAt = BoxDateFormat.parse(value.asString()); - - } else if (memberName.equals("modified_at")) { - this.modifiedAt = BoxDateFormat.parse(value.asString()); - - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); - } + /** {@inheritDoc} */ + @Override + protected void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + + String memberName = member.getName(); + JsonValue value = member.getValue(); + + try { + if (memberName.equals("invited_to")) { + JsonObject enterpriseJSON = value.asObject(); + this.invitedTo = new BoxEnterprise(enterpriseJSON); + } else if (memberName.equals("actionable_by")) { + JsonObject userJSON = value.asObject(); + if (this.actionableBy == null) { + String userID = userJSON.get("id").asString(); + BoxUser user = new BoxUser(getAPI(), userID); + this.actionableBy = user.new Info(userJSON); + } else { + this.actionableBy.update(userJSON); + } + } else if (memberName.equals("invited_by")) { + JsonObject userJSON = value.asObject(); + if (this.invitedBy == null) { + String userID = userJSON.get("id").asString(); + BoxUser user = new BoxUser(getAPI(), userID); + this.invitedBy = user.new Info(userJSON); + } else { + this.invitedBy.update(userJSON); + } + } else if (memberName.equals("status")) { + this.status = value.asString(); + } else if (memberName.equals("created_at")) { + this.createdAt = BoxDateFormat.parse(value.asString()); + + } else if (memberName.equals("modified_at")) { + this.modifiedAt = BoxDateFormat.parse(value.asString()); } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); + } } - + } } diff --git a/src/main/java/com/box/sdk/BoxItem.java b/src/main/java/com/box/sdk/BoxItem.java index 8b14a1321..bedf3fd2d 100644 --- a/src/main/java/com/box/sdk/BoxItem.java +++ b/src/main/java/com/box/sdk/BoxItem.java @@ -11,662 +11,683 @@ import java.util.List; import java.util.Set; -/** - * The abstract base class for items in a user's file tree (files, folders, etc.). - */ +/** The abstract base class for items in a user's file tree (files, folders, etc.). */ public abstract class BoxItem extends BoxResource { + /** + * An array of all possible file fields that can be requested when calling {@link + * #getInfo(String...)}. + */ + public static final String[] ALL_FIELDS = { + "type", + "id", + "sequence_id", + "etag", + "sha1", + "name", + "description", + "size", + "path_collection", + "created_at", + "modified_at", + "trashed_at", + "purged_at", + "content_created_at", + "content_modified_at", + "created_by", + "modified_by", + "owned_by", + "shared_link", + "parent", + "item_status", + "version_number", + "comment_count", + "permissions", + "tags", + "lock", + "extension", + "is_package", + "folder_upload_email", + "item_collection", + "sync_state", + "has_collaborations", + "can_non_owners_invite", + "file_version", + "collections", + "expires_at" + }; + /** Shared Item URL Template. */ + public static final URLTemplate SHARED_ITEM_URL_TEMPLATE = new URLTemplate("shared_items"); + + /** Url template for operations with watermarks. */ + public static final URLTemplate WATERMARK_URL_TEMPLATE = new URLTemplate("/watermark"); + + /** + * Constructs a BoxItem for an item with a given ID. + * + * @param api the API connection to be used by the item. + * @param id the ID of the item. + */ + public BoxItem(BoxAPIConnection api, String id) { + super(api, id); + } + + /** + * Gets an item that was shared with a shared link. + * + * @param api the API connection to be used by the shared item. + * @param sharedLink the shared link to the item. + * @return info about the shared item. + */ + public static BoxItem.Info getSharedItem(BoxAPIConnection api, String sharedLink) { + return getSharedItem(api, sharedLink, null); + } + + /** + * Gets an item that was shared with a password-protected shared link. + * + * @param api the API connection to be used by the shared item. + * @param sharedLink the shared link to the item. + * @param password the password for the shared link. Use `null` if shared link has no password. + * @param fields the fields to retrieve. + * @return info about the shared item. + */ + public static BoxItem.Info getSharedItem( + BoxAPIConnection api, String sharedLink, String password, String... fields) { + QueryStringBuilder builder = new QueryStringBuilder(); + if (fields.length > 0) { + builder.appendParam("fields", fields); + } + URL url = SHARED_ITEM_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString()); + BoxJSONRequest request = new BoxJSONRequest(api, url, "GET"); + + request.addHeader("BoxApi", BoxSharedLink.getSharedLinkHeaderValue(sharedLink, password)); + + try (BoxJSONResponse response = request.send()) { + JsonObject json = Json.parse(response.getJSON()).asObject(); + return (BoxItem.Info) BoxResource.parseInfo(api, json); + } + } + + /** @return URL for the current object, constructed as base URL pus an item specifier. */ + protected URL getItemURL() { + return new URLTemplate("").build(this.getAPI().getBaseURL()); + } + + /** + * Used to retrieve the watermark for the item. If the item does not have a watermark applied to + * it, a 404 Not Found will be returned by API. + * + * @param itemUrl url template for the item. + * @param fields the fields to retrieve. + * @return the watermark associated with the item. + */ + protected BoxWatermark getWatermark(URLTemplate itemUrl, String... fields) { + URL watermarkUrl = itemUrl.build(this.getAPI().getBaseURL(), this.getID()); + QueryStringBuilder builder = new QueryStringBuilder(); + if (fields.length > 0) { + builder.appendParam("fields", fields); + } + URL url = WATERMARK_URL_TEMPLATE.buildWithQuery(watermarkUrl.toString(), builder.toString()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); + try (BoxJSONResponse response = request.send()) { + return new BoxWatermark(response.getJSON()); + } + } + + /** + * Used to apply or update the watermark for the item. + * + * @param itemUrl url template for the item. + * @param imprint the value must be "default", as custom watermarks is not yet supported. + * @return the watermark associated with the item. + */ + protected BoxWatermark applyWatermark(URLTemplate itemUrl, String imprint) { + URL watermarkUrl = itemUrl.build(this.getAPI().getBaseURL(), this.getID()); + URL url = WATERMARK_URL_TEMPLATE.build(watermarkUrl.toString()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); + JsonObject body = + new JsonObject() + .add( + BoxWatermark.WATERMARK_JSON_KEY, + new JsonObject().add(BoxWatermark.WATERMARK_IMPRINT_JSON_KEY, imprint)); + request.setBody(body.toString()); + try (BoxJSONResponse response = request.send()) { + return new BoxWatermark(response.getJSON()); + } + } + + /** + * Removes a watermark from the item. If the item did not have a watermark applied to it, a 404 + * Not Found will be returned by API. + * + * @param itemUrl url template for the item. + */ + protected void removeWatermark(URLTemplate itemUrl) { + URL watermarkUrl = itemUrl.build(this.getAPI().getBaseURL(), this.getID()); + URL url = WATERMARK_URL_TEMPLATE.build(watermarkUrl.toString()); + BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); + request.send().close(); + } + + /** + * Copies this item to another folder. + * + * @param destination the destination folder. + * @return info about the copied item. + */ + public abstract BoxItem.Info copy(BoxFolder destination); + + /** + * Copies this item to another folder and gives it a new name. If the destination is the same + * folder as the item's current parent, then newName must be a new, unique name. + * + * @param destination the destination folder. + * @param newName a new name for the copied item. + * @return info about the copied item. + */ + public abstract BoxItem.Info copy(BoxFolder destination, String newName); + + /** + * Moves this item to another folder. + * + * @param destination the destination folder. + * @return info about the moved item. + */ + public abstract BoxItem.Info move(BoxFolder destination); + + /** + * Moves this item to another folder and gives it a new name. + * + * @param destination the destination folder. + * @param newName a new name for the moved item. + * @return info about the moved item. + */ + public abstract BoxItem.Info move(BoxFolder destination, String newName); + + /** + * Gets information about this item that's limited to a list of specified fields. + * + * @param fields the fields to retrieve. + * @return info about this item containing only the specified fields. + */ + public abstract BoxItem.Info getInfo(String... fields); + + /** + * Sets the collections that this item belongs to. + * + * @param collections the collections that this item should belong to. + * @return info about the item, including the collections it belongs to. + */ + public abstract BoxItem.Info setCollections(BoxCollection... collections); + + /** Contains information about a BoxItem. */ + public abstract class Info extends BoxResource.Info { + private String type; + private String sequenceID; + private String etag; + private String name; + private Date createdAt; + private Date modifiedAt; + private String description; + private long size; + private List pathCollection; + private BoxUser.Info createdBy; + private BoxUser.Info modifiedBy; + private Date trashedAt; + private Date purgedAt; + private Date contentCreatedAt; + private Date contentModifiedAt; + private BoxUser.Info ownedBy; + private BoxSharedLink sharedLink; + private List tags; + private BoxFolder.Info parent; + private String itemStatus; + private Date expiresAt; + private Set collections; + private String downloadUrl; + + /** Constructs an empty Info object. */ + public Info() { + super(); + } + /** - * An array of all possible file fields that can be requested when calling {@link #getInfo(String...)}. + * Constructs an Info object by parsing information from a JSON string. + * + * @param json the JSON string to parse. */ - public static final String[] ALL_FIELDS = {"type", "id", "sequence_id", "etag", "sha1", "name", "description", - "size", "path_collection", "created_at", "modified_at", "trashed_at", "purged_at", "content_created_at", - "content_modified_at", "created_by", "modified_by", "owned_by", "shared_link", "parent", "item_status", - "version_number", "comment_count", "permissions", "tags", "lock", "extension", "is_package", - "folder_upload_email", "item_collection", "sync_state", "has_collaborations", "can_non_owners_invite", - "file_version", "collections", "expires_at"}; + public Info(String json) { + super(json); + } + /** - * Shared Item URL Template. + * Constructs an Info object using an already parsed JSON object. + * + * @param jsonObject the parsed JSON object. */ - public static final URLTemplate SHARED_ITEM_URL_TEMPLATE = new URLTemplate("shared_items"); + Info(JsonObject jsonObject) { + super(jsonObject); + } /** - * Url template for operations with watermarks. + * Gets the item type. + * + * @return the item's type. */ - public static final URLTemplate WATERMARK_URL_TEMPLATE = new URLTemplate("/watermark"); + public String getType() { + return this.type; + } /** - * Constructs a BoxItem for an item with a given ID. + * Gets a unique string identifying the version of the item. * - * @param api the API connection to be used by the item. - * @param id the ID of the item. + * @return a unique string identifying the version of the item. */ - public BoxItem(BoxAPIConnection api, String id) { - super(api, id); + public String getEtag() { + return this.etag; } /** - * Gets an item that was shared with a shared link. + * Gets the name of the item. * - * @param api the API connection to be used by the shared item. - * @param sharedLink the shared link to the item. - * @return info about the shared item. + * @return the name of the item. */ - public static BoxItem.Info getSharedItem(BoxAPIConnection api, String sharedLink) { - return getSharedItem(api, sharedLink, null); + public String getName() { + return this.name; } /** - * Gets an item that was shared with a password-protected shared link. + * Sets the name of the item. * - * @param api the API connection to be used by the shared item. - * @param sharedLink the shared link to the item. - * @param password the password for the shared link. Use `null` if shared link has no password. - * @param fields the fields to retrieve. - * @return info about the shared item. + * @param name the new name of the item. */ - public static BoxItem.Info getSharedItem( - BoxAPIConnection api, String sharedLink, String password, String... fields - ) { - QueryStringBuilder builder = new QueryStringBuilder(); - if (fields.length > 0) { - builder.appendParam("fields", fields); - } - URL url = SHARED_ITEM_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString()); - BoxJSONRequest request = new BoxJSONRequest(api, url, "GET"); - - request.addHeader("BoxApi", BoxSharedLink.getSharedLinkHeaderValue(sharedLink, password)); - - try (BoxJSONResponse response = request.send()) { - JsonObject json = Json.parse(response.getJSON()).asObject(); - return (BoxItem.Info) BoxResource.parseInfo(api, json); - } + public void setName(String name) { + this.name = name; + this.addPendingChange("name", name); } /** - * @return URL for the current object, constructed as base URL pus an item specifier. + * Gets the time the item was created. + * + * @return the time the item was created. */ - protected URL getItemURL() { - return new URLTemplate("").build(this.getAPI().getBaseURL()); + public Date getCreatedAt() { + return this.createdAt; } /** - * Used to retrieve the watermark for the item. - * If the item does not have a watermark applied to it, a 404 Not Found will be returned by API. + * Gets the time the item was last modified. * - * @param itemUrl url template for the item. - * @param fields the fields to retrieve. - * @return the watermark associated with the item. + * @return the time the item was last modified. */ - protected BoxWatermark getWatermark(URLTemplate itemUrl, String... fields) { - URL watermarkUrl = itemUrl.build(this.getAPI().getBaseURL(), this.getID()); - QueryStringBuilder builder = new QueryStringBuilder(); - if (fields.length > 0) { - builder.appendParam("fields", fields); - } - URL url = WATERMARK_URL_TEMPLATE.buildWithQuery(watermarkUrl.toString(), builder.toString()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); - try (BoxJSONResponse response = request.send()) { - return new BoxWatermark(response.getJSON()); - } + public Date getModifiedAt() { + return this.modifiedAt; } /** - * Used to apply or update the watermark for the item. + * Gets the description of the item. * - * @param itemUrl url template for the item. - * @param imprint the value must be "default", as custom watermarks is not yet supported. - * @return the watermark associated with the item. + * @return the description of the item. */ - protected BoxWatermark applyWatermark(URLTemplate itemUrl, String imprint) { - URL watermarkUrl = itemUrl.build(this.getAPI().getBaseURL(), this.getID()); - URL url = WATERMARK_URL_TEMPLATE.build(watermarkUrl.toString()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); - JsonObject body = new JsonObject() - .add(BoxWatermark.WATERMARK_JSON_KEY, new JsonObject() - .add(BoxWatermark.WATERMARK_IMPRINT_JSON_KEY, imprint)); - request.setBody(body.toString()); - try (BoxJSONResponse response = request.send()) { - return new BoxWatermark(response.getJSON()); - } + public String getDescription() { + return this.description; } /** - * Removes a watermark from the item. - * If the item did not have a watermark applied to it, a 404 Not Found will be returned by API. + * Sets the description of the item. * - * @param itemUrl url template for the item. + * @param description the new description of the item. */ - protected void removeWatermark(URLTemplate itemUrl) { - URL watermarkUrl = itemUrl.build(this.getAPI().getBaseURL(), this.getID()); - URL url = WATERMARK_URL_TEMPLATE.build(watermarkUrl.toString()); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); - request.send().close(); + public void setDescription(String description) { + this.description = description; + this.addPendingChange("description", description); } /** - * Copies this item to another folder. + * Gets the size of the item in bytes. * - * @param destination the destination folder. - * @return info about the copied item. + * @return the size of the item in bytes. */ - public abstract BoxItem.Info copy(BoxFolder destination); + public long getSize() { + return this.size; + } /** - * Copies this item to another folder and gives it a new name. If the destination is the same folder as the item's - * current parent, then newName must be a new, unique name. + * Gets the path of folders to the item, starting at the root. * - * @param destination the destination folder. - * @param newName a new name for the copied item. - * @return info about the copied item. + * @return the path of folders to the item. */ - public abstract BoxItem.Info copy(BoxFolder destination, String newName); + public List getPathCollection() { + return this.pathCollection; + } /** - * Moves this item to another folder. + * Gets info about the user who created the item. * - * @param destination the destination folder. - * @return info about the moved item. + * @return info about the user who created the item. */ - public abstract BoxItem.Info move(BoxFolder destination); + public BoxUser.Info getCreatedBy() { + return this.createdBy; + } /** - * Moves this item to another folder and gives it a new name. + * Gets info about the user who last modified the item. * - * @param destination the destination folder. - * @param newName a new name for the moved item. - * @return info about the moved item. + * @return info about the user who last modified the item. */ - public abstract BoxItem.Info move(BoxFolder destination, String newName); + public BoxUser.Info getModifiedBy() { + return this.modifiedBy; + } /** - * Gets information about this item that's limited to a list of specified fields. + * Gets the time that the item was trashed. * - * @param fields the fields to retrieve. - * @return info about this item containing only the specified fields. + * @return the time that the item was trashed. */ - public abstract BoxItem.Info getInfo(String... fields); + public Date getTrashedAt() { + return this.trashedAt; + } /** - * Sets the collections that this item belongs to. + * Gets the time that the item was purged from the trash. * - * @param collections the collections that this item should belong to. - * @return info about the item, including the collections it belongs to. + * @return the time that the item was purged from the trash. */ - public abstract BoxItem.Info setCollections(BoxCollection... collections); + public Date getPurgedAt() { + return this.purgedAt; + } /** - * Contains information about a BoxItem. + * Gets the time that the item was created according to the uploader. + * + * @return the time that the item was created according to the uploader. */ - public abstract class Info extends BoxResource.Info { - private String type; - private String sequenceID; - private String etag; - private String name; - private Date createdAt; - private Date modifiedAt; - private String description; - private long size; - private List pathCollection; - private BoxUser.Info createdBy; - private BoxUser.Info modifiedBy; - private Date trashedAt; - private Date purgedAt; - private Date contentCreatedAt; - private Date contentModifiedAt; - private BoxUser.Info ownedBy; - private BoxSharedLink sharedLink; - private List tags; - private BoxFolder.Info parent; - private String itemStatus; - private Date expiresAt; - private Set collections; - private String downloadUrl; - - /** - * Constructs an empty Info object. - */ - public Info() { - super(); - } - - /** - * Constructs an Info object by parsing information from a JSON string. - * - * @param json the JSON string to parse. - */ - public Info(String json) { - super(json); - } - - /** - * Constructs an Info object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - Info(JsonObject jsonObject) { - super(jsonObject); - } - - /** - * Gets the item type. - * - * @return the item's type. - */ - public String getType() { - return this.type; - } - - /** - * Gets a unique string identifying the version of the item. - * - * @return a unique string identifying the version of the item. - */ - public String getEtag() { - return this.etag; - } - - /** - * Gets the name of the item. - * - * @return the name of the item. - */ - public String getName() { - return this.name; - } - - /** - * Sets the name of the item. - * - * @param name the new name of the item. - */ - public void setName(String name) { - this.name = name; - this.addPendingChange("name", name); - } - - /** - * Gets the time the item was created. - * - * @return the time the item was created. - */ - public Date getCreatedAt() { - return this.createdAt; - } - - /** - * Gets the time the item was last modified. - * - * @return the time the item was last modified. - */ - public Date getModifiedAt() { - return this.modifiedAt; - } - - /** - * Gets the description of the item. - * - * @return the description of the item. - */ - public String getDescription() { - return this.description; - } - - /** - * Sets the description of the item. - * - * @param description the new description of the item. - */ - public void setDescription(String description) { - this.description = description; - this.addPendingChange("description", description); - } - - /** - * Gets the size of the item in bytes. - * - * @return the size of the item in bytes. - */ - public long getSize() { - return this.size; - } - - /** - * Gets the path of folders to the item, starting at the root. - * - * @return the path of folders to the item. - */ - public List getPathCollection() { - return this.pathCollection; - } - - /** - * Gets info about the user who created the item. - * - * @return info about the user who created the item. - */ - public BoxUser.Info getCreatedBy() { - return this.createdBy; - } - - /** - * Gets info about the user who last modified the item. - * - * @return info about the user who last modified the item. - */ - public BoxUser.Info getModifiedBy() { - return this.modifiedBy; - } - - /** - * Gets the time that the item was trashed. - * - * @return the time that the item was trashed. - */ - public Date getTrashedAt() { - return this.trashedAt; - } - - /** - * Gets the time that the item was purged from the trash. - * - * @return the time that the item was purged from the trash. - */ - public Date getPurgedAt() { - return this.purgedAt; - } + public Date getContentCreatedAt() { + return this.contentCreatedAt; + } - /** - * Gets the time that the item was created according to the uploader. - * - * @return the time that the item was created according to the uploader. - */ - public Date getContentCreatedAt() { - return this.contentCreatedAt; - } + /** + * Gets the time that the item was last modified according to the uploader. + * + * @return the time that the item was last modified according to the uploader. + */ + public Date getContentModifiedAt() { + return this.contentModifiedAt; + } - /** - * Gets the time that the item was last modified according to the uploader. - * - * @return the time that the item was last modified according to the uploader. - */ - public Date getContentModifiedAt() { - return this.contentModifiedAt; - } + /** + * Gets the expires at time for this item. + * + * @return the time that the item will expire at. + */ + public Date getExpiresAt() { + return this.expiresAt; + } - /** - * Gets the expires at time for this item. - * - * @return the time that the item will expire at. - */ - public Date getExpiresAt() { - return this.expiresAt; - } + /** + * Gets info about the user who owns the item. + * + * @return info about the user who owns the item. + */ + public BoxUser.Info getOwnedBy() { + return this.ownedBy; + } - /** - * Gets info about the user who owns the item. - * - * @return info about the user who owns the item. - */ - public BoxUser.Info getOwnedBy() { - return this.ownedBy; - } + /** + * Gets the shared link for the item. + * + * @return the shared link for the item. + */ + public BoxSharedLink getSharedLink() { + return this.sharedLink; + } - /** - * Gets the shared link for the item. - * - * @return the shared link for the item. - */ - public BoxSharedLink getSharedLink() { - return this.sharedLink; - } + /** + * Sets a shared link for the item. + * + * @param sharedLink the shared link for the item. + */ + public void setSharedLink(BoxSharedLink sharedLink) { + this.removeChildObject("shared_link"); + this.sharedLink = sharedLink; + this.addChildObject("shared_link", sharedLink); + } - /** - * Sets a shared link for the item. - * - * @param sharedLink the shared link for the item. - */ - public void setSharedLink(BoxSharedLink sharedLink) { - this.removeChildObject("shared_link"); - this.sharedLink = sharedLink; - this.addChildObject("shared_link", sharedLink); - } + /** Removes the shared link for the item. */ + public void removeSharedLink() { + this.addChildObject("shared_link", null); + } - /** - * Removes the shared link for the item. - */ - public void removeSharedLink() { - this.addChildObject("shared_link", null); - } + /** + * Gets a unique ID for use with the {@link EventStream}. + * + * @return a unique ID for use with the EventStream. + */ + public String getSequenceID() { + return this.sequenceID; + } - /** - * Gets a unique ID for use with the {@link EventStream}. - * - * @return a unique ID for use with the EventStream. - */ - public String getSequenceID() { - return this.sequenceID; - } + /** + * Gets a list of all the tags applied to the item. + * + *

Note that this field isn't populated by default and must be specified as a field parameter + * when getting Info about the item. + * + * @return a list of all the tags applied to the item. + */ + public List getTags() { + return this.tags; + } - /** - * Gets a list of all the tags applied to the item. - * - *

Note that this field isn't populated by default and must be specified as a field parameter when getting - * Info about the item.

- * - * @return a list of all the tags applied to the item. - */ - public List getTags() { - return this.tags; - } + /** + * Sets the tags for an item. + * + * @param tags The new tags for the item. + */ + public void setTags(List tags) { + this.tags = tags; + JsonArray tagsJSON = new JsonArray(); + for (String tag : tags) { + tagsJSON.add(tag); + } + this.addPendingChange("tags", tagsJSON); + } - /** - * Sets the tags for an item. - * - * @param tags The new tags for the item. - */ - public void setTags(List tags) { - this.tags = tags; - JsonArray tagsJSON = new JsonArray(); - for (String tag : tags) { - tagsJSON.add(tag); - } - this.addPendingChange("tags", tagsJSON); - } + /** + * Gets info about the parent folder of the item. + * + * @return info about the parent folder of the item. + */ + public BoxFolder.Info getParent() { + return this.parent; + } - /** - * Gets info about the parent folder of the item. - * - * @return info about the parent folder of the item. - */ - public BoxFolder.Info getParent() { - return this.parent; - } + /** + * Gets the status of the item. + * + * @return the status of the item. + */ + public String getItemStatus() { + return this.itemStatus; + } - /** - * Gets the status of the item. - * - * @return the status of the item. - */ - public String getItemStatus() { - return this.itemStatus; - } + /** + * Gets info about the collections that this item belongs to. + * + * @return info about the collections that this item belongs to. + */ + public Iterable getCollections() { + return this.collections; + } - /** - * Gets info about the collections that this item belongs to. - * - * @return info about the collections that this item belongs to. - */ - public Iterable getCollections() { - return this.collections; - } + /** + * * Gets URL that can be used to download the file. + * + * @return + */ + public String getDownloadUrl() { + return this.downloadUrl; + } - /*** - * Gets URL that can be used to download the file. - * @return - */ - public String getDownloadUrl() { - return this.downloadUrl; - } + /** + * Sets the collections that this item belongs to. + * + * @param collections the new list of collections that this item should belong to. + */ + public void setCollections(Iterable collections) { + if (this.collections == null) { + this.collections = new HashSet<>(); + } else { + this.collections.clear(); + } + + JsonArray jsonArray = new JsonArray(); + for (BoxCollection collection : collections) { + JsonObject jsonObject = new JsonObject(); + jsonObject.add("id", collection.getID()); + jsonArray.add(jsonObject); + this.collections.add(collection.new Info()); + } + this.addPendingChange("collections", jsonArray); + } - /** - * Sets the collections that this item belongs to. - * - * @param collections the new list of collections that this item should belong to. - */ - public void setCollections(Iterable collections) { - if (this.collections == null) { - this.collections = new HashSet<>(); + @Override + protected void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + JsonValue value = member.getValue(); + String memberName = member.getName(); + + try { + switch (memberName) { + case "sequence_id": + this.sequenceID = value.asString(); + break; + case "type": + this.type = value.asString(); + break; + case "etag": + this.etag = value.asString(); + break; + case "name": + this.name = value.asString(); + break; + case "created_at": + this.createdAt = BoxDateFormat.parse(value.asString()); + break; + case "modified_at": + this.modifiedAt = BoxDateFormat.parse(value.asString()); + break; + case "description": + this.description = value.asString(); + break; + case "size": + this.size = Double.valueOf(value.toString()).longValue(); + break; + case "trashed_at": + this.trashedAt = BoxDateFormat.parse(value.asString()); + break; + case "purged_at": + this.purgedAt = BoxDateFormat.parse(value.asString()); + break; + case "content_created_at": + this.contentCreatedAt = BoxDateFormat.parse(value.asString()); + break; + case "content_modified_at": + this.contentModifiedAt = BoxDateFormat.parse(value.asString()); + break; + case "expires_at": + this.expiresAt = BoxDateFormat.parse(value.asString()); + break; + case "path_collection": + this.pathCollection = this.parsePathCollection(value.asObject()); + break; + case "created_by": + this.createdBy = this.parseUserInfo(value.asObject()); + break; + case "modified_by": + this.modifiedBy = this.parseUserInfo(value.asObject()); + break; + case "owned_by": + this.ownedBy = this.parseUserInfo(value.asObject()); + break; + case "shared_link": + if (this.sharedLink == null) { + this.setSharedLink(new BoxSharedLink(value.asObject())); } else { - this.collections.clear(); + this.sharedLink.update(value.asObject()); } - - JsonArray jsonArray = new JsonArray(); - for (BoxCollection collection : collections) { - JsonObject jsonObject = new JsonObject(); - jsonObject.add("id", collection.getID()); - jsonArray.add(jsonObject); - this.collections.add(collection.new Info()); + break; + case "tags": + this.tags = this.parseTags(value.asArray()); + break; + case "parent": + JsonObject parentObject = value.asObject(); + if (this.parent == null) { + String id = parentObject.get("id").asString(); + BoxFolder parentFolder = new BoxFolder(getAPI(), id); + this.parent = parentFolder.new Info(parentObject); + } else { + this.parent.update(parentObject); } - this.addPendingChange("collections", jsonArray); - } - - @Override - protected void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - JsonValue value = member.getValue(); - String memberName = member.getName(); - - try { - switch (memberName) { - case "sequence_id": - this.sequenceID = value.asString(); - break; - case "type": - this.type = value.asString(); - break; - case "etag": - this.etag = value.asString(); - break; - case "name": - this.name = value.asString(); - break; - case "created_at": - this.createdAt = BoxDateFormat.parse(value.asString()); - break; - case "modified_at": - this.modifiedAt = BoxDateFormat.parse(value.asString()); - break; - case "description": - this.description = value.asString(); - break; - case "size": - this.size = Double.valueOf(value.toString()).longValue(); - break; - case "trashed_at": - this.trashedAt = BoxDateFormat.parse(value.asString()); - break; - case "purged_at": - this.purgedAt = BoxDateFormat.parse(value.asString()); - break; - case "content_created_at": - this.contentCreatedAt = BoxDateFormat.parse(value.asString()); - break; - case "content_modified_at": - this.contentModifiedAt = BoxDateFormat.parse(value.asString()); - break; - case "expires_at": - this.expiresAt = BoxDateFormat.parse(value.asString()); - break; - case "path_collection": - this.pathCollection = this.parsePathCollection(value.asObject()); - break; - case "created_by": - this.createdBy = this.parseUserInfo(value.asObject()); - break; - case "modified_by": - this.modifiedBy = this.parseUserInfo(value.asObject()); - break; - case "owned_by": - this.ownedBy = this.parseUserInfo(value.asObject()); - break; - case "shared_link": - if (this.sharedLink == null) { - this.setSharedLink(new BoxSharedLink(value.asObject())); - } else { - this.sharedLink.update(value.asObject()); - } - break; - case "tags": - this.tags = this.parseTags(value.asArray()); - break; - case "parent": - JsonObject parentObject = value.asObject(); - if (this.parent == null) { - String id = parentObject.get("id").asString(); - BoxFolder parentFolder = new BoxFolder(getAPI(), id); - this.parent = parentFolder.new Info(parentObject); - } else { - this.parent.update(parentObject); - } - break; - case "item_status": - this.itemStatus = value.asString(); - break; - case "collections": - if (this.collections == null) { - this.collections = new HashSet<>(); - } else { - this.collections.clear(); - } - - BoxAPIConnection api = getAPI(); - JsonArray jsonArray = value.asArray(); - for (JsonValue arrayValue : jsonArray) { - JsonObject jsonObject = arrayValue.asObject(); - String id = jsonObject.get("id").asString(); - BoxCollection collection = new BoxCollection(api, id); - BoxCollection.Info collectionInfo = collection.new Info(jsonObject); - this.collections.add(collectionInfo); - } - break; - case "download_url": - this.downloadUrl = value.asString(); - break; - default: - break; - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); + break; + case "item_status": + this.itemStatus = value.asString(); + break; + case "collections": + if (this.collections == null) { + this.collections = new HashSet<>(); + } else { + this.collections.clear(); } - } - private List parsePathCollection(JsonObject jsonObject) { - int count = jsonObject.get("total_count").asInt(); - List pathCollection = new ArrayList<>(count); - JsonArray entries = jsonObject.get("entries").asArray(); - for (JsonValue value : entries) { - JsonObject entry = value.asObject(); - String id = entry.get("id").asString(); - BoxFolder folder = new BoxFolder(getAPI(), id); - pathCollection.add(folder.new Info(entry)); + BoxAPIConnection api = getAPI(); + JsonArray jsonArray = value.asArray(); + for (JsonValue arrayValue : jsonArray) { + JsonObject jsonObject = arrayValue.asObject(); + String id = jsonObject.get("id").asString(); + BoxCollection collection = new BoxCollection(api, id); + BoxCollection.Info collectionInfo = collection.new Info(jsonObject); + this.collections.add(collectionInfo); } + break; + case "download_url": + this.downloadUrl = value.asString(); + break; + default: + break; + } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); + } + } - return pathCollection; - } + private List parsePathCollection(JsonObject jsonObject) { + int count = jsonObject.get("total_count").asInt(); + List pathCollection = new ArrayList<>(count); + JsonArray entries = jsonObject.get("entries").asArray(); + for (JsonValue value : entries) { + JsonObject entry = value.asObject(); + String id = entry.get("id").asString(); + BoxFolder folder = new BoxFolder(getAPI(), id); + pathCollection.add(folder.new Info(entry)); + } + + return pathCollection; + } - private BoxUser.Info parseUserInfo(JsonObject jsonObject) { - String userID = jsonObject.get("id").asString(); - BoxUser user = new BoxUser(getAPI(), userID); - return user.new Info(jsonObject); - } + private BoxUser.Info parseUserInfo(JsonObject jsonObject) { + String userID = jsonObject.get("id").asString(); + BoxUser user = new BoxUser(getAPI(), userID); + return user.new Info(jsonObject); + } - private List parseTags(JsonArray jsonArray) { - List tags = new ArrayList<>(jsonArray.size()); - for (JsonValue value : jsonArray) { - tags.add(value.asString()); - } + private List parseTags(JsonArray jsonArray) { + List tags = new ArrayList<>(jsonArray.size()); + for (JsonValue value : jsonArray) { + tags.add(value.asString()); + } - return tags; - } + return tags; } + } } diff --git a/src/main/java/com/box/sdk/BoxItemIterator.java b/src/main/java/com/box/sdk/BoxItemIterator.java index cfd17e015..546165f85 100644 --- a/src/main/java/com/box/sdk/BoxItemIterator.java +++ b/src/main/java/com/box/sdk/BoxItemIterator.java @@ -7,56 +7,57 @@ import java.util.Iterator; class BoxItemIterator implements Iterator { - private static final long LIMIT = 1000; - - private final BoxAPIConnection api; - private final JsonIterator iterator; - - BoxItemIterator(BoxAPIConnection api, URL url, PagingParameters pagingParameters) { - this.api = api; - this.iterator = new JsonIterator(api, url, pagingParameters); - this.iterator.setFilter(jsonObject -> { - String type = jsonObject.get("type").asString(); - return (type.equals("file") || type.equals("folder") || type.equals("web_link")); + private static final long LIMIT = 1000; + + private final BoxAPIConnection api; + private final JsonIterator iterator; + + BoxItemIterator(BoxAPIConnection api, URL url, PagingParameters pagingParameters) { + this.api = api; + this.iterator = new JsonIterator(api, url, pagingParameters); + this.iterator.setFilter( + jsonObject -> { + String type = jsonObject.get("type").asString(); + return (type.equals("file") || type.equals("folder") || type.equals("web_link")); }); + } + + BoxItemIterator(BoxAPIConnection api, URL url) { + this(api, url, offset(0, LIMIT)); + } + + BoxItemIterator(BoxAPIConnection api, URL url, long limit, long offset) { + this(api, url, offset(offset, limit)); + } + + public boolean hasNext() { + return this.iterator.hasNext(); + } + + public BoxItem.Info next() { + JsonObject nextJSONObject = this.iterator.next(); + String type = nextJSONObject.get("type").asString(); + String id = nextJSONObject.get("id").asString(); + + BoxItem.Info nextItemInfo; + if (type.equals("folder")) { + BoxFolder folder = new BoxFolder(this.api, id); + nextItemInfo = folder.new Info(nextJSONObject); + } else if (type.equals("file")) { + BoxFile file = new BoxFile(this.api, id); + nextItemInfo = file.new Info(nextJSONObject); + } else if (type.equals("web_link")) { + BoxWebLink link = new BoxWebLink(this.api, id); + nextItemInfo = link.new Info(nextJSONObject); + } else { + assert false : "Unsupported item type: " + type; + throw new BoxAPIException("Unsupported item type: " + type); } - BoxItemIterator(BoxAPIConnection api, URL url) { - this(api, url, offset(0, LIMIT)); - } - - BoxItemIterator(BoxAPIConnection api, URL url, long limit, long offset) { - this(api, url, offset(offset, limit)); - } - - public boolean hasNext() { - return this.iterator.hasNext(); - } + return nextItemInfo; + } - public BoxItem.Info next() { - JsonObject nextJSONObject = this.iterator.next(); - String type = nextJSONObject.get("type").asString(); - String id = nextJSONObject.get("id").asString(); - - BoxItem.Info nextItemInfo; - if (type.equals("folder")) { - BoxFolder folder = new BoxFolder(this.api, id); - nextItemInfo = folder.new Info(nextJSONObject); - } else if (type.equals("file")) { - BoxFile file = new BoxFile(this.api, id); - nextItemInfo = file.new Info(nextJSONObject); - } else if (type.equals("web_link")) { - BoxWebLink link = new BoxWebLink(this.api, id); - nextItemInfo = link.new Info(nextJSONObject); - } else { - assert false : "Unsupported item type: " + type; - throw new BoxAPIException("Unsupported item type: " + type); - } - - return nextItemInfo; - } - - public void remove() { - throw new UnsupportedOperationException(); - } + public void remove() { + throw new UnsupportedOperationException(); + } } diff --git a/src/main/java/com/box/sdk/BoxJSONObject.java b/src/main/java/com/box/sdk/BoxJSONObject.java index 6b7caf6db..e2d58f34d 100644 --- a/src/main/java/com/box/sdk/BoxJSONObject.java +++ b/src/main/java/com/box/sdk/BoxJSONObject.java @@ -8,232 +8,230 @@ import java.util.Map; /** - * The abstract base class for all types that contain JSON data returned by the Box API. The most common implementation - * of BoxJSONObject is {@link BoxResource.Info} and its subclasses. Changes made to a BoxJSONObject will be tracked - * locally until the pending changes are sent back to Box in order to avoid unnecessary network requests. + * The abstract base class for all types that contain JSON data returned by the Box API. The most + * common implementation of BoxJSONObject is {@link BoxResource.Info} and its subclasses. Changes + * made to a BoxJSONObject will be tracked locally until the pending changes are sent back to Box in + * order to avoid unnecessary network requests. */ public abstract class BoxJSONObject { - /** - * A map of other BoxJSONObjects which will be lazily converted to a JsonObject once getPendingChanges is called. - * This allows changes to be made to a child BoxJSONObject and still have those changes reflected in the JSON - * string. - */ - private final Map children; - /** - * The JsonObject that contains any local pending changes. When getPendingChanges is called, this object will be - * encoded to a JSON string. - */ - private JsonObject pendingChanges; - /** - * The current JSON object. - */ - private JsonObject jsonObject; - - /** - * Constructs an empty BoxJSONObject. - */ - public BoxJSONObject() { - this.children = new HashMap(); - } - - /** - * Constructs a BoxJSONObject by decoding it from a JSON string. - * - * @param json the JSON string to decode. - */ - public BoxJSONObject(String json) { - this(Json.parse(json).asObject()); - } - - /** - * Constructs a BoxJSONObject using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - BoxJSONObject(JsonObject jsonObject) { - this(); - - this.update(jsonObject); - } - - /** - * Clears any pending changes from this JSON object. - */ - public void clearPendingChanges() { - this.pendingChanges = null; - } - - /** - * Gets a JSON string containing any pending changes to this object that can be sent back to the Box API. - * - * @return a JSON string containing the pending changes. - */ - public String getPendingChanges() { - JsonObject jsonObject = this.getPendingJSONObject(); - if (jsonObject == null) { - return null; - } - - return jsonObject.toString(); - } - - /** - * Gets a JSON string containing any pending changes to this object that can be sent back to the Box API. - * - * @return a JSON string containing the pending changes. - */ - public JsonObject getPendingChangesAsJsonObject() { - return this.getPendingJSONObject(); - } - - /** - * Invoked with a JSON member whenever this object is updated or created from a JSON object. - * - *

Subclasses should override this method in order to parse any JSON members it knows about. This method is a - * no-op by default.

- * - * @param member the JSON member to be parsed. - */ - void parseJSONMember(JsonObject.Member member) { - } - - /** - * Adds a pending field change that needs to be sent to the API. It will be included in the JSON string the next - * time {@link #getPendingChanges} is called. - * - * @param key the name of the field. - * @param value the new boolean value of the field. - */ - void addPendingChange(String key, boolean value) { - if (this.pendingChanges == null) { - this.pendingChanges = new JsonObject(); - } - - this.pendingChanges.set(key, value); - } - - /** - * Adds a pending field change that needs to be sent to the API. It will be included in the JSON string the next - * time {@link #getPendingChanges} is called. - * - * @param key the name of the field. - * @param value the new String value of the field. - */ - void addPendingChange(String key, String value) { - this.addPendingChange(key, Json.value(value)); - } - - /** - * Adds a pending field change that needs to be sent to the API. It will be included in the JSON string the next - * time {@link #getPendingChanges} is called. - * - * @param key the name of the field. - * @param value the new long value of the field. - */ - void addPendingChange(String key, long value) { - this.addPendingChange(key, Json.value(value)); - } - - /** - * Adds a pending field change that needs to be sent to the API. It will be included in the JSON string the next - * time {@link #getPendingChanges} is called. - * - * @param key the name of the field. - * @param value the new JsonArray value of the field. - */ - void addPendingChange(String key, JsonArray value) { - this.addPendingChange(key, (JsonValue) value); - } - - /** - * Adds a pending field change that needs to be sent to the API. It will be included in the JSON string the next - * time {@link #getPendingChanges} is called. - * - * @param key the name of the field. - * @param value the new JsonObject value of the field. - */ - void addPendingChange(String key, JsonObject value) { - this.addPendingChange(key, (JsonValue) value); - } - - void addChildObject(String fieldName, BoxJSONObject child) { - if (child == null) { - this.addPendingChange(fieldName, Json.NULL); - } else { - this.children.put(fieldName, child); - } - } - - void removeChildObject(String fieldName) { - this.children.remove(fieldName); - } - - /** - * Adds a pending field change that needs to be sent to the API. It will be included in the JSON string the next - * time {@link #getPendingChanges} is called. - * - * @param key the name of the field. - * @param value the JsonValue of the field. - */ - private void addPendingChange(String key, JsonValue value) { + /** + * A map of other BoxJSONObjects which will be lazily converted to a JsonObject once + * getPendingChanges is called. This allows changes to be made to a child BoxJSONObject and still + * have those changes reflected in the JSON string. + */ + private final Map children; + /** + * The JsonObject that contains any local pending changes. When getPendingChanges is called, this + * object will be encoded to a JSON string. + */ + private JsonObject pendingChanges; + /** The current JSON object. */ + private JsonObject jsonObject; + + /** Constructs an empty BoxJSONObject. */ + public BoxJSONObject() { + this.children = new HashMap(); + } + + /** + * Constructs a BoxJSONObject by decoding it from a JSON string. + * + * @param json the JSON string to decode. + */ + public BoxJSONObject(String json) { + this(Json.parse(json).asObject()); + } + + /** + * Constructs a BoxJSONObject using an already parsed JSON object. + * + * @param jsonObject the parsed JSON object. + */ + BoxJSONObject(JsonObject jsonObject) { + this(); + + this.update(jsonObject); + } + + /** Clears any pending changes from this JSON object. */ + public void clearPendingChanges() { + this.pendingChanges = null; + } + + /** + * Gets a JSON string containing any pending changes to this object that can be sent back to the + * Box API. + * + * @return a JSON string containing the pending changes. + */ + public String getPendingChanges() { + JsonObject jsonObject = this.getPendingJSONObject(); + if (jsonObject == null) { + return null; + } + + return jsonObject.toString(); + } + + /** + * Gets a JSON string containing any pending changes to this object that can be sent back to the + * Box API. + * + * @return a JSON string containing the pending changes. + */ + public JsonObject getPendingChangesAsJsonObject() { + return this.getPendingJSONObject(); + } + + /** + * Invoked with a JSON member whenever this object is updated or created from a JSON object. + * + *

Subclasses should override this method in order to parse any JSON members it knows about. + * This method is a no-op by default. + * + * @param member the JSON member to be parsed. + */ + void parseJSONMember(JsonObject.Member member) {} + + /** + * Adds a pending field change that needs to be sent to the API. It will be included in the JSON + * string the next time {@link #getPendingChanges} is called. + * + * @param key the name of the field. + * @param value the new boolean value of the field. + */ + void addPendingChange(String key, boolean value) { + if (this.pendingChanges == null) { + this.pendingChanges = new JsonObject(); + } + + this.pendingChanges.set(key, value); + } + + /** + * Adds a pending field change that needs to be sent to the API. It will be included in the JSON + * string the next time {@link #getPendingChanges} is called. + * + * @param key the name of the field. + * @param value the new String value of the field. + */ + void addPendingChange(String key, String value) { + this.addPendingChange(key, Json.value(value)); + } + + /** + * Adds a pending field change that needs to be sent to the API. It will be included in the JSON + * string the next time {@link #getPendingChanges} is called. + * + * @param key the name of the field. + * @param value the new long value of the field. + */ + void addPendingChange(String key, long value) { + this.addPendingChange(key, Json.value(value)); + } + + /** + * Adds a pending field change that needs to be sent to the API. It will be included in the JSON + * string the next time {@link #getPendingChanges} is called. + * + * @param key the name of the field. + * @param value the new JsonArray value of the field. + */ + void addPendingChange(String key, JsonArray value) { + this.addPendingChange(key, (JsonValue) value); + } + + /** + * Adds a pending field change that needs to be sent to the API. It will be included in the JSON + * string the next time {@link #getPendingChanges} is called. + * + * @param key the name of the field. + * @param value the new JsonObject value of the field. + */ + void addPendingChange(String key, JsonObject value) { + this.addPendingChange(key, (JsonValue) value); + } + + void addChildObject(String fieldName, BoxJSONObject child) { + if (child == null) { + this.addPendingChange(fieldName, Json.NULL); + } else { + this.children.put(fieldName, child); + } + } + + void removeChildObject(String fieldName) { + this.children.remove(fieldName); + } + + /** + * Adds a pending field change that needs to be sent to the API. It will be included in the JSON + * string the next time {@link #getPendingChanges} is called. + * + * @param key the name of the field. + * @param value the JsonValue of the field. + */ + private void addPendingChange(String key, JsonValue value) { + if (this.pendingChanges == null) { + this.pendingChanges = new JsonObject(); + } + + this.pendingChanges.set(key, value); + } + + void removePendingChange(String key) { + if (this.pendingChanges != null) { + this.pendingChanges.remove(key); + } + } + + /** + * Updates this BoxJSONObject using the information in a JSON object and preserves the JSON + * object. + * + * @param jsonObject the JSON object containing updated information. + */ + void update(JsonObject jsonObject) { + this.jsonObject = jsonObject; + + for (JsonObject.Member member : jsonObject) { + if (member.getValue().isNull()) { + continue; + } + + this.parseJSONMember(member); + } + + this.clearPendingChanges(); + } + + /** + * Gets a JsonObject containing any pending changes to this object that can be sent back to the + * Box API. + * + * @return a JsonObject containing the pending changes. + */ + protected JsonObject getPendingJSONObject() { + for (Map.Entry entry : this.children.entrySet()) { + BoxJSONObject child = entry.getValue(); + JsonObject jsonObject = child.getPendingJSONObject(); + if (jsonObject != null) { if (this.pendingChanges == null) { - this.pendingChanges = new JsonObject(); - } - - this.pendingChanges.set(key, value); - } - - void removePendingChange(String key) { - if (this.pendingChanges != null) { - this.pendingChanges.remove(key); - } - } - - /** - * Updates this BoxJSONObject using the information in a JSON object and preserves the JSON object. - * - * @param jsonObject the JSON object containing updated information. - */ - void update(JsonObject jsonObject) { - this.jsonObject = jsonObject; - - for (JsonObject.Member member : jsonObject) { - if (member.getValue().isNull()) { - continue; - } - - this.parseJSONMember(member); + this.pendingChanges = new JsonObject(); } - this.clearPendingChanges(); - } - - /** - * Gets a JsonObject containing any pending changes to this object that can be sent back to the Box API. - * - * @return a JsonObject containing the pending changes. - */ - protected JsonObject getPendingJSONObject() { - for (Map.Entry entry : this.children.entrySet()) { - BoxJSONObject child = entry.getValue(); - JsonObject jsonObject = child.getPendingJSONObject(); - if (jsonObject != null) { - if (this.pendingChanges == null) { - this.pendingChanges = new JsonObject(); - } - - this.pendingChanges.set(entry.getKey(), jsonObject); - } - } - return this.pendingChanges; + this.pendingChanges.set(entry.getKey(), jsonObject); + } } + return this.pendingChanges; + } - /** - * Converts the JSON object into a string literal. - * - * @return a string representation of the JSON object. - */ - public String getJson() { - return this.jsonObject.toString(); - } + /** + * Converts the JSON object into a string literal. + * + * @return a string representation of the JSON object. + */ + public String getJson() { + return this.jsonObject.toString(); + } } diff --git a/src/main/java/com/box/sdk/BoxJSONRequest.java b/src/main/java/com/box/sdk/BoxJSONRequest.java index f53b2df17..f596b2360 100644 --- a/src/main/java/com/box/sdk/BoxJSONRequest.java +++ b/src/main/java/com/box/sdk/BoxJSONRequest.java @@ -11,111 +11,112 @@ /** * Used to make HTTP requests containing JSON to the Box API. * - *

This request type extends BoxAPIRequest to provide additional functionality for handling JSON strings. It - * automatically sets the appropriate "Content-Type" HTTP headers and allows the JSON in the request to be logged.

+ *

This request type extends BoxAPIRequest to provide additional functionality for handling JSON + * strings. It automatically sets the appropriate "Content-Type" HTTP headers and allows the JSON in + * the request to be logged. */ public class BoxJSONRequest extends BoxAPIRequest { - private JsonValue jsonValue; - - protected BoxJSONRequest(BoxAPIConnection api, URL url, String method, String mediaType) { - super(api, url, method, mediaType); - } - - /** - * Constructs an authenticated BoxJSONRequest using a provided BoxAPIConnection. - * - * @param api an API connection for authenticating the request. - * @param url the URL of the request. - * @param method the HTTP method of the request. - */ - public BoxJSONRequest(BoxAPIConnection api, URL url, String method) { - this(api, url, method, APPLICATION_JSON); - } - - /** - * Constructs an authenticated BoxJSONRequest using a provided BoxAPIConnection. - * - * @param api an API connection for authenticating the request. - * @param url the URL of the request. - * @param method the HTTP method of the request. - */ - public BoxJSONRequest(BoxAPIConnection api, URL url, HttpMethod method) { - this(api, url, method.name()); - } - - /** - * Constructs an authenticated BoxJSONRequest. - * - * @param url the URL of the request. - * @param method the HTTP method of the request. - */ - public BoxJSONRequest(URL url, HttpMethod method) { - this(null, url, method); - } - - /** - * Sets the body of this request to a given JSON string. - * - * @param body the JSON string to use as the body. - */ - @Override - public void setBody(String body) { - super.setBody(body); - this.jsonValue = Json.parse(body); - } - - /** - * Sets the body of this request to a given JsonObject. - * - * @param body the JsonObject to use as the body. - */ - public void setBody(JsonObject body) { - super.setBody(body.toString()); - this.jsonValue = body; - } - - /** - * Gets the body of this request as a JsonObject. - * - * @return body represented as JsonObject. - */ - public JsonObject getBodyAsJsonObject() { - if (this.jsonValue.isObject()) { - return this.jsonValue.asObject(); - } - - return null; - } - - /** - * Gets the body of this request as a {@link JsonValue}. - * - * @return body represented as JsonValue - */ - public JsonValue getBodyAsJsonValue() { - return this.jsonValue; + private JsonValue jsonValue; + + protected BoxJSONRequest(BoxAPIConnection api, URL url, String method, String mediaType) { + super(api, url, method, mediaType); + } + + /** + * Constructs an authenticated BoxJSONRequest using a provided BoxAPIConnection. + * + * @param api an API connection for authenticating the request. + * @param url the URL of the request. + * @param method the HTTP method of the request. + */ + public BoxJSONRequest(BoxAPIConnection api, URL url, String method) { + this(api, url, method, APPLICATION_JSON); + } + + /** + * Constructs an authenticated BoxJSONRequest using a provided BoxAPIConnection. + * + * @param api an API connection for authenticating the request. + * @param url the URL of the request. + * @param method the HTTP method of the request. + */ + public BoxJSONRequest(BoxAPIConnection api, URL url, HttpMethod method) { + this(api, url, method.name()); + } + + /** + * Constructs an authenticated BoxJSONRequest. + * + * @param url the URL of the request. + * @param method the HTTP method of the request. + */ + public BoxJSONRequest(URL url, HttpMethod method) { + this(null, url, method); + } + + /** + * Sets the body of this request to a given JSON string. + * + * @param body the JSON string to use as the body. + */ + @Override + public void setBody(String body) { + super.setBody(body); + this.jsonValue = Json.parse(body); + } + + /** + * Sets the body of this request to a given JsonObject. + * + * @param body the JsonObject to use as the body. + */ + public void setBody(JsonObject body) { + super.setBody(body.toString()); + this.jsonValue = body; + } + + /** + * Gets the body of this request as a JsonObject. + * + * @return body represented as JsonObject. + */ + public JsonObject getBodyAsJsonObject() { + if (this.jsonValue.isObject()) { + return this.jsonValue.asObject(); } - @Override - public BoxJSONResponse send() { - return convert(super.send()); + return null; + } + + /** + * Gets the body of this request as a {@link JsonValue}. + * + * @return body represented as JsonValue + */ + public JsonValue getBodyAsJsonValue() { + return this.jsonValue; + } + + @Override + public BoxJSONResponse send() { + return convert(super.send()); + } + + @Override + public BoxJSONResponse send(ProgressListener listener) { + return convert(super.send(listener)); + } + + private BoxJSONResponse convert(BoxAPIResponse response) { + if (response instanceof BoxJSONResponse) { + return (BoxJSONResponse) response; + } else { + return new BoxJSONResponse(response); } + } - @Override - public BoxJSONResponse send(ProgressListener listener) { - return convert(super.send(listener)); - } - - private BoxJSONResponse convert(BoxAPIResponse response) { - if (response instanceof BoxJSONResponse) { - return (BoxJSONResponse) response; - } else { - return new BoxJSONResponse(response); - } - } - - @Override - protected String bodyToString() { - return this.jsonValue != null ? this.jsonValue.toString() : null; - } + @Override + protected String bodyToString() { + return this.jsonValue != null ? this.jsonValue.toString() : null; + } } diff --git a/src/main/java/com/box/sdk/BoxJSONResponse.java b/src/main/java/com/box/sdk/BoxJSONResponse.java index e9247c6db..f2b5045a1 100644 --- a/src/main/java/com/box/sdk/BoxJSONResponse.java +++ b/src/main/java/com/box/sdk/BoxJSONResponse.java @@ -12,105 +12,110 @@ /** * Used to read HTTP responses containing JSON from the Box API. * - *

This request type extends BoxAPIResponse to provide additional functionality for handling JSON strings. It reads - * the response body into a string and allows the JSON in the response to be logged.

+ *

This request type extends BoxAPIResponse to provide additional functionality for handling JSON + * strings. It reads the response body into a string and allows the JSON in the response to be + * logged. */ public class BoxJSONResponse extends BoxAPIResponse { - private static final int BUFFER_SIZE = 8192; - private JsonObject jsonObject; + private static final int BUFFER_SIZE = 8192; + private JsonObject jsonObject; - /** - * Constructs a BoxJSONResponse without an associated HttpURLConnection. - */ - public BoxJSONResponse() { - super(); - } + /** Constructs a BoxJSONResponse without an associated HttpURLConnection. */ + public BoxJSONResponse() { + super(); + } - BoxJSONResponse(BoxAPIResponse response) { - this( - response.getResponseCode(), - response.getRequestMethod(), - response.getRequestUrl(), - response.getHeaders(), - new JsonObject() - ); - } + BoxJSONResponse(BoxAPIResponse response) { + this( + response.getResponseCode(), + response.getRequestMethod(), + response.getRequestUrl(), + response.getHeaders(), + new JsonObject()); + } - /** - * Constructs a BoxAPIResponse with an http response code and response body. - * - * @param responseCode http response code - * @param headers map of http headers - * @param body response body as Json Object - */ - public BoxJSONResponse(int responseCode, - String requestMethod, - String requestUrl, - Map> headers, - JsonObject body - ) { - super(responseCode, requestMethod, requestUrl, headers, body.toString(), ContentType.APPLICATION_JSON); - this.jsonObject = body; - } + /** + * Constructs a BoxAPIResponse with an http response code and response body. + * + * @param responseCode http response code + * @param headers map of http headers + * @param body response body as Json Object + */ + public BoxJSONResponse( + int responseCode, + String requestMethod, + String requestUrl, + Map> headers, + JsonObject body) { + super( + responseCode, + requestMethod, + requestUrl, + headers, + body.toString(), + ContentType.APPLICATION_JSON); + this.jsonObject = body; + } - /** - * Get response as Json Object. - * - * @return response as JsonObject - */ - public JsonObject getJsonObject() { - if (this.jsonObject != null) { - return this.jsonObject; - } else { - return Json.parse(this.getJSON()).asObject(); - } + /** + * Get response as Json Object. + * + * @return response as JsonObject + */ + public JsonObject getJsonObject() { + if (this.jsonObject != null) { + return this.jsonObject; + } else { + return Json.parse(this.getJSON()).asObject(); } + } - /** - * Gets the body of the response as a JSON string. When this method is called, the response's body will be read and - * the response will be disconnected, meaning that the stream returned by {@link #getBody} can no longer be used. - * - * @return the body of the response as a JSON string. - */ - public String getJSON() { - if (this.jsonObject != null) { - return this.jsonObject.toString(); - } else if (this.getBody() == null) { - return null; - } else { - InputStreamReader reader = new InputStreamReader(this.getBody(), StandardCharsets.UTF_8); - StringBuilder builder = new StringBuilder(); - char[] buffer = new char[BUFFER_SIZE]; + /** + * Gets the body of the response as a JSON string. When this method is called, the response's body + * will be read and the response will be disconnected, meaning that the stream returned by {@link + * #getBody} can no longer be used. + * + * @return the body of the response as a JSON string. + */ + public String getJSON() { + if (this.jsonObject != null) { + return this.jsonObject.toString(); + } else if (this.getBody() == null) { + return null; + } else { + InputStreamReader reader = new InputStreamReader(this.getBody(), StandardCharsets.UTF_8); + StringBuilder builder = new StringBuilder(); + char[] buffer = new char[BUFFER_SIZE]; - try { - int read = reader.read(buffer, 0, BUFFER_SIZE); - while (read != -1) { - builder.append(buffer, 0, read); - read = reader.read(buffer, 0, BUFFER_SIZE); - } - - this.close(); - reader.close(); - } catch (IOException e) { - throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e); - } - String jsonAsString = builder.toString(); - try { - this.jsonObject = Json.parse(jsonAsString).asObject(); - } catch (ParseException e) { - throw new RuntimeException("Error parsing JSON:\n" + jsonAsString, e); - } - return jsonAsString; + try { + int read = reader.read(buffer, 0, BUFFER_SIZE); + while (read != -1) { + builder.append(buffer, 0, read); + read = reader.read(buffer, 0, BUFFER_SIZE); } + + this.close(); + reader.close(); + } catch (IOException e) { + throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e); + } + String jsonAsString = builder.toString(); + try { + this.jsonObject = Json.parse(jsonAsString).asObject(); + } catch (ParseException e) { + throw new RuntimeException("Error parsing JSON:\n" + jsonAsString, e); + } + return jsonAsString; } + } - @Override - protected String bodyToString() { - String bodyString = super.bodyToString(); - if (bodyString == null) { - return this.getJSON(); - } else { - return bodyString; - } + @Override + protected String bodyToString() { + String bodyString = super.bodyToString(); + if (bodyString == null) { + return this.getJSON(); + } else { + return bodyString; } + } } diff --git a/src/main/java/com/box/sdk/BoxLegalHoldAssignment.java b/src/main/java/com/box/sdk/BoxLegalHoldAssignment.java index eb305d51c..c068d3e91 100644 --- a/src/main/java/com/box/sdk/BoxLegalHoldAssignment.java +++ b/src/main/java/com/box/sdk/BoxLegalHoldAssignment.java @@ -7,263 +7,221 @@ import java.util.Date; /** - * Represents a legal hold policy assignment. - * Legal hold assignments are used to assign legal hold policies to custodians, folders, files, or file versions. + * Represents a legal hold policy assignment. Legal hold assignments are used to assign legal hold + * policies to custodians, folders, files, or file versions. * - * @see Box legal holds - * - *

Unless otherwise noted, the methods in this class can throw an unchecked {@link BoxAPIException} (unchecked - * meaning that the compiler won't force you to handle it) if an error occurs. If you wish to implement custom error - * handling for errors related to the Box REST API, you should capture this exception explicitly.

+ * @see Box + * legal holds + *

Unless otherwise noted, the methods in this class can throw an unchecked {@link + * BoxAPIException} (unchecked meaning that the compiler won't force you to handle it) if an + * error occurs. If you wish to implement custom error handling for errors related to the Box + * REST API, you should capture this exception explicitly. */ @BoxResourceType("legal_hold_assignment") public class BoxLegalHoldAssignment extends BoxResource { - /** - * Used to assign legal hold policy to file version. - */ - public static final String TYPE_FILE_VERSION = BoxFileVersion.getResourceType(BoxFileVersion.class); + /** Used to assign legal hold policy to file version. */ + public static final String TYPE_FILE_VERSION = + BoxFileVersion.getResourceType(BoxFileVersion.class); + + /** Used to assign legal hold policy to file. */ + public static final String TYPE_FILE = BoxFile.getResourceType(BoxFile.class); + + /** Used to assign legal hold policy to folder. */ + public static final String TYPE_FOLDER = BoxFolder.getResourceType(BoxFolder.class); + + /** Used to assign legal hold policy to user. */ + public static final String TYPE_USER = BoxUser.getResourceType(BoxUser.class); + + /** The URL template used for operation with legal hold policy assignments. */ + public static final URLTemplate ASSIGNMENTS_URL_TEMPLATE = + new URLTemplate("legal_hold_policy_assignments"); + + /** The URL template used for operation with legal hold policy assignment with given ID. */ + public static final URLTemplate LEGAL_HOLD_ASSIGNMENT_URL_TEMPLATE = + new URLTemplate("legal_hold_policy_assignments/%s"); + + /** + * Constructs a BoxLegalHoldAssignment for a resource with a given ID. + * + * @param api the API connection to be used by the resource. + * @param id the ID of the resource. + */ + public BoxLegalHoldAssignment(BoxAPIConnection api, String id) { + super(api, id); + } + + /** + * Creates new legal hold policy assignment. + * + * @param api the API connection to be used by the resource. + * @param policyID ID of policy to create assignment for. + * @param resourceType type of target resource. Can be 'file_version', 'file', 'folder', or + * 'user'. + * @param resourceID ID of the target resource. + * @return info about created legal hold policy assignment. + */ + public static BoxLegalHoldAssignment.Info create( + BoxAPIConnection api, String policyID, String resourceType, String resourceID) { + URL url = ASSIGNMENTS_URL_TEMPLATE.build(api.getBaseURL()); + BoxJSONRequest request = new BoxJSONRequest(api, url, "POST"); + + JsonObject requestJSON = + new JsonObject() + .add("policy_id", policyID) + .add("assign_to", new JsonObject().add("type", resourceType).add("id", resourceID)); + request.setBody(requestJSON.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + BoxLegalHoldAssignment createdAssignment = + new BoxLegalHoldAssignment(api, responseJSON.get("id").asString()); + return createdAssignment.new Info(responseJSON); + } + } + + /** Deletes the legal hold policy assignment. */ + public void delete() { + URL url = LEGAL_HOLD_ASSIGNMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); + request.send().close(); + } + + /** + * @param fields the fields to retrieve. + * @return information about this retention policy. + */ + public BoxLegalHoldAssignment.Info getInfo(String... fields) { + QueryStringBuilder builder = new QueryStringBuilder(); + if (fields.length > 0) { + builder.appendParam("fields", fields); + } + URL url = + LEGAL_HOLD_ASSIGNMENT_URL_TEMPLATE.buildWithQuery( + this.getAPI().getBaseURL(), builder.toString(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + return new Info(responseJSON); + } + } - /** - * Used to assign legal hold policy to file. - */ - public static final String TYPE_FILE = BoxFile.getResourceType(BoxFile.class); + /** Contains information about the legal hold policy. */ + public class Info extends BoxResource.Info { - /** - * Used to assign legal hold policy to folder. - */ - public static final String TYPE_FOLDER = BoxFolder.getResourceType(BoxFolder.class); + /** @see #getLegalHold() */ + private BoxLegalHoldPolicy.Info legalHold; - /** - * Used to assign legal hold policy to user. - */ - public static final String TYPE_USER = BoxUser.getResourceType(BoxUser.class); + /** @see #getAssignedBy() */ + private BoxUser.Info assignedBy; - /** - * The URL template used for operation with legal hold policy assignments. - */ - public static final URLTemplate ASSIGNMENTS_URL_TEMPLATE = new URLTemplate("legal_hold_policy_assignments"); + /** @see #getAssignedAt() */ + private Date assignedAt; - /** - * The URL template used for operation with legal hold policy assignment with given ID. - */ - public static final URLTemplate LEGAL_HOLD_ASSIGNMENT_URL_TEMPLATE - = new URLTemplate("legal_hold_policy_assignments/%s"); + /** @see #getDeletedAt() */ + private Date deletedAt; - /** - * Constructs a BoxLegalHoldAssignment for a resource with a given ID. - * - * @param api the API connection to be used by the resource. - * @param id the ID of the resource. - */ - public BoxLegalHoldAssignment(BoxAPIConnection api, String id) { - super(api, id); - } + /** @see #getAssignedToType() */ + private String assignedToType; - /** - * Creates new legal hold policy assignment. - * - * @param api the API connection to be used by the resource. - * @param policyID ID of policy to create assignment for. - * @param resourceType type of target resource. Can be 'file_version', 'file', 'folder', or 'user'. - * @param resourceID ID of the target resource. - * @return info about created legal hold policy assignment. - */ - public static BoxLegalHoldAssignment.Info create(BoxAPIConnection api, - String policyID, String resourceType, String resourceID) { - URL url = ASSIGNMENTS_URL_TEMPLATE.build(api.getBaseURL()); - BoxJSONRequest request = new BoxJSONRequest(api, url, "POST"); + /** @see #getAssignedToID() */ + private String assignedToID; - JsonObject requestJSON = new JsonObject() - .add("policy_id", policyID) - .add("assign_to", new JsonObject() - .add("type", resourceType) - .add("id", resourceID)); - request.setBody(requestJSON.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - BoxLegalHoldAssignment createdAssignment = - new BoxLegalHoldAssignment(api, responseJSON.get("id").asString()); - return createdAssignment.new Info(responseJSON); - } + /** Constructs an empty Info object. */ + public Info() { + super(); } /** - * Deletes the legal hold policy assignment. + * Constructs an Info object by parsing information from a JSON string. + * + * @param json the JSON string to parse. */ - public void delete() { - URL url = LEGAL_HOLD_ASSIGNMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); - request.send().close(); + public Info(String json) { + super(json); } /** - * @param fields the fields to retrieve. - * @return information about this retention policy. + * Constructs an Info object using an already parsed JSON object. + * + * @param jsonObject the parsed JSON object. */ - public BoxLegalHoldAssignment.Info getInfo(String... fields) { - QueryStringBuilder builder = new QueryStringBuilder(); - if (fields.length > 0) { - builder.appendParam("fields", fields); - } - URL url = LEGAL_HOLD_ASSIGNMENT_URL_TEMPLATE.buildWithQuery( - this.getAPI().getBaseURL(), builder.toString(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - return new Info(responseJSON); - } + Info(JsonObject jsonObject) { + super(jsonObject); } - /** - * Contains information about the legal hold policy. - */ - public class Info extends BoxResource.Info { - - /** - * @see #getLegalHold() - */ - private BoxLegalHoldPolicy.Info legalHold; - - /** - * @see #getAssignedBy() - */ - private BoxUser.Info assignedBy; - - /** - * @see #getAssignedAt() - */ - private Date assignedAt; - - /** - * @see #getDeletedAt() - */ - private Date deletedAt; - - /** - * @see #getAssignedToType() - */ - private String assignedToType; - - /** - * @see #getAssignedToID() - */ - private String assignedToID; - - /** - * Constructs an empty Info object. - */ - public Info() { - super(); - } - - /** - * Constructs an Info object by parsing information from a JSON string. - * - * @param json the JSON string to parse. - */ - public Info(String json) { - super(json); - } - - /** - * Constructs an Info object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - Info(JsonObject jsonObject) { - super(jsonObject); - } - - /** - * {@inheritDoc} - */ - @Override - public BoxResource getResource() { - return BoxLegalHoldAssignment.this; - } + /** {@inheritDoc} */ + @Override + public BoxResource getResource() { + return BoxLegalHoldAssignment.this; + } - /** - * @return info about the policy that this legal hold policy assignment is part of. - */ - public BoxLegalHoldPolicy.Info getLegalHold() { - return this.legalHold; - } + /** @return info about the policy that this legal hold policy assignment is part of. */ + public BoxLegalHoldPolicy.Info getLegalHold() { + return this.legalHold; + } - /** - * @return the info about the user who created that legal hold policy assignment. - */ - public BoxUser.Info getAssignedBy() { - return this.assignedBy; - } + /** @return the info about the user who created that legal hold policy assignment. */ + public BoxUser.Info getAssignedBy() { + return this.assignedBy; + } - /** - * @return the time that the legal hold policy assignment was created. - */ - public Date getAssignedAt() { - return this.assignedAt; - } + /** @return the time that the legal hold policy assignment was created. */ + public Date getAssignedAt() { + return this.assignedAt; + } - /** - * @return the time that the assignment release request was sent. - */ - public Date getDeletedAt() { - return this.deletedAt; - } + /** @return the time that the assignment release request was sent. */ + public Date getDeletedAt() { + return this.deletedAt; + } - /** - * @return the entity type that this is assigned to. - */ - public String getAssignedToType() { - return this.assignedToType; - } + /** @return the entity type that this is assigned to. */ + public String getAssignedToType() { + return this.assignedToType; + } - /** - * @return the entity id that this is assigned to. - */ - public String getAssignedToID() { - return this.assignedToID; - } + /** @return the entity id that this is assigned to. */ + public String getAssignedToID() { + return this.assignedToID; + } - /** - * {@inheritDoc} - */ - @Override - void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - String memberName = member.getName(); - JsonValue value = member.getValue(); - try { - if (memberName.equals("legal_hold_policy")) { - JsonObject policyJSON = value.asObject(); - if (this.legalHold == null) { - String policyID = policyJSON.get("id").asString(); - BoxLegalHoldPolicy policy = new BoxLegalHoldPolicy(getAPI(), policyID); - this.legalHold = policy.new Info(policyJSON); - } else { - this.legalHold.update(policyJSON); - } - } else if (memberName.equals("assigned_to")) { - JsonObject assignmentJSON = value.asObject(); - this.assignedToType = assignmentJSON.get("type").asString(); - this.assignedToID = assignmentJSON.get("id").asString(); - } else if (memberName.equals("assigned_by")) { - JsonObject userJSON = value.asObject(); - if (this.assignedBy == null) { - String userID = userJSON.get("id").asString(); - BoxUser user = new BoxUser(getAPI(), userID); - this.assignedBy = user.new Info(userJSON); - } else { - this.assignedBy.update(userJSON); - } - } else if (memberName.equals("assigned_at")) { - this.assignedAt = BoxDateFormat.parse(value.asString()); - } else if (memberName.equals("deleted_at")) { - this.deletedAt = BoxDateFormat.parse(value.asString()); - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); - } + /** {@inheritDoc} */ + @Override + void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + String memberName = member.getName(); + JsonValue value = member.getValue(); + try { + if (memberName.equals("legal_hold_policy")) { + JsonObject policyJSON = value.asObject(); + if (this.legalHold == null) { + String policyID = policyJSON.get("id").asString(); + BoxLegalHoldPolicy policy = new BoxLegalHoldPolicy(getAPI(), policyID); + this.legalHold = policy.new Info(policyJSON); + } else { + this.legalHold.update(policyJSON); + } + } else if (memberName.equals("assigned_to")) { + JsonObject assignmentJSON = value.asObject(); + this.assignedToType = assignmentJSON.get("type").asString(); + this.assignedToID = assignmentJSON.get("id").asString(); + } else if (memberName.equals("assigned_by")) { + JsonObject userJSON = value.asObject(); + if (this.assignedBy == null) { + String userID = userJSON.get("id").asString(); + BoxUser user = new BoxUser(getAPI(), userID); + this.assignedBy = user.new Info(userJSON); + } else { + this.assignedBy.update(userJSON); + } + } else if (memberName.equals("assigned_at")) { + this.assignedAt = BoxDateFormat.parse(value.asString()); + } else if (memberName.equals("deleted_at")) { + this.deletedAt = BoxDateFormat.parse(value.asString()); } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); + } } + } } diff --git a/src/main/java/com/box/sdk/BoxLegalHoldPolicy.java b/src/main/java/com/box/sdk/BoxLegalHoldPolicy.java index 7cdf5b012..181190867 100644 --- a/src/main/java/com/box/sdk/BoxLegalHoldPolicy.java +++ b/src/main/java/com/box/sdk/BoxLegalHoldPolicy.java @@ -7,609 +7,555 @@ import java.util.Date; /** - * Represents a legal hold policy. Legal Hold Policy information describes the basic characteristics of the Policy, such - * as name, description, and filter dates. + * Represents a legal hold policy. Legal Hold Policy information describes the basic characteristics + * of the Policy, such as name, description, and filter dates. * - * @see Box legal holds - * - *

Unless otherwise noted, the methods in this class can throw an unchecked {@link BoxAPIException} (unchecked - * meaning that the compiler won't force you to handle it) if an error occurs. If you wish to implement custom error - * handling for errors related to the Box REST API, you should capture this exception explicitly.

+ * @see Box legal + * holds + *

Unless otherwise noted, the methods in this class can throw an unchecked {@link + * BoxAPIException} (unchecked meaning that the compiler won't force you to handle it) if an + * error occurs. If you wish to implement custom error handling for errors related to the Box + * REST API, you should capture this exception explicitly. */ @BoxResourceType("legal_hold") public class BoxLegalHoldPolicy extends BoxResource { - /** - * Legal Hold URL Template. - */ - public static final URLTemplate LEGAL_HOLD_URL_TEMPLATE = new URLTemplate("legal_hold_policies/%s"); - /** - * All Legal Hold URL Template. - */ - public static final URLTemplate ALL_LEGAL_HOLD_URL_TEMPLATE = new URLTemplate("legal_hold_policies"); - /** - * Legal Hold Assignments URL Template. - */ - public static final URLTemplate LEGAL_HOLD_ASSIGNMENTS_URL_TEMPLATE - = new URLTemplate("legal_hold_policies/%s/assignments"); - /** - * List of File Version Holds URL Template. - */ - public static final URLTemplate LIST_OF_FILE_VERSION_HOLDS_URL_TEMPLATE - = new URLTemplate("file_version_legal_holds"); - private static final int DEFAULT_LIMIT = 100; + /** Legal Hold URL Template. */ + public static final URLTemplate LEGAL_HOLD_URL_TEMPLATE = + new URLTemplate("legal_hold_policies/%s"); + /** All Legal Hold URL Template. */ + public static final URLTemplate ALL_LEGAL_HOLD_URL_TEMPLATE = + new URLTemplate("legal_hold_policies"); + /** Legal Hold Assignments URL Template. */ + public static final URLTemplate LEGAL_HOLD_ASSIGNMENTS_URL_TEMPLATE = + new URLTemplate("legal_hold_policies/%s/assignments"); + /** List of File Version Holds URL Template. */ + public static final URLTemplate LIST_OF_FILE_VERSION_HOLDS_URL_TEMPLATE = + new URLTemplate("file_version_legal_holds"); + + private static final int DEFAULT_LIMIT = 100; + + /** + * Constructs a BoxLegalHoldPolicy for a resource with a given ID. + * + * @param api the API connection to be used by the resource. + * @param id the ID of the resource. + */ + public BoxLegalHoldPolicy(BoxAPIConnection api, String id) { + super(api, id); + } + + /** + * Creates a new Legal Hold Policy. + * + * @param api the API connection to be used by the resource. + * @param name the name of Legal Hold Policy. + * @return information about the Legal Hold Policy created. + */ + public static BoxLegalHoldPolicy.Info create(BoxAPIConnection api, String name) { + return createOngoing(api, name, null); + } + + /** + * Creates a new Legal Hold Policy. + * + * @param api the API connection to be used by the resource. + * @param name the name of Legal Hold Policy. + * @param description the description of Legal Hold Policy. + * @param filterStartedAt optional date filter applies to Custodian assignments only. + * @param filterEndedAt optional date filter applies to Custodian assignments only. + * @return information about the Legal Hold Policy created. + */ + public static BoxLegalHoldPolicy.Info create( + BoxAPIConnection api, + String name, + String description, + Date filterStartedAt, + Date filterEndedAt) { + URL url = ALL_LEGAL_HOLD_URL_TEMPLATE.build(api.getBaseURL()); + BoxJSONRequest request = new BoxJSONRequest(api, url, "POST"); + JsonObject requestJSON = new JsonObject().add("policy_name", name); + if (description != null) { + requestJSON.add("description", description); + } + if (filterStartedAt != null) { + requestJSON.add("filter_started_at", BoxDateFormat.format(filterStartedAt)); + } + if (filterEndedAt != null) { + requestJSON.add("filter_ended_at", BoxDateFormat.format(filterEndedAt)); + } + request.setBody(requestJSON.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + BoxLegalHoldPolicy createdPolicy = + new BoxLegalHoldPolicy(api, responseJSON.get("id").asString()); + return createdPolicy.new Info(responseJSON); + } + } + + /** + * Creates a new ongoing Legal Hold Policy. + * + * @param api the API connection to be used by the resource. + * @param name the name of Legal Hold Policy. + * @param description the description of Legal Hold Policy. + * @return information about the Legal Hold Policy created. + */ + public static BoxLegalHoldPolicy.Info createOngoing( + BoxAPIConnection api, String name, String description) { + return createOngoing(api, name, description, null); + } + + /** + * Creates a new ongoing Legal Hold Policy. + * + * @param api the API connection to be used by the resource. + * @param name the name of Legal Hold Policy. + * @param description the description of Legal Hold Policy. + * @param filterStartedAt optional date filter applies to Custodian assignments only. + * @return information about the Legal Hold Policy created. + */ + public static BoxLegalHoldPolicy.Info createOngoing( + BoxAPIConnection api, String name, String description, Date filterStartedAt) { + URL url = ALL_LEGAL_HOLD_URL_TEMPLATE.build(api.getBaseURL()); + BoxJSONRequest request = new BoxJSONRequest(api, url, "POST"); + JsonObject requestJSON = new JsonObject().add("policy_name", name).add("is_ongoing", true); + if (description != null) { + requestJSON.add("description", description); + } + if (filterStartedAt != null) { + requestJSON.add("filter_started_at", BoxDateFormat.format(filterStartedAt)); + } + request.setBody(requestJSON.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + BoxLegalHoldPolicy createdPolicy = + new BoxLegalHoldPolicy(api, responseJSON.get("id").asString()); + return createdPolicy.new Info(responseJSON); + } + } + + /** + * Retrieves a list of Legal Hold Policies that belong to your Enterprise as an Iterable. + * + * @param api api the API connection to be used by the resource. + * @return the Iterable of Legal Hold Policies in your Enterprise. + */ + public static Iterable getAll(final BoxAPIConnection api) { + return getAll(api, null, DEFAULT_LIMIT); + } + + /** + * Retrieves a list of Legal Hold Policies that belong to your Enterprise as an Iterable. + * + * @param api api the API connection to be used by the resource. + * @param policyName case insensitive prefix-match filter on Policy name. + * @param limit the limit of retrieved entries per page. + * @param fields the optional fields to retrieve. + * @return the Iterable of Legal Hold Policies in your Enterprise that match the filter + * parameters. + */ + public static Iterable getAll( + final BoxAPIConnection api, String policyName, int limit, String... fields) { + QueryStringBuilder builder = new QueryStringBuilder(); + if (policyName != null) { + builder.appendParam("policy_name", policyName); + } + if (fields.length > 0) { + builder.appendParam("fields", fields); + } + return new BoxResourceIterable( + api, + ALL_LEGAL_HOLD_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString()), + limit) { + + @Override + protected BoxLegalHoldPolicy.Info factory(JsonObject jsonObject) { + BoxLegalHoldPolicy policy = new BoxLegalHoldPolicy(api, jsonObject.get("id").asString()); + return policy.new Info(jsonObject); + } + }; + } + + /** + * Gets information about the Legal Hold. + * + * @param fields the fields to retrieve. + * @return information about this legal hold policy. + */ + public Info getInfo(String... fields) { + QueryStringBuilder builder = new QueryStringBuilder(); + if (fields.length > 0) { + builder.appendParam("fields", fields); + } + URL url = + LEGAL_HOLD_URL_TEMPLATE.buildWithQuery( + this.getAPI().getBaseURL(), builder.toString(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + return new Info(responseJSON); + } + } + + /** Deletes the legal hold policy. */ + public void delete() { + URL url = LEGAL_HOLD_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); + request.send().close(); + } + + /** + * Updates the information about this retention policy with modified locally info. Only + * policy_name, description and release_notes can be modified. + * + * @param info the updated info. + */ + public void updateInfo(BoxLegalHoldPolicy.Info info) { + URL url = LEGAL_HOLD_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); + request.setBody(info.getPendingChanges()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + info.update(responseJSON); + } + } + + /** + * Assigns this legal holds policy to the given box resource. Currently only {@link BoxFile}, + * {@link BoxFileVersion}, {@link BoxFolder} and {@link BoxUser} are supported. + * + * @param resource the box resource to assign legal hold policy to. + * @return info about created legal hold policy assignment. + */ + public BoxLegalHoldAssignment.Info assignTo(BoxResource resource) { + return BoxLegalHoldAssignment.create( + this.getAPI(), + this.getID(), + BoxResource.getResourceType(resource.getClass()), + resource.getID()); + } + + /** + * Returns iterable containing assignments for this single legal hold policy. + * + * @param fields the fields to retrieve. + * @return an iterable containing assignments for this single legal hold policy. + */ + public Iterable getAssignments(String... fields) { + return this.getAssignments(null, null, DEFAULT_LIMIT, fields); + } + + /** + * Returns iterable containing assignments for this single legal hold policy. Parameters can be + * used to filter retrieved assignments. + * + * @param type filter assignments of this type only. Can be "file_version", "file", "folder", + * "user" or null if no type filter is necessary. + * @param id filter assignments to this ID only. Can be null if no id filter is necessary. + * @param limit the limit of entries per page. Default limit is 100. + * @param fields the fields to retrieve. + * @return an iterable containing assignments for this single legal hold policy. + */ + public Iterable getAssignments( + String type, String id, int limit, String... fields) { + QueryStringBuilder builder = new QueryStringBuilder(); + if (type != null) { + builder.appendParam("assign_to_type", type); + } + if (id != null) { + builder.appendParam("assign_to_id", id); + } + if (fields.length > 0) { + builder.appendParam("fields", fields); + } + return new BoxResourceIterable( + this.getAPI(), + LEGAL_HOLD_ASSIGNMENTS_URL_TEMPLATE.buildWithQuery( + this.getAPI().getBaseURL(), builder.toString(), this.getID()), + limit) { + + @Override + protected BoxLegalHoldAssignment.Info factory(JsonObject jsonObject) { + BoxLegalHoldAssignment assignment = + new BoxLegalHoldAssignment( + BoxLegalHoldPolicy.this.getAPI(), jsonObject.get("id").asString()); + return assignment.new Info(jsonObject); + } + }; + } + + /** + * Returns iterable with all non-deleted file version legal holds for this legal hold policy. + * + * @param fields the fields to retrieve. + * @return an iterable containing file version legal holds info. + */ + public Iterable getFileVersionHolds(String... fields) { + return this.getFileVersionHolds(DEFAULT_LIMIT, fields); + } + + /** + * Returns iterable with all non-deleted file version legal holds for this legal hold policy. + * + * @param limit the limit of entries per response. The default value is 100. + * @param fields the fields to retrieve. + * @return an iterable containing file version legal holds info. + */ + public Iterable getFileVersionHolds(int limit, String... fields) { + QueryStringBuilder queryString = + new QueryStringBuilder().appendParam("policy_id", this.getID()); + if (fields.length > 0) { + queryString.appendParam("fields", fields); + } + URL url = + LIST_OF_FILE_VERSION_HOLDS_URL_TEMPLATE.buildWithQuery( + getAPI().getBaseURL(), queryString.toString()); + return new BoxResourceIterable(getAPI(), url, limit) { - /** - * Constructs a BoxLegalHoldPolicy for a resource with a given ID. - * - * @param api the API connection to be used by the resource. - * @param id the ID of the resource. - */ - public BoxLegalHoldPolicy(BoxAPIConnection api, String id) { - super(api, id); + @Override + protected BoxFileVersionLegalHold.Info factory(JsonObject jsonObject) { + BoxFileVersionLegalHold assignment = + new BoxFileVersionLegalHold(getAPI(), jsonObject.get("id").asString()); + return assignment.new Info(jsonObject); + } + }; + } + + /** Contains information about the legal hold policy. */ + public class Info extends BoxResource.Info { + + /** @see #getPolicyName() */ + private String policyName; + + /** @see #getDescription() */ + private String description; + + /** @see #getStatus() */ + private String status; + + /** @see #getAssignmentCountUser() */ + private int assignmentCountUser; + + /** @see #getAssignmentCountFolder() */ + private int assignmentCountFolder; + + /** @see #getAssignmentCountFile() */ + private int assignmentCountFile; + + /** @see #getAssignmentCountFileVersion() */ + private int assignmentCountFileVersion; + + /** @see #getCreatedAt() */ + private BoxUser.Info createdBy; + + /** @see #getCreatedAt() */ + private Date createdAt; + + /** @see #getModifiedAt() */ + private Date modifiedAt; + + /** @see #getDeletedAt() */ + private Date deletedAt; + + /** @see #getFilterStartedAt() */ + private Date filterStartedAt; + + /** @see #getFilterEndedAt() */ + private Date filterEndedAt; + + /** @see #getReleaseNotes() */ + private String releaseNotes; + + /** @see #getIsOngoing() */ + private Boolean isOngoing; + + /** Constructs an empty Info object. */ + public Info() { + super(); } /** - * Creates a new Legal Hold Policy. + * Constructs an Info object by parsing information from a JSON string. * - * @param api the API connection to be used by the resource. - * @param name the name of Legal Hold Policy. - * @return information about the Legal Hold Policy created. + * @param json the JSON string to parse. */ - public static BoxLegalHoldPolicy.Info create(BoxAPIConnection api, String name) { - return createOngoing(api, name, null); + public Info(String json) { + super(json); } /** - * Creates a new Legal Hold Policy. + * Constructs an Info object using an already parsed JSON object. * - * @param api the API connection to be used by the resource. - * @param name the name of Legal Hold Policy. - * @param description the description of Legal Hold Policy. - * @param filterStartedAt optional date filter applies to Custodian assignments only. - * @param filterEndedAt optional date filter applies to Custodian assignments only. - * @return information about the Legal Hold Policy created. + * @param jsonObject the parsed JSON object. */ - public static BoxLegalHoldPolicy.Info create(BoxAPIConnection api, String name, String description, - Date filterStartedAt, Date filterEndedAt) { - URL url = ALL_LEGAL_HOLD_URL_TEMPLATE.build(api.getBaseURL()); - BoxJSONRequest request = new BoxJSONRequest(api, url, "POST"); - JsonObject requestJSON = new JsonObject() - .add("policy_name", name); - if (description != null) { - requestJSON.add("description", description); - } - if (filterStartedAt != null) { - requestJSON.add("filter_started_at", BoxDateFormat.format(filterStartedAt)); - } - if (filterEndedAt != null) { - requestJSON.add("filter_ended_at", BoxDateFormat.format(filterEndedAt)); - } - request.setBody(requestJSON.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - BoxLegalHoldPolicy createdPolicy = new BoxLegalHoldPolicy(api, responseJSON.get("id").asString()); - return createdPolicy.new Info(responseJSON); - } + Info(JsonObject jsonObject) { + super(jsonObject); } - /** - * Creates a new ongoing Legal Hold Policy. - * - * @param api the API connection to be used by the resource. - * @param name the name of Legal Hold Policy. - * @param description the description of Legal Hold Policy. - * @return information about the Legal Hold Policy created. - */ - public static BoxLegalHoldPolicy.Info createOngoing(BoxAPIConnection api, String name, String description) { - return createOngoing(api, name, description, null); + /** {@inheritDoc} */ + @Override + public BoxResource getResource() { + return BoxLegalHoldPolicy.this; } + /** @return the name of the policy. */ + public String getPolicyName() { + return this.policyName; + } /** - * Creates a new ongoing Legal Hold Policy. + * Sets the policy's name. * - * @param api the API connection to be used by the resource. - * @param name the name of Legal Hold Policy. - * @param description the description of Legal Hold Policy. - * @param filterStartedAt optional date filter applies to Custodian assignments only. - * @return information about the Legal Hold Policy created. + * @param policyName the policy's new name. */ - public static BoxLegalHoldPolicy.Info createOngoing( - BoxAPIConnection api, String name, String description, Date filterStartedAt - ) { - URL url = ALL_LEGAL_HOLD_URL_TEMPLATE.build(api.getBaseURL()); - BoxJSONRequest request = new BoxJSONRequest(api, url, "POST"); - JsonObject requestJSON = new JsonObject() - .add("policy_name", name) - .add("is_ongoing", true); - if (description != null) { - requestJSON.add("description", description); - } - if (filterStartedAt != null) { - requestJSON.add("filter_started_at", BoxDateFormat.format(filterStartedAt)); - } - request.setBody(requestJSON.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - BoxLegalHoldPolicy createdPolicy = new BoxLegalHoldPolicy(api, responseJSON.get("id").asString()); - return createdPolicy.new Info(responseJSON); - } + public void setPolicyName(String policyName) { + this.policyName = policyName; + this.addPendingChange("policy_name", policyName); + } + + /** @return the description of the policy. */ + public String getDescription() { + return this.description; } /** - * Retrieves a list of Legal Hold Policies that belong to your Enterprise as an Iterable. + * Sets the policy's description. * - * @param api api the API connection to be used by the resource. - * @return the Iterable of Legal Hold Policies in your Enterprise. + * @param description the policy's new description. */ - public static Iterable getAll(final BoxAPIConnection api) { - return getAll(api, null, DEFAULT_LIMIT); + public void setDescription(String description) { + this.description = description; + this.addPendingChange("description", description); } /** - * Retrieves a list of Legal Hold Policies that belong to your Enterprise as an Iterable. + * Status can be "active", "applying", "releasing" or "released". * - * @param api api the API connection to be used by the resource. - * @param policyName case insensitive prefix-match filter on Policy name. - * @param limit the limit of retrieved entries per page. - * @param fields the optional fields to retrieve. - * @return the Iterable of Legal Hold Policies in your Enterprise that match the filter parameters. + * @return the status of the policy. */ - public static Iterable getAll( - final BoxAPIConnection api, String policyName, int limit, String... fields) { - QueryStringBuilder builder = new QueryStringBuilder(); - if (policyName != null) { - builder.appendParam("policy_name", policyName); - } - if (fields.length > 0) { - builder.appendParam("fields", fields); - } - return new BoxResourceIterable(api, - ALL_LEGAL_HOLD_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString()), - limit) { + public String getStatus() { + return this.status; + } - @Override - protected BoxLegalHoldPolicy.Info factory(JsonObject jsonObject) { - BoxLegalHoldPolicy policy = new BoxLegalHoldPolicy(api, jsonObject.get("id").asString()); - return policy.new Info(jsonObject); - } - }; + /** @return count of users this policy assigned to. */ + public int getAssignmentCountUser() { + return this.assignmentCountUser; } - /** - * Gets information about the Legal Hold. - * - * @param fields the fields to retrieve. - * @return information about this legal hold policy. - */ - public Info getInfo(String... fields) { - QueryStringBuilder builder = new QueryStringBuilder(); - if (fields.length > 0) { - builder.appendParam("fields", fields); - } - URL url = LEGAL_HOLD_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), builder.toString(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - return new Info(responseJSON); - } + /** @return count of folders this policy assigned to. */ + public int getAssignmentCountFolder() { + return this.assignmentCountFolder; } - /** - * Deletes the legal hold policy. - */ - public void delete() { - URL url = LEGAL_HOLD_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); - request.send().close(); + /** @return count of files this policy assigned to. */ + public int getAssignmentCountFile() { + return this.assignmentCountFile; } - /** - * Updates the information about this retention policy with modified locally info. - * Only policy_name, description and release_notes can be modified. - * - * @param info the updated info. - */ - public void updateInfo(BoxLegalHoldPolicy.Info info) { - URL url = LEGAL_HOLD_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); - request.setBody(info.getPendingChanges()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - info.update(responseJSON); - } + /** @return count of file versions this policy assigned to. */ + public int getAssignmentCountFileVersion() { + return this.assignmentCountFileVersion; } - /** - * Assigns this legal holds policy to the given box resource. - * Currently only {@link BoxFile}, {@link BoxFileVersion}, {@link BoxFolder} and {@link BoxUser} are supported. - * - * @param resource the box resource to assign legal hold policy to. - * @return info about created legal hold policy assignment. - */ - public BoxLegalHoldAssignment.Info assignTo(BoxResource resource) { - return BoxLegalHoldAssignment.create( - this.getAPI(), this.getID(), BoxResource.getResourceType(resource.getClass()), resource.getID()); + /** @return info about the user who created this policy. */ + public BoxUser.Info getCreatedBy() { + return this.createdBy; } - /** - * Returns iterable containing assignments for this single legal hold policy. - * - * @param fields the fields to retrieve. - * @return an iterable containing assignments for this single legal hold policy. - */ - public Iterable getAssignments(String... fields) { - return this.getAssignments(null, null, DEFAULT_LIMIT, fields); + /** @return time the policy was created. */ + public Date getCreatedAt() { + return this.createdAt; } - /** - * Returns iterable containing assignments for this single legal hold policy. - * Parameters can be used to filter retrieved assignments. - * - * @param type filter assignments of this type only. - * Can be "file_version", "file", "folder", "user" or null if no type filter is necessary. - * @param id filter assignments to this ID only. Can be null if no id filter is necessary. - * @param limit the limit of entries per page. Default limit is 100. - * @param fields the fields to retrieve. - * @return an iterable containing assignments for this single legal hold policy. - */ - public Iterable getAssignments(String type, String id, int limit, String... fields) { - QueryStringBuilder builder = new QueryStringBuilder(); - if (type != null) { - builder.appendParam("assign_to_type", type); - } - if (id != null) { - builder.appendParam("assign_to_id", id); - } - if (fields.length > 0) { - builder.appendParam("fields", fields); - } - return new BoxResourceIterable( - this.getAPI(), LEGAL_HOLD_ASSIGNMENTS_URL_TEMPLATE.buildWithQuery( - this.getAPI().getBaseURL(), builder.toString(), this.getID()), limit) { + /** @return time the policy was modified. */ + public Date getModifiedAt() { + return this.modifiedAt; + } - @Override - protected BoxLegalHoldAssignment.Info factory(JsonObject jsonObject) { - BoxLegalHoldAssignment assignment = new BoxLegalHoldAssignment( - BoxLegalHoldPolicy.this.getAPI(), jsonObject.get("id").asString()); - return assignment.new Info(jsonObject); - } - }; + /** @return time that the policy release request was sent. */ + public Date getDeletedAt() { + return this.deletedAt; } - /** - * Returns iterable with all non-deleted file version legal holds for this legal hold policy. - * - * @param fields the fields to retrieve. - * @return an iterable containing file version legal holds info. - */ - public Iterable getFileVersionHolds(String... fields) { - return this.getFileVersionHolds(DEFAULT_LIMIT, fields); + /** @return optional date filter applies to Custodian assignments only. */ + public Date getFilterStartedAt() { + return this.filterStartedAt; + } + + /** @return optional date filter applies to Custodian assignments only. */ + public Date getFilterEndedAt() { + return this.filterEndedAt; + } + + /** @return notes around why the policy was released. */ + public String getReleaseNotes() { + return this.releaseNotes; } /** - * Returns iterable with all non-deleted file version legal holds for this legal hold policy. + * Sets the policy's release notes. * - * @param limit the limit of entries per response. The default value is 100. - * @param fields the fields to retrieve. - * @return an iterable containing file version legal holds info. + * @param releaseNotes the policy's new release notes. */ - public Iterable getFileVersionHolds(int limit, String... fields) { - QueryStringBuilder queryString = new QueryStringBuilder().appendParam("policy_id", this.getID()); - if (fields.length > 0) { - queryString.appendParam("fields", fields); - } - URL url = LIST_OF_FILE_VERSION_HOLDS_URL_TEMPLATE.buildWithQuery(getAPI().getBaseURL(), queryString.toString()); - return new BoxResourceIterable(getAPI(), url, limit) { - - @Override - protected BoxFileVersionLegalHold.Info factory(JsonObject jsonObject) { - BoxFileVersionLegalHold assignment - = new BoxFileVersionLegalHold(getAPI(), jsonObject.get("id").asString()); - return assignment.new Info(jsonObject); - } - - }; + public void setReleaseNotes(String releaseNotes) { + this.releaseNotes = releaseNotes; + this.addPendingChange("release_notes", releaseNotes); } /** - * Contains information about the legal hold policy. + * @return boolean indicating whether the policy will continue applying to files based on + * events, indefinitely. */ - public class Info extends BoxResource.Info { - - /** - * @see #getPolicyName() - */ - private String policyName; - - /** - * @see #getDescription() - */ - private String description; - - /** - * @see #getStatus() - */ - private String status; - - /** - * @see #getAssignmentCountUser() - */ - private int assignmentCountUser; - - /** - * @see #getAssignmentCountFolder() - */ - private int assignmentCountFolder; - - /** - * @see #getAssignmentCountFile() - */ - private int assignmentCountFile; - - /** - * @see #getAssignmentCountFileVersion() - */ - private int assignmentCountFileVersion; - - /** - * @see #getCreatedAt() - */ - private BoxUser.Info createdBy; - - /** - * @see #getCreatedAt() - */ - private Date createdAt; - - /** - * @see #getModifiedAt() - */ - private Date modifiedAt; - - /** - * @see #getDeletedAt() - */ - private Date deletedAt; - - /** - * @see #getFilterStartedAt() - */ - private Date filterStartedAt; - - /** - * @see #getFilterEndedAt() - */ - private Date filterEndedAt; - - /** - * @see #getReleaseNotes() - */ - private String releaseNotes; - - /** - * @see #getIsOngoing() - */ - private Boolean isOngoing; - - /** - * Constructs an empty Info object. - */ - public Info() { - super(); - } - - /** - * Constructs an Info object by parsing information from a JSON string. - * - * @param json the JSON string to parse. - */ - public Info(String json) { - super(json); - } - - /** - * Constructs an Info object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - Info(JsonObject jsonObject) { - super(jsonObject); - } - - /** - * {@inheritDoc} - */ - @Override - public BoxResource getResource() { - return BoxLegalHoldPolicy.this; - } - - /** - * @return the name of the policy. - */ - public String getPolicyName() { - return this.policyName; - } - - /** - * Sets the policy's name. - * - * @param policyName the policy's new name. - */ - public void setPolicyName(String policyName) { - this.policyName = policyName; - this.addPendingChange("policy_name", policyName); - } - - /** - * @return the description of the policy. - */ - public String getDescription() { - return this.description; - } - - /** - * Sets the policy's description. - * - * @param description the policy's new description. - */ - public void setDescription(String description) { - this.description = description; - this.addPendingChange("description", description); - } - - /** - * Status can be "active", "applying", "releasing" or "released". - * - * @return the status of the policy. - */ - public String getStatus() { - return this.status; - } - - /** - * @return count of users this policy assigned to. - */ - public int getAssignmentCountUser() { - return this.assignmentCountUser; - } - - /** - * @return count of folders this policy assigned to. - */ - public int getAssignmentCountFolder() { - return this.assignmentCountFolder; - } - - /** - * @return count of files this policy assigned to. - */ - public int getAssignmentCountFile() { - return this.assignmentCountFile; - } - - /** - * @return count of file versions this policy assigned to. - */ - public int getAssignmentCountFileVersion() { - return this.assignmentCountFileVersion; - } - - /** - * @return info about the user who created this policy. - */ - public BoxUser.Info getCreatedBy() { - return this.createdBy; - } - - /** - * @return time the policy was created. - */ - public Date getCreatedAt() { - return this.createdAt; - } - - /** - * @return time the policy was modified. - */ - public Date getModifiedAt() { - return this.modifiedAt; - } - - /** - * @return time that the policy release request was sent. - */ - public Date getDeletedAt() { - return this.deletedAt; - } - - /** - * @return optional date filter applies to Custodian assignments only. - */ - public Date getFilterStartedAt() { - return this.filterStartedAt; - } - - /** - * @return optional date filter applies to Custodian assignments only. - */ - public Date getFilterEndedAt() { - return this.filterEndedAt; - } - - /** - * @return notes around why the policy was released. - */ - public String getReleaseNotes() { - return this.releaseNotes; - } - - /** - * Sets the policy's release notes. - * - * @param releaseNotes the policy's new release notes. - */ - public void setReleaseNotes(String releaseNotes) { - this.releaseNotes = releaseNotes; - this.addPendingChange("release_notes", releaseNotes); - } - - /** - * @return boolean indicating whether the policy will continue applying to files based on events, indefinitely. - */ - public Boolean getIsOngoing() { - return this.isOngoing; - } + public Boolean getIsOngoing() { + return this.isOngoing; + } - /** - * {@inheritDoc} - */ - @Override - void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - String memberName = member.getName(); - JsonValue value = member.getValue(); - try { - if (memberName.equals("policy_name")) { - this.policyName = value.asString(); - } else if (memberName.equals("description")) { - this.description = value.asString(); - } else if (memberName.equals("status")) { - this.status = value.asString(); - } else if (memberName.equals("release_notes")) { - this.releaseNotes = value.asString(); - } else if (memberName.equals("assignment_counts")) { - JsonObject countsJSON = value.asObject(); - this.assignmentCountUser = countsJSON.get("user").asInt(); - this.assignmentCountFolder = countsJSON.get("folder").asInt(); - this.assignmentCountFile = countsJSON.get("file").asInt(); - this.assignmentCountFileVersion = countsJSON.get("file_version").asInt(); - } else if (memberName.equals("created_by")) { - JsonObject userJSON = value.asObject(); - if (this.createdBy == null) { - String userID = userJSON.get("id").asString(); - BoxUser user = new BoxUser(getAPI(), userID); - this.createdBy = user.new Info(userJSON); - } else { - this.createdBy.update(userJSON); - } - } else if (memberName.equals("created_at")) { - this.createdAt = BoxDateFormat.parse(value.asString()); - } else if (memberName.equals("modified_at")) { - this.modifiedAt = BoxDateFormat.parse(value.asString()); - } else if (memberName.equals("deleted_at")) { - this.deletedAt = BoxDateFormat.parse(value.asString()); - } else if (memberName.equals("filter_started_at")) { - this.filterStartedAt = BoxDateFormat.parse(value.asString()); - } else if (memberName.equals("filter_ended_at")) { - this.filterEndedAt = BoxDateFormat.parse(value.asString()); - } else if (memberName.equals("is_ongoing")) { - this.isOngoing = value.asBoolean(); - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); - } - } + /** {@inheritDoc} */ + @Override + void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + String memberName = member.getName(); + JsonValue value = member.getValue(); + try { + if (memberName.equals("policy_name")) { + this.policyName = value.asString(); + } else if (memberName.equals("description")) { + this.description = value.asString(); + } else if (memberName.equals("status")) { + this.status = value.asString(); + } else if (memberName.equals("release_notes")) { + this.releaseNotes = value.asString(); + } else if (memberName.equals("assignment_counts")) { + JsonObject countsJSON = value.asObject(); + this.assignmentCountUser = countsJSON.get("user").asInt(); + this.assignmentCountFolder = countsJSON.get("folder").asInt(); + this.assignmentCountFile = countsJSON.get("file").asInt(); + this.assignmentCountFileVersion = countsJSON.get("file_version").asInt(); + } else if (memberName.equals("created_by")) { + JsonObject userJSON = value.asObject(); + if (this.createdBy == null) { + String userID = userJSON.get("id").asString(); + BoxUser user = new BoxUser(getAPI(), userID); + this.createdBy = user.new Info(userJSON); + } else { + this.createdBy.update(userJSON); + } + } else if (memberName.equals("created_at")) { + this.createdAt = BoxDateFormat.parse(value.asString()); + } else if (memberName.equals("modified_at")) { + this.modifiedAt = BoxDateFormat.parse(value.asString()); + } else if (memberName.equals("deleted_at")) { + this.deletedAt = BoxDateFormat.parse(value.asString()); + } else if (memberName.equals("filter_started_at")) { + this.filterStartedAt = BoxDateFormat.parse(value.asString()); + } else if (memberName.equals("filter_ended_at")) { + this.filterEndedAt = BoxDateFormat.parse(value.asString()); + } else if (memberName.equals("is_ongoing")) { + this.isOngoing = value.asBoolean(); + } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); + } } + } } diff --git a/src/main/java/com/box/sdk/BoxLock.java b/src/main/java/com/box/sdk/BoxLock.java index 15e6a7cab..22ac89a62 100644 --- a/src/main/java/com/box/sdk/BoxLock.java +++ b/src/main/java/com/box/sdk/BoxLock.java @@ -4,136 +4,130 @@ import com.eclipsesource.json.JsonValue; import java.util.Date; -/** - * Represents a lock associated with a File on Box. - */ +/** Represents a lock associated with a File on Box. */ public class BoxLock extends BoxJSONObject { - private String type; - private Date expiresAt; - private Boolean isDownloadPrevented; - private BoxUser.Info createdBy; - private Date createdAt; - private String id; - private BoxAPIConnection api; + private String type; + private Date expiresAt; + private Boolean isDownloadPrevented; + private BoxUser.Info createdBy; + private Date createdAt; + private String id; + private BoxAPIConnection api; - /** - * Constructs a base BoxLock object. - * - * @param type lock type, "lock" or "unlock". - * @param expiresAt lock expiration date. - */ - public BoxLock(String type, Date expiresAt) { - super(); - this.type = type; - this.expiresAt = expiresAt; - this.isDownloadPrevented = false; - } + /** + * Constructs a base BoxLock object. + * + * @param type lock type, "lock" or "unlock". + * @param expiresAt lock expiration date. + */ + public BoxLock(String type, Date expiresAt) { + super(); + this.type = type; + this.expiresAt = expiresAt; + this.isDownloadPrevented = false; + } - /** - * Constructs a BoxLock object. - * - * @param type lock type, "lock" or "unlock". - * @param expiresAt lock expiration date. - * @param isDownloadPrevented if true, download is prevented while locked. - */ - public BoxLock(String type, Date expiresAt, Boolean isDownloadPrevented) { - super(); - this.type = type; - this.expiresAt = expiresAt; - this.isDownloadPrevented = isDownloadPrevented; - } + /** + * Constructs a BoxLock object. + * + * @param type lock type, "lock" or "unlock". + * @param expiresAt lock expiration date. + * @param isDownloadPrevented if true, download is prevented while locked. + */ + public BoxLock(String type, Date expiresAt, Boolean isDownloadPrevented) { + super(); + this.type = type; + this.expiresAt = expiresAt; + this.isDownloadPrevented = isDownloadPrevented; + } - /** - * Constructs an BoxLock object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - * @param api API object. - */ - BoxLock(JsonObject jsonObject, BoxAPIConnection api) { - super(jsonObject); - this.api = api; - } + /** + * Constructs an BoxLock object using an already parsed JSON object. + * + * @param jsonObject the parsed JSON object. + * @param api API object. + */ + BoxLock(JsonObject jsonObject, BoxAPIConnection api) { + super(jsonObject); + this.api = api; + } - /** - * Gets the lock type. - * - * @return the type of a lock. - */ - public String getType() { - return this.type; - } + /** + * Gets the lock type. + * + * @return the type of a lock. + */ + public String getType() { + return this.type; + } - /** - * Gets a locks expiration date. - * - * @return the locks expiration date. - */ - public Date getExpiresAt() { - return this.expiresAt; - } + /** + * Gets a locks expiration date. + * + * @return the locks expiration date. + */ + public Date getExpiresAt() { + return this.expiresAt; + } - /** - * Does the lock prevent downloads. - * - * @return true if lock prevents downloads. - */ - public Boolean getIsDownloadPrevented() { - return this.isDownloadPrevented; - } + /** + * Does the lock prevent downloads. + * + * @return true if lock prevents downloads. + */ + public Boolean getIsDownloadPrevented() { + return this.isDownloadPrevented; + } - /** - * User who created the lock. - * - * @return Lock creator. - */ - public BoxUser.Info getCreatedBy() { - return this.createdBy; - } + /** + * User who created the lock. + * + * @return Lock creator. + */ + public BoxUser.Info getCreatedBy() { + return this.createdBy; + } - /** - * @return Lock's creation date. - */ - public Date getCreatedAt() { - return this.createdAt; - } + /** @return Lock's creation date. */ + public Date getCreatedAt() { + return this.createdAt; + } - /** - * @return Lock's ID. - */ - public String getId() { - return this.id; - } + /** @return Lock's ID. */ + public String getId() { + return this.id; + } - @Override - protected void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); + @Override + protected void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); - String memberName = member.getName(); - JsonValue value = member.getValue(); + String memberName = member.getName(); + JsonValue value = member.getValue(); - try { - if (memberName.equals("type")) { - this.type = value.asString(); - } else if (memberName.equals("expires_at")) { - this.expiresAt = BoxDateFormat.parse(value.asString()); - } else if (memberName.equals("is_download_prevented")) { - this.isDownloadPrevented = value.asBoolean(); - } else if (memberName.equals("created_by")) { - JsonObject userJSON = value.asObject(); - if (this.createdBy == null) { - String userID = userJSON.get("id").asString(); - BoxUser user = new BoxUser(this.api, userID); - this.createdBy = user.new Info(userJSON); - } else { - this.createdBy.update(userJSON); - } - } else if (memberName.equals("created_at")) { - this.createdAt = BoxDateFormat.parse(value.asString()); - } else if (memberName.equals("id")) { - this.id = value.toString(); - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); + try { + if (memberName.equals("type")) { + this.type = value.asString(); + } else if (memberName.equals("expires_at")) { + this.expiresAt = BoxDateFormat.parse(value.asString()); + } else if (memberName.equals("is_download_prevented")) { + this.isDownloadPrevented = value.asBoolean(); + } else if (memberName.equals("created_by")) { + JsonObject userJSON = value.asObject(); + if (this.createdBy == null) { + String userID = userJSON.get("id").asString(); + BoxUser user = new BoxUser(this.api, userID); + this.createdBy = user.new Info(userJSON); + } else { + this.createdBy.update(userJSON); } + } else if (memberName.equals("created_at")) { + this.createdAt = BoxDateFormat.parse(value.asString()); + } else if (memberName.equals("id")) { + this.id = value.toString(); + } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); } + } } diff --git a/src/main/java/com/box/sdk/BoxLogger.java b/src/main/java/com/box/sdk/BoxLogger.java index d8dc30f79..113ea1f75 100644 --- a/src/main/java/com/box/sdk/BoxLogger.java +++ b/src/main/java/com/box/sdk/BoxLogger.java @@ -11,159 +11,155 @@ import java.util.logging.Level; import java.util.logging.Logger; -/** - * Logger class. - */ +/** Logger class. */ public final class BoxLogger { - private static final BoxLogger DEFAULT_LOGGER = new BoxLogger("com.box.sdk"); - private final Logger logger; - - private BoxLogger(String name) { - logger = Logger.getLogger(name); - } - - /** - * Get logger instance - * @return logger instance. - */ - public static BoxLogger defaultLogger() { - return DEFAULT_LOGGER; - } - - /** - * Log message with level DEBUG {@link Level#FINE} - * @param message message to log - */ - public void debug(String message) { - logger.fine(message); - } - - /** - * Log message with level INFO {@link Level#INFO} - * @param message message to log - */ - public void info(String message) { - logger.info(message); - } - - /** - * Log message with level WARNING {@link Level#WARNING} - * @param message message to log - */ - public void warn(String message) { - logger.warning(message); - } - - /** - * Log message with level WARNING {@link Level#SEVERE} - * @param message message to log - */ - public void error(String message) { - logger.severe(message); - } - - /** - * Check if DEBUG level is enabled - * @return true if DEBUG level is enabled - */ - public boolean isDebugEnabled() { - return logger.isLoggable(FINE); - } - - /** - * Check if INFO level is enabled - * @return true if INFO level is enabled - */ - public boolean isInfoEnabled() { - return logger.isLoggable(INFO); - } - - /** - * Check if WARN level is enabled - * @return true if WARN level is enabled - */ - public boolean isWarnEnabled() { - return logger.isLoggable(WARNING); - } - - /** - * Check if ERROR level is enabled - * @return true if ERROR level is enabled - */ - public boolean isErrorEnabled() { - return logger.isLoggable(SEVERE); - } - - /** - * Set logging level to ALL {@link Level#ALL} - */ - public void setLevelToAll() { - this.logger.setLevel(ALL); - } - - /** - * Reset logging level to default. - */ - public void resetToDefaultLevel() { - this.logger.setLevel(null); - } - - /** - * Set logging level to INFO {@link Level#INFO} - */ - public void setLevelToInfo() { - this.logger.setLevel(INFO); - } - - /** - * Set logging level to WARNING {@link Level#WARNING} - */ - public void setLevelToWarning() { - this.logger.setLevel(WARNING); - } - - /** - * Set logging level to ERROR {@link Level#SEVERE} - */ - public void setLevelToError() { - this.logger.setLevel(SEVERE); - } - - /** - * Turns logging off - */ - public void turnLoggingOff() { - this.logger.setLevel(OFF); - } - - /** - * Specify whether this logger should send its output to its parent Logger. This means that any LogRecords - * will also be written to the parent's Handlers, and potentially to its parent, recursively up the namespace. - * - * @param useParentHandlers true if output is to be sent to the logger's parent. - * @throws SecurityException if a security manager exists, this logger is not anonymous, - * and the caller does not have LoggingPermission("control"). - */ - public void setUseParentHandlers(boolean useParentHandlers) { - this.logger.setUseParentHandlers(useParentHandlers); - } - - /** - * Adds handler to logger. - * Check {@link Logger#addHandler(Handler)} - * @param handler a logging handler to add. - */ - public void addHandler(Handler handler) { - logger.addHandler(handler); - } - - /** - * Removes handler from logger. - * Will not fail if handler is null or not registered. - * Check {@link Logger#removeHandler(Handler)} - * @param handler a logging handler to remove. - */ - public void removeHandler(Handler handler) { - logger.removeHandler(handler); - } + private static final BoxLogger DEFAULT_LOGGER = new BoxLogger("com.box.sdk"); + private final Logger logger; + + private BoxLogger(String name) { + logger = Logger.getLogger(name); + } + + /** + * Get logger instance + * + * @return logger instance. + */ + public static BoxLogger defaultLogger() { + return DEFAULT_LOGGER; + } + + /** + * Log message with level DEBUG {@link Level#FINE} + * + * @param message message to log + */ + public void debug(String message) { + logger.fine(message); + } + + /** + * Log message with level INFO {@link Level#INFO} + * + * @param message message to log + */ + public void info(String message) { + logger.info(message); + } + + /** + * Log message with level WARNING {@link Level#WARNING} + * + * @param message message to log + */ + public void warn(String message) { + logger.warning(message); + } + + /** + * Log message with level WARNING {@link Level#SEVERE} + * + * @param message message to log + */ + public void error(String message) { + logger.severe(message); + } + + /** + * Check if DEBUG level is enabled + * + * @return true if DEBUG level is enabled + */ + public boolean isDebugEnabled() { + return logger.isLoggable(FINE); + } + + /** + * Check if INFO level is enabled + * + * @return true if INFO level is enabled + */ + public boolean isInfoEnabled() { + return logger.isLoggable(INFO); + } + + /** + * Check if WARN level is enabled + * + * @return true if WARN level is enabled + */ + public boolean isWarnEnabled() { + return logger.isLoggable(WARNING); + } + + /** + * Check if ERROR level is enabled + * + * @return true if ERROR level is enabled + */ + public boolean isErrorEnabled() { + return logger.isLoggable(SEVERE); + } + + /** Set logging level to ALL {@link Level#ALL} */ + public void setLevelToAll() { + this.logger.setLevel(ALL); + } + + /** Reset logging level to default. */ + public void resetToDefaultLevel() { + this.logger.setLevel(null); + } + + /** Set logging level to INFO {@link Level#INFO} */ + public void setLevelToInfo() { + this.logger.setLevel(INFO); + } + + /** Set logging level to WARNING {@link Level#WARNING} */ + public void setLevelToWarning() { + this.logger.setLevel(WARNING); + } + + /** Set logging level to ERROR {@link Level#SEVERE} */ + public void setLevelToError() { + this.logger.setLevel(SEVERE); + } + + /** Turns logging off */ + public void turnLoggingOff() { + this.logger.setLevel(OFF); + } + + /** + * Specify whether this logger should send its output to its parent Logger. This means that any + * LogRecords will also be written to the parent's Handlers, and potentially to its parent, + * recursively up the namespace. + * + * @param useParentHandlers true if output is to be sent to the logger's parent. + * @throws SecurityException if a security manager exists, this logger is not anonymous, and the + * caller does not have LoggingPermission("control"). + */ + public void setUseParentHandlers(boolean useParentHandlers) { + this.logger.setUseParentHandlers(useParentHandlers); + } + + /** + * Adds handler to logger. Check {@link Logger#addHandler(Handler)} + * + * @param handler a logging handler to add. + */ + public void addHandler(Handler handler) { + logger.addHandler(handler); + } + + /** + * Removes handler from logger. Will not fail if handler is null or not registered. Check {@link + * Logger#removeHandler(Handler)} + * + * @param handler a logging handler to remove. + */ + public void removeHandler(Handler handler) { + logger.removeHandler(handler); + } } diff --git a/src/main/java/com/box/sdk/BoxMetadataCascadePolicy.java b/src/main/java/com/box/sdk/BoxMetadataCascadePolicy.java index 902279459..03d02a4c7 100644 --- a/src/main/java/com/box/sdk/BoxMetadataCascadePolicy.java +++ b/src/main/java/com/box/sdk/BoxMetadataCascadePolicy.java @@ -5,256 +5,253 @@ import com.eclipsesource.json.JsonValue; import java.net.URL; -/** - * Represents a Metadata Cascade Policy. - */ +/** Represents a Metadata Cascade Policy. */ @BoxResourceType("metadata_cascade_policy") public class BoxMetadataCascadePolicy extends BoxResource { - /** - * Get All Metadata Cascade Policies URL. - */ - public static final URLTemplate GET_ALL_METADATA_CASCADE_POLICIES_URL_TEMPLATE = - new URLTemplate("metadata_cascade_policies"); + /** Get All Metadata Cascade Policies URL. */ + public static final URLTemplate GET_ALL_METADATA_CASCADE_POLICIES_URL_TEMPLATE = + new URLTemplate("metadata_cascade_policies"); - /** - * Metadata Cascade Policies URL. - */ - public static final URLTemplate METADATA_CASCADE_POLICIES_URL_TEMPLATE = - new URLTemplate("metadata_cascade_policies/%s"); + /** Metadata Cascade Policies URL. */ + public static final URLTemplate METADATA_CASCADE_POLICIES_URL_TEMPLATE = + new URLTemplate("metadata_cascade_policies/%s"); - /** - * Force Metadata Cascade Policies URL. - */ - public static final URLTemplate FORCE_METADATA_CASCADE_POLICIES_URL_TEMPLATE = - new URLTemplate("metadata_cascade_policies/%s/apply"); + /** Force Metadata Cascade Policies URL. */ + public static final URLTemplate FORCE_METADATA_CASCADE_POLICIES_URL_TEMPLATE = + new URLTemplate("metadata_cascade_policies/%s/apply"); - private static final int DEFAULT_LIMIT = 100; + private static final int DEFAULT_LIMIT = 100; - /** - * Constructs a BoxMetadataCascadePolicy for a metadata cascade policy with a given ID. - * - * @param api the API connection used to make the request. - * @param id the ID of the metadata cascade policy. - */ - public BoxMetadataCascadePolicy(BoxAPIConnection api, String id) { - super(api, id); + /** + * Constructs a BoxMetadataCascadePolicy for a metadata cascade policy with a given ID. + * + * @param api the API connection used to make the request. + * @param id the ID of the metadata cascade policy. + */ + public BoxMetadataCascadePolicy(BoxAPIConnection api, String id) { + super(api, id); + } + + /** + * Retrieves list of Box Metadata Cascade Policies that belong to your Enterprise as an Iterable. + * + * @param api the API connection to be used by the resource. + * @param folderID the ID of the folder to retrieve cascade policies for. + * @param fields optional fields to retrieve for cascade policies. + * @return the Iterable of Box Metadata Cascade Policies in your enterprise. + */ + public static Iterable getAll( + final BoxAPIConnection api, String folderID, String... fields) { + return getAll(api, folderID, null, DEFAULT_LIMIT, fields); + } + + /** + * Retrieves list of Box Metadata Cascade Policies that belong to your Enterprise as an Iterable. + * + * @param api the API connection to be used by the resource. + * @param folderID the ID of the folder to retrieve cascade policies for. + * @param ownerEnterpriseID the ID of the enterprise to retrieve Metadata Cascade Policies for. + * @param limit the number of entries for cascade policies to retrieve. + * @param fields optional fields to retrieve for cascade policies. + * @return the Iterable of Box Metadata Cascade Policies in your enterprise. + */ + public static Iterable getAll( + final BoxAPIConnection api, + String folderID, + String ownerEnterpriseID, + int limit, + String... fields) { + + QueryStringBuilder builder = new QueryStringBuilder(); + builder.appendParam("folder_id", folderID); + if (ownerEnterpriseID != null) { + builder.appendParam("owner_enterprise_id", ownerEnterpriseID); } + if (fields.length > 0) { + builder.appendParam("fields", fields); + } + return new BoxResourceIterable( + api, + GET_ALL_METADATA_CASCADE_POLICIES_URL_TEMPLATE.buildWithQuery( + api.getBaseURL(), builder.toString()), + limit) { + @Override + protected BoxMetadataCascadePolicy.Info factory(JsonObject jsonObject) { + BoxMetadataCascadePolicy cascadePolicy = + new BoxMetadataCascadePolicy(api, jsonObject.get("id").asString()); - /** - * Retrieves list of Box Metadata Cascade Policies that belong to your Enterprise as an Iterable. - * - * @param api the API connection to be used by the resource. - * @param folderID the ID of the folder to retrieve cascade policies for. - * @param fields optional fields to retrieve for cascade policies. - * @return the Iterable of Box Metadata Cascade Policies in your enterprise. - */ - public static Iterable getAll(final BoxAPIConnection api, - String folderID, String... fields) { - return getAll(api, folderID, null, DEFAULT_LIMIT, fields); + return cascadePolicy.new Info(jsonObject); + } + }; + } + + /** + * Creates a new Metadata Cascade Policy on a folder. + * + * @param api the API connection to be used by the resource. + * @param folderID the ID of the folder to create a metadata cascade policy on. + * @param scope the scope of the metadata cascade policy. + * @param templateKey the key of the template. + * @return information about the Metadata Cascade Policy. + */ + public static BoxMetadataCascadePolicy.Info create( + final BoxAPIConnection api, String folderID, String scope, String templateKey) { + URL url = GET_ALL_METADATA_CASCADE_POLICIES_URL_TEMPLATE.build(api.getBaseURL()); + BoxJSONRequest request = new BoxJSONRequest(api, url, "POST"); + JsonObject requestJSON = + new JsonObject() + .add("folder_id", folderID) + .add("scope", scope) + .add("templateKey", templateKey); + request.setBody(requestJSON.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + BoxMetadataCascadePolicy createdMetadataCascadePolicy = + new BoxMetadataCascadePolicy(api, responseJSON.get("id").asString()); + return createdMetadataCascadePolicy.new Info(responseJSON); } + } - /** - * Retrieves list of Box Metadata Cascade Policies that belong to your Enterprise as an Iterable. - * - * @param api the API connection to be used by the resource. - * @param folderID the ID of the folder to retrieve cascade policies for. - * @param ownerEnterpriseID the ID of the enterprise to retrieve Metadata Cascade Policies for. - * @param limit the number of entries for cascade policies to retrieve. - * @param fields optional fields to retrieve for cascade policies. - * @return the Iterable of Box Metadata Cascade Policies in your enterprise. - */ - public static Iterable getAll(final BoxAPIConnection api, - String folderID, String ownerEnterpriseID, int limit, - String... fields) { + /** + * Returns the information for a specific BoxMetadataCascadePolicy. + * + * @param fields the fields to retrieve. + * @return the information about this metadata cascade policy. + */ + public BoxMetadataCascadePolicy.Info getInfo(String... fields) { + QueryStringBuilder builder = new QueryStringBuilder(); + if (fields.length > 0) { + builder.appendParam("fields", fields); + } + URL url = + METADATA_CASCADE_POLICIES_URL_TEMPLATE.buildAlphaWithQuery( + this.getAPI().getBaseURL(), builder.toString(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + return new Info(responseJSON); + } + } - QueryStringBuilder builder = new QueryStringBuilder(); - builder.appendParam("folder_id", folderID); - if (ownerEnterpriseID != null) { - builder.appendParam("owner_enterprise_id", ownerEnterpriseID); - } - if (fields.length > 0) { - builder.appendParam("fields", fields); - } - return new BoxResourceIterable(api, GET_ALL_METADATA_CASCADE_POLICIES_URL_TEMPLATE - .buildWithQuery(api.getBaseURL(), builder.toString()), limit) { - @Override - protected BoxMetadataCascadePolicy.Info factory(JsonObject jsonObject) { - BoxMetadataCascadePolicy cascadePolicy = - new BoxMetadataCascadePolicy(api, jsonObject.get("id").asString()); + /** + * If a policy already exists on a folder, this will apply that policy to all existing files and + * sub folders within the target folder. + * + * @param conflictResolution the desired behavior for conflict-resolution. Set to either none or + * overwrite. + */ + public void forceApply(String conflictResolution) { + + URL url = + FORCE_METADATA_CASCADE_POLICIES_URL_TEMPLATE.buildAlpha( + this.getAPI().getBaseURL(), this.getID()); + BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "POST"); + JsonObject requestJSON = new JsonObject().add("conflict_resolution", conflictResolution); + request.setBody(requestJSON.toString()); + request.send().close(); + } + + /** Deletes the metadata cascade policy. */ + public void delete() { + URL url = + METADATA_CASCADE_POLICIES_URL_TEMPLATE.buildAlpha(this.getAPI().getBaseURL(), this.getID()); + BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); + request.send().close(); + } - return cascadePolicy.new Info(jsonObject); - } - }; + /** Contains information about a BoxMetadataCascadePolicy. */ + public class Info extends BoxResource.Info { + private BoxEnterprise ownerEnterprise; + private BoxFolder.Info parent; + private String scope; + private String templateKey; + + /** Constructs an empty Info object. */ + public Info() { + super(); } /** - * Creates a new Metadata Cascade Policy on a folder. + * Constructs an Info object by parsing information from a JSON string. * - * @param api the API connection to be used by the resource. - * @param folderID the ID of the folder to create a metadata cascade policy on. - * @param scope the scope of the metadata cascade policy. - * @param templateKey the key of the template. - * @return information about the Metadata Cascade Policy. + * @param json the JSON string to parse. */ - public static BoxMetadataCascadePolicy.Info create(final BoxAPIConnection api, String folderID, String scope, - String templateKey) { - URL url = GET_ALL_METADATA_CASCADE_POLICIES_URL_TEMPLATE.build(api.getBaseURL()); - BoxJSONRequest request = new BoxJSONRequest(api, url, "POST"); - JsonObject requestJSON = new JsonObject() - .add("folder_id", folderID) - .add("scope", scope) - .add("templateKey", templateKey); - request.setBody(requestJSON.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - BoxMetadataCascadePolicy createdMetadataCascadePolicy = new BoxMetadataCascadePolicy(api, - responseJSON.get("id").asString()); - return createdMetadataCascadePolicy.new Info(responseJSON); - } + public Info(String json) { + super(json); + } + + Info(JsonObject jsonObject) { + super(jsonObject); } /** - * Returns the information for a specific BoxMetadataCascadePolicy. + * Gets the enterprise the metadata cascade policy belongs to. * - * @param fields the fields to retrieve. - * @return the information about this metadata cascade policy. + * @return the enterprise the metadata cascade policy belongs to. */ - public BoxMetadataCascadePolicy.Info getInfo(String... fields) { - QueryStringBuilder builder = new QueryStringBuilder(); - if (fields.length > 0) { - builder.appendParam("fields", fields); - } - URL url = METADATA_CASCADE_POLICIES_URL_TEMPLATE.buildAlphaWithQuery(this.getAPI().getBaseURL(), - builder.toString(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - return new Info(responseJSON); - } + public BoxEnterprise getOwnerEnterprise() { + return this.ownerEnterprise; } /** - * If a policy already exists on a folder, this will apply that policy to all existing files and sub folders within - * the target folder. + * Gets the folder the metadata cascade policy is on. * - * @param conflictResolution the desired behavior for conflict-resolution. Set to either none or overwrite. + * @return the folder parent of the metadata cascade policy. */ - public void forceApply(String conflictResolution) { - - URL url = FORCE_METADATA_CASCADE_POLICIES_URL_TEMPLATE.buildAlpha(this.getAPI().getBaseURL(), this.getID()); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "POST"); - JsonObject requestJSON = new JsonObject() - .add("conflict_resolution", conflictResolution); - request.setBody(requestJSON.toString()); - request.send().close(); + public BoxFolder.Info getParent() { + return this.parent; } /** - * Deletes the metadata cascade policy. + * Gets the scope of the metadata cascade policy. + * + * @return the scope of the metadata cascade policy. */ - public void delete() { - URL url = METADATA_CASCADE_POLICIES_URL_TEMPLATE.buildAlpha(this.getAPI().getBaseURL(), this.getID()); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); - request.send().close(); + public String getScope() { + return this.scope; } /** - * Contains information about a BoxMetadataCascadePolicy. + * Gets the template key for the metadata cascade policy. + * + * @return the template key for the metadata cascade policy. */ - public class Info extends BoxResource.Info { - private BoxEnterprise ownerEnterprise; - private BoxFolder.Info parent; - private String scope; - private String templateKey; - - /** - * Constructs an empty Info object. - */ - public Info() { - super(); - } - - /** - * Constructs an Info object by parsing information from a JSON string. - * - * @param json the JSON string to parse. - */ - public Info(String json) { - super(json); - } - - Info(JsonObject jsonObject) { - super(jsonObject); - } - - /** - * Gets the enterprise the metadata cascade policy belongs to. - * - * @return the enterprise the metadata cascade policy belongs to. - */ - public BoxEnterprise getOwnerEnterprise() { - return this.ownerEnterprise; - } - - /** - * Gets the folder the metadata cascade policy is on. - * - * @return the folder parent of the metadata cascade policy. - */ - public BoxFolder.Info getParent() { - return this.parent; - } - - /** - * Gets the scope of the metadata cascade policy. - * - * @return the scope of the metadata cascade policy. - */ - public String getScope() { - return this.scope; - } - - /** - * Gets the template key for the metadata cascade policy. - * - * @return the template key for the metadata cascade policy. - */ - public String getTemplateKey() { - return this.templateKey; - } + public String getTemplateKey() { + return this.templateKey; + } - @Override - public BoxMetadataCascadePolicy getResource() { - return BoxMetadataCascadePolicy.this; - } + @Override + public BoxMetadataCascadePolicy getResource() { + return BoxMetadataCascadePolicy.this; + } - @Override - protected void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - String memberName = member.getName(); - JsonValue value = member.getValue(); - try { - if (memberName.equals("owner_enterprise")) { - JsonObject jsonObject = value.asObject(); - this.ownerEnterprise = new BoxEnterprise(jsonObject); - } else if (memberName.equals("parent")) { - JsonObject parentJSON = value.asObject(); - if (this.parent == null) { - String parentID = parentJSON.get("id").asString(); - BoxFolder folder = new BoxFolder(getAPI(), parentID); - this.parent = folder.new Info(parentJSON); - } else { - this.parent.update(parentJSON); - } - } else if (memberName.equals("scope")) { - this.scope = value.asString(); - } else if (memberName.equals("templateKey")) { - this.templateKey = value.asString(); - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); - } + @Override + protected void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + String memberName = member.getName(); + JsonValue value = member.getValue(); + try { + if (memberName.equals("owner_enterprise")) { + JsonObject jsonObject = value.asObject(); + this.ownerEnterprise = new BoxEnterprise(jsonObject); + } else if (memberName.equals("parent")) { + JsonObject parentJSON = value.asObject(); + if (this.parent == null) { + String parentID = parentJSON.get("id").asString(); + BoxFolder folder = new BoxFolder(getAPI(), parentID); + this.parent = folder.new Info(parentJSON); + } else { + this.parent.update(parentJSON); + } + } else if (memberName.equals("scope")) { + this.scope = value.asString(); + } else if (memberName.equals("templateKey")) { + this.templateKey = value.asString(); } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); + } } + } } diff --git a/src/main/java/com/box/sdk/BoxMetadataFilter.java b/src/main/java/com/box/sdk/BoxMetadataFilter.java index 9feed148a..f80ff8395 100644 --- a/src/main/java/com/box/sdk/BoxMetadataFilter.java +++ b/src/main/java/com/box/sdk/BoxMetadataFilter.java @@ -3,119 +3,118 @@ import com.eclipsesource.json.JsonObject; /** - *

BoxMetadataFilter is used to help organize the request for when making metadata filter request - * in conjuction with search. The translation will look something like this: - * [{"templateKey":"marketingCollateral", "scope":"enterprise", "filters":{"documentType": "datasheet"}}]

+ * BoxMetadataFilter is used to help organize the request for when making metadata filter request in + * conjuction with search. The translation will look something like this: + * [{"templateKey":"marketingCollateral", "scope":"enterprise", "filters":{"documentType": + * "datasheet"}}] */ public class BoxMetadataFilter { - private String templateKey; - private String scope = "enterprise"; - private JsonObject filtersList; - - /** - * Constructor for BoxMetadataFilter that initizlizes the JSON Object. - */ - public BoxMetadataFilter() { - this.filtersList = new JsonObject(); + private String templateKey; + private String scope = "enterprise"; + private JsonObject filtersList; + + /** Constructor for BoxMetadataFilter that initizlizes the JSON Object. */ + public BoxMetadataFilter() { + this.filtersList = new JsonObject(); + } + + /** + * Returns the template key that currently set. + * + * @return this.String template key. + */ + public String getTemplateKey() { + return this.templateKey; + } + + /** + * Set the current template key for the search filter. + * + * @param templateKey must be a metadata template key. + */ + public void setTemplateKey(String templateKey) { + this.templateKey = templateKey; + } + + /** + * return this.a list of the current filters that are being set. + * + * @return this.JsonObject filterList. + */ + public JsonObject getFiltersList() { + return this.filtersList; + } + + /** + * Set a filter to the filterList, example: key=documentType, value=special. + * + * @param key the key that the filter should be looking for. + * @param value the specific value that corresponds to the key. + */ + public void addFilter(String key, String value) { + this.filtersList.add(key, value); + } + + /** + * Set a NumberRanger filter to the filter numbers, example: key=documentNumber, lt : 20, gt : 5. + * + * @param key the key that the filter should be looking for. + * @param sizeRange the specific value that corresponds to the key. + */ + public void addNumberRangeFilter(String key, SizeRange sizeRange) { + JsonObject opObj = new JsonObject(); + + if (sizeRange.getLowerBoundBytes() != 0) { + opObj.add("gt", sizeRange.getLowerBoundBytes()); } - - /** - * Returns the template key that currently set. - * - * @return this.String template key. - */ - public String getTemplateKey() { - return this.templateKey; - } - - /** - * Set the current template key for the search filter. - * - * @param templateKey must be a metadata template key. - */ - public void setTemplateKey(String templateKey) { - this.templateKey = templateKey; + if (sizeRange.getUpperBoundBytes() != 0) { + opObj.add("lt", sizeRange.getUpperBoundBytes()); } - /** - * return this.a list of the current filters that are being set. - * - * @return this.JsonObject filterList. - */ - public JsonObject getFiltersList() { - return this.filtersList; - } + this.filtersList.add(key, opObj); + } - /** - * Set a filter to the filterList, example: key=documentType, value=special. - * - * @param key the key that the filter should be looking for. - * @param value the specific value that corresponds to the key. - */ - public void addFilter(String key, String value) { - this.filtersList.add(key, value); - } + /** + * Set a filter to the filterList, example: key=documentNumber, gt : "", lt : "". + * + * @param key the key that the filter should be looking for. + * @param dateRange the date range that is start and end dates + */ + public void addDateRangeFilter(String key, DateRange dateRange) { - /** - * Set a NumberRanger filter to the filter numbers, example: key=documentNumber, lt : 20, gt : 5. - * - * @param key the key that the filter should be looking for. - * @param sizeRange the specific value that corresponds to the key. - */ - public void addNumberRangeFilter(String key, SizeRange sizeRange) { - JsonObject opObj = new JsonObject(); - - if (sizeRange.getLowerBoundBytes() != 0) { - opObj.add("gt", sizeRange.getLowerBoundBytes()); - } - if (sizeRange.getUpperBoundBytes() != 0) { - opObj.add("lt", sizeRange.getUpperBoundBytes()); - } - - this.filtersList.add(key, opObj); - } + JsonObject opObj = new JsonObject(); - /** - * Set a filter to the filterList, example: key=documentNumber, gt : "", lt : "". - * - * @param key the key that the filter should be looking for. - * @param dateRange the date range that is start and end dates - */ - public void addDateRangeFilter(String key, DateRange dateRange) { - - JsonObject opObj = new JsonObject(); - - if (dateRange.getFromDate() != null) { - String dateGtString = BoxDateFormat.format(dateRange.getFromDate()); - //workaround replacing + and - 000 at the end with 'Z' - dateGtString = dateGtString.replaceAll("(\\+|-)(?!-\\|?!\\+)\\d+$", "Z"); - opObj.add("gt", dateGtString); - } - if (dateRange.getToDate() != null) { - String dateLtString = BoxDateFormat.format(dateRange.getToDate()); - //workaround replacing + and - 000 at the end with 'Z' - dateLtString = dateLtString.replaceAll("(\\+|-)(?!-\\|?!\\+)\\d+$", "Z"); - opObj.add("lt", dateLtString); - } - - this.filtersList.add(key, opObj); + if (dateRange.getFromDate() != null) { + String dateGtString = BoxDateFormat.format(dateRange.getFromDate()); + // workaround replacing + and - 000 at the end with 'Z' + dateGtString = dateGtString.replaceAll("(\\+|-)(?!-\\|?!\\+)\\d+$", "Z"); + opObj.add("gt", dateGtString); } - - /** - * return this.the current scope being used. - * - * @return this.String scope. - */ - public String getScope() { - return this.scope; + if (dateRange.getToDate() != null) { + String dateLtString = BoxDateFormat.format(dateRange.getToDate()); + // workaround replacing + and - 000 at the end with 'Z' + dateLtString = dateLtString.replaceAll("(\\+|-)(?!-\\|?!\\+)\\d+$", "Z"); + opObj.add("lt", dateLtString); } - /** - * Set the scope for the key, currently only "enterprise" and "global" are allowed. - * - * @param scope the scope on which to find the template. - */ - public void setScope(String scope) { - this.scope = scope; - } + this.filtersList.add(key, opObj); + } + + /** + * return this.the current scope being used. + * + * @return this.String scope. + */ + public String getScope() { + return this.scope; + } + + /** + * Set the scope for the key, currently only "enterprise" and "global" are allowed. + * + * @param scope the scope on which to find the template. + */ + public void setScope(String scope) { + this.scope = scope; + } } diff --git a/src/main/java/com/box/sdk/BoxMetadataQueryItem.java b/src/main/java/com/box/sdk/BoxMetadataQueryItem.java index 5d2db8e59..1805c1f0b 100644 --- a/src/main/java/com/box/sdk/BoxMetadataQueryItem.java +++ b/src/main/java/com/box/sdk/BoxMetadataQueryItem.java @@ -8,85 +8,85 @@ /** * Represents an individual item returned by a metadata query item. * - *

Unless otherwise noted, the methods in this class can throw an unchecked {@link BoxAPIException} (unchecked - * meaning that the compiler won't force you to handle it) if an error occurs. If you wish to implement custom error - * handling for errors related to the Box REST API, you should capture this exception explicitly. + *

Unless otherwise noted, the methods in this class can throw an unchecked {@link + * BoxAPIException} (unchecked meaning that the compiler won't force you to handle it) if an error + * occurs. If you wish to implement custom error handling for errors related to the Box REST API, + * you should capture this exception explicitly. */ public class BoxMetadataQueryItem extends BoxJSONObject { - private BoxItem.Info item; - private HashMap> metadata; - private BoxAPIConnection api; + private BoxItem.Info item; + private HashMap> metadata; + private BoxAPIConnection api; - /** - * Construct a BoxMetadataQueryItem. - * - * @param jsonObject the parsed JSON object. - * @param api the API connection to be used to fetch interacted item - */ - public BoxMetadataQueryItem(JsonObject jsonObject, BoxAPIConnection api) { - super(jsonObject); - this.api = api; - } + /** + * Construct a BoxMetadataQueryItem. + * + * @param jsonObject the parsed JSON object. + * @param api the API connection to be used to fetch interacted item + */ + public BoxMetadataQueryItem(JsonObject jsonObject, BoxAPIConnection api) { + super(jsonObject); + this.api = api; + } - @Override - protected void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); + @Override + protected void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); - String memberName = member.getName(); - JsonValue value = member.getValue(); - if (memberName.equals("item")) { - String id = value.asObject().get("id").asString(); - String type = value.asObject().get("type").asString(); - this.item = new BoxFile(this.api, id).new Info(value.asObject()); - if (type.equals("folder")) { - BoxFolder folder = new BoxFolder(this.api, id); - this.item = folder.new Info(value.asObject()); - } else if (type.equals("file")) { - BoxFile file = new BoxFile(this.api, id); - this.item = file.new Info(value.asObject()); - } else if (type.equals("web_link")) { - BoxWebLink link = new BoxWebLink(this.api, id); - this.item = link.new Info(value.asObject()); - } else { - assert false : "Unsupported item type: " + type; - throw new BoxAPIException("Unsupported item type: " + type); - } - } else if (memberName.equals("metadata")) { - this.metadata = new HashMap>(); - JsonObject metadataObject = value.asObject(); - for (JsonObject.Member enterprise : metadataObject) { - String enterpriseName = enterprise.getName(); - JsonObject templates = enterprise.getValue().asObject(); - ArrayList enterpriseMetadataArray = new ArrayList(); - for (JsonObject.Member template : templates) { - String templateName = template.getName(); - JsonObject templateValue = template.getValue().asObject(); - Metadata metadataOfTemplate = new Metadata(templateValue); - metadataOfTemplate.add("/$scope", enterpriseName); - metadataOfTemplate.add("/$template", templateName); - enterpriseMetadataArray.add(metadataOfTemplate); - } - this.metadata.put(enterpriseName, enterpriseMetadataArray); - } + String memberName = member.getName(); + JsonValue value = member.getValue(); + if (memberName.equals("item")) { + String id = value.asObject().get("id").asString(); + String type = value.asObject().get("type").asString(); + this.item = new BoxFile(this.api, id).new Info(value.asObject()); + if (type.equals("folder")) { + BoxFolder folder = new BoxFolder(this.api, id); + this.item = folder.new Info(value.asObject()); + } else if (type.equals("file")) { + BoxFile file = new BoxFile(this.api, id); + this.item = file.new Info(value.asObject()); + } else if (type.equals("web_link")) { + BoxWebLink link = new BoxWebLink(this.api, id); + this.item = link.new Info(value.asObject()); + } else { + assert false : "Unsupported item type: " + type; + throw new BoxAPIException("Unsupported item type: " + type); + } + } else if (memberName.equals("metadata")) { + this.metadata = new HashMap>(); + JsonObject metadataObject = value.asObject(); + for (JsonObject.Member enterprise : metadataObject) { + String enterpriseName = enterprise.getName(); + JsonObject templates = enterprise.getValue().asObject(); + ArrayList enterpriseMetadataArray = new ArrayList(); + for (JsonObject.Member template : templates) { + String templateName = template.getName(); + JsonObject templateValue = template.getValue().asObject(); + Metadata metadataOfTemplate = new Metadata(templateValue); + metadataOfTemplate.add("/$scope", enterpriseName); + metadataOfTemplate.add("/$template", templateName); + enterpriseMetadataArray.add(metadataOfTemplate); } + this.metadata.put(enterpriseName, enterpriseMetadataArray); + } } + } - /** - * Get the item which was interacted with. - * - * @return box item - */ - public BoxItem.Info getItem() { - return this.item; - } - - /** - * Get the metadata on the item. - * - * @return HashMap of metadata - */ - public HashMap> getMetadata() { - return this.metadata; - } + /** + * Get the item which was interacted with. + * + * @return box item + */ + public BoxItem.Info getItem() { + return this.item; + } + /** + * Get the metadata on the item. + * + * @return HashMap of metadata + */ + public HashMap> getMetadata() { + return this.metadata; + } } diff --git a/src/main/java/com/box/sdk/BoxMultipartRequest.java b/src/main/java/com/box/sdk/BoxMultipartRequest.java index 6481d5805..afdfb0adc 100644 --- a/src/main/java/com/box/sdk/BoxMultipartRequest.java +++ b/src/main/java/com/box/sdk/BoxMultipartRequest.java @@ -4,31 +4,32 @@ import okhttp3.MediaType; /** - *

Used to make HTTP multipart requests to the Box API.

+ * Used to make HTTP multipart requests to the Box API. * - *

This class partially implements the HTTP multipart standard in order to upload files to Box. The body of this - * request type cannot be set directly. Instead, it can be modified by adding multipart fields and setting file - * contents. The body of multipart requests will not be logged since they are likely to contain binary data.

+ *

This class partially implements the HTTP multipart standard in order to upload files to Box. + * The body of this request type cannot be set directly. Instead, it can be modified by adding + * multipart fields and setting file contents. The body of multipart requests will not be logged + * since they are likely to contain binary data. */ public class BoxMultipartRequest extends AbstractBoxMultipartRequest { - /** - * Constructs an authenticated BoxMultipartRequest using a provided BoxAPIConnection. - * - * @param api an API connection for authenticating the request. - * @param url the URL of the request. - */ - public BoxMultipartRequest(BoxAPIConnection api, URL url) { - super(api, url); - } + /** + * Constructs an authenticated BoxMultipartRequest using a provided BoxAPIConnection. + * + * @param api an API connection for authenticating the request. + * @param url the URL of the request. + */ + public BoxMultipartRequest(BoxAPIConnection api, URL url) { + super(api, url); + } - @Override - protected String getPartName() { - return "file"; - } + @Override + protected String getPartName() { + return "file"; + } - @Override - protected MediaType getPartContentType(String filename) { - return MediaType.parse("application/octet-stream"); - } + @Override + protected MediaType getPartContentType(String filename) { + return MediaType.parse("application/octet-stream"); + } } diff --git a/src/main/java/com/box/sdk/BoxNotificationEmail.java b/src/main/java/com/box/sdk/BoxNotificationEmail.java index 5b833b32e..3d8a1412c 100644 --- a/src/main/java/com/box/sdk/BoxNotificationEmail.java +++ b/src/main/java/com/box/sdk/BoxNotificationEmail.java @@ -4,75 +4,69 @@ import com.eclipsesource.json.JsonObject; import com.eclipsesource.json.JsonValue; -/** - * Represents a notification email object - */ +/** Represents a notification email object */ public class BoxNotificationEmail extends BoxJSONObject { - private boolean isConfirmed; - private String email; + private boolean isConfirmed; + private String email; + /** + * Constructs a BoxNotificationEmail object. + * + * @param email The email address to send the notifications to. + * @param isConfirmed Specifies if this email address has been confirmed. + */ + public BoxNotificationEmail(String email, boolean isConfirmed) { + this(new JsonObject().add("email", email).add("is_confirmed", isConfirmed)); + } - /** - * Constructs a BoxNotificationEmail object. - * - * @param email The email address to send the notifications to. - * @param isConfirmed Specifies if this email address has been confirmed. - */ - public BoxNotificationEmail(String email, boolean isConfirmed) { - this(new JsonObject() - .add("email", email) - .add("is_confirmed", isConfirmed) - ); - } - - /** - * Constructs a BoxNotificationEmail from a JSON string. - * - * @param json the json encoded email alias. - */ - public BoxNotificationEmail(String json) { - this(Json.parse(json).asObject()); - } + /** + * Constructs a BoxNotificationEmail from a JSON string. + * + * @param json the json encoded email alias. + */ + public BoxNotificationEmail(String json) { + this(Json.parse(json).asObject()); + } - /** - * Constructs a BoxNotificationEmail using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - BoxNotificationEmail(JsonObject jsonObject) { - super(jsonObject); - } + /** + * Constructs a BoxNotificationEmail using an already parsed JSON object. + * + * @param jsonObject the parsed JSON object. + */ + BoxNotificationEmail(JsonObject jsonObject) { + super(jsonObject); + } - /** - * Gets if this email address has been confirmed. - * - * @return true if this email address has been confirmed; otherwise false. - */ - public boolean getIsConfirmed() { - return this.isConfirmed; - } + /** + * Gets if this email address has been confirmed. + * + * @return true if this email address has been confirmed; otherwise false. + */ + public boolean getIsConfirmed() { + return this.isConfirmed; + } - /** - * Gets the email address to send notifications to. - * - * @return The email address to send the notifications to. - */ - public String getEmail() { - return this.email; - } + /** + * Gets the email address to send notifications to. + * + * @return The email address to send the notifications to. + */ + public String getEmail() { + return this.email; + } - @Override - void parseJSONMember(JsonObject.Member member) { - JsonValue value = member.getValue(); - String memberName = member.getName(); - try { - if (memberName.equals("is_confirmed")) { - this.isConfirmed = value.asBoolean(); - } else if (memberName.equals("email")) { - this.email = value.asString(); - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); - } + @Override + void parseJSONMember(JsonObject.Member member) { + JsonValue value = member.getValue(); + String memberName = member.getName(); + try { + if (memberName.equals("is_confirmed")) { + this.isConfirmed = value.asBoolean(); + } else if (memberName.equals("email")) { + this.email = value.asString(); + } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); } + } } diff --git a/src/main/java/com/box/sdk/BoxRecentItem.java b/src/main/java/com/box/sdk/BoxRecentItem.java index 8d956f7cc..7b62e9fe5 100644 --- a/src/main/java/com/box/sdk/BoxRecentItem.java +++ b/src/main/java/com/box/sdk/BoxRecentItem.java @@ -10,98 +10,98 @@ /** * Represents an individual recent item. * - *

Unless otherwise noted, the methods in this class can throw an unchecked {@link BoxAPIException} (unchecked - * meaning that the compiler won't force you to handle it) if an error occurs. If you wish to implement custom error - * handling for errors related to the Box REST API, you should capture this exception explicitly.* + *

Unless otherwise noted, the methods in this class can throw an unchecked {@link + * BoxAPIException} (unchecked meaning that the compiler won't force you to handle it) if an error + * occurs. If you wish to implement custom error handling for errors related to the Box REST API, + * you should capture this exception explicitly.* */ public class BoxRecentItem extends BoxJSONObject { - private String type; - private String interactionType; - private BoxItem.Info item; - private Date interactedAt; - private URL interactionSharedLink; - private BoxAPIConnection api; + private String type; + private String interactionType; + private BoxItem.Info item; + private Date interactedAt; + private URL interactionSharedLink; + private BoxAPIConnection api; - /** - * Construct a BoxRecentItem. - * - * @param jsonObject the parsed JSON object. - * @param api the API connection to be used to fetch interacted item - */ - public BoxRecentItem(JsonObject jsonObject, BoxAPIConnection api) { - super(jsonObject); - this.api = api; - } + /** + * Construct a BoxRecentItem. + * + * @param jsonObject the parsed JSON object. + * @param api the API connection to be used to fetch interacted item + */ + public BoxRecentItem(JsonObject jsonObject, BoxAPIConnection api) { + super(jsonObject); + this.api = api; + } - @Override - protected void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); + @Override + protected void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); - String memberName = member.getName(); - JsonValue value = member.getValue(); - try { - if (memberName.equals("type")) { - this.type = value.asString(); - } else if (memberName.equals("interaction_type")) { - this.interactionType = value.asString(); - } else if (memberName.equals("item")) { - String id = value.asObject().get("id").asString(); - this.item = new BoxFile(this.api, id).new Info(value.asObject()); - } else if (memberName.equals("interacted_at")) { - this.interactedAt = BoxDateFormat.parse(value.asString()); - } else if (memberName.equals("interaction_shared_link")) { - this.interactionSharedLink = new URL(value.asString()); - } - } catch (ParseException e) { - assert false : "A ParseException indicates a bug in the SDK."; - } catch (MalformedURLException e) { - assert false : "A ParseException indicates a bug in the SDK."; - } + String memberName = member.getName(); + JsonValue value = member.getValue(); + try { + if (memberName.equals("type")) { + this.type = value.asString(); + } else if (memberName.equals("interaction_type")) { + this.interactionType = value.asString(); + } else if (memberName.equals("item")) { + String id = value.asObject().get("id").asString(); + this.item = new BoxFile(this.api, id).new Info(value.asObject()); + } else if (memberName.equals("interacted_at")) { + this.interactedAt = BoxDateFormat.parse(value.asString()); + } else if (memberName.equals("interaction_shared_link")) { + this.interactionSharedLink = new URL(value.asString()); + } + } catch (ParseException e) { + assert false : "A ParseException indicates a bug in the SDK."; + } catch (MalformedURLException e) { + assert false : "A ParseException indicates a bug in the SDK."; } + } - /** - * Get item type. - * - * @return type of item - */ - public String getType() { - return this.type; - } + /** + * Get item type. + * + * @return type of item + */ + public String getType() { + return this.type; + } - /** - * Get interaction type. - * - * @return interaction type - */ - public String getInteractionType() { - return this.interactionType; - } + /** + * Get interaction type. + * + * @return interaction type + */ + public String getInteractionType() { + return this.interactionType; + } - /** - * Get the item which was interacted with. - * - * @return box item - */ - public BoxItem.Info getItem() { - return this.item; - } + /** + * Get the item which was interacted with. + * + * @return box item + */ + public BoxItem.Info getItem() { + return this.item; + } - /** - * Get the interaction date. - * - * @return interaction date - */ - public Date getInteractedAt() { - return this.interactedAt; - } - - /** - * Get the shared link, if the item was accessed through a shared link. - * - * @return shared link - */ - public URL getInteractionSharedLink() { - return this.interactionSharedLink; - } + /** + * Get the interaction date. + * + * @return interaction date + */ + public Date getInteractedAt() { + return this.interactedAt; + } + /** + * Get the shared link, if the item was accessed through a shared link. + * + * @return shared link + */ + public URL getInteractionSharedLink() { + return this.interactionSharedLink; + } } diff --git a/src/main/java/com/box/sdk/BoxRecents.java b/src/main/java/com/box/sdk/BoxRecents.java index 971c4e209..90179c257 100644 --- a/src/main/java/com/box/sdk/BoxRecents.java +++ b/src/main/java/com/box/sdk/BoxRecents.java @@ -9,38 +9,34 @@ */ public final class BoxRecents { - /** - * Recents URL Template. - */ - public static final URLTemplate RECENTS_URL_TEMPLATE = new URLTemplate("recent_items"); + /** Recents URL Template. */ + public static final URLTemplate RECENTS_URL_TEMPLATE = new URLTemplate("recent_items"); - //Constructor is not allowed - private BoxRecents() { - } - - /** - * Used to retrieve all collaborations associated with the item. - * - * @param api BoxAPIConnection from the associated file. - * @param limit limit of items to be retrieved. Default is 100. Maximum is 1000 - * @param fields the optional fields to retrieve. - * @return An iterable of BoxCollaboration.Info instances associated with the item. - * @see https://developer.box.com/reference#get-recent-items - */ - public static BoxResourceIterable getRecentItems(final BoxAPIConnection api, - int limit, String... fields) { - QueryStringBuilder builder = new QueryStringBuilder(); - if (fields.length > 0) { - builder.appendParam("fields", fields); - } - return new BoxResourceIterable( - api, RECENTS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString()), - limit) { + // Constructor is not allowed + private BoxRecents() {} - @Override - protected BoxRecentItem factory(JsonObject jsonObject) { - return new BoxRecentItem(jsonObject, api); - } - }; + /** + * Used to retrieve all collaborations associated with the item. + * + * @param api BoxAPIConnection from the associated file. + * @param limit limit of items to be retrieved. Default is 100. Maximum is 1000 + * @param fields the optional fields to retrieve. + * @return An iterable of BoxCollaboration.Info instances associated with the item. + * @see https://developer.box.com/reference#get-recent-items + */ + public static BoxResourceIterable getRecentItems( + final BoxAPIConnection api, int limit, String... fields) { + QueryStringBuilder builder = new QueryStringBuilder(); + if (fields.length > 0) { + builder.appendParam("fields", fields); } + return new BoxResourceIterable( + api, RECENTS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString()), limit) { + + @Override + protected BoxRecentItem factory(JsonObject jsonObject) { + return new BoxRecentItem(jsonObject, api); + } + }; + } } diff --git a/src/main/java/com/box/sdk/BoxResource.java b/src/main/java/com/box/sdk/BoxResource.java index 3afc01937..fea42ed12 100644 --- a/src/main/java/com/box/sdk/BoxResource.java +++ b/src/main/java/com/box/sdk/BoxResource.java @@ -8,201 +8,203 @@ import java.util.concurrent.ConcurrentHashMap; /** - * The abstract base class for all resource types (files, folders, comments, collaborations, etc.) used by the API. + * The abstract base class for all resource types (files, folders, comments, collaborations, etc.) + * used by the API. * - *

Every API resource has an ID and a {@link BoxAPIConnection} that it uses to communicate with the API. Some - * resources also have an associated {@link Info} class that contains information about the resource.

+ *

Every API resource has an ID and a {@link BoxAPIConnection} that it uses to communicate with + * the API. Some resources also have an associated {@link Info} class that contains information + * about the resource. */ public abstract class BoxResource { - /** - * @see #initResourceClassByType() - */ - private static final Map> RESOURCE_CLASS_BY_TYPE = initResourceClassByType(); - - private final BoxAPIConnection api; - private final String id; - - /** - * Constructs a BoxResource for a resource with a given ID. - * - * @param api the API connection to be used by the resource. - * @param id the ID of the resource. - */ - public BoxResource(BoxAPIConnection api, String id) { - this.api = api; - this.id = id; + /** @see #initResourceClassByType() */ + private static final Map> RESOURCE_CLASS_BY_TYPE = + initResourceClassByType(); + + private final BoxAPIConnection api; + private final String id; + + /** + * Constructs a BoxResource for a resource with a given ID. + * + * @param api the API connection to be used by the resource. + * @param id the ID of the resource. + */ + public BoxResource(BoxAPIConnection api, String id) { + this.api = api; + this.id = id; + } + + /** + * @return Builds {@link Map} between String {@link #getResourceType(Class)} and {@link + * BoxResource} type. + */ + private static Map> initResourceClassByType() { + Map> result = + new ConcurrentHashMap>(); + result.put(getResourceType(BoxFolder.class), BoxFolder.class); + result.put(getResourceType(BoxFile.class), BoxFile.class); + result.put(getResourceType(BoxComment.class), BoxComment.class); + result.put(getResourceType(BoxCollaboration.class), BoxCollaboration.class); + result.put(getResourceType(BoxTask.class), BoxTask.class); + result.put(getResourceType(BoxTaskAssignment.class), BoxTaskAssignment.class); + result.put(getResourceType(BoxUser.class), BoxUser.class); + result.put(getResourceType(BoxGroup.class), BoxGroup.class); + result.put(getResourceType(BoxGroupMembership.class), BoxGroupMembership.class); + result.put(getResourceType(BoxEvent.class), BoxEvent.class); + result.put(getResourceType(BoxWebHook.class), BoxWebHook.class); + result.put(getResourceType(BoxCollection.class), BoxCollection.class); + result.put(getResourceType(BoxDevicePin.class), BoxDevicePin.class); + result.put(getResourceType(BoxRetentionPolicy.class), BoxRetentionPolicy.class); + result.put( + getResourceType(BoxRetentionPolicyAssignment.class), BoxRetentionPolicyAssignment.class); + result.put(getResourceType(BoxFileVersionRetention.class), BoxFileVersionRetention.class); + result.put(getResourceType(BoxLegalHoldPolicy.class), BoxLegalHoldPolicy.class); + result.put(getResourceType(BoxLegalHoldAssignment.class), BoxLegalHoldAssignment.class); + result.put(getResourceType(BoxFileVersionLegalHold.class), BoxFileVersionLegalHold.class); + result.put(getResourceType(BoxFileUploadSession.class), BoxFileUploadSession.class); + result.put(getResourceType(BoxWebLink.class), BoxWebLink.class); + result.put(getResourceType(BoxStoragePolicy.class), BoxStoragePolicy.class); + result.put(getResourceType(BoxStoragePolicyAssignment.class), BoxStoragePolicyAssignment.class); + result.put(getResourceType(BoxFolderLock.class), BoxFolderLock.class); + result.put(getResourceType(BoxFileRequest.class), BoxFileRequest.class); + + return Collections.unmodifiableMap(result); + } + + /** + * Resolves {@link BoxResourceType} for a provided {@link BoxResource} {@link Class}. + * + * @param clazz {@link BoxResource} type + * @return resolved {@link BoxResourceType#value()} + */ + public static String getResourceType(Class clazz) { + BoxResourceType resource = clazz.getAnnotation(BoxResourceType.class); + if (resource == null) { + throw new IllegalArgumentException( + "Provided BoxResource type does not have @BoxResourceType annotation."); } - - /** - * @return Builds {@link Map} between String {@link #getResourceType(Class)} and {@link BoxResource} type. - */ - private static Map> initResourceClassByType() { - Map> result = - new ConcurrentHashMap>(); - result.put(getResourceType(BoxFolder.class), BoxFolder.class); - result.put(getResourceType(BoxFile.class), BoxFile.class); - result.put(getResourceType(BoxComment.class), BoxComment.class); - result.put(getResourceType(BoxCollaboration.class), BoxCollaboration.class); - result.put(getResourceType(BoxTask.class), BoxTask.class); - result.put(getResourceType(BoxTaskAssignment.class), BoxTaskAssignment.class); - result.put(getResourceType(BoxUser.class), BoxUser.class); - result.put(getResourceType(BoxGroup.class), BoxGroup.class); - result.put(getResourceType(BoxGroupMembership.class), BoxGroupMembership.class); - result.put(getResourceType(BoxEvent.class), BoxEvent.class); - result.put(getResourceType(BoxWebHook.class), BoxWebHook.class); - result.put(getResourceType(BoxCollection.class), BoxCollection.class); - result.put(getResourceType(BoxDevicePin.class), BoxDevicePin.class); - result.put(getResourceType(BoxRetentionPolicy.class), BoxRetentionPolicy.class); - result.put(getResourceType(BoxRetentionPolicyAssignment.class), BoxRetentionPolicyAssignment.class); - result.put(getResourceType(BoxFileVersionRetention.class), BoxFileVersionRetention.class); - result.put(getResourceType(BoxLegalHoldPolicy.class), BoxLegalHoldPolicy.class); - result.put(getResourceType(BoxLegalHoldAssignment.class), BoxLegalHoldAssignment.class); - result.put(getResourceType(BoxFileVersionLegalHold.class), BoxFileVersionLegalHold.class); - result.put(getResourceType(BoxFileUploadSession.class), BoxFileUploadSession.class); - result.put(getResourceType(BoxWebLink.class), BoxWebLink.class); - result.put(getResourceType(BoxStoragePolicy.class), BoxStoragePolicy.class); - result.put(getResourceType(BoxStoragePolicyAssignment.class), BoxStoragePolicyAssignment.class); - result.put(getResourceType(BoxFolderLock.class), BoxFolderLock.class); - result.put(getResourceType(BoxFileRequest.class), BoxFileRequest.class); - - return Collections.unmodifiableMap(result); + return resource.value(); + } + + static BoxResource.Info parseInfo(BoxAPIConnection api, JsonObject jsonObject) { + String type = jsonObject.get("type").asString(); + String id = jsonObject.get("id").asString(); + + try { + Class resourceClass = RESOURCE_CLASS_BY_TYPE.get(type); + Constructor resourceConstructor = + resourceClass.getConstructor(BoxAPIConnection.class, String.class); + + Class infoClass = + resourceClass.getClassLoader().loadClass(resourceClass.getCanonicalName() + "$Info"); + Constructor infoConstructor = + infoClass.getDeclaredConstructor(resourceClass, JsonObject.class); + + BoxResource resource = resourceConstructor.newInstance(api, id); + return (BoxResource.Info) infoConstructor.newInstance(resource, jsonObject); + + } catch (ClassNotFoundException e) { + return null; + } catch (NoSuchMethodException e) { + return null; + } catch (IllegalAccessException e) { + throw new BoxAPIException("Can not create BoxResource.Info instance:", e); + } catch (InvocationTargetException e) { + throw new BoxAPIException("Can not create BoxResource.Info instance:", e); + } catch (InstantiationException e) { + throw new BoxAPIException("Can not create BoxResource.Info instance:", e); } - - /** - * Resolves {@link BoxResourceType} for a provided {@link BoxResource} {@link Class}. - * - * @param clazz {@link BoxResource} type - * @return resolved {@link BoxResourceType#value()} - */ - public static String getResourceType(Class clazz) { - BoxResourceType resource = clazz.getAnnotation(BoxResourceType.class); - if (resource == null) { - throw new IllegalArgumentException("Provided BoxResource type does not have @BoxResourceType annotation."); - } - return resource.value(); + } + + /** + * Gets the API connection used by this resource. + * + * @return the API connection used by this resource. + */ + public BoxAPIConnection getAPI() { + return this.api; + } + + /** + * Gets the ID of this resource. + * + * @return the ID of this resource. + */ + public String getID() { + return this.id; + } + + /** + * Indicates whether this BoxResource is equal to another BoxResource. Two BoxResources are equal + * if they have the same type and ID. + * + * @param other the other BoxResource to compare. + * @return true if the type and IDs of the two resources are equal; otherwise false. + */ + @Override + public boolean equals(Object other) { + if (other == null) { + return false; } - static BoxResource.Info parseInfo(BoxAPIConnection api, JsonObject jsonObject) { - String type = jsonObject.get("type").asString(); - String id = jsonObject.get("id").asString(); - - try { - Class resourceClass = RESOURCE_CLASS_BY_TYPE.get(type); - Constructor resourceConstructor = - resourceClass.getConstructor(BoxAPIConnection.class, String.class); - - Class infoClass = resourceClass.getClassLoader().loadClass(resourceClass.getCanonicalName() + "$Info"); - Constructor infoConstructor = infoClass.getDeclaredConstructor(resourceClass, JsonObject.class); - - BoxResource resource = resourceConstructor.newInstance(api, id); - return (BoxResource.Info) infoConstructor.newInstance(resource, jsonObject); - - } catch (ClassNotFoundException e) { - return null; - } catch (NoSuchMethodException e) { - return null; - } catch (IllegalAccessException e) { - throw new BoxAPIException("Can not create BoxResource.Info instance:", e); - } catch (InvocationTargetException e) { - throw new BoxAPIException("Can not create BoxResource.Info instance:", e); - } catch (InstantiationException e) { - throw new BoxAPIException("Can not create BoxResource.Info instance:", e); - } + if (this.getClass().equals(other.getClass())) { + BoxResource otherResource = (BoxResource) other; + return this.getID().equals(otherResource.getID()); } - /** - * Gets the API connection used by this resource. - * - * @return the API connection used by this resource. - */ - public BoxAPIConnection getAPI() { - return this.api; + return false; + } + + /** + * Returns a hash code value for this BoxResource. + * + * @return a hash code value for this BoxResource. + */ + @Override + public int hashCode() { + return this.getID().hashCode(); + } + + /** Contains information about a BoxResource. */ + public abstract class Info extends BoxJSONObject { + /** Constructs an empty Info object. */ + public Info() { + super(); } /** - * Gets the ID of this resource. + * Constructs an Info object by parsing information from a JSON string. * - * @return the ID of this resource. + * @param json the JSON string to parse. */ - public String getID() { - return this.id; + public Info(String json) { + super(json); } /** - * Indicates whether this BoxResource is equal to another BoxResource. Two BoxResources are equal if they have the - * same type and ID. + * Constructs an Info object using an already parsed JSON object. * - * @param other the other BoxResource to compare. - * @return true if the type and IDs of the two resources are equal; otherwise false. + * @param jsonObject the parsed JSON object. */ - @Override - public boolean equals(Object other) { - if (other == null) { - return false; - } - - if (this.getClass().equals(other.getClass())) { - BoxResource otherResource = (BoxResource) other; - return this.getID().equals(otherResource.getID()); - } - - return false; + Info(JsonObject jsonObject) { + super(jsonObject); } /** - * Returns a hash code value for this BoxResource. + * Gets the ID of the resource associated with this Info. * - * @return a hash code value for this BoxResource. + * @return the ID of the associated resource. */ - @Override - public int hashCode() { - return this.getID().hashCode(); + public String getID() { + return BoxResource.this.getID(); } /** - * Contains information about a BoxResource. + * Gets the resource associated with this Info. + * + * @return the associated resource. */ - public abstract class Info extends BoxJSONObject { - /** - * Constructs an empty Info object. - */ - public Info() { - super(); - } - - /** - * Constructs an Info object by parsing information from a JSON string. - * - * @param json the JSON string to parse. - */ - public Info(String json) { - super(json); - } - - /** - * Constructs an Info object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - Info(JsonObject jsonObject) { - super(jsonObject); - } - - /** - * Gets the ID of the resource associated with this Info. - * - * @return the ID of the associated resource. - */ - public String getID() { - return BoxResource.this.getID(); - } - - /** - * Gets the resource associated with this Info. - * - * @return the associated resource. - */ - public abstract BoxResource getResource(); - } + public abstract BoxResource getResource(); + } } diff --git a/src/main/java/com/box/sdk/BoxResourceIterable.java b/src/main/java/com/box/sdk/BoxResourceIterable.java index b4eb855e5..fbfbfd57e 100644 --- a/src/main/java/com/box/sdk/BoxResourceIterable.java +++ b/src/main/java/com/box/sdk/BoxResourceIterable.java @@ -16,244 +16,212 @@ */ public abstract class BoxResourceIterable implements Iterable { - /** - * Parameter for max page size. - */ - public static final String PARAMETER_LIMIT = "limit"; - - /** - * Parameter for marker for the beginning of next page. - */ - public static final String PARAMETER_MARKER = "marker"; - - /** - * Body Parameter for marker for the beginning of next page. - */ - public static final String BODY_PARAMETER_MARKER_NEXT = "next_marker"; - - /** - * Body parameter for page entries. - */ - public static final String BODY_PARAMETER_ENTRIES = "entries"; - - /** - * The API connection to be used by the resource. - */ - private final BoxAPIConnection api; - - /** - * To end-point with paging support. - */ - private final URL url; - - /** - * The maximum number of items to return in a page. - */ - private final int limit; - - /** - * The iterator that gets the next items. - */ - private final IteratorImpl iterator; + /** Parameter for max page size. */ + public static final String PARAMETER_LIMIT = "limit"; + + /** Parameter for marker for the beginning of next page. */ + public static final String PARAMETER_MARKER = "marker"; + + /** Body Parameter for marker for the beginning of next page. */ + public static final String BODY_PARAMETER_MARKER_NEXT = "next_marker"; + + /** Body parameter for page entries. */ + public static final String BODY_PARAMETER_ENTRIES = "entries"; + + /** The API connection to be used by the resource. */ + private final BoxAPIConnection api; + + /** To end-point with paging support. */ + private final URL url; + + /** The maximum number of items to return in a page. */ + private final int limit; + + /** The iterator that gets the next items. */ + private final IteratorImpl iterator; + + /** + * Constructor. + * + * @param api the API connection to be used by the resource + * @param url endpoint with paging support + * @param limit the maximum number of items to return in a page + */ + public BoxResourceIterable(BoxAPIConnection api, URL url, int limit) { + this(api, url, limit, null, null); + } + + /** + * Constructor. + * + * @param api the API connection to be used by the resource. + * @param url to endpoint with paging support. + * @param limit the maximum number of items to return in a page. + * @param body the body to send to the requested endpoint. + */ + public BoxResourceIterable(BoxAPIConnection api, URL url, int limit, JsonObject body) { + this(api, url, limit, body, null); + } + + /** + * Constructor. + * + * @param api the API connection to be used by the resource. + * @param url to endpoint with paging support. + * @param limit the maximum number of items to return in a page. + * @param marker the marker where the iterator will begin + */ + public BoxResourceIterable(BoxAPIConnection api, URL url, int limit, String marker) { + this(api, url, limit, null, marker); + } + + /** + * Constructor. + * + * @param api the API connection to be used by the resource. + * @param url to endpoint with paging support. + * @param limit the maximum number of items to return in a page. + * @param body the body to send to the requested endpoint. + * @param marker the marker where the iterator will begin + */ + public BoxResourceIterable( + BoxAPIConnection api, URL url, int limit, JsonObject body, String marker) { + this.api = api; + this.url = url; + this.limit = limit; + this.iterator = new IteratorImpl(marker, body); + } + + /** + * Factory to build a new instance for a received JSON item. + * + * @param jsonObject of the item + * @return the item instance + */ + protected abstract T factory(JsonObject jsonObject); + + /** + * Builds internal read-only iterator over {@link BoxResource}-s. + * + * @return iterator implementation + * @see Iterable#iterator() + */ + @Override + public Iterator iterator() { + return this.iterator; + } + + /** + * Builds internal read-only iterator over {@link BoxResource}-s. + * + * @return iterator implementation + * @see Iterable#iterator() + */ + public String getNextMarker() { + return this.iterator.markerNext; + } + + /** Paging implementation. */ + private class IteratorImpl implements Iterator { + + /** + * Base 64 encoded string that represents where the paging should being. It should be left blank + * to begin paging. + */ + private String markerNext; + + /** Current loaded page. */ + private JsonArray page; + + /** Cursor within the page (index of a next item for read). */ + private int pageCursor; + + /** The body to include in the request. */ + private JsonObject body; /** * Constructor. * - * @param api the API connection to be used by the resource - * @param url endpoint with paging support - * @param limit the maximum number of items to return in a page + * @param marker the marker at which the iterator will begin + * @param body Request body */ - public BoxResourceIterable(BoxAPIConnection api, URL url, int limit) { - this(api, url, limit, null, null); + IteratorImpl(String marker, JsonObject body) { + this.markerNext = marker; + this.body = body; + this.loadNextPage(); } - /** - * Constructor. - * - * @param api the API connection to be used by the resource. - * @param url to endpoint with paging support. - * @param limit the maximum number of items to return in a page. - * @param body the body to send to the requested endpoint. - */ - public BoxResourceIterable(BoxAPIConnection api, URL url, int limit, JsonObject body) { - this(api, url, limit, body, null); - } + /** Loads next page. */ + private void loadNextPage() { + String existingQuery = BoxResourceIterable.this.url.getQuery(); + QueryStringBuilder builder = new QueryStringBuilder(existingQuery); + builder.appendParam(PARAMETER_LIMIT, BoxResourceIterable.this.limit); + if (this.markerNext != null) { + if (this.body != null) { + this.body.set("marker", this.markerNext); + } else { + builder.appendParam(PARAMETER_MARKER, this.markerNext); + } + } + + URL url; + try { + url = builder.replaceQuery(BoxResourceIterable.this.url); + } catch (MalformedURLException e) { + throw new BoxAPIException("Couldn't append a query string to the provided URL."); + } + + BoxJSONRequest request; + if (this.body != null) { + request = new BoxJSONRequest(BoxResourceIterable.this.api, url, "POST"); + request.setBody(this.body.toString()); + } else { + request = new BoxJSONRequest(BoxResourceIterable.this.api, url, "GET"); + } + + try (BoxJSONResponse response = request.send()) { + JsonObject pageBody = Json.parse(response.getJSON()).asObject(); + + JsonValue markerNextValue = pageBody.get(BODY_PARAMETER_MARKER_NEXT); + if (markerNextValue != null && markerNextValue.isString()) { + this.markerNext = markerNextValue.asString(); + } else { + this.markerNext = null; + } - /** - * Constructor. - * - * @param api the API connection to be used by the resource. - * @param url to endpoint with paging support. - * @param limit the maximum number of items to return in a page. - * @param marker the marker where the iterator will begin - */ - public BoxResourceIterable(BoxAPIConnection api, URL url, int limit, String marker) { - this(api, url, limit, null, marker); + this.page = pageBody.get(BODY_PARAMETER_ENTRIES).asArray(); + this.pageCursor = 0; + } } - /** - * Constructor. - * - * @param api the API connection to be used by the resource. - * @param url to endpoint with paging support. - * @param limit the maximum number of items to return in a page. - * @param body the body to send to the requested endpoint. - * @param marker the marker where the iterator will begin - */ - public BoxResourceIterable(BoxAPIConnection api, URL url, int limit, JsonObject body, String marker) { - this.api = api; - this.url = url; - this.limit = limit; - this.iterator = new IteratorImpl(marker, body); + /** {@inheritDoc} */ + @Override + public boolean hasNext() { + if (this.pageCursor < this.page.size()) { + return true; + } + if (this.markerNext == null || this.markerNext.isEmpty()) { + return false; + } + this.loadNextPage(); + return !this.page.isEmpty(); } - /** - * Factory to build a new instance for a received JSON item. - * - * @param jsonObject of the item - * @return the item instance - */ - protected abstract T factory(JsonObject jsonObject); - - /** - * Builds internal read-only iterator over {@link BoxResource}-s. - * - * @return iterator implementation - * @see Iterable#iterator() - */ + /** {@inheritDoc} */ @Override - public Iterator iterator() { - return this.iterator; - } + public T next() { + if (!this.hasNext()) { + throw new NoSuchElementException(); + } - /** - * Builds internal read-only iterator over {@link BoxResource}-s. - * - * @return iterator implementation - * @see Iterable#iterator() - */ - public String getNextMarker() { - return this.iterator.markerNext; + JsonObject entry = this.page.get(this.pageCursor++).asObject(); + return BoxResourceIterable.this.factory(entry); } - /** - * Paging implementation. - */ - private class IteratorImpl implements Iterator { - - /** - * Base 64 encoded string that represents where the paging should being. It should be left blank to begin - * paging. - */ - private String markerNext; - - /** - * Current loaded page. - */ - private JsonArray page; - - /** - * Cursor within the page (index of a next item for read). - */ - private int pageCursor; - - /** - * The body to include in the request. - */ - private JsonObject body; - - /** - * Constructor. - * - * @param marker the marker at which the iterator will begin - * @param body Request body - */ - IteratorImpl(String marker, JsonObject body) { - this.markerNext = marker; - this.body = body; - this.loadNextPage(); - } - - /** - * Loads next page. - */ - private void loadNextPage() { - String existingQuery = BoxResourceIterable.this.url.getQuery(); - QueryStringBuilder builder = new QueryStringBuilder(existingQuery); - builder.appendParam(PARAMETER_LIMIT, BoxResourceIterable.this.limit); - if (this.markerNext != null) { - if (this.body != null) { - this.body.set("marker", this.markerNext); - } else { - builder.appendParam(PARAMETER_MARKER, this.markerNext); - } - } - - URL url; - try { - url = builder.replaceQuery(BoxResourceIterable.this.url); - } catch (MalformedURLException e) { - throw new BoxAPIException("Couldn't append a query string to the provided URL."); - } - - BoxJSONRequest request; - if (this.body != null) { - request = new BoxJSONRequest(BoxResourceIterable.this.api, url, "POST"); - request.setBody(this.body.toString()); - } else { - request = new BoxJSONRequest(BoxResourceIterable.this.api, url, "GET"); - } - - try (BoxJSONResponse response = request.send()) { - JsonObject pageBody = Json.parse(response.getJSON()).asObject(); - - JsonValue markerNextValue = pageBody.get(BODY_PARAMETER_MARKER_NEXT); - if (markerNextValue != null && markerNextValue.isString()) { - this.markerNext = markerNextValue.asString(); - } else { - this.markerNext = null; - } - - this.page = pageBody.get(BODY_PARAMETER_ENTRIES).asArray(); - this.pageCursor = 0; - } - } - - /** - * {@inheritDoc} - */ - @Override - public boolean hasNext() { - if (this.pageCursor < this.page.size()) { - return true; - } - if (this.markerNext == null || this.markerNext.isEmpty()) { - return false; - } - this.loadNextPage(); - return !this.page.isEmpty(); - } - - /** - * {@inheritDoc} - */ - @Override - public T next() { - if (!this.hasNext()) { - throw new NoSuchElementException(); - } - - JsonObject entry = this.page.get(this.pageCursor++).asObject(); - return BoxResourceIterable.this.factory(entry); - } - - /** - * @throws UnsupportedOperationException Remove is not supported - */ - @Override - public void remove() { - throw new UnsupportedOperationException(); - } + /** @throws UnsupportedOperationException Remove is not supported */ + @Override + public void remove() { + throw new UnsupportedOperationException(); } - + } } diff --git a/src/main/java/com/box/sdk/BoxResourceType.java b/src/main/java/com/box/sdk/BoxResourceType.java index 08bf13b9d..378f03a1e 100644 --- a/src/main/java/com/box/sdk/BoxResourceType.java +++ b/src/main/java/com/box/sdk/BoxResourceType.java @@ -18,14 +18,11 @@ @Retention(RetentionPolicy.RUNTIME) public @interface BoxResourceType { - // Bug in checkstyle: Unused Javadoc tag. - // TODO checkstyle: need re-evaluation after checkstyle update - //CHECKSTYLE:OFF - - /** - * @return Type of resource (e.g.: folder, file, comment, etc...). - */ - //CHECKSTYLE:ON - String value(); + // Bug in checkstyle: Unused Javadoc tag. + // TODO checkstyle: need re-evaluation after checkstyle update + // CHECKSTYLE:OFF + /** @return Type of resource (e.g.: folder, file, comment, etc...). */ + // CHECKSTYLE:ON + String value(); } diff --git a/src/main/java/com/box/sdk/BoxRetentionPolicy.java b/src/main/java/com/box/sdk/BoxRetentionPolicy.java index b23e2ac82..94298bef3 100644 --- a/src/main/java/com/box/sdk/BoxRetentionPolicy.java +++ b/src/main/java/com/box/sdk/BoxRetentionPolicy.java @@ -1,834 +1,801 @@ -package com.box.sdk; - -import com.eclipsesource.json.Json; -import com.eclipsesource.json.JsonArray; -import com.eclipsesource.json.JsonObject; -import com.eclipsesource.json.JsonValue; -import java.net.URL; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -/** - * Represents a retention policy. - * A retention policy blocks permanent deletion of content for a specified amount of time. - * Admins can create retention policies and then later assign them to specific folders or their entire enterprise. - * - * @see Box retention policy - * - *

Unless otherwise noted, the methods in this class can throw an unchecked {@link BoxAPIException} (unchecked - * meaning that the compiler won't force you to handle it) if an error occurs. If you wish to implement custom error - * handling for errors related to the Box REST API, you should capture this exception explicitly.

- */ -@BoxResourceType("retention_policy") -public class BoxRetentionPolicy extends BoxResource { - /** - * The URL template used for operation with retention policies. - */ - public static final URLTemplate RETENTION_POLICIES_URL_TEMPLATE = new URLTemplate("retention_policies"); - - /** - * The URL template used for operation with retention policy with given ID. - */ - public static final URLTemplate POLICY_URL_TEMPLATE = new URLTemplate("retention_policies/%s"); - - /** - * The URL template used for operation with retention policy assignments. - */ - public static final URLTemplate ASSIGNMENTS_URL_TEMPLATE = new URLTemplate("retention_policies/%s/assignments"); - - /** - * Will cause the content retained by the policy to be permanently deleted. - */ - public static final String ACTION_PERMANENTLY_DELETE = "permanently_delete"; - - /** - * Will lift the retention policy from the content, allowing it to be deleted by users. - */ - public static final String ACTION_REMOVE_RETENTION = "remove_retention"; - - /** - * Status corresponding to active retention policy. - */ - public static final String STATUS_ACTIVE = "active"; - - /** - * Status corresponding to retired retention policy. - */ - public static final String STATUS_RETIRED = "retired"; - - /** - * The default limit of entries per response. - */ - private static final int DEFAULT_LIMIT = 100; - - /** - * Constructs a retention policy for a resource with a given ID. - * - * @param api the API connection to be used by the resource. - * @param id the ID of the resource. - */ - public BoxRetentionPolicy(BoxAPIConnection api, String id) { - super(api, id); - } - - /** - * Used to create a new indefinite retention policy. - * - * @param api the API connection to be used by the created user. - * @param name the name of the retention policy. - * @return the created retention policy's info. - */ - public static BoxRetentionPolicy.Info createIndefinitePolicy(BoxAPIConnection api, String name) { - return createRetentionPolicy( - api, name, BoxRetentionPolicyType.Indefinite, 0, BoxRetentionPolicyAction.RemoveRetention - ); - } - - /** - * Used to create a new indefinite retention policy with optional parameters. - * - * @param api the API connection to be used by the created user. - * @param name the name of the retention policy. - * @param optionalParams the optional parameters. - * @return the created retention policy's info. - */ - public static BoxRetentionPolicy.Info createIndefinitePolicy( - BoxAPIConnection api, String name, RetentionPolicyParams optionalParams - ) { - return createRetentionPolicy( - api, name, BoxRetentionPolicyType.Indefinite, 0, BoxRetentionPolicyAction.RemoveRetention, optionalParams - ); - } - - /** - * Used to create a new finite retention policy. - * - * @param api the API connection to be used by the created user. - * @param name the name of the retention policy. - * @param length the duration in days that the retention policy will be active for after being assigned to content. - * @param action the disposition action can be "permanently_delete" or "remove_retention". - * @return the created retention policy's info. - */ - public static BoxRetentionPolicy.Info createFinitePolicy(BoxAPIConnection api, - String name, - int length, - BoxRetentionPolicyAction action) { - return createRetentionPolicy(api, name, BoxRetentionPolicyType.Finite, length, action); - } - - /** - * Used to create a new finite retention policy with optional parameters. - * - * @param api the API connection to be used by the created user. - * @param name the name of the retention policy. - * @param length the duration in days that the retention policy will be active for after being assigned to content. - * @param action the disposition action can be "permanently_delete" or "remove_retention". - * @param optionalParams the optional parameters. - * @return the created retention policy's info. - */ - public static BoxRetentionPolicy.Info createFinitePolicy( - BoxAPIConnection api, - String name, - int length, - BoxRetentionPolicyAction action, - RetentionPolicyParams optionalParams - ) { - return createRetentionPolicy(api, name, BoxRetentionPolicyType.Finite, length, action, optionalParams); - } - - /** - * Used to create a new retention policy. - * - * @param api the API connection to be used by the created user. - * @param name the name of the retention policy. - * @param type the type of the retention policy. Can be "finite" or "indefinite". - * @param length the duration in days that the retention policy will be active for after being assigned to content. - * @param action the disposition action can be "permanently_delete" or "remove_retention". - * @return the created retention policy's info. - */ - private static BoxRetentionPolicy.Info createRetentionPolicy(BoxAPIConnection api, - String name, - BoxRetentionPolicyType type, - int length, - BoxRetentionPolicyAction action) { - return createRetentionPolicy(api, name, type, length, action, null); - } - - /** - * Used to create a new retention policy with optional parameters. - * - * @param api the API connection to be used by the created user. - * @param name the name of the retention policy. - * @param type the type of the retention policy. Can be "finite" or "indefinite". - * @param length the duration in days that the retention policy will be active for after being assigned to content. - * @param action the disposition action can be "permanently_delete" or "remove_retention". - * @param optionalParams the optional parameters. - * @return the created retention policy's info. - */ - private static BoxRetentionPolicy.Info createRetentionPolicy( - BoxAPIConnection api, - String name, - BoxRetentionPolicyType type, - int length, - BoxRetentionPolicyAction action, - RetentionPolicyParams optionalParams - ) { - URL url = RETENTION_POLICIES_URL_TEMPLATE.build(api.getBaseURL()); - BoxJSONRequest request = new BoxJSONRequest(api, url, "POST"); - JsonObject requestJSON = new JsonObject() - .add("policy_name", name) - .add("policy_type", type.value) - .add("disposition_action", action.value); - if (type != BoxRetentionPolicyType.Indefinite) { - requestJSON.add("retention_length", length); - } - if (optionalParams != null) { - requestJSON.add("can_owner_extend_retention", optionalParams.getCanOwnerExtendRetention()); - requestJSON.add("are_owners_notified", optionalParams.getAreOwnersNotified()); - requestJSON.add("description", optionalParams.getDescription()); - requestJSON.add("retention_type", optionalParams.getRetentionType().toJSONString()); - - List customNotificationRecipients = optionalParams.getCustomNotificationRecipients(); - if (customNotificationRecipients.size() > 0) { - JsonArray users = new JsonArray(); - for (BoxUser.Info user : customNotificationRecipients) { - JsonObject userJSON = new JsonObject() - .add("type", "user") - .add("id", user.getID()); - users.add(userJSON); - } - requestJSON.add("custom_notification_recipients", users); - } - } - request.setBody(requestJSON.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - BoxRetentionPolicy createdPolicy = new BoxRetentionPolicy(api, responseJSON.get("id").asString()); - return createdPolicy.new Info(responseJSON); - } - } - - /** - * Returns all the retention policies. - * - * @param api the API connection to be used by the resource. - * @param fields the fields to retrieve. - * @return an iterable with all the retention policies. - */ - public static Iterable getAll(final BoxAPIConnection api, String... fields) { - return getAll(null, null, null, DEFAULT_LIMIT, api, fields); - } - - /** - * Returns all the retention policies with specified filters. - * - * @param name a name to filter the retention policies by. A trailing partial match search is performed. - * Set to null if no name filtering is required. - * @param type a policy type to filter the retention policies by. Set to null if no type filtering is required. - * @param userID a user id to filter the retention policies by. Set to null if no type filtering is required. - * @param limit the limit of items per single response. The default value is 100. - * @param api the API connection to be used by the resource. - * @param fields the fields to retrieve. - * @return an iterable with all the retention policies met search conditions. - */ - public static Iterable getAll( - String name, String type, String userID, int limit, final BoxAPIConnection api, String... fields) { - QueryStringBuilder queryString = new QueryStringBuilder(); - if (name != null) { - queryString.appendParam("policy_name", name); - } - if (type != null) { - queryString.appendParam("policy_type", type); - } - if (userID != null) { - queryString.appendParam("created_by_user_id", userID); - } - if (fields.length > 0) { - queryString.appendParam("fields", fields); - } - URL url = RETENTION_POLICIES_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), queryString.toString()); - return new BoxResourceIterable(api, url, limit) { - - @Override - protected BoxRetentionPolicy.Info factory(JsonObject jsonObject) { - BoxRetentionPolicy policy = new BoxRetentionPolicy(api, jsonObject.get("id").asString()); - return policy.new Info(jsonObject); - } - - }; - } - - /** - * Returns iterable with all folder assignments of this retention policy. - * - * @param fields the fields to retrieve. - * @return an iterable containing all folder assignments. - */ - public Iterable getFolderAssignments(String... fields) { - return this.getFolderAssignments(DEFAULT_LIMIT, fields); - } - - /** - * Returns iterable with all folder assignments of this retention policy. - * - * @param limit the limit of entries per response. The default value is 100. - * @param fields the fields to retrieve. - * @return an iterable containing all folder assignments. - */ - public Iterable getFolderAssignments(int limit, String... fields) { - return this.getAssignments(BoxRetentionPolicyAssignment.TYPE_FOLDER, limit, fields); - } - - /** - * Returns iterable with all enterprise assignments of this retention policy. - * - * @param fields the fields to retrieve. - * @return an iterable containing all enterprise assignments. - */ - public Iterable getEnterpriseAssignments(String... fields) { - return this.getEnterpriseAssignments(DEFAULT_LIMIT, fields); - } - - /** - * Returns iterable with all enterprise assignments of this retention policy. - * - * @param limit the limit of entries per response. The default value is 100. - * @param fields the fields to retrieve. - * @return an iterable containing all enterprise assignments. - */ - public Iterable getEnterpriseAssignments(int limit, String... fields) { - return this.getAssignments(BoxRetentionPolicyAssignment.TYPE_ENTERPRISE, limit, fields); - } - - /** - * Returns iterable with all assignments of this retention policy. - * - * @param fields the fields to retrieve. - * @return an iterable containing all assignments. - */ - public Iterable getAllAssignments(String... fields) { - return this.getAllAssignments(DEFAULT_LIMIT, fields); - } - - /** - * Returns iterable with all assignments of this retention policy. - * - * @param limit the limit of entries per response. The default value is 100. - * @param fields the fields to retrieve. - * @return an iterable containing all assignments. - */ - public Iterable getAllAssignments(int limit, String... fields) { - return this.getAssignments(null, limit, fields); - } - - /** - * Returns iterable with all assignments of given type of this retention policy. - * - * @param type the type of the retention policy assignment to retrieve. Can either be "folder" or "enterprise". - * @param limit the limit of entries per response. The default value is 100. - * @param fields the fields to retrieve. - * @return an iterable containing all assignments of given type. - */ - private Iterable getAssignments(String type, int limit, String... fields) { - QueryStringBuilder queryString = new QueryStringBuilder(); - if (type != null) { - queryString.appendParam("type", type); - } - if (fields.length > 0) { - queryString.appendParam("fields", fields); - } - URL url = ASSIGNMENTS_URL_TEMPLATE.buildWithQuery(getAPI().getBaseURL(), queryString.toString(), getID()); - return new BoxResourceIterable(getAPI(), url, limit) { - - @Override - protected BoxRetentionPolicyAssignment.Info factory(JsonObject jsonObject) { - BoxRetentionPolicyAssignment assignment - = new BoxRetentionPolicyAssignment(getAPI(), jsonObject.get("id").asString()); - return assignment.new Info(jsonObject); - } - - }; - } - - /** - * Assigns this retention policy to folder. - * - * @param folder the folder to assign policy to. - * @return info about created assignment. - */ - public BoxRetentionPolicyAssignment.Info assignTo(BoxFolder folder) { - return BoxRetentionPolicyAssignment.createAssignmentToFolder(this.getAPI(), this.getID(), folder.getID()); - } - - /** - * Assigns this retention policy to the current enterprise. - * - * @return info about created assignment. - */ - public BoxRetentionPolicyAssignment.Info assignToEnterprise() { - return BoxRetentionPolicyAssignment.createAssignmentToEnterprise(this.getAPI(), this.getID()); - } - - /** - * Assigns this retention policy to a metadata template, optionally with certain field values. - * - * @param templateID the ID of the metadata template to apply to. - * @param fieldFilters optional field value filters. - * @return info about the created assignment. - */ - public BoxRetentionPolicyAssignment.Info assignToMetadataTemplate(String templateID, - MetadataFieldFilter... fieldFilters) { - return assignToMetadataTemplate(templateID, null, fieldFilters); - } - - /** - * Assigns this retention policy to a metadata template, optionally with certain field values. - * - * @param templateID the ID of the metadata template to apply to. - * @param startDateField the date the retention policy assignment begins. This field can be a date field's metadata attribute key id. - * @param fieldFilters optional field value filters. - * @return info about the created assignment. - */ - public BoxRetentionPolicyAssignment.Info assignToMetadataTemplate(String templateID, - String startDateField, - MetadataFieldFilter... fieldFilters) { - return BoxRetentionPolicyAssignment.createAssignmentToMetadata(this.getAPI(), this.getID(), templateID, - startDateField, fieldFilters); - } - - /** - * Updates the information about this retention policy with any info fields that have been modified locally. - * - * @param info the updated info. - */ - public void updateInfo(BoxRetentionPolicy.Info info) { - URL url = POLICY_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); - request.setBody(info.getPendingChanges()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - info.update(responseJSON); - } - } - - /** - * Returns information about this retention policy. - * - * @param fields the fields to retrieve. - * @return information about this retention policy. - */ - public BoxRetentionPolicy.Info getInfo(String... fields) { - QueryStringBuilder builder = new QueryStringBuilder(); - if (fields.length > 0) { - builder.appendParam("fields", fields); - } - URL url = POLICY_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), builder.toString(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - return new Info(responseJSON); - } - } - - /** - * Contains information about the retention policy. - */ - public class Info extends BoxResource.Info { - - /** - * @see #getPolicyName() - */ - private String policyName; - - /** - * @see #getPolicyType() - */ - private String policyType; - - /** - * @see #getRetentionLength() - */ - private int retentionLength; - - /** - * @see #getDispositionAction() - */ - private String dispositionAction; - - /** - * @see #getStatus() - */ - private String status; - - /** - * @see #getCreatedBy() - */ - private BoxUser.Info createdBy; - - /** - * @see #getCreatedAt() - */ - private Date createdAt; - - /** - * @see #getModifiedAt() - */ - private Date modifiedAt; - - /** - * @see #getCanOwnerExtendRetention() - */ - private boolean canOwnerExtendRetention; - - /** - * @see #getAreOwnersNotified() - */ - private boolean areOwnersNotified; - - /** - * @see #getDescription() - */ - private String description; - - /** - * @see #getRetentionType() - */ - private RetentionPolicyParams.RetentionType retentionType; - - private List customNotificationRecipients; - - /** - * Constructs an empty Info object. - */ - public Info() { - super(); - } - - /** - * Constructs an Info object by parsing information from a JSON string. - * - * @param json the JSON string to parse. - */ - public Info(String json) { - super(json); - } - - /** - * Constructs an Info object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - Info(JsonObject jsonObject) { - super(jsonObject); - } - - /** - * {@inheritDoc} - */ - @Override - public BoxResource getResource() { - return BoxRetentionPolicy.this; - } - - /** - * Gets the name given to the retention policy. - * - * @return name given to the retention policy. - */ - public String getPolicyName() { - return this.policyName; - } - - /** - * Update the policy name to a new value. - * - * @param policyName the new policy name. - */ - public void setPolicyName(String policyName) { - this.policyName = policyName; - this.addPendingChange("policy_name", policyName); - } - - /** - * Gets the type of the retention policy. - * A retention policy type can either be "finite", - * where a specific amount of time to retain the content is known upfront, - * or "indefinite", where the amount of time to retain the content is still unknown. - * - * @return the type of the retention policy. - */ - public String getPolicyType() { - return this.policyType; - } - - /** - * Gets the length of the retention policy. This length specifies the duration - * in days that the retention policy will be active for after being assigned to content. - * - * @return the length of the retention policy. - */ - public int getRetentionLength() { - return this.retentionLength; - } - - /** - * - * @param retentionLength The length of the retention policy. - */ - public void setRetentionLength(int retentionLength) { - this.retentionLength = retentionLength; - this.addPendingChange("retention_length", retentionLength); - } - - /** - * Gets the disposition action of the retention policy. - * This action can be "permanently_delete", or "remove_retention". - * - * @return the disposition action of the retention policy. - */ - public String getDispositionAction() { - return this.dispositionAction; - } - - /** - * Set the action to take when retention period ends. - * - * @param dispositionAction the new action. - */ - public void setDispositionAction(String dispositionAction) { - this.dispositionAction = dispositionAction; - this.addPendingChange("disposition_action", dispositionAction); - } - - /** - * Gets the status of the retention policy. - * The status can be "active" or "retired". - * - * @return the status of the retention policy. - */ - public String getStatus() { - return this.status; - } - - /** - * Set the policy status. - * - * @param status the new status value. - */ - public void setStatus(String status) { - this.status = status; - this.addPendingChange("status", status); - } - - /** - * Gets info about the user created the retention policy. - * - * @return info about the user created the retention policy. - */ - public BoxUser.Info getCreatedBy() { - return this.createdBy; - } - - /** - * Gets the time that the retention policy was created. - * - * @return the time that the retention policy was created. - */ - public Date getCreatedAt() { - return this.createdAt; - } - - /** - * Gets the time that the retention policy was last modified. - * - * @return the time that the retention policy was last modified. - */ - public Date getModifiedAt() { - return this.modifiedAt; - } - - /** - * Gets the flag to denote that the owner of a retained file can extend the retention when near expiration. - * - * @return the boolean flag. - */ - public boolean getCanOwnerExtendRetention() { - return this.canOwnerExtendRetention; - } - - /** - * Gets the flag to denote that owners and co-owners of a retained file will get notified when near expiration. - * - * @return the boolean flag. - */ - public boolean getAreOwnersNotified() { - return this.areOwnersNotified; - } - - /** - * Gets the additional text desription of the retention policy. - * - * @return the additional text desription of the retention policy - */ - public String getDescription() { - return this.description; - } - - /** - * Set the additional text desription of the retention policy. - * - * @param description the new text desription of the retention policy - */ - public void setDescription(String description) { - this.description = description; - this.addPendingChange("description", description); - } - - /** - * - * @return retention type. It can be one of values: `modifiable` or `non-modifiable`. - * `modifiable` means that you can modify the retention policy. For example, you can add or remove folders, - * shorten or lengthen the policy duration, or delete the assignment. - * `non-modifiable` means that can modify the retention policy only in a limited way: add a folder, - * lengthen the duration, retire the policy, change the disposition action or notification settings. - * You cannot perform other actions, such as deleting the assignment or shortening the policy duration. - */ - public RetentionPolicyParams.RetentionType getRetentionType() { - return retentionType; - } - - /** - * - * It is not possible to set retention type to `modifiable` once it was set to `non-modifiable`. - */ - public void setRetentionTypeToNonModifiable() { - this.retentionType = RetentionPolicyParams.RetentionType.NON_MODIFIABLE; - this.addPendingChange("retention_type", retentionType.toJSONString()); - } - - /** - * Gets the list of users to be notified of a retained file when near expiration. - * - * @return the list of users to be notified. - */ - public List getCustomNotificationRecipients() { - return this.customNotificationRecipients; - } - - /** - * {@inheritDoc} - */ - @Override - void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - String memberName = member.getName(); - JsonValue value = member.getValue(); - try { - switch (memberName) { - case "policy_name": - this.policyName = value.asString(); - break; - case "policy_type": - this.policyType = value.asString(); - break; - case "retention_length": - int intVal; - if (value.asString().equals(BoxRetentionPolicyType.Indefinite.value)) { - intVal = -1; - } else { - intVal = Integer.parseInt(value.asString()); - } - this.retentionLength = intVal; - break; - case "disposition_action": - this.dispositionAction = value.asString(); - break; - case "status": - this.status = value.asString(); - break; - case "created_by": - JsonObject userJSON = value.asObject(); - if (this.createdBy == null) { - String userID = userJSON.get("id").asString(); - BoxUser user = new BoxUser(getAPI(), userID); - this.createdBy = user.new Info(userJSON); - } else { - this.createdBy.update(userJSON); - } - break; - case "created_at": - this.createdAt = BoxDateFormat.parse(value.asString()); - break; - case "modified_at": - this.modifiedAt = BoxDateFormat.parse(value.asString()); - break; - case "can_owner_extend_retention": - this.canOwnerExtendRetention = value.asBoolean(); - break; - case "are_owners_notified": - this.areOwnersNotified = value.asBoolean(); - break; - case "description": - this.description = value.asString(); - break; - case "retention_type": - this.retentionType = RetentionPolicyParams.RetentionType.fromJSONString(value.asString()); - break; - case "custom_notification_recipients": - List recipients = new ArrayList<>(); - for (JsonValue recipientJSON : value.asArray()) { - String userID = recipientJSON.asObject().get("id").asString(); - BoxUser user = new BoxUser(getAPI(), userID); - recipients.add(user.new Info(recipientJSON.asObject())); - } - this.customNotificationRecipients = recipients; - break; - default: - break; - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); - } - } - } - - private enum BoxRetentionPolicyType { - /** - * Type for finite retention policies. Finite retention policies has the duration. - */ - Finite("finite"), - /** - * Type for indefinite retention policies. Indefinite retention policies can have only - * {@link BoxRetentionPolicyAction#RemoveRetention} assigned action. - */ - Indefinite("indefinite"); - - private final String value; - - BoxRetentionPolicyType(String value) { - this.value = value; - } - } - - /** - * The disposition action of the retention policy. - */ - public enum BoxRetentionPolicyAction { - /** - * Will cause the content retained by the policy to be permanently deleted. - */ - PermanentlyDelete("permanently_delete"), - - /** - * Will lift the retention policy from the content, allowing it to be deleted by users. - */ - RemoveRetention("remove_retention"); - - private final String value; - - BoxRetentionPolicyAction(String value) { - this.value = value; - } - } -} +package com.box.sdk; + +import com.eclipsesource.json.Json; +import com.eclipsesource.json.JsonArray; +import com.eclipsesource.json.JsonObject; +import com.eclipsesource.json.JsonValue; +import java.net.URL; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +/** + * Represents a retention policy. A retention policy blocks permanent deletion of content for a + * specified amount of time. Admins can create retention policies and then later assign them to + * specific folders or their entire enterprise. + * + * @see Box retention + * policy + *

Unless otherwise noted, the methods in this class can throw an unchecked {@link + * BoxAPIException} (unchecked meaning that the compiler won't force you to handle it) if an + * error occurs. If you wish to implement custom error handling for errors related to the Box + * REST API, you should capture this exception explicitly. + */ +@BoxResourceType("retention_policy") +public class BoxRetentionPolicy extends BoxResource { + /** The URL template used for operation with retention policies. */ + public static final URLTemplate RETENTION_POLICIES_URL_TEMPLATE = + new URLTemplate("retention_policies"); + + /** The URL template used for operation with retention policy with given ID. */ + public static final URLTemplate POLICY_URL_TEMPLATE = new URLTemplate("retention_policies/%s"); + + /** The URL template used for operation with retention policy assignments. */ + public static final URLTemplate ASSIGNMENTS_URL_TEMPLATE = + new URLTemplate("retention_policies/%s/assignments"); + + /** Will cause the content retained by the policy to be permanently deleted. */ + public static final String ACTION_PERMANENTLY_DELETE = "permanently_delete"; + + /** Will lift the retention policy from the content, allowing it to be deleted by users. */ + public static final String ACTION_REMOVE_RETENTION = "remove_retention"; + + /** Status corresponding to active retention policy. */ + public static final String STATUS_ACTIVE = "active"; + + /** Status corresponding to retired retention policy. */ + public static final String STATUS_RETIRED = "retired"; + + /** The default limit of entries per response. */ + private static final int DEFAULT_LIMIT = 100; + + /** + * Constructs a retention policy for a resource with a given ID. + * + * @param api the API connection to be used by the resource. + * @param id the ID of the resource. + */ + public BoxRetentionPolicy(BoxAPIConnection api, String id) { + super(api, id); + } + + /** + * Used to create a new indefinite retention policy. + * + * @param api the API connection to be used by the created user. + * @param name the name of the retention policy. + * @return the created retention policy's info. + */ + public static BoxRetentionPolicy.Info createIndefinitePolicy(BoxAPIConnection api, String name) { + return createRetentionPolicy( + api, name, BoxRetentionPolicyType.Indefinite, 0, BoxRetentionPolicyAction.RemoveRetention); + } + + /** + * Used to create a new indefinite retention policy with optional parameters. + * + * @param api the API connection to be used by the created user. + * @param name the name of the retention policy. + * @param optionalParams the optional parameters. + * @return the created retention policy's info. + */ + public static BoxRetentionPolicy.Info createIndefinitePolicy( + BoxAPIConnection api, String name, RetentionPolicyParams optionalParams) { + return createRetentionPolicy( + api, + name, + BoxRetentionPolicyType.Indefinite, + 0, + BoxRetentionPolicyAction.RemoveRetention, + optionalParams); + } + + /** + * Used to create a new finite retention policy. + * + * @param api the API connection to be used by the created user. + * @param name the name of the retention policy. + * @param length the duration in days that the retention policy will be active for after being + * assigned to content. + * @param action the disposition action can be "permanently_delete" or "remove_retention". + * @return the created retention policy's info. + */ + public static BoxRetentionPolicy.Info createFinitePolicy( + BoxAPIConnection api, String name, int length, BoxRetentionPolicyAction action) { + return createRetentionPolicy(api, name, BoxRetentionPolicyType.Finite, length, action); + } + + /** + * Used to create a new finite retention policy with optional parameters. + * + * @param api the API connection to be used by the created user. + * @param name the name of the retention policy. + * @param length the duration in days that the retention policy will be active for after being + * assigned to content. + * @param action the disposition action can be "permanently_delete" or "remove_retention". + * @param optionalParams the optional parameters. + * @return the created retention policy's info. + */ + public static BoxRetentionPolicy.Info createFinitePolicy( + BoxAPIConnection api, + String name, + int length, + BoxRetentionPolicyAction action, + RetentionPolicyParams optionalParams) { + return createRetentionPolicy( + api, name, BoxRetentionPolicyType.Finite, length, action, optionalParams); + } + + /** + * Used to create a new retention policy. + * + * @param api the API connection to be used by the created user. + * @param name the name of the retention policy. + * @param type the type of the retention policy. Can be "finite" or "indefinite". + * @param length the duration in days that the retention policy will be active for after being + * assigned to content. + * @param action the disposition action can be "permanently_delete" or "remove_retention". + * @return the created retention policy's info. + */ + private static BoxRetentionPolicy.Info createRetentionPolicy( + BoxAPIConnection api, + String name, + BoxRetentionPolicyType type, + int length, + BoxRetentionPolicyAction action) { + return createRetentionPolicy(api, name, type, length, action, null); + } + + /** + * Used to create a new retention policy with optional parameters. + * + * @param api the API connection to be used by the created user. + * @param name the name of the retention policy. + * @param type the type of the retention policy. Can be "finite" or "indefinite". + * @param length the duration in days that the retention policy will be active for after being + * assigned to content. + * @param action the disposition action can be "permanently_delete" or "remove_retention". + * @param optionalParams the optional parameters. + * @return the created retention policy's info. + */ + private static BoxRetentionPolicy.Info createRetentionPolicy( + BoxAPIConnection api, + String name, + BoxRetentionPolicyType type, + int length, + BoxRetentionPolicyAction action, + RetentionPolicyParams optionalParams) { + URL url = RETENTION_POLICIES_URL_TEMPLATE.build(api.getBaseURL()); + BoxJSONRequest request = new BoxJSONRequest(api, url, "POST"); + JsonObject requestJSON = + new JsonObject() + .add("policy_name", name) + .add("policy_type", type.value) + .add("disposition_action", action.value); + if (type != BoxRetentionPolicyType.Indefinite) { + requestJSON.add("retention_length", length); + } + if (optionalParams != null) { + requestJSON.add("can_owner_extend_retention", optionalParams.getCanOwnerExtendRetention()); + requestJSON.add("are_owners_notified", optionalParams.getAreOwnersNotified()); + requestJSON.add("description", optionalParams.getDescription()); + requestJSON.add("retention_type", optionalParams.getRetentionType().toJSONString()); + + List customNotificationRecipients = + optionalParams.getCustomNotificationRecipients(); + if (customNotificationRecipients.size() > 0) { + JsonArray users = new JsonArray(); + for (BoxUser.Info user : customNotificationRecipients) { + JsonObject userJSON = new JsonObject().add("type", "user").add("id", user.getID()); + users.add(userJSON); + } + requestJSON.add("custom_notification_recipients", users); + } + } + request.setBody(requestJSON.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + BoxRetentionPolicy createdPolicy = + new BoxRetentionPolicy(api, responseJSON.get("id").asString()); + return createdPolicy.new Info(responseJSON); + } + } + + /** + * Returns all the retention policies. + * + * @param api the API connection to be used by the resource. + * @param fields the fields to retrieve. + * @return an iterable with all the retention policies. + */ + public static Iterable getAll( + final BoxAPIConnection api, String... fields) { + return getAll(null, null, null, DEFAULT_LIMIT, api, fields); + } + + /** + * Returns all the retention policies with specified filters. + * + * @param name a name to filter the retention policies by. A trailing partial match search is + * performed. Set to null if no name filtering is required. + * @param type a policy type to filter the retention policies by. Set to null if no type filtering + * is required. + * @param userID a user id to filter the retention policies by. Set to null if no type filtering + * is required. + * @param limit the limit of items per single response. The default value is 100. + * @param api the API connection to be used by the resource. + * @param fields the fields to retrieve. + * @return an iterable with all the retention policies met search conditions. + */ + public static Iterable getAll( + String name, + String type, + String userID, + int limit, + final BoxAPIConnection api, + String... fields) { + QueryStringBuilder queryString = new QueryStringBuilder(); + if (name != null) { + queryString.appendParam("policy_name", name); + } + if (type != null) { + queryString.appendParam("policy_type", type); + } + if (userID != null) { + queryString.appendParam("created_by_user_id", userID); + } + if (fields.length > 0) { + queryString.appendParam("fields", fields); + } + URL url = + RETENTION_POLICIES_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), queryString.toString()); + return new BoxResourceIterable(api, url, limit) { + + @Override + protected BoxRetentionPolicy.Info factory(JsonObject jsonObject) { + BoxRetentionPolicy policy = new BoxRetentionPolicy(api, jsonObject.get("id").asString()); + return policy.new Info(jsonObject); + } + }; + } + + /** + * Returns iterable with all folder assignments of this retention policy. + * + * @param fields the fields to retrieve. + * @return an iterable containing all folder assignments. + */ + public Iterable getFolderAssignments(String... fields) { + return this.getFolderAssignments(DEFAULT_LIMIT, fields); + } + + /** + * Returns iterable with all folder assignments of this retention policy. + * + * @param limit the limit of entries per response. The default value is 100. + * @param fields the fields to retrieve. + * @return an iterable containing all folder assignments. + */ + public Iterable getFolderAssignments( + int limit, String... fields) { + return this.getAssignments(BoxRetentionPolicyAssignment.TYPE_FOLDER, limit, fields); + } + + /** + * Returns iterable with all enterprise assignments of this retention policy. + * + * @param fields the fields to retrieve. + * @return an iterable containing all enterprise assignments. + */ + public Iterable getEnterpriseAssignments(String... fields) { + return this.getEnterpriseAssignments(DEFAULT_LIMIT, fields); + } + + /** + * Returns iterable with all enterprise assignments of this retention policy. + * + * @param limit the limit of entries per response. The default value is 100. + * @param fields the fields to retrieve. + * @return an iterable containing all enterprise assignments. + */ + public Iterable getEnterpriseAssignments( + int limit, String... fields) { + return this.getAssignments(BoxRetentionPolicyAssignment.TYPE_ENTERPRISE, limit, fields); + } + + /** + * Returns iterable with all assignments of this retention policy. + * + * @param fields the fields to retrieve. + * @return an iterable containing all assignments. + */ + public Iterable getAllAssignments(String... fields) { + return this.getAllAssignments(DEFAULT_LIMIT, fields); + } + + /** + * Returns iterable with all assignments of this retention policy. + * + * @param limit the limit of entries per response. The default value is 100. + * @param fields the fields to retrieve. + * @return an iterable containing all assignments. + */ + public Iterable getAllAssignments( + int limit, String... fields) { + return this.getAssignments(null, limit, fields); + } + + /** + * Returns iterable with all assignments of given type of this retention policy. + * + * @param type the type of the retention policy assignment to retrieve. Can either be "folder" or + * "enterprise". + * @param limit the limit of entries per response. The default value is 100. + * @param fields the fields to retrieve. + * @return an iterable containing all assignments of given type. + */ + private Iterable getAssignments( + String type, int limit, String... fields) { + QueryStringBuilder queryString = new QueryStringBuilder(); + if (type != null) { + queryString.appendParam("type", type); + } + if (fields.length > 0) { + queryString.appendParam("fields", fields); + } + URL url = + ASSIGNMENTS_URL_TEMPLATE.buildWithQuery( + getAPI().getBaseURL(), queryString.toString(), getID()); + return new BoxResourceIterable(getAPI(), url, limit) { + + @Override + protected BoxRetentionPolicyAssignment.Info factory(JsonObject jsonObject) { + BoxRetentionPolicyAssignment assignment = + new BoxRetentionPolicyAssignment(getAPI(), jsonObject.get("id").asString()); + return assignment.new Info(jsonObject); + } + }; + } + + /** + * Assigns this retention policy to folder. + * + * @param folder the folder to assign policy to. + * @return info about created assignment. + */ + public BoxRetentionPolicyAssignment.Info assignTo(BoxFolder folder) { + return BoxRetentionPolicyAssignment.createAssignmentToFolder( + this.getAPI(), this.getID(), folder.getID()); + } + + /** + * Assigns this retention policy to the current enterprise. + * + * @return info about created assignment. + */ + public BoxRetentionPolicyAssignment.Info assignToEnterprise() { + return BoxRetentionPolicyAssignment.createAssignmentToEnterprise(this.getAPI(), this.getID()); + } + + /** + * Assigns this retention policy to a metadata template, optionally with certain field values. + * + * @param templateID the ID of the metadata template to apply to. + * @param fieldFilters optional field value filters. + * @return info about the created assignment. + */ + public BoxRetentionPolicyAssignment.Info assignToMetadataTemplate( + String templateID, MetadataFieldFilter... fieldFilters) { + return assignToMetadataTemplate(templateID, null, fieldFilters); + } + + /** + * Assigns this retention policy to a metadata template, optionally with certain field values. + * + * @param templateID the ID of the metadata template to apply to. + * @param startDateField the date the retention policy assignment begins. This field can be a date + * field's metadata attribute key id. + * @param fieldFilters optional field value filters. + * @return info about the created assignment. + */ + public BoxRetentionPolicyAssignment.Info assignToMetadataTemplate( + String templateID, String startDateField, MetadataFieldFilter... fieldFilters) { + return BoxRetentionPolicyAssignment.createAssignmentToMetadata( + this.getAPI(), this.getID(), templateID, startDateField, fieldFilters); + } + + /** + * Updates the information about this retention policy with any info fields that have been + * modified locally. + * + * @param info the updated info. + */ + public void updateInfo(BoxRetentionPolicy.Info info) { + URL url = POLICY_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); + request.setBody(info.getPendingChanges()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + info.update(responseJSON); + } + } + + /** + * Returns information about this retention policy. + * + * @param fields the fields to retrieve. + * @return information about this retention policy. + */ + public BoxRetentionPolicy.Info getInfo(String... fields) { + QueryStringBuilder builder = new QueryStringBuilder(); + if (fields.length > 0) { + builder.appendParam("fields", fields); + } + URL url = + POLICY_URL_TEMPLATE.buildWithQuery( + this.getAPI().getBaseURL(), builder.toString(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + return new Info(responseJSON); + } + } + + /** Contains information about the retention policy. */ + public class Info extends BoxResource.Info { + + /** @see #getPolicyName() */ + private String policyName; + + /** @see #getPolicyType() */ + private String policyType; + + /** @see #getRetentionLength() */ + private int retentionLength; + + /** @see #getDispositionAction() */ + private String dispositionAction; + + /** @see #getStatus() */ + private String status; + + /** @see #getCreatedBy() */ + private BoxUser.Info createdBy; + + /** @see #getCreatedAt() */ + private Date createdAt; + + /** @see #getModifiedAt() */ + private Date modifiedAt; + + /** @see #getCanOwnerExtendRetention() */ + private boolean canOwnerExtendRetention; + + /** @see #getAreOwnersNotified() */ + private boolean areOwnersNotified; + + /** @see #getDescription() */ + private String description; + + /** @see #getRetentionType() */ + private RetentionPolicyParams.RetentionType retentionType; + + private List customNotificationRecipients; + + /** Constructs an empty Info object. */ + public Info() { + super(); + } + + /** + * Constructs an Info object by parsing information from a JSON string. + * + * @param json the JSON string to parse. + */ + public Info(String json) { + super(json); + } + + /** + * Constructs an Info object using an already parsed JSON object. + * + * @param jsonObject the parsed JSON object. + */ + Info(JsonObject jsonObject) { + super(jsonObject); + } + + /** {@inheritDoc} */ + @Override + public BoxResource getResource() { + return BoxRetentionPolicy.this; + } + + /** + * Gets the name given to the retention policy. + * + * @return name given to the retention policy. + */ + public String getPolicyName() { + return this.policyName; + } + + /** + * Update the policy name to a new value. + * + * @param policyName the new policy name. + */ + public void setPolicyName(String policyName) { + this.policyName = policyName; + this.addPendingChange("policy_name", policyName); + } + + /** + * Gets the type of the retention policy. A retention policy type can either be "finite", where + * a specific amount of time to retain the content is known upfront, or "indefinite", where the + * amount of time to retain the content is still unknown. + * + * @return the type of the retention policy. + */ + public String getPolicyType() { + return this.policyType; + } + + /** + * Gets the length of the retention policy. This length specifies the duration in days that the + * retention policy will be active for after being assigned to content. + * + * @return the length of the retention policy. + */ + public int getRetentionLength() { + return this.retentionLength; + } + + /** @param retentionLength The length of the retention policy. */ + public void setRetentionLength(int retentionLength) { + this.retentionLength = retentionLength; + this.addPendingChange("retention_length", retentionLength); + } + + /** + * Gets the disposition action of the retention policy. This action can be "permanently_delete", + * or "remove_retention". + * + * @return the disposition action of the retention policy. + */ + public String getDispositionAction() { + return this.dispositionAction; + } + + /** + * Set the action to take when retention period ends. + * + * @param dispositionAction the new action. + */ + public void setDispositionAction(String dispositionAction) { + this.dispositionAction = dispositionAction; + this.addPendingChange("disposition_action", dispositionAction); + } + + /** + * Gets the status of the retention policy. The status can be "active" or "retired". + * + * @return the status of the retention policy. + */ + public String getStatus() { + return this.status; + } + + /** + * Set the policy status. + * + * @param status the new status value. + */ + public void setStatus(String status) { + this.status = status; + this.addPendingChange("status", status); + } + + /** + * Gets info about the user created the retention policy. + * + * @return info about the user created the retention policy. + */ + public BoxUser.Info getCreatedBy() { + return this.createdBy; + } + + /** + * Gets the time that the retention policy was created. + * + * @return the time that the retention policy was created. + */ + public Date getCreatedAt() { + return this.createdAt; + } + + /** + * Gets the time that the retention policy was last modified. + * + * @return the time that the retention policy was last modified. + */ + public Date getModifiedAt() { + return this.modifiedAt; + } + + /** + * Gets the flag to denote that the owner of a retained file can extend the retention when near + * expiration. + * + * @return the boolean flag. + */ + public boolean getCanOwnerExtendRetention() { + return this.canOwnerExtendRetention; + } + + /** + * Gets the flag to denote that owners and co-owners of a retained file will get notified when + * near expiration. + * + * @return the boolean flag. + */ + public boolean getAreOwnersNotified() { + return this.areOwnersNotified; + } + + /** + * Gets the additional text desription of the retention policy. + * + * @return the additional text desription of the retention policy + */ + public String getDescription() { + return this.description; + } + + /** + * Set the additional text desription of the retention policy. + * + * @param description the new text desription of the retention policy + */ + public void setDescription(String description) { + this.description = description; + this.addPendingChange("description", description); + } + + /** + * @return retention type. It can be one of values: `modifiable` or `non-modifiable`. + * `modifiable` means that you can modify the retention policy. For example, you can add or + * remove folders, shorten or lengthen the policy duration, or delete the assignment. + * `non-modifiable` means that can modify the retention policy only in a limited way: add a + * folder, lengthen the duration, retire the policy, change the disposition action or + * notification settings. You cannot perform other actions, such as deleting the assignment + * or shortening the policy duration. + */ + public RetentionPolicyParams.RetentionType getRetentionType() { + return retentionType; + } + + /** + * It is not possible to set retention type to `modifiable` once it was set to `non-modifiable`. + */ + public void setRetentionTypeToNonModifiable() { + this.retentionType = RetentionPolicyParams.RetentionType.NON_MODIFIABLE; + this.addPendingChange("retention_type", retentionType.toJSONString()); + } + + /** + * Gets the list of users to be notified of a retained file when near expiration. + * + * @return the list of users to be notified. + */ + public List getCustomNotificationRecipients() { + return this.customNotificationRecipients; + } + + /** {@inheritDoc} */ + @Override + void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + String memberName = member.getName(); + JsonValue value = member.getValue(); + try { + switch (memberName) { + case "policy_name": + this.policyName = value.asString(); + break; + case "policy_type": + this.policyType = value.asString(); + break; + case "retention_length": + int intVal; + if (value.asString().equals(BoxRetentionPolicyType.Indefinite.value)) { + intVal = -1; + } else { + intVal = Integer.parseInt(value.asString()); + } + this.retentionLength = intVal; + break; + case "disposition_action": + this.dispositionAction = value.asString(); + break; + case "status": + this.status = value.asString(); + break; + case "created_by": + JsonObject userJSON = value.asObject(); + if (this.createdBy == null) { + String userID = userJSON.get("id").asString(); + BoxUser user = new BoxUser(getAPI(), userID); + this.createdBy = user.new Info(userJSON); + } else { + this.createdBy.update(userJSON); + } + break; + case "created_at": + this.createdAt = BoxDateFormat.parse(value.asString()); + break; + case "modified_at": + this.modifiedAt = BoxDateFormat.parse(value.asString()); + break; + case "can_owner_extend_retention": + this.canOwnerExtendRetention = value.asBoolean(); + break; + case "are_owners_notified": + this.areOwnersNotified = value.asBoolean(); + break; + case "description": + this.description = value.asString(); + break; + case "retention_type": + this.retentionType = + RetentionPolicyParams.RetentionType.fromJSONString(value.asString()); + break; + case "custom_notification_recipients": + List recipients = new ArrayList<>(); + for (JsonValue recipientJSON : value.asArray()) { + String userID = recipientJSON.asObject().get("id").asString(); + BoxUser user = new BoxUser(getAPI(), userID); + recipients.add(user.new Info(recipientJSON.asObject())); + } + this.customNotificationRecipients = recipients; + break; + default: + break; + } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); + } + } + } + + private enum BoxRetentionPolicyType { + /** Type for finite retention policies. Finite retention policies has the duration. */ + Finite("finite"), + /** + * Type for indefinite retention policies. Indefinite retention policies can have only {@link + * BoxRetentionPolicyAction#RemoveRetention} assigned action. + */ + Indefinite("indefinite"); + + private final String value; + + BoxRetentionPolicyType(String value) { + this.value = value; + } + } + + /** The disposition action of the retention policy. */ + public enum BoxRetentionPolicyAction { + /** Will cause the content retained by the policy to be permanently deleted. */ + PermanentlyDelete("permanently_delete"), + + /** Will lift the retention policy from the content, allowing it to be deleted by users. */ + RemoveRetention("remove_retention"); + + private final String value; + + BoxRetentionPolicyAction(String value) { + this.value = value; + } + } +} diff --git a/src/main/java/com/box/sdk/BoxRetentionPolicyAssignment.java b/src/main/java/com/box/sdk/BoxRetentionPolicyAssignment.java index a50e6bb64..8e9795047 100644 --- a/src/main/java/com/box/sdk/BoxRetentionPolicyAssignment.java +++ b/src/main/java/com/box/sdk/BoxRetentionPolicyAssignment.java @@ -1,442 +1,408 @@ -package com.box.sdk; - -import com.eclipsesource.json.Json; -import com.eclipsesource.json.JsonArray; -import com.eclipsesource.json.JsonObject; -import com.eclipsesource.json.JsonValue; -import java.net.URL; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -/** - * Represents a retention policy assignment. - * - *

Unless otherwise noted, the methods in this class can throw an unchecked {@link BoxAPIException} (unchecked - * meaning that the compiler won't force you to handle it) if an error occurs. If you wish to implement custom error - * handling for errors related to the Box REST API, you should capture this exception explicitly.

- */ -@BoxResourceType("retention_policy_assignment") -public class BoxRetentionPolicyAssignment extends BoxResource { - - /** - * Type for folder policy assignment. - */ - public static final String TYPE_FOLDER = "folder"; - - /** - * Type for enterprise policy assignment. - */ - public static final String TYPE_ENTERPRISE = "enterprise"; - - /** - * Type for metadata policy assignment. - */ - public static final String TYPE_METADATA = "metadata_template"; - - /** - * The URL template used for operation with retention policy assignments. - */ - public static final URLTemplate ASSIGNMENTS_URL_TEMPLATE = new URLTemplate("retention_policy_assignments"); - - /** - * The URL template used for operation with retention policy assignment with given ID. - */ - public static final URLTemplate RETENTION_POLICY_ASSIGNMENT_URL_TEMPLATE - = new URLTemplate("retention_policy_assignments/%s"); - - /** - * The URL template used for operation with files under retention with given retention policy assignment ID. - */ - public static final URLTemplate FILES_UNDER_RETENTION_URL_TEMPLATE - = new URLTemplate("retention_policy_assignments/%s/files_under_retention"); - - /** - * The URL template used for operation with file versions under retention with given retention policy assignment ID. - */ - public static final URLTemplate FILE_VERSIONS_UNDER_RETENTION_URL_TEMPLATE - = new URLTemplate("retention_policy_assignments/%s/file_versions_under_retention"); - - private static final int DEFAULT_LIMIT = 100; - - /** - * Constructs a BoxResource for a resource with a given ID. - * - * @param api the API connection to be used by the resource. - * @param id the ID of the resource. - */ - public BoxRetentionPolicyAssignment(BoxAPIConnection api, String id) { - super(api, id); - } - - /** - * Assigns retention policy with givenID to the enterprise. - * - * @param api the API connection to be used by the created assignment. - * @param policyID id of the assigned retention policy. - * @return info about created assignment. - */ - public static BoxRetentionPolicyAssignment.Info createAssignmentToEnterprise(BoxAPIConnection api, - String policyID) { - return createAssignment(api, policyID, new JsonObject().add("type", TYPE_ENTERPRISE), null, null); - } - - /** - * Assigns retention policy with givenID to the folder. - * - * @param api the API connection to be used by the created assignment. - * @param policyID id of the assigned retention policy. - * @param folderID id of the folder to assign policy to. - * @return info about created assignment. - */ - public static BoxRetentionPolicyAssignment.Info createAssignmentToFolder(BoxAPIConnection api, String policyID, - String folderID) { - return createAssignment( - api, policyID, new JsonObject().add("type", TYPE_FOLDER).add("id", folderID), null, null); - } - - /** - * Assigns a retention policy to all items with a given metadata template, optionally matching on fields. - * - * @param api the API connection to be used by the created assignment. - * @param policyID id of the assigned retention policy. - * @param templateID the ID of the metadata template to assign the policy to. - * @param filter optional fields to match against in the metadata template. - * @return info about the created assignment. - */ - public static BoxRetentionPolicyAssignment.Info createAssignmentToMetadata(BoxAPIConnection api, - String policyID, - String templateID, - MetadataFieldFilter... filter) { - return createAssignmentToMetadata(api, policyID, templateID, null, filter); - } - - /** - * Assigns a retention policy to all items with a given metadata template, optionally matching on fields. - * - * @param api the API connection to be used by the created assignment. - * @param policyID id of the assigned retention policy. - * @param templateID the ID of the metadata template to assign the policy to. - * @param startDateField The date the retention policy assignment begins. This field can be a date field's metadata attribute key id. - * @param filter optional fields to match against in the metadata template. - * @return info about the created assignment. - */ - public static BoxRetentionPolicyAssignment.Info createAssignmentToMetadata(BoxAPIConnection api, - String policyID, - String templateID, - String startDateField, - MetadataFieldFilter... filter) { - JsonObject assignTo = new JsonObject().add("type", TYPE_METADATA).add("id", templateID); - JsonArray filters = null; - if (filter.length > 0) { - filters = new JsonArray(); - for (MetadataFieldFilter f : filter) { - filters.add(f.getJsonObject()); - } - } - return createAssignment(api, policyID, assignTo, startDateField, filters); - } - - /** - * Assigns retention policy with givenID to folder or enterprise. - * - * @param api the API connection to be used by the created assignment. - * @param policyID id of the assigned retention policy. - * @param assignTo object representing folder or enterprise to assign policy to. - * @param filter Filters - * @return info about created assignment. - */ - private static BoxRetentionPolicyAssignment.Info createAssignment(BoxAPIConnection api, - String policyID, - JsonObject assignTo, - String startDateField, - JsonArray filter) { - URL url = ASSIGNMENTS_URL_TEMPLATE.build(api.getBaseURL()); - BoxJSONRequest request = new BoxJSONRequest(api, url, "POST"); - - JsonObject requestJSON = new JsonObject() - .add("policy_id", policyID) - .add("assign_to", assignTo); - - if (filter != null) { - requestJSON.add("filter_fields", filter); - } - if (startDateField != null) { - requestJSON.add("start_date_field", startDateField); - } - - request.setBody(requestJSON.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - BoxRetentionPolicyAssignment createdAssignment - = new BoxRetentionPolicyAssignment(api, responseJSON.get("id").asString()); - return createdAssignment.new Info(responseJSON); - } - } - - /** - * @param fields the fields to retrieve. - * @return information about this retention policy assignment. - */ - public BoxRetentionPolicyAssignment.Info getInfo(String... fields) { - QueryStringBuilder builder = new QueryStringBuilder(); - if (fields.length > 0) { - builder.appendParam("fields", fields); - } - URL url = RETENTION_POLICY_ASSIGNMENT_URL_TEMPLATE.buildWithQuery( - this.getAPI().getBaseURL(), builder.toString(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - return new Info(responseJSON); - } - } - - /** - * Retrieves all files under retention for assignment as Iterable. Default limit is 100 - * - * @param fields the fields to retrieve. - * @return an iterable contains information about all files under retentions as Iterable. - */ - public Iterable getFilesUnderRetention(String... fields) { - return this.getFilesUnderRetention(DEFAULT_LIMIT, fields); - } - - /** - * Retrieves all files under retention for assignment as Iterable. - * - * @param limit the limit of retrieved entries per page. - * @param fields the fields to retrieve. - * @return an iterable contains information about all files under retentions as Iterable. - */ - public Iterable getFilesUnderRetention(int limit, String... fields) { - QueryStringBuilder queryString = new QueryStringBuilder(); - if (fields.length > 0) { - queryString.appendParam("fields", fields); - } - URL url = FILES_UNDER_RETENTION_URL_TEMPLATE.buildWithQuery(getAPI().getBaseURL(), - queryString.toString(), getID()); - return new BoxResourceIterable(getAPI(), url, limit) { - @Override - protected BoxFile.Info factory(JsonObject jsonObject) { - BoxFile boxFile = new BoxFile(getAPI(), jsonObject.get("id").asString()); - return boxFile.new Info(jsonObject); - } - }; - } - - /** - * Retrieves all file version under retention for assignment as Iterable. Default limit is 100. - * - * @param fields the fields to retrieve. - * @return an iterable contains information about all file versions under retentions as Iterable. - */ - public Iterable getFileVersionsUnderRetention(String... fields) { - return this.getFileVersionsUnderRetention(DEFAULT_LIMIT, fields); - } - - /** - * Retrieves all file version under retention for assignment as Iterable. - * - * @param limit the limit of retrieved entries per page. - * @param fields the fields to retrieve. - * @return an iterable contains information about all file versions under retentions as Iterable. - */ - public Iterable getFileVersionsUnderRetention(int limit, String... fields) { - QueryStringBuilder queryString = new QueryStringBuilder(); - if (fields.length > 0) { - queryString.appendParam("fields", fields); - } - URL url = FILE_VERSIONS_UNDER_RETENTION_URL_TEMPLATE.buildWithQuery(getAPI().getBaseURL(), - queryString.toString(), getID()); - return new BoxResourceIterable(getAPI(), url, limit) { - @Override - protected BoxFile.Info factory(JsonObject jsonObject) { - BoxFile boxFile = new BoxFile(getAPI(), jsonObject.get("id").asString()); - return boxFile.new Info(jsonObject); - } - }; - } - - /** - * Deletes retention policy assignment. - */ - public void delete() { - URL url = RETENTION_POLICY_ASSIGNMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); - request.send().close(); - } - - /** - * Contains information about the retention policy. - */ - public class Info extends BoxResource.Info { - - /** - * @see #getRetentionPolicy() - */ - private BoxRetentionPolicy.Info retentionPolicy; - - /** - * @see #getAssignedBy() - */ - private BoxUser.Info assignedBy; - - /** - * @see #getAssignedAt() - */ - private Date assignedAt; - - /** - * @see #getAssignedToType() - */ - private String assignedToType; - - /** - * @see #getAssignedToID() - */ - private String assignedToID; - - /** - * @see #getStartDateField() - */ - private String startDateField; - - private List filterFields; - - /** - * Constructs an empty Info object. - */ - public Info() { - super(); - } - - /** - * Constructs an Info object by parsing information from a JSON string. - * - * @param json the JSON string to parse. - */ - public Info(String json) { - super(json); - } - - /** - * Constructs an Info object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - Info(JsonObject jsonObject) { - super(jsonObject); - } - - /** - * {@inheritDoc} - */ - @Override - public BoxResource getResource() { - return BoxRetentionPolicyAssignment.this; - } - - /** - * @return the retention policy that has been assigned to this content. - */ - public BoxRetentionPolicy.Info getRetentionPolicy() { - return this.retentionPolicy; - } - - /** - * @return the info about the user that created the retention policy assignment. - */ - public BoxUser.Info getAssignedBy() { - return this.assignedBy; - } - - /** - * @return the time that the retention policy assignment was created. - */ - public Date getAssignedAt() { - return this.assignedAt; - } - - /** - * @return type of the content that is under retention. Can either be "enterprise" or "folder". - */ - public String getAssignedToType() { - return this.assignedToType; - } - - /** - * @return id of the folder that is under retention. - */ - public String getAssignedToID() { - return this.assignedToID; - } - - /** - * @return date the retention policy assignment begins - */ - public String getStartDateField() { - return this.startDateField; - } - - /** - * @return the array of metadata field filters, if present - */ - public List getFilterFields() { - - return this.filterFields; - } - - /** - * {@inheritDoc} - */ - @Override - void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - String memberName = member.getName(); - JsonValue value = member.getValue(); - try { - if (memberName.equals("retention_policy")) { - JsonObject policyJSON = value.asObject(); - if (this.retentionPolicy == null) { - String policyID = policyJSON.get("id").asString(); - BoxRetentionPolicy policy = new BoxRetentionPolicy(getAPI(), policyID); - this.retentionPolicy = policy.new Info(policyJSON); - } else { - this.retentionPolicy.update(policyJSON); - } - } else if (memberName.equals("assigned_to")) { - JsonObject assignmentJSON = value.asObject(); - this.assignedToType = assignmentJSON.get("type").asString(); - if (this.assignedToType.equals(TYPE_ENTERPRISE)) { - this.assignedToID = null; - } else { - this.assignedToID = assignmentJSON.get("id").asString(); - } - } else if (memberName.equals("assigned_by")) { - JsonObject userJSON = value.asObject(); - if (this.assignedBy == null) { - String userID = userJSON.get("id").asString(); - BoxUser user = new BoxUser(getAPI(), userID); - this.assignedBy = user.new Info(userJSON); - } else { - this.assignedBy.update(userJSON); - } - } else if (memberName.equals("assigned_at")) { - this.assignedAt = BoxDateFormat.parse(value.asString()); - } else if (memberName.equals("start_date_field")) { - this.startDateField = value.asString(); - } else if (memberName.equals("filter_fields")) { - JsonArray jsonFilters = value.asArray(); - List filterFields = new ArrayList<>(); - for (int i = 0; i < jsonFilters.size(); i++) { - filterFields.add(new MetadataFieldFilter(jsonFilters.get(i).asObject())); - } - this.filterFields = filterFields; - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); - } - } - } -} +package com.box.sdk; + +import com.eclipsesource.json.Json; +import com.eclipsesource.json.JsonArray; +import com.eclipsesource.json.JsonObject; +import com.eclipsesource.json.JsonValue; +import java.net.URL; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +/** + * Represents a retention policy assignment. + * + *

Unless otherwise noted, the methods in this class can throw an unchecked {@link + * BoxAPIException} (unchecked meaning that the compiler won't force you to handle it) if an error + * occurs. If you wish to implement custom error handling for errors related to the Box REST API, + * you should capture this exception explicitly. + */ +@BoxResourceType("retention_policy_assignment") +public class BoxRetentionPolicyAssignment extends BoxResource { + + /** Type for folder policy assignment. */ + public static final String TYPE_FOLDER = "folder"; + + /** Type for enterprise policy assignment. */ + public static final String TYPE_ENTERPRISE = "enterprise"; + + /** Type for metadata policy assignment. */ + public static final String TYPE_METADATA = "metadata_template"; + + /** The URL template used for operation with retention policy assignments. */ + public static final URLTemplate ASSIGNMENTS_URL_TEMPLATE = + new URLTemplate("retention_policy_assignments"); + + /** The URL template used for operation with retention policy assignment with given ID. */ + public static final URLTemplate RETENTION_POLICY_ASSIGNMENT_URL_TEMPLATE = + new URLTemplate("retention_policy_assignments/%s"); + + /** + * The URL template used for operation with files under retention with given retention policy + * assignment ID. + */ + public static final URLTemplate FILES_UNDER_RETENTION_URL_TEMPLATE = + new URLTemplate("retention_policy_assignments/%s/files_under_retention"); + + /** + * The URL template used for operation with file versions under retention with given retention + * policy assignment ID. + */ + public static final URLTemplate FILE_VERSIONS_UNDER_RETENTION_URL_TEMPLATE = + new URLTemplate("retention_policy_assignments/%s/file_versions_under_retention"); + + private static final int DEFAULT_LIMIT = 100; + + /** + * Constructs a BoxResource for a resource with a given ID. + * + * @param api the API connection to be used by the resource. + * @param id the ID of the resource. + */ + public BoxRetentionPolicyAssignment(BoxAPIConnection api, String id) { + super(api, id); + } + + /** + * Assigns retention policy with givenID to the enterprise. + * + * @param api the API connection to be used by the created assignment. + * @param policyID id of the assigned retention policy. + * @return info about created assignment. + */ + public static BoxRetentionPolicyAssignment.Info createAssignmentToEnterprise( + BoxAPIConnection api, String policyID) { + return createAssignment( + api, policyID, new JsonObject().add("type", TYPE_ENTERPRISE), null, null); + } + + /** + * Assigns retention policy with givenID to the folder. + * + * @param api the API connection to be used by the created assignment. + * @param policyID id of the assigned retention policy. + * @param folderID id of the folder to assign policy to. + * @return info about created assignment. + */ + public static BoxRetentionPolicyAssignment.Info createAssignmentToFolder( + BoxAPIConnection api, String policyID, String folderID) { + return createAssignment( + api, policyID, new JsonObject().add("type", TYPE_FOLDER).add("id", folderID), null, null); + } + + /** + * Assigns a retention policy to all items with a given metadata template, optionally matching on + * fields. + * + * @param api the API connection to be used by the created assignment. + * @param policyID id of the assigned retention policy. + * @param templateID the ID of the metadata template to assign the policy to. + * @param filter optional fields to match against in the metadata template. + * @return info about the created assignment. + */ + public static BoxRetentionPolicyAssignment.Info createAssignmentToMetadata( + BoxAPIConnection api, String policyID, String templateID, MetadataFieldFilter... filter) { + return createAssignmentToMetadata(api, policyID, templateID, null, filter); + } + + /** + * Assigns a retention policy to all items with a given metadata template, optionally matching on + * fields. + * + * @param api the API connection to be used by the created assignment. + * @param policyID id of the assigned retention policy. + * @param templateID the ID of the metadata template to assign the policy to. + * @param startDateField The date the retention policy assignment begins. This field can be a date + * field's metadata attribute key id. + * @param filter optional fields to match against in the metadata template. + * @return info about the created assignment. + */ + public static BoxRetentionPolicyAssignment.Info createAssignmentToMetadata( + BoxAPIConnection api, + String policyID, + String templateID, + String startDateField, + MetadataFieldFilter... filter) { + JsonObject assignTo = new JsonObject().add("type", TYPE_METADATA).add("id", templateID); + JsonArray filters = null; + if (filter.length > 0) { + filters = new JsonArray(); + for (MetadataFieldFilter f : filter) { + filters.add(f.getJsonObject()); + } + } + return createAssignment(api, policyID, assignTo, startDateField, filters); + } + + /** + * Assigns retention policy with givenID to folder or enterprise. + * + * @param api the API connection to be used by the created assignment. + * @param policyID id of the assigned retention policy. + * @param assignTo object representing folder or enterprise to assign policy to. + * @param filter Filters + * @return info about created assignment. + */ + private static BoxRetentionPolicyAssignment.Info createAssignment( + BoxAPIConnection api, + String policyID, + JsonObject assignTo, + String startDateField, + JsonArray filter) { + URL url = ASSIGNMENTS_URL_TEMPLATE.build(api.getBaseURL()); + BoxJSONRequest request = new BoxJSONRequest(api, url, "POST"); + + JsonObject requestJSON = new JsonObject().add("policy_id", policyID).add("assign_to", assignTo); + + if (filter != null) { + requestJSON.add("filter_fields", filter); + } + if (startDateField != null) { + requestJSON.add("start_date_field", startDateField); + } + + request.setBody(requestJSON.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + BoxRetentionPolicyAssignment createdAssignment = + new BoxRetentionPolicyAssignment(api, responseJSON.get("id").asString()); + return createdAssignment.new Info(responseJSON); + } + } + + /** + * @param fields the fields to retrieve. + * @return information about this retention policy assignment. + */ + public BoxRetentionPolicyAssignment.Info getInfo(String... fields) { + QueryStringBuilder builder = new QueryStringBuilder(); + if (fields.length > 0) { + builder.appendParam("fields", fields); + } + URL url = + RETENTION_POLICY_ASSIGNMENT_URL_TEMPLATE.buildWithQuery( + this.getAPI().getBaseURL(), builder.toString(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + return new Info(responseJSON); + } + } + + /** + * Retrieves all files under retention for assignment as Iterable. Default limit is 100 + * + * @param fields the fields to retrieve. + * @return an iterable contains information about all files under retentions as Iterable. + */ + public Iterable getFilesUnderRetention(String... fields) { + return this.getFilesUnderRetention(DEFAULT_LIMIT, fields); + } + + /** + * Retrieves all files under retention for assignment as Iterable. + * + * @param limit the limit of retrieved entries per page. + * @param fields the fields to retrieve. + * @return an iterable contains information about all files under retentions as Iterable. + */ + public Iterable getFilesUnderRetention(int limit, String... fields) { + QueryStringBuilder queryString = new QueryStringBuilder(); + if (fields.length > 0) { + queryString.appendParam("fields", fields); + } + URL url = + FILES_UNDER_RETENTION_URL_TEMPLATE.buildWithQuery( + getAPI().getBaseURL(), queryString.toString(), getID()); + return new BoxResourceIterable(getAPI(), url, limit) { + @Override + protected BoxFile.Info factory(JsonObject jsonObject) { + BoxFile boxFile = new BoxFile(getAPI(), jsonObject.get("id").asString()); + return boxFile.new Info(jsonObject); + } + }; + } + + /** + * Retrieves all file version under retention for assignment as Iterable. Default limit is 100. + * + * @param fields the fields to retrieve. + * @return an iterable contains information about all file versions under retentions as Iterable. + */ + public Iterable getFileVersionsUnderRetention(String... fields) { + return this.getFileVersionsUnderRetention(DEFAULT_LIMIT, fields); + } + + /** + * Retrieves all file version under retention for assignment as Iterable. + * + * @param limit the limit of retrieved entries per page. + * @param fields the fields to retrieve. + * @return an iterable contains information about all file versions under retentions as Iterable. + */ + public Iterable getFileVersionsUnderRetention(int limit, String... fields) { + QueryStringBuilder queryString = new QueryStringBuilder(); + if (fields.length > 0) { + queryString.appendParam("fields", fields); + } + URL url = + FILE_VERSIONS_UNDER_RETENTION_URL_TEMPLATE.buildWithQuery( + getAPI().getBaseURL(), queryString.toString(), getID()); + return new BoxResourceIterable(getAPI(), url, limit) { + @Override + protected BoxFile.Info factory(JsonObject jsonObject) { + BoxFile boxFile = new BoxFile(getAPI(), jsonObject.get("id").asString()); + return boxFile.new Info(jsonObject); + } + }; + } + + /** Deletes retention policy assignment. */ + public void delete() { + URL url = + RETENTION_POLICY_ASSIGNMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); + request.send().close(); + } + + /** Contains information about the retention policy. */ + public class Info extends BoxResource.Info { + + /** @see #getRetentionPolicy() */ + private BoxRetentionPolicy.Info retentionPolicy; + + /** @see #getAssignedBy() */ + private BoxUser.Info assignedBy; + + /** @see #getAssignedAt() */ + private Date assignedAt; + + /** @see #getAssignedToType() */ + private String assignedToType; + + /** @see #getAssignedToID() */ + private String assignedToID; + + /** @see #getStartDateField() */ + private String startDateField; + + private List filterFields; + + /** Constructs an empty Info object. */ + public Info() { + super(); + } + + /** + * Constructs an Info object by parsing information from a JSON string. + * + * @param json the JSON string to parse. + */ + public Info(String json) { + super(json); + } + + /** + * Constructs an Info object using an already parsed JSON object. + * + * @param jsonObject the parsed JSON object. + */ + Info(JsonObject jsonObject) { + super(jsonObject); + } + + /** {@inheritDoc} */ + @Override + public BoxResource getResource() { + return BoxRetentionPolicyAssignment.this; + } + + /** @return the retention policy that has been assigned to this content. */ + public BoxRetentionPolicy.Info getRetentionPolicy() { + return this.retentionPolicy; + } + + /** @return the info about the user that created the retention policy assignment. */ + public BoxUser.Info getAssignedBy() { + return this.assignedBy; + } + + /** @return the time that the retention policy assignment was created. */ + public Date getAssignedAt() { + return this.assignedAt; + } + + /** + * @return type of the content that is under retention. Can either be "enterprise" or "folder". + */ + public String getAssignedToType() { + return this.assignedToType; + } + + /** @return id of the folder that is under retention. */ + public String getAssignedToID() { + return this.assignedToID; + } + + /** @return date the retention policy assignment begins */ + public String getStartDateField() { + return this.startDateField; + } + + /** @return the array of metadata field filters, if present */ + public List getFilterFields() { + + return this.filterFields; + } + + /** {@inheritDoc} */ + @Override + void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + String memberName = member.getName(); + JsonValue value = member.getValue(); + try { + if (memberName.equals("retention_policy")) { + JsonObject policyJSON = value.asObject(); + if (this.retentionPolicy == null) { + String policyID = policyJSON.get("id").asString(); + BoxRetentionPolicy policy = new BoxRetentionPolicy(getAPI(), policyID); + this.retentionPolicy = policy.new Info(policyJSON); + } else { + this.retentionPolicy.update(policyJSON); + } + } else if (memberName.equals("assigned_to")) { + JsonObject assignmentJSON = value.asObject(); + this.assignedToType = assignmentJSON.get("type").asString(); + if (this.assignedToType.equals(TYPE_ENTERPRISE)) { + this.assignedToID = null; + } else { + this.assignedToID = assignmentJSON.get("id").asString(); + } + } else if (memberName.equals("assigned_by")) { + JsonObject userJSON = value.asObject(); + if (this.assignedBy == null) { + String userID = userJSON.get("id").asString(); + BoxUser user = new BoxUser(getAPI(), userID); + this.assignedBy = user.new Info(userJSON); + } else { + this.assignedBy.update(userJSON); + } + } else if (memberName.equals("assigned_at")) { + this.assignedAt = BoxDateFormat.parse(value.asString()); + } else if (memberName.equals("start_date_field")) { + this.startDateField = value.asString(); + } else if (memberName.equals("filter_fields")) { + JsonArray jsonFilters = value.asArray(); + List filterFields = new ArrayList<>(); + for (int i = 0; i < jsonFilters.size(); i++) { + filterFields.add(new MetadataFieldFilter(jsonFilters.get(i).asObject())); + } + this.filterFields = filterFields; + } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); + } + } + } +} diff --git a/src/main/java/com/box/sdk/BoxSearch.java b/src/main/java/com/box/sdk/BoxSearch.java index c2efcedfa..8f3be9118 100644 --- a/src/main/java/com/box/sdk/BoxSearch.java +++ b/src/main/java/com/box/sdk/BoxSearch.java @@ -7,99 +7,101 @@ import java.net.URL; /** - * Represents search on Box. This class can be used to search through your box instance. - * In addition this lets you take advantage of all the advanced search features. + * Represents search on Box. This class can be used to search through your box instance. In addition + * this lets you take advantage of all the advanced search features. * - *

Unless otherwise noted, the methods in this class can throw an unchecked {@link BoxAPIException} (unchecked - * meaning that the compiler won't force you to handle it) if an error occurs. If you wish to implement custom error - * handling for errors related to the Box REST API, you should capture this exception explicitly.

+ *

Unless otherwise noted, the methods in this class can throw an unchecked {@link + * BoxAPIException} (unchecked meaning that the compiler won't force you to handle it) if an error + * occurs. If you wish to implement custom error handling for errors related to the Box REST API, + * you should capture this exception explicitly. */ public class BoxSearch { - /** - * Search URL Template. - */ - public static final URLTemplate SEARCH_URL_TEMPLATE = new URLTemplate("search"); - private final BoxAPIConnection api; + /** Search URL Template. */ + public static final URLTemplate SEARCH_URL_TEMPLATE = new URLTemplate("search"); - /** - * Constructs a Search to be used by everything. - * - * @param api the API connection to be used by the search. - */ - public BoxSearch(BoxAPIConnection api) { - this.api = api; - } + private final BoxAPIConnection api; - /** - * Searches all descendant folders using a given query and query parameters. - * - * @param offset is the starting position. - * @param limit the maximum number of items to return. The default is 30 and the maximum is 200. - * @param bsp containing query and advanced search capabilities. - * @return a PartialCollection containing the search results. - */ - public PartialCollection searchRange(long offset, long limit, final BoxSearchParameters bsp) { - QueryStringBuilder builder = bsp.getQueryParameters() - .appendParam("limit", limit) - .appendParam("offset", offset); - URL url = SEARCH_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), builder.toString()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - String totalCountString = responseJSON.get("total_count").toString(); - long fullSize = Double.valueOf(totalCountString).longValue(); - PartialCollection results = new PartialCollection<>(offset, limit, fullSize); - JsonArray jsonArray = responseJSON.get("entries").asArray(); - for (JsonValue value : jsonArray) { - JsonObject jsonObject = value.asObject(); - BoxItem.Info parsedItemInfo = (BoxItem.Info) BoxResource.parseInfo(this.getAPI(), jsonObject); - if (parsedItemInfo != null) { - results.add(parsedItemInfo); - } - } - return results; + /** + * Constructs a Search to be used by everything. + * + * @param api the API connection to be used by the search. + */ + public BoxSearch(BoxAPIConnection api) { + this.api = api; + } + + /** + * Searches all descendant folders using a given query and query parameters. + * + * @param offset is the starting position. + * @param limit the maximum number of items to return. The default is 30 and the maximum is 200. + * @param bsp containing query and advanced search capabilities. + * @return a PartialCollection containing the search results. + */ + public PartialCollection searchRange( + long offset, long limit, final BoxSearchParameters bsp) { + QueryStringBuilder builder = + bsp.getQueryParameters().appendParam("limit", limit).appendParam("offset", offset); + URL url = SEARCH_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), builder.toString()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + String totalCountString = responseJSON.get("total_count").toString(); + long fullSize = Double.valueOf(totalCountString).longValue(); + PartialCollection results = new PartialCollection<>(offset, limit, fullSize); + JsonArray jsonArray = responseJSON.get("entries").asArray(); + for (JsonValue value : jsonArray) { + JsonObject jsonObject = value.asObject(); + BoxItem.Info parsedItemInfo = + (BoxItem.Info) BoxResource.parseInfo(this.getAPI(), jsonObject); + if (parsedItemInfo != null) { + results.add(parsedItemInfo); } + } + return results; } + } - /** - * Searches all descendant folders using a given query and query parameters. - * - * @param offset is the starting position. - * @param limit the maximum number of items to return. The default is 30 and the maximum is 200. - * @param bsp containing query and advanced search capabilities. - * @return a PartialCollection containing the search results. - */ - public PartialCollection searchRangeIncludeSharedLinks(long offset, long limit, - final BoxSearchParameters bsp) { - QueryStringBuilder builder = bsp.getQueryParameters() + /** + * Searches all descendant folders using a given query and query parameters. + * + * @param offset is the starting position. + * @param limit the maximum number of items to return. The default is 30 and the maximum is 200. + * @param bsp containing query and advanced search capabilities. + * @return a PartialCollection containing the search results. + */ + public PartialCollection searchRangeIncludeSharedLinks( + long offset, long limit, final BoxSearchParameters bsp) { + QueryStringBuilder builder = + bsp.getQueryParameters() .appendParam("include_recent_shared_links", "true") .appendParam("limit", limit) .appendParam("offset", offset); - URL url = SEARCH_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), builder.toString()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - String totalCountString = responseJSON.get("total_count").toString(); - long fullSize = Double.valueOf(totalCountString).longValue(); - PartialCollection results = new PartialCollection<>(offset, - limit, fullSize); - JsonArray jsonArray = responseJSON.get("entries").asArray(); - for (JsonValue value : jsonArray) { - JsonObject jsonObject = value.asObject(); - BoxSearchSharedLink parsedItem = new BoxSearchSharedLink(jsonObject, this.getAPI()); - results.add(parsedItem); - } - return results; - } + URL url = SEARCH_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), builder.toString()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + String totalCountString = responseJSON.get("total_count").toString(); + long fullSize = Double.valueOf(totalCountString).longValue(); + PartialCollection results = + new PartialCollection<>(offset, limit, fullSize); + JsonArray jsonArray = responseJSON.get("entries").asArray(); + for (JsonValue value : jsonArray) { + JsonObject jsonObject = value.asObject(); + BoxSearchSharedLink parsedItem = new BoxSearchSharedLink(jsonObject, this.getAPI()); + results.add(parsedItem); + } + return results; } + } - /** - * Gets the API connection used by this resource. - * - * @return the API connection used by this resource. - */ - public BoxAPIConnection getAPI() { - return this.api; - } + /** + * Gets the API connection used by this resource. + * + * @return the API connection used by this resource. + */ + public BoxAPIConnection getAPI() { + return this.api; + } } diff --git a/src/main/java/com/box/sdk/BoxSearchParameters.java b/src/main/java/com/box/sdk/BoxSearchParameters.java index c3377ff60..d18e0f5d4 100644 --- a/src/main/java/com/box/sdk/BoxSearchParameters.java +++ b/src/main/java/com/box/sdk/BoxSearchParameters.java @@ -7,516 +7,516 @@ /** * Used to Setup Box Search Parameters * - *

Advanced Search support here allows a number of parameters be specified to take full advantage of - * box search capabilities. Query parameter is required in all cases except when Metadata templates - * searching is being used.

+ *

Advanced Search support here allows a number of parameters be specified to take full advantage + * of box search capabilities. Query parameter is required in all cases except when Metadata + * templates searching is being used. */ public class BoxSearchParameters { - private String query; - private List fields; - private String scope; - private List fileExtensions; - private DateRange createdRange; - private DateRange updatedRange; - private SizeRange sizeRange; - private List ownerUserIds; - private List ancestorFolderIds; - private List contentTypes; - private String type; - private String trashContent; - private BoxMetadataFilter metadataFilter; - private String sort; - private String direction; - private List deleterUserIds; - private DateRange deletedRange; - - /** - * Creates a Box Search Parameters Objects without query set, specific for Metadata Only Searches. - */ - public BoxSearchParameters() { - } - - /** - * Creates a Box Search Parameters Objects with a query initiated. - * - * @param query parameter. - */ - public BoxSearchParameters(String query) { - this.query = query; - } - - /** - * Clears the Parameters before performing a new search. - * - * @return this.true; - */ - public boolean clearParameters() { - this.query = null; - this.fields = null; - this.scope = null; - this.fileExtensions = null; - this.createdRange = null; - this.updatedRange = null; - this.sizeRange = null; - this.ownerUserIds = null; - this.ancestorFolderIds = null; - this.contentTypes = null; - this.type = null; - this.trashContent = null; - this.metadataFilter = null; - this.sort = null; - this.direction = null; - this.deleterUserIds = null; - this.deletedRange = null; - return true; - } - - /** - * Get existing query String that is being used. - * - * @return this.query string. - */ - public String getQuery() { - return this.query; - } - - /** - * Set query string for that will be used to search. - * - * @param query is a String value. - */ - public void setQuery(String query) { - this.query = query; - } - - /** - * Get the existing fields that are used for the search criteria. - * - * @return this.List of fields. - */ - public List getFields() { - return this.fields; - } - - /** - * Set the existing fields that are used for the search criteria. - * - * @param fields specify what fields to be returned. - */ - public void setFields(List fields) { - this.fields = fields; - } - - /** - * Get the scope on which you want to search, ["enterprise","scope"]. - * - * @return this.current scope that is set. - */ - public String getScope() { - return this.scope; - } - - /** - * Set the scope for how you want to search, ["enterprise","scope"]. - * - * @param scope set scope you want to search. - */ - public void setScope(String scope) { - this.scope = scope; - } - - /** - * Get file extension filter (jpg,docx). - * - * @return this.list of extensions. - */ - public List getFileExtensions() { - return this.fileExtensions; - } - - /** - * Set file extension by providing a list of strings [jpg,docx]. - * - * @param fileExtensions applied as a filter for extensions. - */ - public void setFileExtensions(List fileExtensions) { - this.fileExtensions = fileExtensions; - } - - /** - * Get the DateRange filter to specify the when a file was created. - * - * @return this.createdRange DateRange. - */ - public DateRange getCreatedRange() { - return this.createdRange; - } - - /** - * Set the from DateRange filter to specify when a file was created. - * - * @param createdRange a start and end date on which a file was created. - */ - public void setCreatedRange(DateRange createdRange) { - this.createdRange = createdRange; - } - - /** - * Get the DateRange filter to specify the when a file was updated. - * - * @return this.updatedRange DateRange. - */ - public DateRange getUpdatedRange() { - return this.updatedRange; - } - - /** - * Set the from DateRange filter to specify when a file was updated. - * - * @param updatedRange a start and end date on which a file was updated. - */ - public void setUpdatedRange(DateRange updatedRange) { - this.updatedRange = updatedRange; - } - - /** - * Return the size range that is being used as a filter. - * - * @return this.sizeRange. - */ - public SizeRange getSizeRange() { - return this.sizeRange; - } - - /** - * Set the file size range for lower and upper bounds Bytes. - * - * @param sizeRange a size filter. - */ - public void setSizeRange(SizeRange sizeRange) { - this.sizeRange = sizeRange; - } + private String query; + private List fields; + private String scope; + private List fileExtensions; + private DateRange createdRange; + private DateRange updatedRange; + private SizeRange sizeRange; + private List ownerUserIds; + private List ancestorFolderIds; + private List contentTypes; + private String type; + private String trashContent; + private BoxMetadataFilter metadataFilter; + private String sort; + private String direction; + private List deleterUserIds; + private DateRange deletedRange; + + /** + * Creates a Box Search Parameters Objects without query set, specific for Metadata Only Searches. + */ + public BoxSearchParameters() {} + + /** + * Creates a Box Search Parameters Objects with a query initiated. + * + * @param query parameter. + */ + public BoxSearchParameters(String query) { + this.query = query; + } + + /** + * Clears the Parameters before performing a new search. + * + * @return this.true; + */ + public boolean clearParameters() { + this.query = null; + this.fields = null; + this.scope = null; + this.fileExtensions = null; + this.createdRange = null; + this.updatedRange = null; + this.sizeRange = null; + this.ownerUserIds = null; + this.ancestorFolderIds = null; + this.contentTypes = null; + this.type = null; + this.trashContent = null; + this.metadataFilter = null; + this.sort = null; + this.direction = null; + this.deleterUserIds = null; + this.deletedRange = null; + return true; + } + + /** + * Get existing query String that is being used. + * + * @return this.query string. + */ + public String getQuery() { + return this.query; + } + + /** + * Set query string for that will be used to search. + * + * @param query is a String value. + */ + public void setQuery(String query) { + this.query = query; + } + + /** + * Get the existing fields that are used for the search criteria. + * + * @return this.List of fields. + */ + public List getFields() { + return this.fields; + } + + /** + * Set the existing fields that are used for the search criteria. + * + * @param fields specify what fields to be returned. + */ + public void setFields(List fields) { + this.fields = fields; + } + + /** + * Get the scope on which you want to search, ["enterprise","scope"]. + * + * @return this.current scope that is set. + */ + public String getScope() { + return this.scope; + } + + /** + * Set the scope for how you want to search, ["enterprise","scope"]. + * + * @param scope set scope you want to search. + */ + public void setScope(String scope) { + this.scope = scope; + } + + /** + * Get file extension filter (jpg,docx). + * + * @return this.list of extensions. + */ + public List getFileExtensions() { + return this.fileExtensions; + } + + /** + * Set file extension by providing a list of strings [jpg,docx]. + * + * @param fileExtensions applied as a filter for extensions. + */ + public void setFileExtensions(List fileExtensions) { + this.fileExtensions = fileExtensions; + } + + /** + * Get the DateRange filter to specify the when a file was created. + * + * @return this.createdRange DateRange. + */ + public DateRange getCreatedRange() { + return this.createdRange; + } + + /** + * Set the from DateRange filter to specify when a file was created. + * + * @param createdRange a start and end date on which a file was created. + */ + public void setCreatedRange(DateRange createdRange) { + this.createdRange = createdRange; + } + + /** + * Get the DateRange filter to specify the when a file was updated. + * + * @return this.updatedRange DateRange. + */ + public DateRange getUpdatedRange() { + return this.updatedRange; + } + + /** + * Set the from DateRange filter to specify when a file was updated. + * + * @param updatedRange a start and end date on which a file was updated. + */ + public void setUpdatedRange(DateRange updatedRange) { + this.updatedRange = updatedRange; + } + + /** + * Return the size range that is being used as a filter. + * + * @return this.sizeRange. + */ + public SizeRange getSizeRange() { + return this.sizeRange; + } + + /** + * Set the file size range for lower and upper bounds Bytes. + * + * @param sizeRange a size filter. + */ + public void setSizeRange(SizeRange sizeRange) { + this.sizeRange = sizeRange; + } + + /** + * Return the list of owner id's that are being applied as a search filter on the results. + * + * @return ownerUserIds. + */ + public List getOwnerUserIds() { + return this.ownerUserIds; + } + + /** + * Set the owner id's to be applied as a filter to restrict the results on specific file owners. + * + * @param ownerUserIds applied ownerId's. + */ + public void setOwnerUserIds(List ownerUserIds) { + this.ownerUserIds = ownerUserIds; + } + + /** + * Return the list of folder ids that is currently being used as applied filter. + * + * @return ancestorFolderIds. + */ + public List getAncestorFolderIds() { + return this.ancestorFolderIds; + } + + /** + * Set the list of folder id's to be applied as a filter on the search filters. + * + * @param ancestorFolderIds a list of folder ids that will contain results to specific folders. + */ + public void setAncestorFolderIds(List ancestorFolderIds) { + this.ancestorFolderIds = ancestorFolderIds; + } + + /** + * Return content types that or being applied as a filter (name,description,tags,file_content). + * + * @return contentTypes. + */ + public List getContentTypes() { + return this.contentTypes; + } + + /** + * Set list of content types that will be used as a filters. + * + * @param contentTypes a list of content types such as (name,description,tags,file_content). + */ + public void setContentTypes(List contentTypes) { + this.contentTypes = contentTypes; + } + + /** + * Return the type you want to return in your search. + * + * @return String type. + */ + public String getType() { + return this.type; + } + + /** + * Set the type you want to search for can be file, folder, or web_link. + * + * @param type can be file, folder, or web_link. + */ + public void setType(String type) { + this.type = type; + } + + /** + * Return the specified trash search preference. + * + * @return String trashContent. + */ + public String getTrashContent() { + return this.trashContent; + } + + /** + * Set trash filter. Can be trashed_only or non_trashed_only, without this parameter default to + * non_trashed_only. + * + * @param trashContent Can be trashed_only or non_trashed_only. + */ + public void setTrashContent(String trashContent) { + this.trashContent = trashContent; + } + + /** + * Retrieve the existing BoxMetaDataFilter. + * + * @return this.BoxMetaDataFilter + */ + public BoxMetadataFilter getMetadataFilter() { + return this.metadataFilter; + } + + /** + * Set the current list of Metadata Filters. + * + * @param metadataFilter a list of the current metadata filters. + */ + public void setMetadataFilter(BoxMetadataFilter metadataFilter) { + this.metadataFilter = metadataFilter; + } + + /** + * Retrieve the sort field for Box Search. + * + * @return String identifier for Sort. + */ + public String getSort() { + return this.sort; + } + + /** + * Set the sort field for Box Search. + * + * @param sortBy the field to sort the Box Search results by. + */ + public void setSort(String sortBy) { + this.sort = sortBy; + } + + /** + * Retrieves the sort direction for Box Search results. + * + * @return The direction of the Box Search sort. + */ + public String getDirection() { + return this.direction; + } + + /** + * Set the direction of the sort for the Box Search results. + * + * @param direction can be DESC or ASC. + */ + public void setDirection(String direction) { + this.direction = direction; + } + + /** + * Limits the search results to items that were deleted by the given list of users, defined as a + * list of comma separated user IDs. The trash_content parameter needs to be set to trashed_only. + * + * @return deleterUserIds. + */ + public List getDeleterUserIds() { + return this.deleterUserIds; + } + + /** + * Limits the search results to items that were deleted by the given list of users, defined as a + * list of comma separated user IDs. The trash_content parameter needs to be set to trashed_only. + * + * @param deleterUserIds a list of user ids. + */ + public void setDeleterUserIds(List deleterUserIds) { + this.deleterUserIds = deleterUserIds; + } + + /** + * Limits the search results to items that were deleted within the given date range. The + * trash_content parameter needs to be set to trashed_only. + * + * @return deletedRange. + */ + public DateRange getDeletedRange() { + return this.deletedRange; + } + + /** + * Limits the search results to items that were deleted within the given date range. The + * trash_content parameter needs to be set to trashed_only. + * + * @param deletedRange a date range. + */ + public void setDeletedRange(DateRange deletedRange) { + this.deletedRange = deletedRange; + } + + /** + * Checks String to see if the parameter is null. + * + * @param paramValue Object that will be checked if null. + * @return this.true if the parameter that is being checked is not null + */ + private boolean isNullOrEmpty(Object paramValue) { + boolean isNullOrEmpty = false; + if (paramValue == null) { + isNullOrEmpty = true; + } + if (paramValue instanceof String) { + if (((String) paramValue).trim().equalsIgnoreCase("")) { + isNullOrEmpty = true; + } + } else if (paramValue instanceof List) { + return ((List) paramValue).isEmpty(); + } + return isNullOrEmpty; + } + + /** + * Add BoxMetaDataFilter to the JsonArray boxMetadataFilterRequestArray. + * + * @return JsonArray that is formated Json request + */ + private JsonArray formatBoxMetadataFilterRequest() { + JsonArray boxMetadataFilterRequestArray = new JsonArray(); + + JsonObject boxMetadataFilter = + new JsonObject() + .add("templateKey", this.metadataFilter.getTemplateKey()) + .add("scope", this.metadataFilter.getScope()) + .add("filters", this.metadataFilter.getFiltersList()); + boxMetadataFilterRequestArray.add(boxMetadataFilter); - /** - * Return the list of owner id's that are being applied as a search filter on the results. - * - * @return ownerUserIds. - */ - public List getOwnerUserIds() { - return this.ownerUserIds; - } + return boxMetadataFilterRequestArray; + } - /** - * Set the owner id's to be applied as a filter to restrict the results on specific file owners. - * - * @param ownerUserIds applied ownerId's. - */ - public void setOwnerUserIds(List ownerUserIds) { - this.ownerUserIds = ownerUserIds; + /** + * Concat a List into a CSV String. + * + * @param list list to concat + * @return csv string + */ + private String listToCSV(List list) { + String csvStr = ""; + for (String item : list) { + csvStr += "," + item; } - /** - * Return the list of folder ids that is currently being used as applied filter. - * - * @return ancestorFolderIds. - */ - public List getAncestorFolderIds() { - return this.ancestorFolderIds; - } + return csvStr.length() > 1 ? csvStr.substring(1) : csvStr; + } - /** - * Set the list of folder id's to be applied as a filter on the search filters. - * - * @param ancestorFolderIds a list of folder ids that will contain results to specific folders. - */ - public void setAncestorFolderIds(List ancestorFolderIds) { - this.ancestorFolderIds = ancestorFolderIds; - } + /** + * Get the Query Paramaters to be used for search request. + * + * @return this.QueryStringBuilder. + */ + public QueryStringBuilder getQueryParameters() { + QueryStringBuilder builder = new QueryStringBuilder(); - /** - * Return content types that or being applied as a filter (name,description,tags,file_content). - * - * @return contentTypes. - */ - public List getContentTypes() { - return this.contentTypes; + if (this.isNullOrEmpty(this.query) && this.metadataFilter == null) { + throw new BoxAPIException( + "BoxSearchParameters requires either a search query or Metadata filter to be set."); } - /** - * Set list of content types that will be used as a filters. - * - * @param contentTypes a list of content types such as (name,description,tags,file_content). - */ - public void setContentTypes(List contentTypes) { - this.contentTypes = contentTypes; + // Set the query of the search + if (!this.isNullOrEmpty(this.query)) { + builder.appendParam("query", this.query); } - - /** - * Return the type you want to return in your search. - * - * @return String type. - */ - public String getType() { - return this.type; + // Set the scope of the search + if (!this.isNullOrEmpty(this.scope)) { + builder.appendParam("scope", this.scope); } - - /** - * Set the type you want to search for can be file, folder, or web_link. - * - * @param type can be file, folder, or web_link. - */ - public void setType(String type) { - this.type = type; + // Acceptable Value: "jpg,png" + if (!this.isNullOrEmpty(this.fileExtensions)) { + builder.appendParam("file_extensions", this.listToCSV(this.fileExtensions)); } - - /** - * Return the specified trash search preference. - * - * @return String trashContent. - */ - public String getTrashContent() { - return this.trashContent; + // Created Date Range: From Date - To Date + if ((this.createdRange != null)) { + builder.appendParam("created_at_range", this.createdRange.buildRangeString()); } - - /** - * Set trash filter. Can be trashed_only or non_trashed_only, without this parameter default to non_trashed_only. - * - * @param trashContent Can be trashed_only or non_trashed_only. - */ - public void setTrashContent(String trashContent) { - this.trashContent = trashContent; + // Updated Date Range: From Date - To Date + if ((this.updatedRange != null)) { + builder.appendParam("updated_at_range", this.updatedRange.buildRangeString()); } - - /** - * Retrieve the existing BoxMetaDataFilter. - * - * @return this.BoxMetaDataFilter - */ - public BoxMetadataFilter getMetadataFilter() { - return this.metadataFilter; + // Filesize Range + if ((this.sizeRange != null)) { + builder.appendParam("size_range", this.sizeRange.buildRangeString()); } - - /** - * Set the current list of Metadata Filters. - * - * @param metadataFilter a list of the current metadata filters. - */ - public void setMetadataFilter(BoxMetadataFilter metadataFilter) { - this.metadataFilter = metadataFilter; + // Owner Id's + if (!this.isNullOrEmpty(this.ownerUserIds)) { + builder.appendParam("owner_user_ids", this.listToCSV(this.ownerUserIds)); } - - /** - * Retrieve the sort field for Box Search. - * - * @return String identifier for Sort. - */ - public String getSort() { - return this.sort; + // Ancestor ID's + if (!this.isNullOrEmpty(this.ancestorFolderIds)) { + builder.appendParam("ancestor_folder_ids", this.listToCSV(this.ancestorFolderIds)); } - - /** - * Set the sort field for Box Search. - * - * @param sortBy the field to sort the Box Search results by. - */ - public void setSort(String sortBy) { - this.sort = sortBy; + // Content Types: "name, description" + if (!this.isNullOrEmpty(this.contentTypes)) { + builder.appendParam("content_types", this.listToCSV(this.contentTypes)); } - - /** - * Retrieves the sort direction for Box Search results. - * - * @return The direction of the Box Search sort. - */ - public String getDirection() { - return this.direction; + // Type of File: "file,folder,web_link" + if (this.type != null) { + builder.appendParam("type", this.type); } - - /** - * Set the direction of the sort for the Box Search results. - * - * @param direction can be DESC or ASC. - */ - public void setDirection(String direction) { - this.direction = direction; + // Trash Content + if (!this.isNullOrEmpty(this.trashContent)) { + builder.appendParam("trash_content", this.trashContent); } - - /** - * Limits the search results to items that were deleted by the given list of users, defined as a list of comma separated user IDs. - * The trash_content parameter needs to be set to trashed_only. - * - * @return deleterUserIds. - */ - public List getDeleterUserIds() { - return this.deleterUserIds; + // Metadata filters + if (this.metadataFilter != null) { + builder.appendParam("mdfilters", this.formatBoxMetadataFilterRequest().toString()); } - - /** - * Limits the search results to items that were deleted by the given list of users, defined as a list of comma separated user IDs. - * The trash_content parameter needs to be set to trashed_only. - * - * @param deleterUserIds a list of user ids. - */ - public void setDeleterUserIds(List deleterUserIds) { - this.deleterUserIds = deleterUserIds; + // Fields + if (!this.isNullOrEmpty(this.fields)) { + builder.appendParam("fields", this.listToCSV(this.fields)); } - - /** - * Limits the search results to items that were deleted within the given date range. - * The trash_content parameter needs to be set to trashed_only. - * - * @return deletedRange. - */ - public DateRange getDeletedRange() { - return this.deletedRange; + // Sort + if (!this.isNullOrEmpty(this.sort)) { + builder.appendParam("sort", this.sort); } - - /** - * Limits the search results to items that were deleted within the given date range. - * The trash_content parameter needs to be set to trashed_only. - * - * @param deletedRange a date range. - */ - public void setDeletedRange(DateRange deletedRange) { - this.deletedRange = deletedRange; + // Direction + if (!this.isNullOrEmpty(this.direction)) { + builder.appendParam("direction", this.direction); } - - /** - * Checks String to see if the parameter is null. - * - * @param paramValue Object that will be checked if null. - * @return this.true if the parameter that is being checked is not null - */ - private boolean isNullOrEmpty(Object paramValue) { - boolean isNullOrEmpty = false; - if (paramValue == null) { - isNullOrEmpty = true; - } - if (paramValue instanceof String) { - if (((String) paramValue).trim().equalsIgnoreCase("")) { - isNullOrEmpty = true; - } - } else if (paramValue instanceof List) { - return ((List) paramValue).isEmpty(); - } - return isNullOrEmpty; + // Deleter User Ids + if (!this.isNullOrEmpty(this.deleterUserIds)) { + builder.appendParam("deleter_user_ids", this.listToCSV(this.deleterUserIds)); } - - /** - * Add BoxMetaDataFilter to the JsonArray boxMetadataFilterRequestArray. - * - * @return JsonArray that is formated Json request - */ - private JsonArray formatBoxMetadataFilterRequest() { - JsonArray boxMetadataFilterRequestArray = new JsonArray(); - - JsonObject boxMetadataFilter = new JsonObject() - .add("templateKey", this.metadataFilter.getTemplateKey()) - .add("scope", this.metadataFilter.getScope()) - .add("filters", this.metadataFilter.getFiltersList()); - boxMetadataFilterRequestArray.add(boxMetadataFilter); - - return boxMetadataFilterRequestArray; + // Deleted Range + if ((this.deletedRange != null)) { + builder.appendParam("deleted_range", this.deletedRange.buildRangeString()); } - /** - * Concat a List into a CSV String. - * - * @param list list to concat - * @return csv string - */ - private String listToCSV(List list) { - String csvStr = ""; - for (String item : list) { - csvStr += "," + item; - } - - return csvStr.length() > 1 ? csvStr.substring(1) : csvStr; - } - - /** - * Get the Query Paramaters to be used for search request. - * - * @return this.QueryStringBuilder. - */ - public QueryStringBuilder getQueryParameters() { - QueryStringBuilder builder = new QueryStringBuilder(); - - if (this.isNullOrEmpty(this.query) && this.metadataFilter == null) { - throw new BoxAPIException( - "BoxSearchParameters requires either a search query or Metadata filter to be set." - ); - } - - //Set the query of the search - if (!this.isNullOrEmpty(this.query)) { - builder.appendParam("query", this.query); - } - //Set the scope of the search - if (!this.isNullOrEmpty(this.scope)) { - builder.appendParam("scope", this.scope); - } - //Acceptable Value: "jpg,png" - if (!this.isNullOrEmpty(this.fileExtensions)) { - builder.appendParam("file_extensions", this.listToCSV(this.fileExtensions)); - } - //Created Date Range: From Date - To Date - if ((this.createdRange != null)) { - builder.appendParam("created_at_range", this.createdRange.buildRangeString()); - } - //Updated Date Range: From Date - To Date - if ((this.updatedRange != null)) { - builder.appendParam("updated_at_range", this.updatedRange.buildRangeString()); - } - //Filesize Range - if ((this.sizeRange != null)) { - builder.appendParam("size_range", this.sizeRange.buildRangeString()); - } - //Owner Id's - if (!this.isNullOrEmpty(this.ownerUserIds)) { - builder.appendParam("owner_user_ids", this.listToCSV(this.ownerUserIds)); - } - //Ancestor ID's - if (!this.isNullOrEmpty(this.ancestorFolderIds)) { - builder.appendParam("ancestor_folder_ids", this.listToCSV(this.ancestorFolderIds)); - } - //Content Types: "name, description" - if (!this.isNullOrEmpty(this.contentTypes)) { - builder.appendParam("content_types", this.listToCSV(this.contentTypes)); - } - //Type of File: "file,folder,web_link" - if (this.type != null) { - builder.appendParam("type", this.type); - } - //Trash Content - if (!this.isNullOrEmpty(this.trashContent)) { - builder.appendParam("trash_content", this.trashContent); - } - //Metadata filters - if (this.metadataFilter != null) { - builder.appendParam("mdfilters", this.formatBoxMetadataFilterRequest().toString()); - } - //Fields - if (!this.isNullOrEmpty(this.fields)) { - builder.appendParam("fields", this.listToCSV(this.fields)); - } - //Sort - if (!this.isNullOrEmpty(this.sort)) { - builder.appendParam("sort", this.sort); - } - //Direction - if (!this.isNullOrEmpty(this.direction)) { - builder.appendParam("direction", this.direction); - } - //Deleter User Ids - if (!this.isNullOrEmpty(this.deleterUserIds)) { - builder.appendParam("deleter_user_ids", this.listToCSV(this.deleterUserIds)); - } - //Deleted Range - if ((this.deletedRange != null)) { - builder.appendParam("deleted_range", this.deletedRange.buildRangeString()); - } - - return builder; - } + return builder; + } } diff --git a/src/main/java/com/box/sdk/BoxSearchSharedLink.java b/src/main/java/com/box/sdk/BoxSearchSharedLink.java index 0a74797a0..c49897f38 100644 --- a/src/main/java/com/box/sdk/BoxSearchSharedLink.java +++ b/src/main/java/com/box/sdk/BoxSearchSharedLink.java @@ -8,88 +8,87 @@ /** * Represents a search item when searching shared links. * - *

Unless otherwise noted, the methods in this class can throw an unchecked {@link BoxAPIException} (unchecked - * meaning that the compiler won't force you to handle it) if an error occurs. If you wish to implement custom error - * handling for errors related to the Box REST API, you should capture this exception explicitly.* + *

Unless otherwise noted, the methods in this class can throw an unchecked {@link + * BoxAPIException} (unchecked meaning that the compiler won't force you to handle it) if an error + * occurs. If you wish to implement custom error handling for errors related to the Box REST API, + * you should capture this exception explicitly.* */ public class BoxSearchSharedLink extends BoxJSONObject { - private String type; - private BoxItem.Info item; - private URL accessibleViaSharedLink; - private BoxAPIConnection api; + private String type; + private BoxItem.Info item; + private URL accessibleViaSharedLink; + private BoxAPIConnection api; - /** - * Construct a BoxRecentItem. - * - * @param jsonObject the parsed JSON object. - * @param api the API connection to be used to fetch interacted item - */ - public BoxSearchSharedLink(JsonObject jsonObject, BoxAPIConnection api) { - super(jsonObject); - this.api = api; - } + /** + * Construct a BoxRecentItem. + * + * @param jsonObject the parsed JSON object. + * @param api the API connection to be used to fetch interacted item + */ + public BoxSearchSharedLink(JsonObject jsonObject, BoxAPIConnection api) { + super(jsonObject); + this.api = api; + } - @Override - protected void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); + @Override + protected void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); - String memberName = member.getName(); - JsonValue value = member.getValue(); - try { - if (memberName.equals("type")) { - this.type = value.asString(); - } else if (memberName.equals("item")) { - JsonObject jsonObject = value.asObject(); - String type = jsonObject.get("type").asString(); - String id = jsonObject.get("id").asString(); + String memberName = member.getName(); + JsonValue value = member.getValue(); + try { + if (memberName.equals("type")) { + this.type = value.asString(); + } else if (memberName.equals("item")) { + JsonObject jsonObject = value.asObject(); + String type = jsonObject.get("type").asString(); + String id = jsonObject.get("id").asString(); - if (type.equals("folder")) { - BoxFolder folder = new BoxFolder(this.api, id); - this.item = folder.new Info(jsonObject); - } else if (type.equals("file")) { - BoxFile file = new BoxFile(this.api, id); - this.item = file.new Info(jsonObject); - } else if (type.equals("web_link")) { - BoxWebLink link = new BoxWebLink(this.api, id); - this.item = link.new Info(jsonObject); - } else { - assert false : "Unsupported item type: " + type; - throw new BoxAPIException("Unsupported item type: " + type); - } - } else if (memberName.equals("accessible_via_shared_link")) { - this.accessibleViaSharedLink = new URL(value.asString()); - } - } catch (MalformedURLException e) { - assert false : "A ParseException indicates a bug in the SDK."; + if (type.equals("folder")) { + BoxFolder folder = new BoxFolder(this.api, id); + this.item = folder.new Info(jsonObject); + } else if (type.equals("file")) { + BoxFile file = new BoxFile(this.api, id); + this.item = file.new Info(jsonObject); + } else if (type.equals("web_link")) { + BoxWebLink link = new BoxWebLink(this.api, id); + this.item = link.new Info(jsonObject); + } else { + assert false : "Unsupported item type: " + type; + throw new BoxAPIException("Unsupported item type: " + type); } + } else if (memberName.equals("accessible_via_shared_link")) { + this.accessibleViaSharedLink = new URL(value.asString()); + } + } catch (MalformedURLException e) { + assert false : "A ParseException indicates a bug in the SDK."; } + } - /** - * Get item type. - * - * @return type of item - */ - public String getType() { - return this.type; - } - - /** - * Get the item which was interacted with. - * - * @return box item - */ - public BoxItem.Info getItem() { - return this.item; - } + /** + * Get item type. + * + * @return type of item + */ + public String getType() { + return this.type; + } - /** - * Get the optional shared link through which the user has access to this item. - * - * @return shared link - */ - public URL getAccessibleViaSharedLink() { - return this.accessibleViaSharedLink; - } + /** + * Get the item which was interacted with. + * + * @return box item + */ + public BoxItem.Info getItem() { + return this.item; + } + /** + * Get the optional shared link through which the user has access to this item. + * + * @return shared link + */ + public URL getAccessibleViaSharedLink() { + return this.accessibleViaSharedLink; + } } - diff --git a/src/main/java/com/box/sdk/BoxSensitiveDataSanitizer.java b/src/main/java/com/box/sdk/BoxSensitiveDataSanitizer.java index 320feee6e..0bf153315 100644 --- a/src/main/java/com/box/sdk/BoxSensitiveDataSanitizer.java +++ b/src/main/java/com/box/sdk/BoxSensitiveDataSanitizer.java @@ -7,65 +7,75 @@ import okhttp3.Headers; import org.jetbrains.annotations.NotNull; -/** - * Class used to sanitize sensitive data from payload. - */ +/** Class used to sanitize sensitive data from payload. */ public final class BoxSensitiveDataSanitizer { - private static final Set SENSITIVE_KEYS = new HashSet<>(Arrays.asList("authorization", "access_token", - "refresh_token", "subject_token", "token", "client_id", "client_secret", "code", "shared_link", "download_url", - "jwt_private_key", "jwt_private_key_passphrase", "password")); + private static final Set SENSITIVE_KEYS = + new HashSet<>( + Arrays.asList( + "authorization", + "access_token", + "refresh_token", + "subject_token", + "token", + "client_id", + "client_secret", + "code", + "shared_link", + "download_url", + "jwt_private_key", + "jwt_private_key_passphrase", + "password")); - private BoxSensitiveDataSanitizer() { - } + private BoxSensitiveDataSanitizer() {} - /** - * Add key that should be sanitized - * - * @param key key to be sanitized - */ - public static void addKeyToSanitize(String key) { - SENSITIVE_KEYS.add(key); - } + /** + * Add key that should be sanitized + * + * @param key key to be sanitized + */ + public static void addKeyToSanitize(String key) { + SENSITIVE_KEYS.add(key); + } - @NotNull - static Headers sanitizeHeaders(Headers originalHeaders) { - Headers.Builder sanitizedHeadersBuilder = originalHeaders.newBuilder(); + @NotNull + static Headers sanitizeHeaders(Headers originalHeaders) { + Headers.Builder sanitizedHeadersBuilder = originalHeaders.newBuilder(); - for (String originalHeaderName : originalHeaders.names()) { - if (isSensitiveKey(originalHeaderName)) { - sanitizedHeadersBuilder.set(originalHeaderName, "[REDACTED]"); - } else { - String headerValue = originalHeaders.get(originalHeaderName); - if (headerValue != null) { - sanitizedHeadersBuilder.set(originalHeaderName, headerValue); - } - } + for (String originalHeaderName : originalHeaders.names()) { + if (isSensitiveKey(originalHeaderName)) { + sanitizedHeadersBuilder.set(originalHeaderName, "[REDACTED]"); + } else { + String headerValue = originalHeaders.get(originalHeaderName); + if (headerValue != null) { + sanitizedHeadersBuilder.set(originalHeaderName, headerValue); } - - return sanitizedHeadersBuilder.build(); + } } - /** - * Sanitize the json body. Only for the first level of the json. - * - * @param originalBody the original json body - * @return the sanitized json body - */ - @NotNull - static JsonObject sanitizeJsonBody(JsonObject originalBody) { - JsonObject sanitizedBody = new JsonObject(); + return sanitizedHeadersBuilder.build(); + } - for (String key : originalBody.names()) { - if (isSensitiveKey(key)) { - sanitizedBody.set(key, "[REDACATED]"); - } else { - sanitizedBody.set(key, originalBody.get(key)); - } - } - return sanitizedBody; - } + /** + * Sanitize the json body. Only for the first level of the json. + * + * @param originalBody the original json body + * @return the sanitized json body + */ + @NotNull + static JsonObject sanitizeJsonBody(JsonObject originalBody) { + JsonObject sanitizedBody = new JsonObject(); - private static boolean isSensitiveKey(@NotNull String key) { - return SENSITIVE_KEYS.contains(key.toLowerCase(java.util.Locale.ROOT)); + for (String key : originalBody.names()) { + if (isSensitiveKey(key)) { + sanitizedBody.set(key, "[REDACATED]"); + } else { + sanitizedBody.set(key, originalBody.get(key)); + } } + return sanitizedBody; + } + + private static boolean isSensitiveKey(@NotNull String key) { + return SENSITIVE_KEYS.contains(key.toLowerCase(java.util.Locale.ROOT)); + } } diff --git a/src/main/java/com/box/sdk/BoxSharedLink.java b/src/main/java/com/box/sdk/BoxSharedLink.java index 263eb3882..be9a4dd4c 100644 --- a/src/main/java/com/box/sdk/BoxSharedLink.java +++ b/src/main/java/com/box/sdk/BoxSharedLink.java @@ -4,459 +4,440 @@ import com.eclipsesource.json.JsonValue; import java.util.Date; -/** - * Represents a link to a file or folder on Box. - */ +/** Represents a link to a file or folder on Box. */ public class BoxSharedLink extends BoxJSONObject { - private String url; - private String downloadUrl; - private String vanityUrl; - private String vanityName; - private boolean isPasswordEnabled; - private String password; - private Date unsharedAt; - private long downloadCount; - private long previewCount; - private Access access; - private Access effectiveAccess; - private Permissions permissions; - - /** - * Constructs a BoxSharedLink with default settings. - */ - public BoxSharedLink() { + private String url; + private String downloadUrl; + private String vanityUrl; + private String vanityName; + private boolean isPasswordEnabled; + private String password; + private Date unsharedAt; + private long downloadCount; + private long previewCount; + private Access access; + private Access effectiveAccess; + private Permissions permissions; + + /** Constructs a BoxSharedLink with default settings. */ + public BoxSharedLink() {} + + /** + * Constructs a BoxSharedLink from a JSON string. + * + * @param json the JSON encoded shared link. + */ + public BoxSharedLink(String json) { + super(json); + } + + BoxSharedLink(JsonObject jsonObject) { + super(jsonObject); + } + + BoxSharedLink( + BoxSharedLink.Access access, Date unshareDate, BoxSharedLink.Permissions permissions) { + this.setAccess(access); + this.setPermissions(permissions); + + if (unshareDate != null) { + this.setUnsharedDate(unshareDate); } - - /** - * Constructs a BoxSharedLink from a JSON string. - * - * @param json the JSON encoded shared link. - */ - public BoxSharedLink(String json) { - super(json); + } + + BoxSharedLink( + BoxSharedLink.Access access, + Date unshareDate, + BoxSharedLink.Permissions permissions, + String password) { + this.setAccess(access); + this.setPermissions(permissions); + this.setPassword(password); + + if (unshareDate != null) { + this.setUnsharedDate(unshareDate); } - - BoxSharedLink(JsonObject jsonObject) { - super(jsonObject); + } + + /** + * Get the URL of this shared link. + * + * @return the URL of this shared link. + */ + public String getURL() { + return this.url; + } + + /** + * Gets the direct download URL of this shared link. + * + * @return the direct download URL of this shared link. + */ + public String getDownloadURL() { + return this.downloadUrl; + } + + /** + * Gets the vanity URL of this shared link. + * + * @return the vanity URL of this shared link. + */ + public String getVanityURL() { + return this.vanityUrl; + } + + /** + * Returns vanity name used to create vanity URL. + * + * @return Vanity name + */ + public String getVanityName() { + return vanityName; + } + + /** + * Sets vanity name used to create vanity URL. For example: vanityName = myCustomName will produce + * vanityUrl as: https://app.box.com/v/myCustomName Custom URLs should not be used when sharing + * sensitive content as vanity URLs are a lot easier to guess than regular shared links. + * + * @param vanityName Vanity name. Vanity name must be at least 12 characters long. + */ + public void setVanityName(String vanityName) { + if (vanityName != null && vanityName.length() < 12) { + throw new IllegalArgumentException("The vanityName has to be at least 12 characters long."); } - - BoxSharedLink(BoxSharedLink.Access access, Date unshareDate, BoxSharedLink.Permissions permissions) { - this.setAccess(access); - this.setPermissions(permissions); - - if (unshareDate != null) { - this.setUnsharedDate(unshareDate); - } + this.vanityName = vanityName; + this.addPendingChange("vanity_name", vanityName); + } + + /** + * Gets whether or not a password is enabled on this shared link. + * + * @return true if there's a password enabled on this shared link; otherwise false. + */ + public boolean getIsPasswordEnabled() { + return this.isPasswordEnabled; + } + + /** + * Gets the time that this shared link will be deactivated. + * + * @return the time that this shared link will be deactivated. + */ + public Date getUnsharedDate() { + return this.unsharedAt; + } + + /** + * Sets the time that this shared link will be deactivated. + * + * @param unsharedDate the time that this shared link will be deactivated. + */ + public void setUnsharedDate(Date unsharedDate) { + this.unsharedAt = unsharedDate; + this.addPendingChange("unshared_at", BoxDateFormat.format(unsharedDate)); + } + + /** + * Gets the number of times that this shared link has been downloaded. + * + * @return the number of times that this link has been downloaded. + */ + public long getDownloadCount() { + return this.downloadCount; + } + + /** + * Gets the number of times that this shared link has been previewed. + * + * @return the number of times that this link has been previewed. + */ + public long getPreviewCount() { + return this.previewCount; + } + + /** + * Gets the access level of this shared link. + * + * @return the access level of this shared link. + */ + public Access getAccess() { + return this.access; + } + + /** + * Sets the access level of this shared link. + * + * @param access the new access level of this shared link. + */ + public void setAccess(Access access) { + this.access = access; + this.addPendingChange("access", access.toJSONValue()); + } + + /** + * Sets the password of this shared link. + * + * @param password the password of this shared link. + */ + public void setPassword(String password) { + this.password = password; + this.addPendingChange("password", password); + } + + /** + * Gets the effective access level of this shared link. + * + * @return the effective access level of this shared link. + *

Note there is no setEffectiveAccess metho becaused this cannot be changed via the API + */ + public Access getEffectiveAccess() { + return this.effectiveAccess; + } + + /** + * Gets the permissions associated with this shared link. + * + * @return the permissions associated with this shared link. + */ + public Permissions getPermissions() { + return this.permissions; + } + + /** + * Sets the permissions associated with this shared link. + * + * @param permissions the new permissions for this shared link. + */ + public void setPermissions(Permissions permissions) { + if (this.permissions != null && this.permissions.equals(permissions)) { + return; } - BoxSharedLink(BoxSharedLink.Access access, Date unshareDate, BoxSharedLink.Permissions permissions, - String password) { - this.setAccess(access); - this.setPermissions(permissions); - this.setPassword(password); - - if (unshareDate != null) { - this.setUnsharedDate(unshareDate); + this.removeChildObject("permissions"); + this.permissions = permissions; + this.addChildObject("permissions", permissions); + } + + private Access parseAccessValue(JsonValue value) { + String accessString = value.asString().toUpperCase(java.util.Locale.ROOT); + return Access.valueOf(accessString); + } + + @Override + protected JsonObject getPendingJSONObject() { + JsonObject result = super.getPendingJSONObject(); + if (result == null) { + result = new JsonObject(); + } + return result; + } + + @Override + void parseJSONMember(JsonObject.Member member) { + JsonValue value = member.getValue(); + String memberName = member.getName(); + + try { + if (memberName.equals("url")) { + this.url = value.asString(); + } else if (memberName.equals("download_url")) { + this.downloadUrl = value.asString(); + } else if (memberName.equals("vanity_url")) { + this.vanityUrl = value.asString(); + } else if (memberName.equals("vanity_name")) { + this.vanityName = value.asString(); + } else if (memberName.equals("is_password_enabled")) { + this.isPasswordEnabled = value.asBoolean(); + } else if (memberName.equals("unshared_at")) { + this.unsharedAt = BoxDateFormat.parse(value.asString()); + } else if (memberName.equals("download_count")) { + this.downloadCount = Double.valueOf(value.toString()).longValue(); + } else if (memberName.equals("preview_count")) { + this.previewCount = Double.valueOf(value.toString()).longValue(); + } else if (memberName.equals("access")) { + this.access = this.parseAccessValue(value); + } else if (memberName.equals("effective_access")) { + this.effectiveAccess = this.parseAccessValue(value); + } else if (memberName.equals("permissions")) { + if (this.permissions == null) { + this.setPermissions(new Permissions(value.asObject())); + } else { + this.permissions.update(value.asObject()); } + } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); } + } - /** - * Get the URL of this shared link. - * - * @return the URL of this shared link. - */ - public String getURL() { - return this.url; + public static String getSharedLinkHeaderValue(String sharedLink, String password) { + String boxAPIValue = "shared_link=" + sharedLink; + if (password != null) { + boxAPIValue += "&shared_link_password=" + password; } + return boxAPIValue; + } - /** - * Gets the direct download URL of this shared link. - * - * @return the direct download URL of this shared link. - */ - public String getDownloadURL() { - return this.downloadUrl; - } + /** Enumerates the possible access levels that can be set on a shared link. */ + public enum Access { + /** The default access level for the user or enterprise. */ + DEFAULT(null), - /** - * Gets the vanity URL of this shared link. - * - * @return the vanity URL of this shared link. - */ - public String getVanityURL() { - return this.vanityUrl; - } + /** The link can be accessed by anyone. */ + OPEN("open"), - /** - * Returns vanity name used to create vanity URL. - * - * @return Vanity name - */ - public String getVanityName() { - return vanityName; - } + /** The link can be accessed by other users within the company. */ + COMPANY("company"), - /** - * Sets vanity name used to create vanity URL. - * For example: - * vanityName = myCustomName - * will produce vanityUrl as: - * https://app.box.com/v/myCustomName - * Custom URLs should not be used when sharing sensitive content - * as vanity URLs are a lot easier to guess than regular shared links. - * - * @param vanityName Vanity name. Vanity name must be at least 12 characters long. - */ - public void setVanityName(String vanityName) { - if (vanityName != null && vanityName.length() < 12) { - throw new IllegalArgumentException("The vanityName has to be at least 12 characters long."); - } - this.vanityName = vanityName; - this.addPendingChange("vanity_name", vanityName); - } + /** The link can be accessed by other collaborators. */ + COLLABORATORS("collaborators"); - /** - * Gets whether or not a password is enabled on this shared link. - * - * @return true if there's a password enabled on this shared link; otherwise false. - */ - public boolean getIsPasswordEnabled() { - return this.isPasswordEnabled; + private final String jsonValue; + + Access(String jsonValue) { + this.jsonValue = jsonValue; } - /** - * Gets the time that this shared link will be deactivated. - * - * @return the time that this shared link will be deactivated. - */ - public Date getUnsharedDate() { - return this.unsharedAt; + String toJSONValue() { + return this.jsonValue; } + } - /** - * Sets the time that this shared link will be deactivated. - * - * @param unsharedDate the time that this shared link will be deactivated. - */ - public void setUnsharedDate(Date unsharedDate) { - this.unsharedAt = unsharedDate; - this.addPendingChange("unshared_at", BoxDateFormat.format(unsharedDate)); + /** Contains permissions fields that can be set on a shared link. */ + public static class Permissions extends BoxJSONObject { + private boolean canDownload; + private boolean canPreview; + private boolean canEdit; + + /** Constructs a Permissions object with all permissions disabled. */ + public Permissions() {} + + Permissions(boolean canPreview, boolean canDownload, boolean canEdit) { + this.setCanPreview(canPreview); + this.setCanDownload(canDownload); + this.setCanEdit(canEdit); } /** - * Gets the number of times that this shared link has been downloaded. + * Constructs a Permissions object from a JSON string. * - * @return the number of times that this link has been downloaded. + * @param json the JSON encoded shared link permissions. */ - public long getDownloadCount() { - return this.downloadCount; + public Permissions(String json) { + super(json); } - /** - * Gets the number of times that this shared link has been previewed. - * - * @return the number of times that this link has been previewed. - */ - public long getPreviewCount() { - return this.previewCount; + Permissions(JsonObject jsonObject) { + super(jsonObject); } /** - * Gets the access level of this shared link. + * Gets whether the shared link can be downloaded. * - * @return the access level of this shared link. + * @return true if the shared link can be downloaded; otherwise false. */ - public Access getAccess() { - return this.access; + public boolean getCanDownload() { + return this.canDownload; } /** - * Sets the access level of this shared link. + * Sets whether or not the shared link can be downloaded. * - * @param access the new access level of this shared link. + * @param enabled true if the shared link can be downloaded; otherwise false. */ - public void setAccess(Access access) { - this.access = access; - this.addPendingChange("access", access.toJSONValue()); + public void setCanDownload(boolean enabled) { + this.canDownload = enabled; + this.addPendingChange("can_download", enabled); } /** - * Sets the password of this shared link. + * Gets whether the shared link can be previewed. * - * @param password the password of this shared link. + * @return true if the shared link can be previewed; otherwise false. */ - public void setPassword(String password) { - this.password = password; - this.addPendingChange("password", password); + public boolean getCanPreview() { + return this.canPreview; } /** - * Gets the effective access level of this shared link. + * Sets whether the shared link can be previewed. * - * @return the effective access level of this shared link. - *

- * Note there is no setEffectiveAccess metho becaused this - * cannot be changed via the API + * @param enabled true if the shared link can be previewed; otherwise false. */ - public Access getEffectiveAccess() { - return this.effectiveAccess; + public void setCanPreview(boolean enabled) { + this.canPreview = enabled; + this.addPendingChange("can_preview", enabled); } /** - * Gets the permissions associated with this shared link. + * Gets whether the shared link allows for editing of files. * - * @return the permissions associated with this shared link. + * @return true if the shared link allows for editing of files; otherwise false. */ - public Permissions getPermissions() { - return this.permissions; + public boolean getCanEdit() { + return canEdit; } /** - * Sets the permissions associated with this shared link. + * Sets whether the shared link allows for editing of files. For folders this value will always + * be set to false. * - * @param permissions the new permissions for this shared link. + * @param enabled true if the shared link allows for editing of files; otherwise false. */ - public void setPermissions(Permissions permissions) { - if (this.permissions != null && this.permissions.equals(permissions)) { - return; - } - - this.removeChildObject("permissions"); - this.permissions = permissions; - this.addChildObject("permissions", permissions); - } - - private Access parseAccessValue(JsonValue value) { - String accessString = value.asString().toUpperCase(java.util.Locale.ROOT); - return Access.valueOf(accessString); - } - - @Override - protected JsonObject getPendingJSONObject() { - JsonObject result = super.getPendingJSONObject(); - if (result == null) { - result = new JsonObject(); - } - return result; + public void setCanEdit(boolean enabled) { + this.canEdit = enabled; + this.addPendingChange("can_edit", enabled); } @Override void parseJSONMember(JsonObject.Member member) { - JsonValue value = member.getValue(); - String memberName = member.getName(); - - try { - if (memberName.equals("url")) { - this.url = value.asString(); - } else if (memberName.equals("download_url")) { - this.downloadUrl = value.asString(); - } else if (memberName.equals("vanity_url")) { - this.vanityUrl = value.asString(); - } else if (memberName.equals("vanity_name")) { - this.vanityName = value.asString(); - } else if (memberName.equals("is_password_enabled")) { - this.isPasswordEnabled = value.asBoolean(); - } else if (memberName.equals("unshared_at")) { - this.unsharedAt = BoxDateFormat.parse(value.asString()); - } else if (memberName.equals("download_count")) { - this.downloadCount = Double.valueOf(value.toString()).longValue(); - } else if (memberName.equals("preview_count")) { - this.previewCount = Double.valueOf(value.toString()).longValue(); - } else if (memberName.equals("access")) { - this.access = this.parseAccessValue(value); - } else if (memberName.equals("effective_access")) { - this.effectiveAccess = this.parseAccessValue(value); - } else if (memberName.equals("permissions")) { - if (this.permissions == null) { - this.setPermissions(new Permissions(value.asObject())); - } else { - this.permissions.update(value.asObject()); - } - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); - } + JsonValue value = member.getValue(); + String memberName = member.getName(); + if (memberName.equals("can_download")) { + this.canDownload = value.asBoolean(); + } + if (memberName.equals("can_preview")) { + this.canPreview = value.asBoolean(); + } + if (memberName.equals("can_edit")) { + this.canEdit = value.asBoolean(); + } } - public static String getSharedLinkHeaderValue(String sharedLink, String password) { - String boxAPIValue = "shared_link=" + sharedLink; - if (password != null) { - boxAPIValue += "&shared_link_password=" + password; - } - return boxAPIValue; + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || this.getClass() != o.getClass()) { + return false; + } + + Permissions that = (Permissions) o; + + return this.canDownload == that.canDownload + && this.canPreview == that.canPreview + && this.canEdit == that.canEdit; } - /** - * Enumerates the possible access levels that can be set on a shared link. - */ - public enum Access { - /** - * The default access level for the user or enterprise. - */ - DEFAULT(null), - - /** - * The link can be accessed by anyone. - */ - OPEN("open"), - - /** - * The link can be accessed by other users within the company. - */ - COMPANY("company"), - - /** - * The link can be accessed by other collaborators. - */ - COLLABORATORS("collaborators"); - - private final String jsonValue; - - Access(String jsonValue) { - this.jsonValue = jsonValue; - } - - String toJSONValue() { - return this.jsonValue; - } + @Override + public int hashCode() { + int result = (this.canDownload ? 1 : 0); + result = 31 * result + (this.canPreview ? 1 : 0); + result = 31 * result + (this.canEdit ? 1 : 0); + return result; } - /** - * Contains permissions fields that can be set on a shared link. - */ - public static class Permissions extends BoxJSONObject { - private boolean canDownload; - private boolean canPreview; - private boolean canEdit; - - /** - * Constructs a Permissions object with all permissions disabled. - */ - public Permissions() { - } - - Permissions(boolean canPreview, boolean canDownload, boolean canEdit) { - this.setCanPreview(canPreview); - this.setCanDownload(canDownload); - this.setCanEdit(canEdit); - } - - /** - * Constructs a Permissions object from a JSON string. - * - * @param json the JSON encoded shared link permissions. - */ - public Permissions(String json) { - super(json); - } - - Permissions(JsonObject jsonObject) { - super(jsonObject); - } - - /** - * Gets whether the shared link can be downloaded. - * - * @return true if the shared link can be downloaded; otherwise false. - */ - public boolean getCanDownload() { - return this.canDownload; - } - - /** - * Sets whether or not the shared link can be downloaded. - * - * @param enabled true if the shared link can be downloaded; otherwise false. - */ - public void setCanDownload(boolean enabled) { - this.canDownload = enabled; - this.addPendingChange("can_download", enabled); - } - - /** - * Gets whether the shared link can be previewed. - * - * @return true if the shared link can be previewed; otherwise false. - */ - public boolean getCanPreview() { - return this.canPreview; - } - - /** - * Sets whether the shared link can be previewed. - * - * @param enabled true if the shared link can be previewed; otherwise false. - */ - public void setCanPreview(boolean enabled) { - this.canPreview = enabled; - this.addPendingChange("can_preview", enabled); - } - - /** - * Gets whether the shared link allows for editing of files. - * - * @return true if the shared link allows for editing of files; otherwise false. - */ - public boolean getCanEdit() { - return canEdit; - } - - /** - * Sets whether the shared link allows for editing of files. - * For folders this value will always be set to false. - * - * @param enabled true if the shared link allows for editing of files; otherwise false. - */ - public void setCanEdit(boolean enabled) { - this.canEdit = enabled; - this.addPendingChange("can_edit", enabled); - } - - @Override - void parseJSONMember(JsonObject.Member member) { - JsonValue value = member.getValue(); - String memberName = member.getName(); - if (memberName.equals("can_download")) { - this.canDownload = value.asBoolean(); - } - if (memberName.equals("can_preview")) { - this.canPreview = value.asBoolean(); - } - if (memberName.equals("can_edit")) { - this.canEdit = value.asBoolean(); - } - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || this.getClass() != o.getClass()) { - return false; - } - - Permissions that = (Permissions) o; - - return this.canDownload == that.canDownload - && this.canPreview == that.canPreview - && this.canEdit == that.canEdit; - } - - @Override - public int hashCode() { - int result = (this.canDownload ? 1 : 0); - result = 31 * result + (this.canPreview ? 1 : 0); - result = 31 * result + (this.canEdit ? 1 : 0); - return result; - } - - @Override - public String toString() { - return "Permissions{canDownload=" + this.canDownload - + ", canPreview=" + this.canPreview - + ", canEdit=" + this.canEdit - + '}'; - } + @Override + public String toString() { + return "Permissions{canDownload=" + + this.canDownload + + ", canPreview=" + + this.canPreview + + ", canEdit=" + + this.canEdit + + '}'; } + } } diff --git a/src/main/java/com/box/sdk/BoxSignRequest.java b/src/main/java/com/box/sdk/BoxSignRequest.java index 2627c759f..d0886f82f 100644 --- a/src/main/java/com/box/sdk/BoxSignRequest.java +++ b/src/main/java/com/box/sdk/BoxSignRequest.java @@ -10,761 +10,740 @@ import java.util.List; /** - * Represents a Sign Request used by Box Sign. - * Sign Requests are used to request e-signatures on documents from signers. - * A Sign Request can refer to one or more Box Files and can be sent to one or more Box Sign Request Signers. + * Represents a Sign Request used by Box Sign. Sign Requests are used to request e-signatures on + * documents from signers. A Sign Request can refer to one or more Box Files and can be sent to one + * or more Box Sign Request Signers. * * @see Box Sign Request - * - *

Unless otherwise noted, the methods in this class can throw an unchecked {@link BoxAPIException} (unchecked - * meaning that the compiler won't force you to handle it) if an error occurs. If you wish to implement custom error - * handling for errors related to the Box REST API, you should capture this exception explicitly.

+ *

Unless otherwise noted, the methods in this class can throw an unchecked {@link + * BoxAPIException} (unchecked meaning that the compiler won't force you to handle it) if an + * error occurs. If you wish to implement custom error handling for errors related to the Box + * REST API, you should capture this exception explicitly. */ @BoxResourceType("sign_request") public class BoxSignRequest extends BoxResource { + /** The URL template used for operation Sign Request operations. */ + public static final URLTemplate SIGN_REQUESTS_URL_TEMPLATE = new URLTemplate("sign_requests"); + + /** The URL template used for Sign Request operations with a given ID. */ + public static final URLTemplate SIGN_REQUEST_URL_TEMPLATE = new URLTemplate("sign_requests/%s"); + + /** The URL template used to cancel an existing Sign Request. */ + public static final URLTemplate SIGN_REQUEST_CANCEL_URL_TEMPLATE = + new URLTemplate("sign_requests/%s/cancel"); + + /** The URL template used to resend an existing Sign Request. */ + public static final URLTemplate SIGN_REQUEST_RESEND_URL_TEMPLATE = + new URLTemplate("sign_requests/%s/resend"); + + /** The default limit of entries per response. */ + private static final int DEFAULT_LIMIT = 100; + + /** + * Constructs a BoxResource for a resource with a given ID. + * + * @param api the API connection to be used by the resource. + * @param id the ID of the resource. + */ + public BoxSignRequest(BoxAPIConnection api, String id) { + super(api, id); + } + + /** + * Used to create a new sign request using existing BoxFile.Info models. + * + * @param api the API connection to be used by the created user. + * @param sourceFiles the list of BoxFile.Info files to create a signing document from. + * @param signers the list of signers for this sign request. + * @param parentFolderId the id of the destination folder to place sign request specific data in. + * @param optionalParams the optional parameters. + * @return the created sign request's info. + */ + public static BoxSignRequest.Info createSignRequestFromFiles( + BoxAPIConnection api, + List sourceFiles, + List signers, + String parentFolderId, + BoxSignRequestCreateParams optionalParams) { + return createSignRequest( + api, toBoxSignRequestFiles(sourceFiles), signers, parentFolderId, optionalParams); + } + + /** + * Used to create a new sign request using BoxFile.Info models. + * + * @param api the API connection to be used by the created user. + * @param sourceFiles the list of BoxFile.Info files to create a signing document from. + * @param signers the list of signers for this sign request. + * @param parentFolderId the id of the destination folder to place sign request specific data in. + * @return the created sign request's info. + */ + public static BoxSignRequest.Info createSignRequestFromFiles( + BoxAPIConnection api, + List sourceFiles, + List signers, + String parentFolderId) { + + return createSignRequest( + api, toBoxSignRequestFiles(sourceFiles), signers, parentFolderId, null); + } + + /** + * Used to create a new sign request. + * + * @param api the API connection to be used by the created user. + * @param sourceFiles the list of files to a signing document from. + * @param signers the list of signers for this sign request. + * @param parentFolderId the id of the destination folder to place sign request specific data in. + * @return the created sign request's info. + */ + public static BoxSignRequest.Info createSignRequest( + BoxAPIConnection api, + List sourceFiles, + List signers, + String parentFolderId) { + return createSignRequest(api, sourceFiles, signers, parentFolderId, null); + } + + /** + * Used to create a new sign request with optional parameters. + * + * @param api the API connection to be used by the created user. + * @param signers the list of signers for this sign request. + * @param sourceFiles the list of files to a signing document from. + * @param parentFolderId the id of the destination folder to place sign request specific data in. + * @param optionalParams the optional parameters. + * @return the created sign request's info. + */ + public static BoxSignRequest.Info createSignRequest( + BoxAPIConnection api, + List sourceFiles, + List signers, + String parentFolderId, + BoxSignRequestCreateParams optionalParams) { + + JsonObject requestJSON = new JsonObject(); + + JsonArray sourceFilesJSON = new JsonArray(); + for (BoxSignRequestFile sourceFile : sourceFiles) { + sourceFilesJSON.add(sourceFile.getJSONObject()); + } + requestJSON.add("source_files", sourceFilesJSON); + + JsonArray signersJSON = new JsonArray(); + for (BoxSignRequestSigner signer : signers) { + signersJSON.add(signer.getJSONObject()); + } + requestJSON.add("signers", signersJSON); + + JsonObject parentFolderJSON = new JsonObject(); + parentFolderJSON.add("id", parentFolderId); + parentFolderJSON.add("type", "folder"); + requestJSON.add("parent_folder", parentFolderJSON); + + if (optionalParams != null) { + optionalParams.appendParamsAsJson(requestJSON); + } + + URL url = SIGN_REQUESTS_URL_TEMPLATE.build(api.getBaseURL()); + BoxJSONRequest request = new BoxJSONRequest(api, url, "POST"); + request.setBody(requestJSON.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + BoxSignRequest signRequest = new BoxSignRequest(api, responseJSON.get("id").asString()); + return signRequest.new Info(responseJSON); + } + } + + /** + * Returns all the sign requests. + * + * @param api the API connection to be used by the resource. + * @param fields the fields to retrieve. + * @return an iterable with all the sign requests. + */ + public static Iterable getAll(final BoxAPIConnection api, String... fields) { + return getAll(api, DEFAULT_LIMIT, fields); + } + + /** + * Returns all the sign requests. + * + * @param api the API connection to be used by the resource. + * @param limit the limit of items per single response. The default value is 100. + * @param fields the fields to retrieve. + * @return an iterable with all the sign requests. + */ + public static Iterable getAll( + final BoxAPIConnection api, int limit, String... fields) { + QueryStringBuilder queryString = new QueryStringBuilder(); + if (fields.length > 0) { + queryString.appendParam("fields", fields); + } + URL url = SIGN_REQUESTS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), queryString.toString()); + return new BoxResourceIterable(api, url, limit) { + + @Override + protected BoxSignRequest.Info factory(JsonObject jsonObject) { + BoxSignRequest signRequest = new BoxSignRequest(api, jsonObject.get("id").asString()); + return signRequest.new Info(jsonObject); + } + }; + } + + private static List toBoxSignRequestFiles(List sourceFiles) { + List files = new ArrayList<>(); + for (BoxFile.Info sourceFile : sourceFiles) { + BoxSignRequestFile file = BoxSignRequestFile.fromFile(sourceFile); + files.add(file); + } + + return files; + } + + /** + * Returns information about this sign request. + * + * @param fields the fields to retrieve. + * @return information about this sign request. + */ + public BoxSignRequest.Info getInfo(String... fields) { + QueryStringBuilder builder = new QueryStringBuilder(); + if (fields.length > 0) { + builder.appendParam("fields", fields); + } + URL url = + SIGN_REQUEST_URL_TEMPLATE.buildAlphaWithQuery( + this.getAPI().getBaseURL(), builder.toString(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + return new BoxSignRequest.Info(responseJSON); + } + } + + /** + * Cancels a sign request if it has not yet been signed or declined. Any outstanding signers will + * no longer be able to sign the document. + * + * @return the cancelled sign request's info. + */ + public BoxSignRequest.Info cancel() { + URL url = + SIGN_REQUEST_CANCEL_URL_TEMPLATE.buildAlphaWithQuery( + getAPI().getBaseURL(), "", this.getID()); + BoxJSONRequest request = new BoxJSONRequest(getAPI(), url, "POST"); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + return new BoxSignRequest.Info(responseJSON); + } + } + + /** + * Attempts to resend a Sign Request to all signers that have not signed yet. There is a 10 minute + * cooling-off period between each resend request. If you make a resend call during the + * cooling-off period, a BoxAPIException will be thrown. + */ + public void resend() { + URL url = + SIGN_REQUEST_RESEND_URL_TEMPLATE.buildAlphaWithQuery( + getAPI().getBaseURL(), "", this.getID()); + BoxAPIRequest request = new BoxAPIRequest(getAPI(), url, "POST"); + request.send().close(); + } + + /** Represents a status of the sign request. */ + public enum BoxSignRequestStatus { + + /** Converting status. */ + Converting("converting"), + + /** Created status. */ + Created("created"), + + /** Sent status. */ + Sent("sent"), + + /** Viewed status. */ + Viewed("viewed"), + + /** Signed status. */ + Signed("signed"), + + /** Cancelled status. */ + Cancelled("cancelled"), + + /** Declined status. */ + Declined("declined"), + + /** Error converting status. */ + ErrorConverting("error_converting"), + + /** Error sending status. */ + ErrorSending("error_sending"), + + /** Expired status. */ + Expired("expired"), + + /** Finalizing status. */ + Finalizing("finalizing"), + + /** Error finalizing status. */ + ErrorFinalizing("error_finalizing"); + + private final String jsonValue; + + BoxSignRequestStatus(String jsonValue) { + this.jsonValue = jsonValue; + } + + static BoxSignRequestStatus fromJSONString(String jsonValue) { + switch (jsonValue) { + case "converting": + return Converting; + case "created": + return Created; + case "sent": + return Sent; + case "viewed": + return Viewed; + case "signed": + return Signed; + case "cancelled": + return Cancelled; + case "declined": + return Declined; + case "error_converting": + return ErrorConverting; + case "error_sending": + return ErrorSending; + case "expired": + return Expired; + case "finalizing": + return Finalizing; + case "error_finalizing": + return ErrorFinalizing; + default: + } + throw new IllegalArgumentException( + "The provided JSON value isn't a valid BoxSignRequestStatus value."); + } + } + + /** Contains information about the Sign Request. */ + public class Info extends BoxResource.Info { + + private boolean isDocumentPreparationNeeded; + private boolean areTextSignaturesEnabled; + private boolean areDatesEnabled; + private BoxSignRequestSignatureColor signatureColor; + private String emailSubject; + private String emailMessage; + private boolean areRemindersEnabled; + private List sourceFiles; + private BoxFolder.Info parentFolder; + private List signers; + private String name; + private List prefillTags; + private Integer daysValid; + private String externalId; + private String prepareUrl; + private BoxFile.Info signingLog; + private BoxSignRequestStatus status; + private BoxSignRequestSignFiles signFiles; + private Date autoExpireAt; + private String redirectUrl; + private String declinedRedirectUrl; + private String templateId; + + /** Constructs an empty Info object. */ + public Info() { + super(); + } + /** - * The URL template used for operation Sign Request operations. + * Constructs an Info object by parsing information from a JSON string. + * + * @param json the JSON string to parse. */ - public static final URLTemplate SIGN_REQUESTS_URL_TEMPLATE = new URLTemplate("sign_requests"); + public Info(String json) { + super(json); + } /** - * The URL template used for Sign Request operations with a given ID. + * Constructs an Info object using an already parsed JSON object. + * + * @param jsonObject the parsed JSON object. */ - public static final URLTemplate SIGN_REQUEST_URL_TEMPLATE = new URLTemplate("sign_requests/%s"); + Info(JsonObject jsonObject) { + super(jsonObject); + } /** - * The URL template used to cancel an existing Sign Request. + * Indicates if the sender should receive a prepare_url in the response to complete document + * preparation via UI. + * + * @return true if document preparation is needed, otherwise false. */ - public static final URLTemplate SIGN_REQUEST_CANCEL_URL_TEMPLATE = new URLTemplate("sign_requests/%s/cancel"); + public boolean getIsDocumentPreparationNeeded() { + return this.isDocumentPreparationNeeded; + } /** - * The URL template used to resend an existing Sign Request. + * Gets the flag indicating if usage of signatures generated by typing (text) is enabled. + * + * @return true if text signatures are enabled, otherwise false. */ - public static final URLTemplate SIGN_REQUEST_RESEND_URL_TEMPLATE = new URLTemplate("sign_requests/%s/resend"); + public boolean getAreTextSignaturesEnabled() { + return this.areTextSignaturesEnabled; + } /** - * The default limit of entries per response. + * Gets the flag indicating if ability for signer to add dates is enabled. + * + * @return true if ability for signer to add dates is enabled, otherwise false. */ - private static final int DEFAULT_LIMIT = 100; + public boolean getAreDatesEnabled() { + return this.areDatesEnabled; + } /** - * Constructs a BoxResource for a resource with a given ID. + * Gets the forced, specific color for the signature. * - * @param api the API connection to be used by the resource. - * @param id the ID of the resource. + * @return signature color (blue, black, red). */ - public BoxSignRequest(BoxAPIConnection api, String id) { - super(api, id); + public BoxSignRequestSignatureColor getSignatureColor() { + return this.signatureColor; } /** - * Used to create a new sign request using existing BoxFile.Info models. + * Gets the subject of the sign request email. * - * @param api the API connection to be used by the created user. - * @param sourceFiles the list of BoxFile.Info files to create a signing document from. - * @param signers the list of signers for this sign request. - * @param parentFolderId the id of the destination folder to place sign request specific data in. - * @param optionalParams the optional parameters. - * @return the created sign request's info. + * @return subject of the sign request email. */ - public static BoxSignRequest.Info createSignRequestFromFiles(BoxAPIConnection api, - List sourceFiles, - List signers, - String parentFolderId, - BoxSignRequestCreateParams optionalParams) { - return createSignRequest(api, toBoxSignRequestFiles(sourceFiles), signers, parentFolderId, optionalParams); + public String getEmailSubject() { + return this.emailSubject; } /** - * Used to create a new sign request using BoxFile.Info models. + * Gets the message to include in the sign request email. * - * @param api the API connection to be used by the created user. - * @param sourceFiles the list of BoxFile.Info files to create a signing document from. - * @param signers the list of signers for this sign request. - * @param parentFolderId the id of the destination folder to place sign request specific data in. - * @return the created sign request's info. + * @return message of sign request email. */ - public static BoxSignRequest.Info createSignRequestFromFiles(BoxAPIConnection api, - List sourceFiles, - List signers, - String parentFolderId) { - - return createSignRequest(api, toBoxSignRequestFiles(sourceFiles), signers, parentFolderId, null); + public String getEmailMessage() { + return this.emailMessage; } /** - * Used to create a new sign request. + * Gets the flag indicating if sending reminders for signers to sign a document on day 3, 8, 13 + * and 18 (or less if the document has been digitally signed already) is enabled. * - * @param api the API connection to be used by the created user. - * @param sourceFiles the list of files to a signing document from. - * @param signers the list of signers for this sign request. - * @param parentFolderId the id of the destination folder to place sign request specific data in. - * @return the created sign request's info. + * @return true if reminders are enabled, otherwise false. */ - public static BoxSignRequest.Info createSignRequest(BoxAPIConnection api, List sourceFiles, - List signers, String parentFolderId) { - return createSignRequest(api, sourceFiles, signers, parentFolderId, null); + public boolean getAreRemindersEnabled() { + return this.areRemindersEnabled; } /** - * Used to create a new sign request with optional parameters. + * Gets the list of files to create a signing document from. * - * @param api the API connection to be used by the created user. - * @param signers the list of signers for this sign request. - * @param sourceFiles the list of files to a signing document from. - * @param parentFolderId the id of the destination folder to place sign request specific data in. - * @param optionalParams the optional parameters. - * @return the created sign request's info. + * @return list of files to create a signing document from. */ - public static BoxSignRequest.Info createSignRequest(BoxAPIConnection api, List sourceFiles, - List signers, String parentFolderId, - BoxSignRequestCreateParams optionalParams) { - - JsonObject requestJSON = new JsonObject(); - - JsonArray sourceFilesJSON = new JsonArray(); - for (BoxSignRequestFile sourceFile : sourceFiles) { - sourceFilesJSON.add(sourceFile.getJSONObject()); - } - requestJSON.add("source_files", sourceFilesJSON); - - JsonArray signersJSON = new JsonArray(); - for (BoxSignRequestSigner signer : signers) { - signersJSON.add(signer.getJSONObject()); - } - requestJSON.add("signers", signersJSON); - - JsonObject parentFolderJSON = new JsonObject(); - parentFolderJSON.add("id", parentFolderId); - parentFolderJSON.add("type", "folder"); - requestJSON.add("parent_folder", parentFolderJSON); - - if (optionalParams != null) { - optionalParams.appendParamsAsJson(requestJSON); - } - - URL url = SIGN_REQUESTS_URL_TEMPLATE.build(api.getBaseURL()); - BoxJSONRequest request = new BoxJSONRequest(api, url, "POST"); - request.setBody(requestJSON.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - BoxSignRequest signRequest = new BoxSignRequest(api, responseJSON.get("id").asString()); - return signRequest.new Info(responseJSON); - } + public List getSourceFiles() { + return this.sourceFiles; } /** - * Returns all the sign requests. + * Gets the destination folder to place sign request specific data in (copy of source files, + * signing log etc.). * - * @param api the API connection to be used by the resource. - * @param fields the fields to retrieve. - * @return an iterable with all the sign requests. + * @return destination folder to place sign request specific data in. */ - public static Iterable getAll(final BoxAPIConnection api, String... fields) { - return getAll(api, DEFAULT_LIMIT, fields); + public BoxFolder.Info getParentFolder() { + return this.parentFolder; } /** - * Returns all the sign requests. + * Gets the list of signers for this sign request. * - * @param api the API connection to be used by the resource. - * @param limit the limit of items per single response. The default value is 100. - * @param fields the fields to retrieve. - * @return an iterable with all the sign requests. + * @return list of signers for this sign request. */ - public static Iterable getAll(final BoxAPIConnection api, int limit, String... fields) { - QueryStringBuilder queryString = new QueryStringBuilder(); - if (fields.length > 0) { - queryString.appendParam("fields", fields); - } - URL url = SIGN_REQUESTS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), queryString.toString()); - return new BoxResourceIterable(api, url, limit) { - - @Override - protected BoxSignRequest.Info factory(JsonObject jsonObject) { - BoxSignRequest signRequest = new BoxSignRequest(api, jsonObject.get("id").asString()); - return signRequest.new Info(jsonObject); - } - - }; + public List getSigners() { + return this.signers; } - private static List toBoxSignRequestFiles(List sourceFiles) { - List files = new ArrayList<>(); - for (BoxFile.Info sourceFile : sourceFiles) { - BoxSignRequestFile file = BoxSignRequestFile.fromFile(sourceFile); - files.add(file); - } - - return files; + /** + * Gets the name of this sign request. + * + * @return name of this sign request. + */ + public String getName() { + return this.name; } /** - * Returns information about this sign request. + * Gets the list of prefill tags. * - * @param fields the fields to retrieve. - * @return information about this sign request. + * @return list of prefill tags. */ - public BoxSignRequest.Info getInfo(String... fields) { - QueryStringBuilder builder = new QueryStringBuilder(); - if (fields.length > 0) { - builder.appendParam("fields", fields); - } - URL url = SIGN_REQUEST_URL_TEMPLATE.buildAlphaWithQuery( - this.getAPI().getBaseURL(), builder.toString(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - return new BoxSignRequest.Info(responseJSON); - } + public List getPrefillTags() { + return this.prefillTags; } /** - * Cancels a sign request if it has not yet been signed or declined. - * Any outstanding signers will no longer be able to sign the document. + * Gets the number of days after which this request will automatically expire if not completed. * - * @return the cancelled sign request's info. + * @return number of days after which this request will automatically expire if not completed. */ - public BoxSignRequest.Info cancel() { - URL url = SIGN_REQUEST_CANCEL_URL_TEMPLATE.buildAlphaWithQuery(getAPI().getBaseURL(), "", this.getID()); - BoxJSONRequest request = new BoxJSONRequest(getAPI(), url, "POST"); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - return new BoxSignRequest.Info(responseJSON); - } + public Integer getDaysValid() { + return this.daysValid; } /** - * Attempts to resend a Sign Request to all signers that have not signed yet. - * There is a 10 minute cooling-off period between each resend request. - * If you make a resend call during the cooling-off period, a BoxAPIException will be thrown. + * Gets the reference id in an external system that this sign request is related to. + * + * @return external id. */ - public void resend() { - URL url = SIGN_REQUEST_RESEND_URL_TEMPLATE.buildAlphaWithQuery(getAPI().getBaseURL(), "", this.getID()); - BoxAPIRequest request = new BoxAPIRequest(getAPI(), url, "POST"); - request.send().close(); + public String getExternalId() { + return this.externalId; } /** - * Represents a status of the sign request. + * Gets the URL that can be used by the sign request sender to prepare the document through the + * UI. + * + * @return prepare url. */ - public enum BoxSignRequestStatus { - - /** - * Converting status. - */ - Converting("converting"), - - /** - * Created status. - */ - Created("created"), - - /** - * Sent status. - */ - Sent("sent"), - - /** - * Viewed status. - */ - Viewed("viewed"), - - /** - * Signed status. - */ - Signed("signed"), - - /** - * Cancelled status. - */ - Cancelled("cancelled"), - - /** - * Declined status. - */ - Declined("declined"), - - /** - * Error converting status. - */ - ErrorConverting("error_converting"), - - /** - * Error sending status. - */ - ErrorSending("error_sending"), - - /** - * Expired status. - */ - Expired("expired"), - - /** - * Finalizing status. - */ - Finalizing("finalizing"), - - /** - * Error finalizing status. - */ - ErrorFinalizing("error_finalizing"); - - private final String jsonValue; - - BoxSignRequestStatus(String jsonValue) { - this.jsonValue = jsonValue; - } - - static BoxSignRequestStatus fromJSONString(String jsonValue) { - switch (jsonValue) { - case "converting": - return Converting; - case "created": - return Created; - case "sent": - return Sent; - case "viewed": - return Viewed; - case "signed": - return Signed; - case "cancelled": - return Cancelled; - case "declined": - return Declined; - case "error_converting": - return ErrorConverting; - case "error_sending": - return ErrorSending; - case "expired": - return Expired; - case "finalizing": - return Finalizing; - case "error_finalizing": - return ErrorFinalizing; - default: - } - throw new IllegalArgumentException("The provided JSON value isn't a valid BoxSignRequestStatus value."); - } + public String getPrepareUrl() { + return this.prepareUrl; } /** - * Contains information about the Sign Request. + * Gets the reference to a file that will hold a log of all signer activity for this request. + * + * @return signing log. */ - public class Info extends BoxResource.Info { - - private boolean isDocumentPreparationNeeded; - private boolean areTextSignaturesEnabled; - private boolean areDatesEnabled; - private BoxSignRequestSignatureColor signatureColor; - private String emailSubject; - private String emailMessage; - private boolean areRemindersEnabled; - private List sourceFiles; - private BoxFolder.Info parentFolder; - private List signers; - private String name; - private List prefillTags; - private Integer daysValid; - private String externalId; - private String prepareUrl; - private BoxFile.Info signingLog; - private BoxSignRequestStatus status; - private BoxSignRequestSignFiles signFiles; - private Date autoExpireAt; - private String redirectUrl; - private String declinedRedirectUrl; - private String templateId; - - /** - * Constructs an empty Info object. - */ - public Info() { - super(); - } - - /** - * Constructs an Info object by parsing information from a JSON string. - * - * @param json the JSON string to parse. - */ - public Info(String json) { - super(json); - } - - /** - * Constructs an Info object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - Info(JsonObject jsonObject) { - super(jsonObject); - } - - /** - * Indicates if the sender should receive a prepare_url in the response to complete document preparation via UI. - * - * @return true if document preparation is needed, otherwise false. - */ - public boolean getIsDocumentPreparationNeeded() { - return this.isDocumentPreparationNeeded; - } - - /** - * Gets the flag indicating if usage of signatures generated by typing (text) is enabled. - * - * @return true if text signatures are enabled, otherwise false. - */ - public boolean getAreTextSignaturesEnabled() { - return this.areTextSignaturesEnabled; - } - - /** - * Gets the flag indicating if ability for signer to add dates is enabled. - * - * @return true if ability for signer to add dates is enabled, otherwise false. - */ - public boolean getAreDatesEnabled() { - return this.areDatesEnabled; - } - - /** - * Gets the forced, specific color for the signature. - * - * @return signature color (blue, black, red). - */ - public BoxSignRequestSignatureColor getSignatureColor() { - return this.signatureColor; - } - - /** - * Gets the subject of the sign request email. - * - * @return subject of the sign request email. - */ - public String getEmailSubject() { - return this.emailSubject; - } - - /** - * Gets the message to include in the sign request email. - * - * @return message of sign request email. - */ - public String getEmailMessage() { - return this.emailMessage; - } - - /** - * Gets the flag indicating if sending reminders for signers to sign a document on day 3, 8, 13 and 18 - * (or less if the document has been digitally signed already) is enabled. - * - * @return true if reminders are enabled, otherwise false. - */ - public boolean getAreRemindersEnabled() { - return this.areRemindersEnabled; - } - - /** - * Gets the list of files to create a signing document from. - * - * @return list of files to create a signing document from. - */ - public List getSourceFiles() { - return this.sourceFiles; - } - - /** - * Gets the destination folder to place sign request specific data in (copy of source files, signing log etc.). - * - * @return destination folder to place sign request specific data in. - */ - public BoxFolder.Info getParentFolder() { - return this.parentFolder; - } - - /** - * Gets the list of signers for this sign request. - * - * @return list of signers for this sign request. - */ - public List getSigners() { - return this.signers; - } - - /** - * Gets the name of this sign request. - * - * @return name of this sign request. - */ - public String getName() { - return this.name; - } - - /** - * Gets the list of prefill tags. - * - * @return list of prefill tags. - */ - public List getPrefillTags() { - return this.prefillTags; - } - - /** - * Gets the number of days after which this request will automatically expire if not completed. - * - * @return number of days after which this request will automatically expire if not completed. - */ - public Integer getDaysValid() { - return this.daysValid; - } - - /** - * Gets the reference id in an external system that this sign request is related to. - * - * @return external id. - */ - public String getExternalId() { - return this.externalId; - } - - /** - * Gets the URL that can be used by the sign request sender to prepare the document through the UI. - * - * @return prepare url. - */ - public String getPrepareUrl() { - return this.prepareUrl; - } - - /** - * Gets the reference to a file that will hold a log of all signer activity for this request. - * - * @return signing log. - */ - public BoxFile.Info getSigningLog() { - return this.signingLog; - } - - /** - * Gets the status of the sign request. - * - * @return sign request's status. - */ - public BoxSignRequestStatus getStatus() { - return this.status; - } + public BoxFile.Info getSigningLog() { + return this.signingLog; + } - /** - * List of files that will be signed, which are copies of the original source files. - * A new version of these files are created as signers sign and can be downloaded - * at any point in the signing process. - * - * @return sign files. - */ - public BoxSignRequestSignFiles getSignFiles() { - return this.signFiles; - } + /** + * Gets the status of the sign request. + * + * @return sign request's status. + */ + public BoxSignRequestStatus getStatus() { + return this.status; + } - /** - * Uses days_valid to calculate the date and time that - * the sign request will expire, if unsigned. - * - * @return auto expires at date. - */ - public Date getAutoExpireAt() { - return this.autoExpireAt; - } + /** + * List of files that will be signed, which are copies of the original source files. A new + * version of these files are created as signers sign and can be downloaded at any point in the + * signing process. + * + * @return sign files. + */ + public BoxSignRequestSignFiles getSignFiles() { + return this.signFiles; + } - /** - * Gets the URL that will be redirected to after the signer completes the sign request. - * - * @return redirect url. - */ - public String getRedirectUrl() { - return this.redirectUrl; - } + /** + * Uses days_valid to calculate the date and time that the sign request will expire, if + * unsigned. + * + * @return auto expires at date. + */ + public Date getAutoExpireAt() { + return this.autoExpireAt; + } - /** - * Gets the URL that will be redirected to after the signer declines the sign request. - * - * @return declined redirect url. - */ - public String getDeclinedRedirectUrl() { - return this.declinedRedirectUrl; - } + /** + * Gets the URL that will be redirected to after the signer completes the sign request. + * + * @return redirect url. + */ + public String getRedirectUrl() { + return this.redirectUrl; + } - /** - * Gets the id of the template that was used to create this sign request. - * - * @return sign template id. - */ - public String getTemplateId() { - return this.templateId; - } + /** + * Gets the URL that will be redirected to after the signer declines the sign request. + * + * @return declined redirect url. + */ + public String getDeclinedRedirectUrl() { + return this.declinedRedirectUrl; + } - /** - * {@inheritDoc} - */ - @Override - public BoxSignRequest getResource() { - return BoxSignRequest.this; - } + /** + * Gets the id of the template that was used to create this sign request. + * + * @return sign template id. + */ + public String getTemplateId() { + return this.templateId; + } - /** - * {@inheritDoc} - */ - @Override - void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - String memberName = member.getName(); - JsonValue value = member.getValue(); - try { - switch (memberName) { - case "is_document_preparation_needed": - this.isDocumentPreparationNeeded = value.asBoolean(); - break; - case "are_text_signatures_enabled": - this.areTextSignaturesEnabled = value.asBoolean(); - break; - case "are_dates_enabled": - this.areDatesEnabled = value.asBoolean(); - break; - case "signature_color": - this.signatureColor = BoxSignRequestSignatureColor.fromJSONString(value.asString()); - break; - case "email_subject": - this.emailSubject = value.asString(); - break; - case "email_message": - this.emailMessage = value.asString(); - break; - case "are_reminders_enabled": - this.areRemindersEnabled = value.asBoolean(); - break; - case "signers": - List signers = new ArrayList<>(); - for (JsonValue signerJSON : value.asArray()) { - BoxSignRequestSigner signer = new BoxSignRequestSigner(signerJSON.asObject(), getAPI()); - signers.add(signer); - } - this.signers = signers; - break; - case "source_files": - this.sourceFiles = this.getFiles(value.asArray()); - break; - case "parent_folder": - JsonObject folderJSON = value.asObject(); - String folderID = folderJSON.get("id").asString(); - BoxFolder folder = new BoxFolder(getAPI(), folderID); - this.parentFolder = folder.new Info(folderJSON); - break; - case "name": - this.name = value.asString(); - break; - case "prefill_tags": - List prefillTags = new ArrayList<>(); - for (JsonValue prefillTagJSON : value.asArray()) { - BoxSignRequestPrefillTag prefillTag = - new BoxSignRequestPrefillTag(prefillTagJSON.asObject()); - prefillTags.add(prefillTag); - } - this.prefillTags = prefillTags; - break; - case "days_valid": - this.daysValid = value.asInt(); - break; - case "external_id": - this.externalId = value.asString(); - break; - case "prepare_url": - this.prepareUrl = value.asString(); - break; - case "signing_log": - JsonObject signingLogJSON = value.asObject(); - String fileID = signingLogJSON.get("id").asString(); - BoxFile file = new BoxFile(getAPI(), fileID); - this.signingLog = file.new Info(signingLogJSON); - break; - case "status": - this.status = BoxSignRequestStatus.fromJSONString(value.asString()); - break; - case "sign_files": - JsonObject signFilesJSON = value.asObject(); - JsonValue filesArray = signFilesJSON.get("files"); - List signFiles = this.getFiles(filesArray); - boolean isReadyForDownload = signFilesJSON.get("is_ready_for_download").asBoolean(); - this.signFiles = new BoxSignRequestSignFiles(signFiles, isReadyForDownload); - break; - case "auto_expire_at": - this.autoExpireAt = BoxDateFormat.parse(value.asString()); - break; - case "redirect_url": - this.redirectUrl = value.asString(); - break; - case "declined_redirect_url": - this.declinedRedirectUrl = value.asString(); - break; - case "template_id": - this.templateId = value.asString(); - break; - default: - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); - } - } + /** {@inheritDoc} */ + @Override + public BoxSignRequest getResource() { + return BoxSignRequest.this; + } - private List getFiles(JsonValue filesArray) { - List files = new ArrayList<>(); - for (JsonValue fileJSON : filesArray.asArray()) { - String fileID = fileJSON.asObject().get("id").asString(); - BoxFile file = new BoxFile(getAPI(), fileID); - files.add(file.new Info(fileJSON.asObject())); + /** {@inheritDoc} */ + @Override + void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + String memberName = member.getName(); + JsonValue value = member.getValue(); + try { + switch (memberName) { + case "is_document_preparation_needed": + this.isDocumentPreparationNeeded = value.asBoolean(); + break; + case "are_text_signatures_enabled": + this.areTextSignaturesEnabled = value.asBoolean(); + break; + case "are_dates_enabled": + this.areDatesEnabled = value.asBoolean(); + break; + case "signature_color": + this.signatureColor = BoxSignRequestSignatureColor.fromJSONString(value.asString()); + break; + case "email_subject": + this.emailSubject = value.asString(); + break; + case "email_message": + this.emailMessage = value.asString(); + break; + case "are_reminders_enabled": + this.areRemindersEnabled = value.asBoolean(); + break; + case "signers": + List signers = new ArrayList<>(); + for (JsonValue signerJSON : value.asArray()) { + BoxSignRequestSigner signer = + new BoxSignRequestSigner(signerJSON.asObject(), getAPI()); + signers.add(signer); } - return files; - } - - /** - * List of files that will be signed, which are copies of the original source files. - * A new version of these files are created as signers sign and can be downloaded - * at any point in the signing process. - */ - public class BoxSignRequestSignFiles { - private final List files; - private final boolean isReadyToDownload; - - /** - * Constructs a BoxSignRequestSignFiles. - * - * @param files list that signing events will occur on. - * @param isReadyToDownload indicating whether a change to the document is processing. - */ - public BoxSignRequestSignFiles(List files, boolean isReadyToDownload) { - this.files = files; - this.isReadyToDownload = isReadyToDownload; + this.signers = signers; + break; + case "source_files": + this.sourceFiles = this.getFiles(value.asArray()); + break; + case "parent_folder": + JsonObject folderJSON = value.asObject(); + String folderID = folderJSON.get("id").asString(); + BoxFolder folder = new BoxFolder(getAPI(), folderID); + this.parentFolder = folder.new Info(folderJSON); + break; + case "name": + this.name = value.asString(); + break; + case "prefill_tags": + List prefillTags = new ArrayList<>(); + for (JsonValue prefillTagJSON : value.asArray()) { + BoxSignRequestPrefillTag prefillTag = + new BoxSignRequestPrefillTag(prefillTagJSON.asObject()); + prefillTags.add(prefillTag); } + this.prefillTags = prefillTags; + break; + case "days_valid": + this.daysValid = value.asInt(); + break; + case "external_id": + this.externalId = value.asString(); + break; + case "prepare_url": + this.prepareUrl = value.asString(); + break; + case "signing_log": + JsonObject signingLogJSON = value.asObject(); + String fileID = signingLogJSON.get("id").asString(); + BoxFile file = new BoxFile(getAPI(), fileID); + this.signingLog = file.new Info(signingLogJSON); + break; + case "status": + this.status = BoxSignRequestStatus.fromJSONString(value.asString()); + break; + case "sign_files": + JsonObject signFilesJSON = value.asObject(); + JsonValue filesArray = signFilesJSON.get("files"); + List signFiles = this.getFiles(filesArray); + boolean isReadyForDownload = signFilesJSON.get("is_ready_for_download").asBoolean(); + this.signFiles = new BoxSignRequestSignFiles(signFiles, isReadyForDownload); + break; + case "auto_expire_at": + this.autoExpireAt = BoxDateFormat.parse(value.asString()); + break; + case "redirect_url": + this.redirectUrl = value.asString(); + break; + case "declined_redirect_url": + this.declinedRedirectUrl = value.asString(); + break; + case "template_id": + this.templateId = value.asString(); + break; + default: + } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); + } + } - /** - * Gets the list of files that signing events will occur on - these are copies of the original source files. - * - * @return list of files. - */ - public List getFiles() { - return this.files; - } + private List getFiles(JsonValue filesArray) { + List files = new ArrayList<>(); + for (JsonValue fileJSON : filesArray.asArray()) { + String fileID = fileJSON.asObject().get("id").asString(); + BoxFile file = new BoxFile(getAPI(), fileID); + files.add(file.new Info(fileJSON.asObject())); + } + return files; + } - /** - * Gets the flag indicating whether a change to the document is processing and the PDF may be out of date. - * It is recommended to wait until processing has finished before downloading the PDF. - * Webhooks are not sent until processing has been completed. - * - * @return true if files are ready to download, otherwise false. - */ - public boolean getIsReadyToDownload() { - return this.isReadyToDownload; - } - } + /** + * List of files that will be signed, which are copies of the original source files. A new + * version of these files are created as signers sign and can be downloaded at any point in the + * signing process. + */ + public class BoxSignRequestSignFiles { + private final List files; + private final boolean isReadyToDownload; + + /** + * Constructs a BoxSignRequestSignFiles. + * + * @param files list that signing events will occur on. + * @param isReadyToDownload indicating whether a change to the document is processing. + */ + public BoxSignRequestSignFiles(List files, boolean isReadyToDownload) { + this.files = files; + this.isReadyToDownload = isReadyToDownload; + } + + /** + * Gets the list of files that signing events will occur on - these are copies of the original + * source files. + * + * @return list of files. + */ + public List getFiles() { + return this.files; + } + + /** + * Gets the flag indicating whether a change to the document is processing and the PDF may be + * out of date. It is recommended to wait until processing has finished before downloading the + * PDF. Webhooks are not sent until processing has been completed. + * + * @return true if files are ready to download, otherwise false. + */ + public boolean getIsReadyToDownload() { + return this.isReadyToDownload; + } } + } } diff --git a/src/main/java/com/box/sdk/BoxSignRequestCreateParams.java b/src/main/java/com/box/sdk/BoxSignRequestCreateParams.java index e3751b279..0eb681639 100644 --- a/src/main/java/com/box/sdk/BoxSignRequestCreateParams.java +++ b/src/main/java/com/box/sdk/BoxSignRequestCreateParams.java @@ -12,340 +12,345 @@ */ public class BoxSignRequestCreateParams { - private Boolean isDocumentPreparationNeeded; - private Boolean areTextSignaturesEnabled; - private Boolean areDatesEnabled; - private BoxSignRequestSignatureColor signatureColor; - private String emailSubject; - private String emailMessage; - private Boolean areRemindersEnabled; - private String name; - private List prefillTags; - private Integer daysValid; - private String externalId; - private String redirectUrl; - private String declinedRedirectUrl; - private String templateId; - - /** - * Gets the flag indicating if the sender should be taken into the builder flow to prepare the document. - * - * @return true if document preparation is needed, otherwise false. - */ - public boolean getIsDocumentPreparationNeeded() { - return this.isDocumentPreparationNeeded; + private Boolean isDocumentPreparationNeeded; + private Boolean areTextSignaturesEnabled; + private Boolean areDatesEnabled; + private BoxSignRequestSignatureColor signatureColor; + private String emailSubject; + private String emailMessage; + private Boolean areRemindersEnabled; + private String name; + private List prefillTags; + private Integer daysValid; + private String externalId; + private String redirectUrl; + private String declinedRedirectUrl; + private String templateId; + + /** + * Gets the flag indicating if the sender should be taken into the builder flow to prepare the + * document. + * + * @return true if document preparation is needed, otherwise false. + */ + public boolean getIsDocumentPreparationNeeded() { + return this.isDocumentPreparationNeeded; + } + + /** + * Sets the flag indicating if the sender should be taken into the builder flow to prepare the + * document. + * + * @param isDocumentPreparationNeeded whether or not sender should be taken into the builder flow + * to prepare the document. + * @return this BoxSignRequestCreateParams object for chaining. + */ + public BoxSignRequestCreateParams setIsDocumentPreparationNeeded( + boolean isDocumentPreparationNeeded) { + this.isDocumentPreparationNeeded = isDocumentPreparationNeeded; + return this; + } + + /** + * Gets the flag indicating if usage of signatures generated by typing (text) is enabled. Default + * is true. + * + * @return true if text signatures are enabled, otherwise false. + */ + public boolean getAreTextSignaturesEnabled() { + return this.areTextSignaturesEnabled; + } + + /** + * Sets the flag indicating if usage of signatures generated by typing (text) is enabled. Default + * is true. + * + * @param areTextSignaturesEnabled indicating if text signatures are enabled for signers. + * @return this BoxSignRequestCreateParams object for chaining. + */ + public BoxSignRequestCreateParams setAreTextSignaturesEnabled(boolean areTextSignaturesEnabled) { + this.areTextSignaturesEnabled = areTextSignaturesEnabled; + return this; + } + + /** + * Gets the flag indicating if ability for signer to add dates is enabled. Default is true. + * + * @return true if ability for signer to add dates is enabled, otherwise false. + */ + public boolean getAreDatesEnabled() { + return this.areDatesEnabled; + } + + /** + * Sets the flag indicating if ability for signer to add dates is enabled. Default is true. + * + * @param areDatesEnabled indicating if ability for signer to add dates is enabled. + * @return this BoxSignRequestCreateParams object for chaining. + */ + public BoxSignRequestCreateParams setAreDatesEnabled(boolean areDatesEnabled) { + this.areDatesEnabled = areDatesEnabled; + return this; + } + + /** + * Gets the forced, specific color for the signature. + * + * @return signature color (blue, black, red). + */ + public BoxSignRequestSignatureColor getSignatureColor() { + return this.signatureColor; + } + + /** + * Sets the forced, specific color for the signature. + * + * @param signatureColor blue, black or red. + * @return this BoxSignRequestCreateParams object for chaining. + */ + public BoxSignRequestCreateParams setSignatureColor(BoxSignRequestSignatureColor signatureColor) { + this.signatureColor = signatureColor; + return this; + } + + /** + * Gets the subject of sign request email. + * + * @return subject of sign request email. + */ + public String getEmailSubject() { + return this.emailSubject; + } + + /** + * Sets the subject of sign request email. This is cleaned by sign request. + * + * @param emailSubject included in sign request email. + * @return this BoxSignRequestCreateParams object for chaining. + */ + public BoxSignRequestCreateParams setEmailSubject(String emailSubject) { + this.emailSubject = emailSubject; + return this; + } + + /** + * Gets the message to include in sign request email. + * + * @return message of sign request email. + */ + public String getEmailMessage() { + return this.emailMessage; + } + + /** + * Sets the message to include in sign request email. This is cleaned,but some html tags are + * allowed. Links included in the message are also converted to actual links in the email. The + * message may contain the following html tags: a, abbr, acronym, b, blockquote, code, em, i, ul, + * li, ol, and strong. Be aware that when the text to html ratio is too high, the email may end up + * in spam filters. Custom styles on these tags are not allowed. + * + * @param emailMessage included in sign request email. + * @return this BoxSignRequestCreateParams object for chaining. + */ + public BoxSignRequestCreateParams setEmailMessage(String emailMessage) { + this.emailMessage = emailMessage; + return this; + } + + /** + * Gets the flag indicating if remind for signers to sign a document on day 3, 8, 13 and 18 (or + * less if the document has been digitally signed already) is enabled. + * + * @return true if reminders are enabled, otherwise false. + */ + public boolean getAreRemindersEnabled() { + return this.areRemindersEnabled; + } + + /** + * Sets the flag indicating if remind for signers to sign a document on day 3, 8, 13 and 18 (or + * less if the document has been digitally signed already) is enabled. + * + * @param areRemindersEnabled indicating if reminders are enabled. + * @return this BoxSignRequestCreateParams object for chaining. + */ + public BoxSignRequestCreateParams setAreRemindersEnabled(boolean areRemindersEnabled) { + this.areRemindersEnabled = areRemindersEnabled; + return this; + } + + /** + * Gets the name of this sign request. + * + * @return name of this sign request. + */ + public String getName() { + return this.name; + } + + /** + * Sets the name of this sign request. + * + * @param name of this sign request. + * @return this BoxSignRequestCreateParams object for chaining. + */ + public BoxSignRequestCreateParams setName(String name) { + this.name = name; + return this; + } + + /** + * Gets the number of days after which this request will automatically expire if not completed. + * + * @return number of days after which this request will automatically expire if not completed. + */ + public int getDaysValid() { + return this.daysValid; + } + + /** + * Sets the number of days after which this request will automatically expire if not completed. + * + * @param daysValid of this sign request. + * @return this BoxSignRequestCreateParams object for chaining. + */ + public BoxSignRequestCreateParams setDaysValid(int daysValid) { + this.daysValid = daysValid; + return this; + } + + /** + * Gets an ID that serve as reference in an external system that the sign request is related to. + * + * @return external id. + */ + public String getExternalId() { + return this.externalId; + } + + /** + * Sets the reference id in an external system that this sign request is related to. + * + * @param externalId of this sign request. + * @return this BoxSignRequestCreateParams object for chaining. + */ + public BoxSignRequestCreateParams setExternalId(String externalId) { + this.externalId = externalId; + return this; + } + + /** + * Gets the list of prefill tags. + * + * @return list of prefill tags. + */ + public List getPrefillTags() { + return this.prefillTags; + } + + /** + * Sets the list of prefill tags. When a document contains sign related tags in the content, you + * can prefill them using this prefillTags by referencing the 'id' of the tag as the externalId + * field of the prefill tag. + * + * @param prefillTags list for this sign request. + * @return this BoxSignRequestCreateParams object for chaining. + */ + public BoxSignRequestCreateParams setPrefillTags(List prefillTags) { + this.prefillTags = prefillTags; + return this; + } + + /** + * Gets the redirect URL that a signer will be redirected to after signing a document. + * + * @return redirect url. + */ + public String getRedirectUrl() { + return this.redirectUrl; + } + + /** + * Sets the redirect URL that a signer will be redirected to after signing a document. + * + * @param redirectUrl of this sign request. + * @return this BoxSignRequestCreateParams object for chaining. + */ + public BoxSignRequestCreateParams setRedirectUrl(String redirectUrl) { + this.redirectUrl = redirectUrl; + return this; + } + + /** + * Gets the URL that a signer will be redirected to after declining to sign a document. + * + * @return decline redirect url. + */ + public String getDeclinedRedirectUrl() { + return this.declinedRedirectUrl; + } + + /** + * Sets the URL that a signer will be redirected to after declining to sign a document. + * + * @param declinedRedirectUrl of this sign request. + * @return this BoxSignRequestCreateParams object for chaining. + */ + public BoxSignRequestCreateParams setDeclinedRedirectUrl(String declinedRedirectUrl) { + this.declinedRedirectUrl = declinedRedirectUrl; + return this; + } + + /** + * Gets the Sign Template ID of the Sign Request. + * + * @return template id. + */ + public String getTemplateId() { + return this.templateId; + } + + /** + * Sets the Sign Template ID will be use to create the sign request. + * + * @param templateId for this sign request. + * @return this BoxSignRequestCreateParams object for chaining. + */ + public BoxSignRequestCreateParams setTemplateId(String templateId) { + this.templateId = templateId; + return this; + } + + /** + * Used to append BoxSignRequestCreateParams to request. + * + * @param requestJSON request in json to append data to. + */ + public void appendParamsAsJson(JsonObject requestJSON) { + JsonUtils.addIfNotNull( + requestJSON, "is_document_preparation_needed", this.isDocumentPreparationNeeded); + JsonUtils.addIfNotNull( + requestJSON, "are_text_signatures_enabled", this.areTextSignaturesEnabled); + JsonUtils.addIfNotNull(requestJSON, "are_dates_enabled", this.areDatesEnabled); + JsonUtils.addIfNotNull(requestJSON, "signature_color", this.signatureColor); + JsonUtils.addIfNotNull(requestJSON, "email_subject", this.emailSubject); + JsonUtils.addIfNotNull(requestJSON, "email_message", this.emailMessage); + JsonUtils.addIfNotNull(requestJSON, "are_reminders_enabled", this.areRemindersEnabled); + JsonUtils.addIfNotNull(requestJSON, "name", this.name); + JsonUtils.addIfNotNull(requestJSON, "days_valid", this.daysValid); + JsonUtils.addIfNotNull(requestJSON, "external_id", this.externalId); + JsonUtils.addIfNotNull(requestJSON, "redirect_url", this.redirectUrl); + JsonUtils.addIfNotNull(requestJSON, "declined_redirect_url", this.declinedRedirectUrl); + JsonUtils.addIfNotNull(requestJSON, "template_id", this.templateId); + + if (this.prefillTags != null) { + JsonArray prefillTagsJSON = new JsonArray(); + for (BoxSignRequestPrefillTag prefillTag : this.prefillTags) { + prefillTagsJSON.add(prefillTag.getJSONObject()); + } + requestJSON.add("prefill_tags", prefillTagsJSON); } - /** - * Sets the flag indicating if the sender should be taken into the builder flow to prepare the document. - * - * @param isDocumentPreparationNeeded whether or not sender should be taken - * into the builder flow to prepare the document. - * @return this BoxSignRequestCreateParams object for chaining. - */ - public BoxSignRequestCreateParams setIsDocumentPreparationNeeded(boolean isDocumentPreparationNeeded) { - this.isDocumentPreparationNeeded = isDocumentPreparationNeeded; - return this; - } - - /** - * Gets the flag indicating if usage of signatures generated by typing (text) is enabled. Default is true. - * - * @return true if text signatures are enabled, otherwise false. - */ - public boolean getAreTextSignaturesEnabled() { - return this.areTextSignaturesEnabled; - } - - /** - * Sets the flag indicating if usage of signatures generated by typing (text) is enabled. Default is true. - * - * @param areTextSignaturesEnabled indicating if text signatures are enabled for signers. - * @return this BoxSignRequestCreateParams object for chaining. - */ - public BoxSignRequestCreateParams setAreTextSignaturesEnabled(boolean areTextSignaturesEnabled) { - this.areTextSignaturesEnabled = areTextSignaturesEnabled; - return this; - } - - /** - * Gets the flag indicating if ability for signer to add dates is enabled. Default is true. - * - * @return true if ability for signer to add dates is enabled, otherwise false. - */ - public boolean getAreDatesEnabled() { - return this.areDatesEnabled; - } - - /** - * Sets the flag indicating if ability for signer to add dates is enabled. Default is true. - * - * @param areDatesEnabled indicating if ability for signer to add dates is enabled. - * @return this BoxSignRequestCreateParams object for chaining. - */ - public BoxSignRequestCreateParams setAreDatesEnabled(boolean areDatesEnabled) { - this.areDatesEnabled = areDatesEnabled; - return this; - } - - /** - * Gets the forced, specific color for the signature. - * - * @return signature color (blue, black, red). - */ - public BoxSignRequestSignatureColor getSignatureColor() { - return this.signatureColor; - } - - /** - * Sets the forced, specific color for the signature. - * - * @param signatureColor blue, black or red. - * @return this BoxSignRequestCreateParams object for chaining. - */ - public BoxSignRequestCreateParams setSignatureColor(BoxSignRequestSignatureColor signatureColor) { - this.signatureColor = signatureColor; - return this; - } - - /** - * Gets the subject of sign request email. - * - * @return subject of sign request email. - */ - public String getEmailSubject() { - return this.emailSubject; - } - - /** - * Sets the subject of sign request email. This is cleaned by sign request. - * - * @param emailSubject included in sign request email. - * @return this BoxSignRequestCreateParams object for chaining. - */ - public BoxSignRequestCreateParams setEmailSubject(String emailSubject) { - this.emailSubject = emailSubject; - return this; - } - - /** - * Gets the message to include in sign request email. - * - * @return message of sign request email. - */ - public String getEmailMessage() { - return this.emailMessage; - } - - /** - * Sets the message to include in sign request email. This is cleaned,but some html tags are allowed. - * Links included in the message are also converted to actual links in the email. - * The message may contain the following html tags: - * a, abbr, acronym, b, blockquote, code, em, i, ul, li, ol, and strong. - * Be aware that when the text to html ratio is too high, the email may end up in spam filters. - * Custom styles on these tags are not allowed. - * - * @param emailMessage included in sign request email. - * @return this BoxSignRequestCreateParams object for chaining. - */ - public BoxSignRequestCreateParams setEmailMessage(String emailMessage) { - this.emailMessage = emailMessage; - return this; - } - - /** - * Gets the flag indicating if remind for signers to sign a document on day 3, 8, 13 and 18 - * (or less if the document has been digitally signed already) is enabled. - * - * @return true if reminders are enabled, otherwise false. - */ - public boolean getAreRemindersEnabled() { - return this.areRemindersEnabled; - } - - /** - * Sets the flag indicating if remind for signers to sign a document on day 3, 8, 13 and 18 - * (or less if the document has been digitally signed already) is enabled. - * - * @param areRemindersEnabled indicating if reminders are enabled. - * @return this BoxSignRequestCreateParams object for chaining. - */ - public BoxSignRequestCreateParams setAreRemindersEnabled(boolean areRemindersEnabled) { - this.areRemindersEnabled = areRemindersEnabled; - return this; - } - - /** - * Gets the name of this sign request. - * - * @return name of this sign request. - */ - public String getName() { - return this.name; - } - - /** - * Sets the name of this sign request. - * - * @param name of this sign request. - * @return this BoxSignRequestCreateParams object for chaining. - */ - public BoxSignRequestCreateParams setName(String name) { - this.name = name; - return this; - } - - /** - * Gets the number of days after which this request will automatically expire if not completed. - * - * @return number of days after which this request will automatically expire if not completed. - */ - public int getDaysValid() { - return this.daysValid; - } - - /** - * Sets the number of days after which this request will automatically expire if not completed. - * - * @param daysValid of this sign request. - * @return this BoxSignRequestCreateParams object for chaining. - */ - public BoxSignRequestCreateParams setDaysValid(int daysValid) { - this.daysValid = daysValid; - return this; - } - - /** - * Gets an ID that serve as reference in an external system that the sign request is related to. - * - * @return external id. - */ - public String getExternalId() { - return this.externalId; - } - - /** - * Sets the reference id in an external system that this sign request is related to. - * - * @param externalId of this sign request. - * @return this BoxSignRequestCreateParams object for chaining. - */ - public BoxSignRequestCreateParams setExternalId(String externalId) { - this.externalId = externalId; - return this; - } - - /** - * Gets the list of prefill tags. - * - * @return list of prefill tags. - */ - public List getPrefillTags() { - return this.prefillTags; - } - - /** - * Sets the list of prefill tags. When a document contains sign related tags in the content, - * you can prefill them using this prefillTags by referencing - * the 'id' of the tag as the externalId field of the prefill tag. - * - * @param prefillTags list for this sign request. - * @return this BoxSignRequestCreateParams object for chaining. - */ - public BoxSignRequestCreateParams setPrefillTags(List prefillTags) { - this.prefillTags = prefillTags; - return this; - } - - /** - * Gets the redirect URL that a signer will be redirected to after signing a document. - * - * @return redirect url. - */ - public String getRedirectUrl() { - return this.redirectUrl; - } - - /** - * Sets the redirect URL that a signer will be redirected to after signing a document. - * - * @param redirectUrl of this sign request. - * @return this BoxSignRequestCreateParams object for chaining. - */ - public BoxSignRequestCreateParams setRedirectUrl(String redirectUrl) { - this.redirectUrl = redirectUrl; - return this; - } - - /** - * Gets the URL that a signer will be redirected to after declining to sign a document. - * - * @return decline redirect url. - */ - public String getDeclinedRedirectUrl() { - return this.declinedRedirectUrl; - } - - /** - * Sets the URL that a signer will be redirected to after declining to sign a document. - * - * @param declinedRedirectUrl of this sign request. - * @return this BoxSignRequestCreateParams object for chaining. - */ - public BoxSignRequestCreateParams setDeclinedRedirectUrl(String declinedRedirectUrl) { - this.declinedRedirectUrl = declinedRedirectUrl; - return this; - } - - /** - * Gets the Sign Template ID of the Sign Request. - * - * @return template id. - */ - public String getTemplateId() { - return this.templateId; - } - - /** - * Sets the Sign Template ID will be use to create the sign request. - * - * @param templateId for this sign request. - * @return this BoxSignRequestCreateParams object for chaining. - */ - public BoxSignRequestCreateParams setTemplateId(String templateId) { - this.templateId = templateId; - return this; - } - - /** - * Used to append BoxSignRequestCreateParams to request. - * - * @param requestJSON request in json to append data to. - */ - public void appendParamsAsJson(JsonObject requestJSON) { - JsonUtils.addIfNotNull(requestJSON, "is_document_preparation_needed", - this.isDocumentPreparationNeeded); - JsonUtils.addIfNotNull(requestJSON, "are_text_signatures_enabled", this.areTextSignaturesEnabled); - JsonUtils.addIfNotNull(requestJSON, "are_dates_enabled", this.areDatesEnabled); - JsonUtils.addIfNotNull(requestJSON, "signature_color", this.signatureColor); - JsonUtils.addIfNotNull(requestJSON, "email_subject", this.emailSubject); - JsonUtils.addIfNotNull(requestJSON, "email_message", this.emailMessage); - JsonUtils.addIfNotNull(requestJSON, "are_reminders_enabled", this.areRemindersEnabled); - JsonUtils.addIfNotNull(requestJSON, "name", this.name); - JsonUtils.addIfNotNull(requestJSON, "days_valid", this.daysValid); - JsonUtils.addIfNotNull(requestJSON, "external_id", this.externalId); - JsonUtils.addIfNotNull(requestJSON, "redirect_url", this.redirectUrl); - JsonUtils.addIfNotNull(requestJSON, "declined_redirect_url", this.declinedRedirectUrl); - JsonUtils.addIfNotNull(requestJSON, "template_id", this.templateId); - - if (this.prefillTags != null) { - JsonArray prefillTagsJSON = new JsonArray(); - for (BoxSignRequestPrefillTag prefillTag : this.prefillTags) { - prefillTagsJSON.add(prefillTag.getJSONObject()); - } - requestJSON.add("prefill_tags", prefillTagsJSON); - } - - return; - } + return; + } } diff --git a/src/main/java/com/box/sdk/BoxSignRequestFile.java b/src/main/java/com/box/sdk/BoxSignRequestFile.java index 55ec75ea2..24795590c 100644 --- a/src/main/java/com/box/sdk/BoxSignRequestFile.java +++ b/src/main/java/com/box/sdk/BoxSignRequestFile.java @@ -2,99 +2,96 @@ import com.eclipsesource.json.JsonObject; -/** - * Represents a Box File to be included in a sign request. - */ +/** Represents a Box File to be included in a sign request. */ public class BoxSignRequestFile { - private String fileId; - private String fileVersionId; + private String fileId; + private String fileVersionId; - /** - * Constructs a BoxSignRequestFile with specific file version to be used during sign request creation. - * - * @param fileId id of the file. - * @param fileVersionId id of the file versionm. - */ - public BoxSignRequestFile(String fileId, String fileVersionId) { - this.fileId = fileId; - this.fileVersionId = fileVersionId; - } - - /** - * Constructs a BoxSignRequestFile to be used during sign request creation. - * - * @param fileId id of the file. - */ - public BoxSignRequestFile(String fileId) { - this.fileId = fileId; - } + /** + * Constructs a BoxSignRequestFile with specific file version to be used during sign request + * creation. + * + * @param fileId id of the file. + * @param fileVersionId id of the file versionm. + */ + public BoxSignRequestFile(String fileId, String fileVersionId) { + this.fileId = fileId; + this.fileVersionId = fileVersionId; + } - static BoxSignRequestFile fromFile(BoxFile.Info sourceFile) { - BoxSignRequestFile file = new BoxSignRequestFile(sourceFile.getID()); - if (sourceFile.getVersion() != null) { - file.setFileVersionId(sourceFile.getVersionNumber()); - } + /** + * Constructs a BoxSignRequestFile to be used during sign request creation. + * + * @param fileId id of the file. + */ + public BoxSignRequestFile(String fileId) { + this.fileId = fileId; + } - return file; + static BoxSignRequestFile fromFile(BoxFile.Info sourceFile) { + BoxSignRequestFile file = new BoxSignRequestFile(sourceFile.getID()); + if (sourceFile.getVersion() != null) { + file.setFileVersionId(sourceFile.getVersionNumber()); } - /** - * Gets the file id of the file. - * - * @return file id of the file. - */ - public String getFileId() { - return this.fileId; - } + return file; + } - /** - * Sets the file id. - * - * @param fileId of the file. - * @return this BoxSignRequestFile object for chaining. - */ - public BoxSignRequestFile setFileId(String fileId) { - this.fileId = fileId; - return this; - } + /** + * Gets the file id of the file. + * + * @return file id of the file. + */ + public String getFileId() { + return this.fileId; + } - /** - * Gets the file version id of the file. - * - * @return file version id of the file. - */ - public String getFileVersionId() { - return this.fileVersionId; - } + /** + * Sets the file id. + * + * @param fileId of the file. + * @return this BoxSignRequestFile object for chaining. + */ + public BoxSignRequestFile setFileId(String fileId) { + this.fileId = fileId; + return this; + } - /** - * Sets the file version id. - * - * @param fileVersionId of the file. - * @return this BoxSignRequestFile object for chaining. - */ - public BoxSignRequestFile setFileVersionId(String fileVersionId) { - this.fileVersionId = fileVersionId; - return this; - } + /** + * Gets the file version id of the file. + * + * @return file version id of the file. + */ + public String getFileVersionId() { + return this.fileVersionId; + } - /** - * Gets a JSON object representing this class. - * - * @return the JSON object representing this class. - */ - public JsonObject getJSONObject() { - JsonObject fileJSON = new JsonObject() - .add("id", this.fileId) - .add("type", "file"); + /** + * Sets the file version id. + * + * @param fileVersionId of the file. + * @return this BoxSignRequestFile object for chaining. + */ + public BoxSignRequestFile setFileVersionId(String fileVersionId) { + this.fileVersionId = fileVersionId; + return this; + } - if (this.fileVersionId != null) { - JsonObject fileVersionJSON = new JsonObject(); - fileVersionJSON.add("id", this.fileVersionId); - fileVersionJSON.add("type", "file_version"); - fileJSON.add("file_version", fileVersionJSON); - } + /** + * Gets a JSON object representing this class. + * + * @return the JSON object representing this class. + */ + public JsonObject getJSONObject() { + JsonObject fileJSON = new JsonObject().add("id", this.fileId).add("type", "file"); - return fileJSON; + if (this.fileVersionId != null) { + JsonObject fileVersionJSON = new JsonObject(); + fileVersionJSON.add("id", this.fileVersionId); + fileVersionJSON.add("type", "file_version"); + fileJSON.add("file_version", fileVersionJSON); } + + return fileJSON; + } } diff --git a/src/main/java/com/box/sdk/BoxSignRequestPrefillTag.java b/src/main/java/com/box/sdk/BoxSignRequestPrefillTag.java index 6ff41b9f5..8921b86a5 100644 --- a/src/main/java/com/box/sdk/BoxSignRequestPrefillTag.java +++ b/src/main/java/com/box/sdk/BoxSignRequestPrefillTag.java @@ -8,140 +8,138 @@ import java.util.Date; /** - * Represents a prefill tag used in BoxSignRequest. When a document contains sign related tags in the content, - * you can prefill them using this prefillTag by referencing the - * 'id' of the tag as the externalId field of the prefill tag. + * Represents a prefill tag used in BoxSignRequest. When a document contains sign related tags in + * the content, you can prefill them using this prefillTag by referencing the 'id' of the tag as the + * externalId field of the prefill tag. */ public class BoxSignRequestPrefillTag extends BoxJSONObject { - private String documentTagId; - private String textValue; - private Boolean checkboxValue; - private Date dateValue; + private String documentTagId; + private String textValue; + private Boolean checkboxValue; + private Date dateValue; - /** - * Constructs a BoxSignRequestPrefillTag with text prefill value. - * - * @param documentTagId if of the tag. - * @param textValue text prefill value. - */ - public BoxSignRequestPrefillTag(String documentTagId, String textValue) { - this.documentTagId = documentTagId; - this.textValue = textValue; - } + /** + * Constructs a BoxSignRequestPrefillTag with text prefill value. + * + * @param documentTagId if of the tag. + * @param textValue text prefill value. + */ + public BoxSignRequestPrefillTag(String documentTagId, String textValue) { + this.documentTagId = documentTagId; + this.textValue = textValue; + } - /** - * Constructs a BoxSignRequestPrefillTag with checkbox prefill value. - * - * @param documentTagId if of the tag. - * @param checkboxValue checkbox prefill value. - */ - public BoxSignRequestPrefillTag(String documentTagId, Boolean checkboxValue) { - this.documentTagId = documentTagId; - this.checkboxValue = checkboxValue; - } + /** + * Constructs a BoxSignRequestPrefillTag with checkbox prefill value. + * + * @param documentTagId if of the tag. + * @param checkboxValue checkbox prefill value. + */ + public BoxSignRequestPrefillTag(String documentTagId, Boolean checkboxValue) { + this.documentTagId = documentTagId; + this.checkboxValue = checkboxValue; + } - /** - * Constructs a BoxSignRequestPrefillTag with date prefill value. - * - * @param documentTagId if of the tag. - * @param dateValue date prefill value. - */ - public BoxSignRequestPrefillTag(String documentTagId, Date dateValue) { - this.documentTagId = documentTagId; - this.dateValue = dateValue; - } + /** + * Constructs a BoxSignRequestPrefillTag with date prefill value. + * + * @param documentTagId if of the tag. + * @param dateValue date prefill value. + */ + public BoxSignRequestPrefillTag(String documentTagId, Date dateValue) { + this.documentTagId = documentTagId; + this.dateValue = dateValue; + } - /** - * Constructs a BoxSignRequestPrefillTag from a JSON string. - * - * @param json the JSON encoded enterprise. - */ - public BoxSignRequestPrefillTag(String json) { - super(json); - } + /** + * Constructs a BoxSignRequestPrefillTag from a JSON string. + * + * @param json the JSON encoded enterprise. + */ + public BoxSignRequestPrefillTag(String json) { + super(json); + } - /** - * Constructs an BoxSignRequestPrefillTag object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - BoxSignRequestPrefillTag(JsonObject jsonObject) { - super(jsonObject); - } + /** + * Constructs an BoxSignRequestPrefillTag object using an already parsed JSON object. + * + * @param jsonObject the parsed JSON object. + */ + BoxSignRequestPrefillTag(JsonObject jsonObject) { + super(jsonObject); + } - /** - * Gets the reference id of a particular tag added to the content - * of the files being used to create the sign request. - * - * @return document tag id. - */ - public String getDocumentTagId() { - return this.documentTagId; - } + /** + * Gets the reference id of a particular tag added to the content of the files being used to + * create the sign request. + * + * @return document tag id. + */ + public String getDocumentTagId() { + return this.documentTagId; + } - /** - * Gets the text prefill value. - * - * @return text prefill value. - */ - public String getTextValue() { - return this.textValue; - } + /** + * Gets the text prefill value. + * + * @return text prefill value. + */ + public String getTextValue() { + return this.textValue; + } - /** - * Gets the checkbox prefill value. - * - * @return checkbox prefill value. - */ - public Boolean getCheckboxValue() { - return this.checkboxValue; - } + /** + * Gets the checkbox prefill value. + * + * @return checkbox prefill value. + */ + public Boolean getCheckboxValue() { + return this.checkboxValue; + } - /** - * Gets the date prefill value. - * - * @return date prefill value. - */ - public Date getDateValue() { - return this.dateValue; - } + /** + * Gets the date prefill value. + * + * @return date prefill value. + */ + public Date getDateValue() { + return this.dateValue; + } - /** - * Gets a JSON object representing this class. - * - * @return the JSON object representing this class. - */ - public JsonObject getJSONObject() { - JsonObject prefillTagObj = new JsonObject(); - JsonUtils.addIfNotNull(prefillTagObj, "document_tag_id", this.documentTagId); - JsonUtils.addIfNotNull(prefillTagObj, "text_value", this.textValue); - JsonUtils.addIfNotNull(prefillTagObj, "checkbox_value", this.checkboxValue); - if (this.dateValue != null) { - prefillTagObj.add("date_value", formatAsDateOnly(this.dateValue)); - } - - return prefillTagObj; + /** + * Gets a JSON object representing this class. + * + * @return the JSON object representing this class. + */ + public JsonObject getJSONObject() { + JsonObject prefillTagObj = new JsonObject(); + JsonUtils.addIfNotNull(prefillTagObj, "document_tag_id", this.documentTagId); + JsonUtils.addIfNotNull(prefillTagObj, "text_value", this.textValue); + JsonUtils.addIfNotNull(prefillTagObj, "checkbox_value", this.checkboxValue); + if (this.dateValue != null) { + prefillTagObj.add("date_value", formatAsDateOnly(this.dateValue)); } - /** - * {@inheritDoc} - */ - @Override - void parseJSONMember(JsonObject.Member member) { - JsonValue value = member.getValue(); - String memberName = member.getName(); - try { - if ("document_tag_id".equals(memberName)) { - this.documentTagId = value.asString(); - } else if ("text_value".equals(memberName)) { - this.textValue = value.asString(); - } else if ("checkbox_value".equals(memberName)) { - this.checkboxValue = value.asBoolean(); - } else if ("date_value".equals(memberName)) { - this.dateValue = BoxDateFormat.parseDateOnly(value.asString()); - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); - } + return prefillTagObj; + } + + /** {@inheritDoc} */ + @Override + void parseJSONMember(JsonObject.Member member) { + JsonValue value = member.getValue(); + String memberName = member.getName(); + try { + if ("document_tag_id".equals(memberName)) { + this.documentTagId = value.asString(); + } else if ("text_value".equals(memberName)) { + this.textValue = value.asString(); + } else if ("checkbox_value".equals(memberName)) { + this.checkboxValue = value.asBoolean(); + } else if ("date_value".equals(memberName)) { + this.dateValue = BoxDateFormat.parseDateOnly(value.asString()); + } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); } + } } diff --git a/src/main/java/com/box/sdk/BoxSignRequestSignatureColor.java b/src/main/java/com/box/sdk/BoxSignRequestSignatureColor.java index fb1d4afb2..d64f6629c 100644 --- a/src/main/java/com/box/sdk/BoxSignRequestSignatureColor.java +++ b/src/main/java/com/box/sdk/BoxSignRequestSignatureColor.java @@ -1,40 +1,32 @@ package com.box.sdk; -/** - * Specific, forced color for a signature. - */ +/** Specific, forced color for a signature. */ public enum BoxSignRequestSignatureColor { - /** - * Blue signature color. - */ - Blue("blue"), + /** Blue signature color. */ + Blue("blue"), - /** - * Black signature color. - */ - Black("black"), + /** Black signature color. */ + Black("black"), - /** - * Red signature color. - */ - Red("red"); + /** Red signature color. */ + Red("red"); - private final String jsonValue; + private final String jsonValue; - BoxSignRequestSignatureColor(String jsonValue) { - this.jsonValue = jsonValue; - } + BoxSignRequestSignatureColor(String jsonValue) { + this.jsonValue = jsonValue; + } - static BoxSignRequestSignatureColor fromJSONString(String jsonValue) { - if ("blue".equals(jsonValue)) { - return Blue; - } else if ("black".equals(jsonValue)) { - return Black; - } else if ("red".equals(jsonValue)) { - return Red; - } - throw new IllegalArgumentException("The provided JSON value isn't a valid " - + "BoxSignRequestSignatureColor."); + static BoxSignRequestSignatureColor fromJSONString(String jsonValue) { + if ("blue".equals(jsonValue)) { + return Blue; + } else if ("black".equals(jsonValue)) { + return Black; + } else if ("red".equals(jsonValue)) { + return Red; } + throw new IllegalArgumentException( + "The provided JSON value isn't a valid " + "BoxSignRequestSignatureColor."); + } } diff --git a/src/main/java/com/box/sdk/BoxSignRequestSigner.java b/src/main/java/com/box/sdk/BoxSignRequestSigner.java index d68d949f8..2b77b2f32 100644 --- a/src/main/java/com/box/sdk/BoxSignRequestSigner.java +++ b/src/main/java/com/box/sdk/BoxSignRequestSigner.java @@ -9,836 +9,783 @@ import java.util.Date; import java.util.List; -/** - * Represents a signer in BoxSignRequest. - */ +/** Represents a signer in BoxSignRequest. */ public class BoxSignRequestSigner extends BoxJSONObject { - private String email; - private BoxSignRequestSignerRole role; - private Boolean isInPerson; - private Integer order; - private String embedUrlExternalUserId; - private Boolean hasViewedEmail; - private Boolean hasViewedDocument; - private BoxSignerDecision signerDecision; - private List inputs; - private String embedUrl; - private String redirectUrl; - private String declinedRedirectUrl; - private String iframeableEmedUrl; - private String signerGroupId; - private Boolean loginRequired; - private String password; - private Boolean suppressNotifications; - private String verificationPhoneNumber; - private BoxAPIConnection api; - - /** - * Constructs a BoxSignRequestSigner with an email. - * - * @param email of signer. - */ - public BoxSignRequestSigner(String email) { - this.email = email; - } - - /** - * Construct a BoxSignRequestSigner. + private String email; + private BoxSignRequestSignerRole role; + private Boolean isInPerson; + private Integer order; + private String embedUrlExternalUserId; + private Boolean hasViewedEmail; + private Boolean hasViewedDocument; + private BoxSignerDecision signerDecision; + private List inputs; + private String embedUrl; + private String redirectUrl; + private String declinedRedirectUrl; + private String iframeableEmedUrl; + private String signerGroupId; + private Boolean loginRequired; + private String password; + private Boolean suppressNotifications; + private String verificationPhoneNumber; + private BoxAPIConnection api; + + /** + * Constructs a BoxSignRequestSigner with an email. + * + * @param email of signer. + */ + public BoxSignRequestSigner(String email) { + this.email = email; + } + + /** + * Construct a BoxSignRequestSigner. + * + * @param jsonObject the parsed JSON object. + * @param api the API connection to be used to fetch interacted item + */ + public BoxSignRequestSigner(JsonObject jsonObject, BoxAPIConnection api) { + super(jsonObject); + this.api = api; + } + + /** + * Gets the email address of the signer. + * + * @return email address of the signer. + */ + public String getEmail() { + return this.email; + } + + /** + * Sets the email address of the signer. + * + * @param email address of the signer. + * @return this BoxSignRequestSigner object for chaining. + */ + public BoxSignRequestSigner setEmail(String email) { + this.email = email; + return this; + } + + /** + * Gets the role of the signer. + * + * @return role of the signer. + */ + public BoxSignRequestSignerRole getRole() { + return this.role; + } + + /** + * Sets the role of the signer. If role is not set it's FinalCopyReader by default. + * + * @param role of the signer. + * @return this BoxSignRequestSigner object for chaining. + */ + public BoxSignRequestSigner setRole(BoxSignRequestSignerRole role) { + this.role = role; + return this; + } + + /** + * Gets the flag that when used in combination with an embed url on the sender. After the sender + * signs, they will be redirected to the next InPerson signer. + * + * @return true if is in person signer, otherwise false. + */ + public boolean getIsInPerson() { + return this.isInPerson; + } + + /** + * Gets the order of signer. + * + * @return order of signer. + */ + public int getOrder() { + return this.order; + } + + /** + * Sets the order of signer. + * + * @param order of signer. + * @return this BoxSignRequestSigner object for chaining. + */ + public BoxSignRequestSigner setOrder(Integer order) { + this.order = order; + return this; + } + + /** + * Gets the user id for this signer in external application responsible for authentication when + * accessing the embed url. + * + * @return embed url external user id. + */ + public String getEmbedUrlExternalUserId() { + return this.embedUrlExternalUserId; + } + + /** + * Sets the user id for this signer in external application responsible for authentication when + * accessing the embed url. + * + * @param embedUrlExternalUserId for this signer in external application responsible for + * authentication when accessing the embed url. + * @return this BoxSignRequestSigner object for chaining. + */ + public BoxSignRequestSigner setEmbedUrlExternalUserId(String embedUrlExternalUserId) { + this.embedUrlExternalUserId = embedUrlExternalUserId; + return this; + } + + /** + * Gets the flag indicating if signer has viewed the sign request email. + * + * @return true if the signer has viewed the sign request email, otherwise false. + */ + public boolean getHasViewedEmail() { + return this.hasViewedEmail; + } + + /** + * Gets the flag indicating if signer has viewed the document. + * + * @return true if the signer has viewed the document, otherwise false. + */ + public boolean getHasViewedDocument() { + return this.hasViewedDocument; + } + + /** + * Gets the final decision made by signer. + * + * @return final decision made by signer. + */ + public BoxSignerDecision getSignerDecision() { + return this.signerDecision; + } + + /** + * Gets the inputs created by a signer on a sign request. + * + * @return list of inputs created by a signer on a sign request. + */ + public List getInputs() { + return this.inputs; + } + + /** + * Gets the url to direct signer to for signing. + * + * @return url to direct signer to for signing. + */ + public String getEmbedUrl() { + return this.embedUrl; + } + + /** + * Gets the flag that is used in combination with an embed url for a the sender. After the sender + * signs, they will be redirected to the next InPerson signer. + * + * @return true if is in person signer, otherwise false. + */ + public Boolean getInPerson() { + return this.isInPerson; + } + + /** + * Sets the flag that is used in combination with an embed url for a the sender. After the sender + * signs, they will be redirected to the next InPerson signer. + * + * @param isInPerson flag. + * @return this BoxSignRequestSigner object for chaining. + */ + public BoxSignRequestSigner setInPerson(Boolean isInPerson) { + this.isInPerson = isInPerson; + return this; + } + + /** + * Gets the redirect url for the signer. + * + * @return redirect url for the signer. + */ + public String getRedirectUrl() { + return this.redirectUrl; + } + + /** + * Sets the redirect url for the signer. + * + * @param redirectUrl for the signer. + * @return this BoxSignRequestSigner object for chaining. + */ + public BoxSignRequestSigner setRedirectUrl(String redirectUrl) { + this.redirectUrl = redirectUrl; + return this; + } + + /** + * Gets the declined redirect url for the signer. + * + * @return declined redirect url for the signer. + */ + public String getDeclinedRedirectUrl() { + return this.declinedRedirectUrl; + } + + /** + * Sets the declined redirect url for the signer. + * + * @param declinedRedirectUrl for the signer. + * @return this BoxSignRequestSigner object for chaining. + */ + public BoxSignRequestSigner setDeclinedRedirectUrl(String declinedRedirectUrl) { + this.declinedRedirectUrl = declinedRedirectUrl; + return this; + } + + /** + * Gets the URL designed for signing documents within an HTML iframe tag. It will be returned in + * the response only if the embedUrlExternalUserId parameter was passed in the create sign request + * call. + * + * @return url for signing documents within an HTML iframe tag. + */ + public String getIframeableEmedUrl() { + return this.iframeableEmedUrl; + } + + /** + * Sets the URL designed for signing documents within an HTML iframe tag. It will be returned in + * the response only if the embedUrlExternalUserId parameter was passed in the create sign request + * call. + * + * @param iframeableEmedUrl url for signing documents within an HTML iframe tag. + * @return this BoxSignRequestSigner object for chaining. + */ + public BoxSignRequestSigner setIframeableEmedUrl(String iframeableEmedUrl) { + this.iframeableEmedUrl = iframeableEmedUrl; + return this; + } + + /** + * Gets the signer group id. It is sufficient for only one signer from the group to sign the + * document. + * + * @return id of the group to which the sign request will be sent. + */ + public String getSignerGroupId() { + return this.signerGroupId; + } + + /** + * Sets the group id. If specified, signers sharing the same group ID will be assigned to the same + * input. The group ID can be any string value, but it must be consistent across all signers. It + * is sufficient for only one signer from the group to sign the document. + * + * @param signerGroupId id of the group to which the sign request will be sent + * @return this BoxSignRequestSigner object for chaining. + */ + public BoxSignRequestSigner setSignerGroupId(String signerGroupId) { + this.signerGroupId = signerGroupId; + return this; + } + + /** + * If set to true, signer will need to login to a Box account before signing the request. If the + * signer does not have an existing account, they will have an option to create a free Box + * account. + * + * @return true if login is required for the signer, otherwise false. + */ + public Boolean getLoginRequired() { + return this.loginRequired; + } + + /** + * If set to true, signer will need to login to a Box account before signing the request. If the + * signer does not have an existing account, they will have an option to create a free Box + * account. + * + * @param loginRequired indicates if login is required for the signer. + * @return this BoxSignRequestSigner object for chaining. + */ + public BoxSignRequestSigner setLoginRequired(Boolean loginRequired) { + this.loginRequired = loginRequired; + return this; + } + + /** + * If set, the signer is required to enter the password before they are able to sign a document. + * This field is write only. + * + * @return password required for the signer to access the sign request. + */ + public String getPassword() { + return this.password; + } + + /** + * Sets the password required for the signer to access the sign request. + * + * @param password required for the signer to access the sign request. + * @return this BoxSignRequestSigner object for chaining. + */ + public BoxSignRequestSigner setPassword(String password) { + this.password = password; + return this; + } + + /** + * Gets the flag that suppresses email notifications for the signer. + * + * @return true if email notifications are suppressed for the signer, otherwise false. + */ + public Boolean getSuppressNotifications() { + return this.suppressNotifications; + } + + /** + * Sets the flag that suppresses email notifications for the signer. + * + * @param suppressNotifications indicates if email notifications are suppressed for the signer. + * @return this BoxSignRequestSigner object for chaining. + */ + public BoxSignRequestSigner setSuppressNotifications(Boolean suppressNotifications) { + this.suppressNotifications = suppressNotifications; + return this; + } + + /** + * Gets the phone number used for verification. If set, this phone number is be used to verify the + * signer via two factor authentication before they are able to sign the document. + * + * @return phone number used for verification. + */ + public String getVerificationPhoneNumber() { + return this.verificationPhoneNumber; + } + + /** + * Sets the phone number used for verification. If set, this phone number is be used to verify the + * signer via two factor authentication before they are able to sign the document. + * + * @param verificationPhoneNumber phone number used for verification. + * @return this BoxSignRequestSigner object for chaining. + */ + public BoxSignRequestSigner setVerificationPhoneNumber(String verificationPhoneNumber) { + this.verificationPhoneNumber = verificationPhoneNumber; + return this; + } + + /** {@inheritDoc} */ + @Override + void parseJSONMember(JsonObject.Member member) { + JsonValue value = member.getValue(); + String memberName = member.getName(); + try { + switch (memberName) { + case "email": + this.email = value.asString(); + break; + case "role": + this.role = BoxSignRequestSignerRole.fromJSONString(value.asString()); + break; + case "is_in_person": + this.isInPerson = value.asBoolean(); + break; + case "order": + this.order = value.asInt(); + break; + case "embed_url_external_user_id": + this.embedUrlExternalUserId = value.asString(); + break; + case "has_viewed_email": + this.hasViewedEmail = value.asBoolean(); + break; + case "has_viewed_document": + this.hasViewedDocument = value.asBoolean(); + break; + case "signer_decision": + JsonObject signerDecisionJSON = value.asObject(); + this.signerDecision = new BoxSignerDecision(signerDecisionJSON); + break; + case "inputs": + List inputs = new ArrayList<>(); + for (JsonValue inputJSON : value.asArray()) { + BoxSignerInput input = new BoxSignerInput(inputJSON.asObject()); + inputs.add(input); + } + this.inputs = inputs; + break; + case "embed_url": + this.embedUrl = value.asString(); + break; + case "redirect_url": + this.redirectUrl = value.asString(); + break; + case "declined_redirect_url": + this.declinedRedirectUrl = value.asString(); + break; + case "iframeable_embed_url": + this.iframeableEmedUrl = value.asString(); + break; + case "signer_group_id": + this.signerGroupId = value.asString(); + break; + case "login_required": + this.loginRequired = value.asBoolean(); + break; + case "suppress_notifications": + this.suppressNotifications = value.asBoolean(); + break; + case "verification_phone_number": + this.verificationPhoneNumber = value.asString(); + default: + return; + } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); + } + } + + /** + * Gets a JSON object representing this class. + * + * @return the JSON object representing this class. + */ + public JsonObject getJSONObject() { + JsonObject jsonObj = new JsonObject(); + JsonUtils.addIfNotNull(jsonObj, "email", this.email); + JsonUtils.addIfNotNull(jsonObj, "role", this.role); + JsonUtils.addIfNotNull(jsonObj, "is_in_person", this.isInPerson); + JsonUtils.addIfNotNull(jsonObj, "order", this.order); + JsonUtils.addIfNotNull(jsonObj, "embed_url_external_user_id", this.embedUrlExternalUserId); + JsonUtils.addIfNotNull(jsonObj, "redirect_url", this.redirectUrl); + JsonUtils.addIfNotNull(jsonObj, "declined_redirect_url", this.declinedRedirectUrl); + JsonUtils.addIfNotNull(jsonObj, "signer_group_id", this.signerGroupId); + JsonUtils.addIfNotNull(jsonObj, "login_required", this.loginRequired); + JsonUtils.addIfNotNull(jsonObj, "password", this.password); + JsonUtils.addIfNotNull(jsonObj, "suppress_notifications", this.suppressNotifications); + JsonUtils.addIfNotNull(jsonObj, "verification_phone_number", this.verificationPhoneNumber); + return jsonObj; + } + + /** Type of decision made by signer. */ + public enum BoxSignRequestSignerDecisionType { + + /** Signed decision. */ + Signed("signed"), + + /** Declined decision. */ + Declined("declined"); + + private final String jsonValue; + + BoxSignRequestSignerDecisionType(String jsonValue) { + this.jsonValue = jsonValue; + } + + static BoxSignRequestSignerDecisionType fromJSONString(String jsonValue) { + if ("signed".equals(jsonValue)) { + return Signed; + } else if ("declined".equals(jsonValue)) { + return Declined; + } + throw new IllegalArgumentException( + "The provided JSON value isn't a valid " + "BoxSignRequestSignerDecisionType."); + } + } + + /** Represents a type of input. */ + public enum BoxSignRequestInputType { + + /** Signature input. */ + Signature("signature"), + + /** Text input. */ + Text("text"), + + /** Checkbox input. */ + Checkbox("checkbox"), + + /** Date input. */ + Date("date"); + + private final String jsonValue; + + BoxSignRequestInputType(String jsonValue) { + this.jsonValue = jsonValue; + } + + static BoxSignRequestInputType fromJSONString(String jsonValue) { + if ("signature".equals(jsonValue)) { + return Signature; + } else if ("text".equals(jsonValue)) { + return Text; + } else if ("checkbox".equals(jsonValue)) { + return Checkbox; + } else if ("date".equals(jsonValue)) { + return Date; + } + throw new IllegalArgumentException( + "The provided JSON value isn't a valid " + "BoxSignRequestInputType."); + } + } + + /** Represents a content type of input. */ + public enum BoxSignRequestInputContentType { + /** Initial content type */ + Initial("initial"), + /** Stamp content type */ + Stamp("stamp"), + /** Signature content type */ + Signature("signature"), + /** Company content type */ + Company("company"), + /** Title content type */ + Title("title"), + /** Email content type */ + Email("email"), + /** Full name content type */ + FullName("full_name"), + /** First name content type */ + FirstName("first_name"), + /** Last name content type */ + LastName("last_name"), + /** Text content type */ + Text("text"), + /** Date content type */ + Date("date"), + /** Checkbox content type */ + Checkbox("checkbox"); + + private final String jsonValue; + + BoxSignRequestInputContentType(String jsonValue) { + this.jsonValue = jsonValue; + } + + static BoxSignRequestInputContentType fromJSONString(String jsonValue) { + switch (jsonValue) { + case "initial": + return Initial; + case "stamp": + return Stamp; + case "signature": + return Signature; + case "company": + return Company; + case "title": + return Title; + case "email": + return Email; + case "full_name": + return FullName; + case "first_name": + return FirstName; + case "last_name": + return LastName; + case "text": + return Text; + case "date": + return Date; + case "checkbox": + return Checkbox; + default: + throw new IllegalArgumentException( + format( + "The provided JSON value '%s' isn't a valid BoxSignRequestInputContentType.", + jsonValue)); + } + } + } + + /** Represents a final decision made by signer (type and time the decision was made). */ + public class BoxSignerDecision extends BoxJSONObject { + private BoxSignRequestSignerDecisionType type; + private Date finalizedAt; + private String additionalInfo; + + /** + * Constructs a BoxSignerDecision object using an already parsed JSON object. * * @param jsonObject the parsed JSON object. - * @param api the API connection to be used to fetch interacted item - */ - public BoxSignRequestSigner(JsonObject jsonObject, BoxAPIConnection api) { - super(jsonObject); - this.api = api; - } - - /** - * Gets the email address of the signer. - * - * @return email address of the signer. - */ - public String getEmail() { - return this.email; - } - - /** - * Sets the email address of the signer. - * - * @param email address of the signer. - * @return this BoxSignRequestSigner object for chaining. - */ - public BoxSignRequestSigner setEmail(String email) { - this.email = email; - return this; - } - - /** - * Gets the role of the signer. - * - * @return role of the signer. - */ - public BoxSignRequestSignerRole getRole() { - return this.role; - } - - /** - * Sets the role of the signer. If role is not set it's FinalCopyReader by default. - * - * @param role of the signer. - * @return this BoxSignRequestSigner object for chaining. - */ - public BoxSignRequestSigner setRole(BoxSignRequestSignerRole role) { - this.role = role; - return this; - } - - /** - * Gets the flag that when used in combination with an embed url on the sender. After the sender signs, - * they will be redirected to the next InPerson signer. - * - * @return true if is in person signer, otherwise false. - */ - public boolean getIsInPerson() { - return this.isInPerson; - } - - /** - * Gets the order of signer. - * - * @return order of signer. - */ - public int getOrder() { - return this.order; - } - - /** - * Sets the order of signer. - * - * @param order of signer. - * @return this BoxSignRequestSigner object for chaining. - */ - public BoxSignRequestSigner setOrder(Integer order) { - this.order = order; - return this; - } - - /** - * Gets the user id for this signer in external application responsible - * for authentication when accessing the embed url. - * - * @return embed url external user id. */ - public String getEmbedUrlExternalUserId() { - return this.embedUrlExternalUserId; + public BoxSignerDecision(JsonObject jsonObject) { + super(jsonObject); } /** - * Sets the user id for this signer in external application responsible - * for authentication when accessing the embed url. + * Gets the type of decision made by signer. * - * @param embedUrlExternalUserId for this signer in external application responsible - * for authentication when accessing the embed url. - * @return this BoxSignRequestSigner object for chaining. + * @return type of decision made by signer. */ - public BoxSignRequestSigner setEmbedUrlExternalUserId(String embedUrlExternalUserId) { - this.embedUrlExternalUserId = embedUrlExternalUserId; - return this; + public BoxSignRequestSignerDecisionType getType() { + return this.type; } /** - * Gets the flag indicating if signer has viewed the sign request email. + * Gets the date/time that the decision was made. * - * @return true if the signer has viewed the sign request email, otherwise false. + * @return date/time that the decision was made. */ - public boolean getHasViewedEmail() { - return this.hasViewedEmail; + public Date getFinalizedAt() { + return this.finalizedAt; } /** - * Gets the flag indicating if signer has viewed the document. + * Gets the additional info about the decision, such as the decline reason from the signer. * - * @return true if the signer has viewed the document, otherwise false. + * @return additional information about the decision. */ - public boolean getHasViewedDocument() { - return this.hasViewedDocument; + public String getAdditionalInfo() { + return this.additionalInfo; } - /** - * Gets the final decision made by signer. - * - * @return final decision made by signer. - */ - public BoxSignerDecision getSignerDecision() { - return this.signerDecision; - } - - /** - * Gets the inputs created by a signer on a sign request. - * - * @return list of inputs created by a signer on a sign request. - */ - public List getInputs() { - return this.inputs; - } - - /** - * Gets the url to direct signer to for signing. - * - * @return url to direct signer to for signing. - */ - public String getEmbedUrl() { - return this.embedUrl; - } - - /** - * Gets the flag that is used in combination with an embed url for a the sender. After the sender signs, - * they will be redirected to the next InPerson signer. - * - * @return true if is in person signer, otherwise false. - */ - public Boolean getInPerson() { - return this.isInPerson; - } - - /** - * Sets the flag that is used in combination with an embed url for a the sender. After the sender signs, - * they will be redirected to the next InPerson signer. - * - * @param isInPerson flag. - * @return this BoxSignRequestSigner object for chaining. - */ - public BoxSignRequestSigner setInPerson(Boolean isInPerson) { - this.isInPerson = isInPerson; - return this; - } - - /** - * Gets the redirect url for the signer. - * - * @return redirect url for the signer. - */ - public String getRedirectUrl() { - return this.redirectUrl; - } - - /** - * Sets the redirect url for the signer. - * - * @param redirectUrl for the signer. - * @return this BoxSignRequestSigner object for chaining. - */ - public BoxSignRequestSigner setRedirectUrl(String redirectUrl) { - this.redirectUrl = redirectUrl; - return this; - } - - /** - * Gets the declined redirect url for the signer. - * - * @return declined redirect url for the signer. - */ - public String getDeclinedRedirectUrl() { - return this.declinedRedirectUrl; - } - - /** - * Sets the declined redirect url for the signer. - * - * @param declinedRedirectUrl for the signer. - * @return this BoxSignRequestSigner object for chaining. - */ - public BoxSignRequestSigner setDeclinedRedirectUrl(String declinedRedirectUrl) { - this.declinedRedirectUrl = declinedRedirectUrl; - return this; - } - - /** - * Gets the URL designed for signing documents within an HTML iframe tag. - * It will be returned in the response only if the embedUrlExternalUserId parameter was passed - * in the create sign request call. - * - * @return url for signing documents within an HTML iframe tag. - */ - public String getIframeableEmedUrl() { - return this.iframeableEmedUrl; - } - - /** - * Sets the URL designed for signing documents within an HTML iframe tag. - * It will be returned in the response only if the embedUrlExternalUserId parameter was passed - * in the create sign request call. - * - * @param iframeableEmedUrl url for signing documents within an HTML iframe tag. - * @return this BoxSignRequestSigner object for chaining. - */ - public BoxSignRequestSigner setIframeableEmedUrl(String iframeableEmedUrl) { - this.iframeableEmedUrl = iframeableEmedUrl; - return this; - } - - /** - * Gets the signer group id. It is sufficient for only one signer from the group to sign the document. - * - * @return id of the group to which the sign request will be sent. - */ - public String getSignerGroupId() { - return this.signerGroupId; + /** {@inheritDoc} */ + @Override + void parseJSONMember(JsonObject.Member member) { + JsonValue value = member.getValue(); + String memberName = member.getName(); + try { + if (memberName.equals("type")) { + this.type = BoxSignRequestSignerDecisionType.fromJSONString(value.asString()); + } else if (memberName.equals("finalized_at")) { + this.finalizedAt = BoxDateFormat.parse(value.asString()); + } else if (memberName.equals("additional_info")) { + this.additionalInfo = value.asString(); + } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); + } } + } - /** - * Sets the group id. If specified, signers sharing the same group ID will be assigned to the same input. - * The group ID can be any string value, but it must be consistent across all signers. - * It is sufficient for only one signer from the group to sign the document. - * - * @param signerGroupId id of the group to which the sign request will be sent - * @return this BoxSignRequestSigner object for chaining. - */ - public BoxSignRequestSigner setSignerGroupId(String signerGroupId) { - this.signerGroupId = signerGroupId; - return this; - } + /** Represents an input created by a signer on a sign request. */ + public class BoxSignerInput extends BoxJSONObject { + private String documentTagId; + private String textValue; + private boolean checkboxValue; + private BoxSignRequestInputContentType contentType; + private Date dateValue; + private BoxSignRequestInputType type; + private int pageIndex; /** - * If set to true, signer will need to login to a Box account before signing the request. - * If the signer does not have an existing account, they will have an option to create a free Box account. + * Constructs a BoxSignerInput object using an already parsed JSON object. * - * @return true if login is required for the signer, otherwise false. + * @param jsonObject the parsed JSON object. */ - public Boolean getLoginRequired() { - return this.loginRequired; + public BoxSignerInput(JsonObject jsonObject) { + super(jsonObject); } /** - * If set to true, signer will need to login to a Box account before signing the request. - * If the signer does not have an existing account, they will have an option to create a free Box account. + * Gets the reference of the id of a particular tag added to the content of the files being used + * to create the sign request. * - * @param loginRequired indicates if login is required for the signer. - * @return this BoxSignRequestSigner object for chaining. + * @return document tag id. */ - public BoxSignRequestSigner setLoginRequired(Boolean loginRequired) { - this.loginRequired = loginRequired; - return this; + public String getDocumentTagId() { + return this.documentTagId; } /** - * If set, the signer is required to enter the password before they are able to sign a document. - * This field is write only. + * Gets the text prefill value. * - * @return password required for the signer to access the sign request. + * @return text prefill value. */ - public String getPassword() { - return this.password; + public String getTextValue() { + return this.textValue; } /** - * Sets the password required for the signer to access the sign request. + * Gets the checkbox prefill value. * - * @param password required for the signer to access the sign request. - * @return this BoxSignRequestSigner object for chaining. + * @return checkbox prefill value. */ - public BoxSignRequestSigner setPassword(String password) { - this.password = password; - return this; + public boolean getIsCheckboxValue() { + return this.checkboxValue; } /** - * Gets the flag that suppresses email notifications for the signer. + * Gets the content type of the input. * - * @return true if email notifications are suppressed for the signer, otherwise false. + * @return content type of the input. */ - public Boolean getSuppressNotifications() { - return this.suppressNotifications; + public BoxSignRequestInputContentType getContentType() { + return this.contentType; } /** - * Sets the flag that suppresses email notifications for the signer. + * Gets the date prefill value. * - * @param suppressNotifications indicates if email notifications are suppressed for the signer. - * @return this BoxSignRequestSigner object for chaining. + * @return date prefill value. */ - public BoxSignRequestSigner setSuppressNotifications(Boolean suppressNotifications) { - this.suppressNotifications = suppressNotifications; - return this; + public Date getDateValue() { + return this.dateValue; } /** - * Gets the phone number used for verification. - * If set, this phone number is be used to verify the signer via two factor authentication - * before they are able to sign the document. + * Gets the type of input. * - * @return phone number used for verification. + * @return type of input. */ - public String getVerificationPhoneNumber() { - return this.verificationPhoneNumber; + public BoxSignRequestInputType getType() { + return this.type; } /** - * Sets the phone number used for verification. - * If set, this phone number is be used to verify the signer via two factor authentication - * before they are able to sign the document. + * Gets the index of page that input is on. * - * @param verificationPhoneNumber phone number used for verification. - * @return this BoxSignRequestSigner object for chaining. + * @return index of page that input is on. */ - public BoxSignRequestSigner setVerificationPhoneNumber(String verificationPhoneNumber) { - this.verificationPhoneNumber = verificationPhoneNumber; - return this; + public int getPageIndex() { + return this.pageIndex; } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override void parseJSONMember(JsonObject.Member member) { - JsonValue value = member.getValue(); - String memberName = member.getName(); - try { - switch (memberName) { - case "email": - this.email = value.asString(); - break; - case "role": - this.role = BoxSignRequestSignerRole.fromJSONString(value.asString()); - break; - case "is_in_person": - this.isInPerson = value.asBoolean(); - break; - case "order": - this.order = value.asInt(); - break; - case "embed_url_external_user_id": - this.embedUrlExternalUserId = value.asString(); - break; - case "has_viewed_email": - this.hasViewedEmail = value.asBoolean(); - break; - case "has_viewed_document": - this.hasViewedDocument = value.asBoolean(); - break; - case "signer_decision": - JsonObject signerDecisionJSON = value.asObject(); - this.signerDecision = new BoxSignerDecision(signerDecisionJSON); - break; - case "inputs": - List inputs = new ArrayList<>(); - for (JsonValue inputJSON : value.asArray()) { - BoxSignerInput input = new BoxSignerInput(inputJSON.asObject()); - inputs.add(input); - } - this.inputs = inputs; - break; - case "embed_url": - this.embedUrl = value.asString(); - break; - case "redirect_url": - this.redirectUrl = value.asString(); - break; - case "declined_redirect_url": - this.declinedRedirectUrl = value.asString(); - break; - case "iframeable_embed_url": - this.iframeableEmedUrl = value.asString(); - break; - case "signer_group_id": - this.signerGroupId = value.asString(); - break; - case "login_required": - this.loginRequired = value.asBoolean(); - break; - case "suppress_notifications": - this.suppressNotifications = value.asBoolean(); - break; - case "verification_phone_number": - this.verificationPhoneNumber = value.asString(); - default: - return; - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); - } - } - - /** - * Gets a JSON object representing this class. - * - * @return the JSON object representing this class. - */ - public JsonObject getJSONObject() { - JsonObject jsonObj = new JsonObject(); - JsonUtils.addIfNotNull(jsonObj, "email", this.email); - JsonUtils.addIfNotNull(jsonObj, "role", this.role); - JsonUtils.addIfNotNull(jsonObj, "is_in_person", this.isInPerson); - JsonUtils.addIfNotNull(jsonObj, "order", this.order); - JsonUtils.addIfNotNull(jsonObj, "embed_url_external_user_id", this.embedUrlExternalUserId); - JsonUtils.addIfNotNull(jsonObj, "redirect_url", this.redirectUrl); - JsonUtils.addIfNotNull(jsonObj, "declined_redirect_url", this.declinedRedirectUrl); - JsonUtils.addIfNotNull(jsonObj, "signer_group_id", this.signerGroupId); - JsonUtils.addIfNotNull(jsonObj, "login_required", this.loginRequired); - JsonUtils.addIfNotNull(jsonObj, "password", this.password); - JsonUtils.addIfNotNull(jsonObj, "suppress_notifications", this.suppressNotifications); - JsonUtils.addIfNotNull(jsonObj, "verification_phone_number", this.verificationPhoneNumber); - return jsonObj; - } - - /** - * Type of decision made by signer. - */ - public enum BoxSignRequestSignerDecisionType { - - /** - * Signed decision. - */ - Signed("signed"), - - /** - * Declined decision. - */ - Declined("declined"); - - private final String jsonValue; - - BoxSignRequestSignerDecisionType(String jsonValue) { - this.jsonValue = jsonValue; - } - - static BoxSignRequestSignerDecisionType fromJSONString(String jsonValue) { - if ("signed".equals(jsonValue)) { - return Signed; - } else if ("declined".equals(jsonValue)) { - return Declined; - } - throw new IllegalArgumentException( - "The provided JSON value isn't a valid " + "BoxSignRequestSignerDecisionType."); - } - } - - /** - * Represents a type of input. - */ - public enum BoxSignRequestInputType { - - /** - * Signature input. - */ - Signature("signature"), - - /** - * Text input. - */ - Text("text"), - - /** - * Checkbox input. - */ - Checkbox("checkbox"), - - /** - * Date input. - */ - Date("date"); - - private final String jsonValue; - - BoxSignRequestInputType(String jsonValue) { - this.jsonValue = jsonValue; - } - - static BoxSignRequestInputType fromJSONString(String jsonValue) { - if ("signature".equals(jsonValue)) { - return Signature; - } else if ("text".equals(jsonValue)) { - return Text; - } else if ("checkbox".equals(jsonValue)) { - return Checkbox; - } else if ("date".equals(jsonValue)) { - return Date; - } - throw new IllegalArgumentException("The provided JSON value isn't a valid " + "BoxSignRequestInputType."); - } - } - - /** - * Represents a content type of input. - */ - public enum BoxSignRequestInputContentType { - /** - * Initial content type - */ - Initial("initial"), - /** - * Stamp content type - */ - Stamp("stamp"), - /** - * Signature content type - */ - Signature("signature"), - /** - * Company content type - */ - Company("company"), - /** - * Title content type - */ - Title("title"), - /** - * Email content type - */ - Email("email"), - /** - * Full name content type - */ - FullName("full_name"), - /** - * First name content type - */ - FirstName("first_name"), - /** - * Last name content type - */ - LastName("last_name"), - /** - * Text content type - */ - Text("text"), - /** - * Date content type - */ - Date("date"), - /** - * Checkbox content type - */ - Checkbox("checkbox"); - - private final String jsonValue; - - BoxSignRequestInputContentType(String jsonValue) { - this.jsonValue = jsonValue; - } - - static BoxSignRequestInputContentType fromJSONString(String jsonValue) { - switch (jsonValue) { - case "initial": - return Initial; - case "stamp": - return Stamp; - case "signature": - return Signature; - case "company": - return Company; - case "title": - return Title; - case "email": - return Email; - case "full_name": - return FullName; - case "first_name": - return FirstName; - case "last_name": - return LastName; - case "text": - return Text; - case "date": - return Date; - case "checkbox": - return Checkbox; - default: - throw new IllegalArgumentException( - format("The provided JSON value '%s' isn't a valid BoxSignRequestInputContentType.", jsonValue) - ); - } - } - } - - /** - * Represents a final decision made by signer (type and time the decision was made). - */ - public class BoxSignerDecision extends BoxJSONObject { - private BoxSignRequestSignerDecisionType type; - private Date finalizedAt; - private String additionalInfo; - - /** - * Constructs a BoxSignerDecision object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - public BoxSignerDecision(JsonObject jsonObject) { - super(jsonObject); - } - - /** - * Gets the type of decision made by signer. - * - * @return type of decision made by signer. - */ - public BoxSignRequestSignerDecisionType getType() { - return this.type; - } - - /** - * Gets the date/time that the decision was made. - * - * @return date/time that the decision was made. - */ - public Date getFinalizedAt() { - return this.finalizedAt; - } - - /** - * Gets the additional info about the decision, such as the decline reason from the signer. - * - * @return additional information about the decision. - */ - public String getAdditionalInfo() { - return this.additionalInfo; - } - - /** - * {@inheritDoc} - */ - @Override - void parseJSONMember(JsonObject.Member member) { - JsonValue value = member.getValue(); - String memberName = member.getName(); - try { - if (memberName.equals("type")) { - this.type = BoxSignRequestSignerDecisionType.fromJSONString(value.asString()); - } else if (memberName.equals("finalized_at")) { - this.finalizedAt = BoxDateFormat.parse(value.asString()); - } else if (memberName.equals("additional_info")) { - this.additionalInfo = value.asString(); - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); - } - } - } - - /** - * Represents an input created by a signer on a sign request. - */ - public class BoxSignerInput extends BoxJSONObject { - private String documentTagId; - private String textValue; - private boolean checkboxValue; - private BoxSignRequestInputContentType contentType; - private Date dateValue; - private BoxSignRequestInputType type; - private int pageIndex; - - /** - * Constructs a BoxSignerInput object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - public BoxSignerInput(JsonObject jsonObject) { - super(jsonObject); - } - - /** - * Gets the reference of the id of a particular tag added to the content - * of the files being used to create the sign request. - * - * @return document tag id. - */ - public String getDocumentTagId() { - return this.documentTagId; - } - - /** - * Gets the text prefill value. - * - * @return text prefill value. - */ - public String getTextValue() { - return this.textValue; - } - - /** - * Gets the checkbox prefill value. - * - * @return checkbox prefill value. - */ - public boolean getIsCheckboxValue() { - return this.checkboxValue; - } - - /** - * Gets the content type of the input. - * - * @return content type of the input. - */ - public BoxSignRequestInputContentType getContentType() { - return this.contentType; - } - - /** - * Gets the date prefill value. - * - * @return date prefill value. - */ - public Date getDateValue() { - return this.dateValue; - } - - /** - * Gets the type of input. - * - * @return type of input. - */ - public BoxSignRequestInputType getType() { - return this.type; - } - - /** - * Gets the index of page that input is on. - * - * @return index of page that input is on. - */ - public int getPageIndex() { - return this.pageIndex; - } - - /** - * {@inheritDoc} - */ - @Override - void parseJSONMember(JsonObject.Member member) { - JsonValue value = member.getValue(); - String memberName = member.getName(); - try { - switch (memberName) { - case "documentTagId": - this.documentTagId = value.asString(); - break; - case "text_value": - this.textValue = value.asString(); - break; - case "checkbox_value": - this.checkboxValue = value.asBoolean(); - break; - case "content_type": - this.contentType = BoxSignRequestInputContentType.fromJSONString(value.asString()); - break; - case "date_value": - this.dateValue = BoxDateFormat.parseDateOnly(value.asString()); - break; - case "type": - this.type = BoxSignRequestInputType.fromJSONString(value.asString()); - break; - case "page_index": - this.pageIndex = value.asInt(); - break; - default: - return; - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); - } + JsonValue value = member.getValue(); + String memberName = member.getName(); + try { + switch (memberName) { + case "documentTagId": + this.documentTagId = value.asString(); + break; + case "text_value": + this.textValue = value.asString(); + break; + case "checkbox_value": + this.checkboxValue = value.asBoolean(); + break; + case "content_type": + this.contentType = BoxSignRequestInputContentType.fromJSONString(value.asString()); + break; + case "date_value": + this.dateValue = BoxDateFormat.parseDateOnly(value.asString()); + break; + case "type": + this.type = BoxSignRequestInputType.fromJSONString(value.asString()); + break; + case "page_index": + this.pageIndex = value.asInt(); + break; + default: + return; } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); + } } + } } - - diff --git a/src/main/java/com/box/sdk/BoxSignRequestSignerRole.java b/src/main/java/com/box/sdk/BoxSignRequestSignerRole.java index c0ae8f644..8d5b2dcc8 100644 --- a/src/main/java/com/box/sdk/BoxSignRequestSignerRole.java +++ b/src/main/java/com/box/sdk/BoxSignRequestSignerRole.java @@ -2,40 +2,35 @@ /** * Defines the role of the signer in the sign request. Signers will need to sign the document, - * Approvers may just approve the document. - * Finally, FinalCopyReader will only receive the finished sign request with a sign log. + * Approvers may just approve the document. Finally, FinalCopyReader will only receive the finished + * sign request with a sign log. */ public enum BoxSignRequestSignerRole { - /** - * Signer role. Needs to sign the document. - */ - Signer("signer"), + /** Signer role. Needs to sign the document. */ + Signer("signer"), - /** - * Approver role. Approves the document. - */ - Approver("approver"), + /** Approver role. Approves the document. */ + Approver("approver"), - /** - * Final copy reader role. Receives finished sign request with sign log. - */ - FinalCopyReader("final_copy_reader"); + /** Final copy reader role. Receives finished sign request with sign log. */ + FinalCopyReader("final_copy_reader"); - private final String jsonValue; + private final String jsonValue; - BoxSignRequestSignerRole(String jsonValue) { - this.jsonValue = jsonValue; - } + BoxSignRequestSignerRole(String jsonValue) { + this.jsonValue = jsonValue; + } - static BoxSignRequestSignerRole fromJSONString(String jsonValue) { - if ("signer".equals(jsonValue)) { - return Signer; - } else if ("approver".equals(jsonValue)) { - return Approver; - } else if ("final_copy_reader".equals(jsonValue)) { - return FinalCopyReader; - } - throw new IllegalArgumentException("The provided JSON value isn't a valid BoxSignRequestSignerRole."); + static BoxSignRequestSignerRole fromJSONString(String jsonValue) { + if ("signer".equals(jsonValue)) { + return Signer; + } else if ("approver".equals(jsonValue)) { + return Approver; + } else if ("final_copy_reader".equals(jsonValue)) { + return FinalCopyReader; } + throw new IllegalArgumentException( + "The provided JSON value isn't a valid BoxSignRequestSignerRole."); + } } diff --git a/src/main/java/com/box/sdk/BoxSignTemplate.java b/src/main/java/com/box/sdk/BoxSignTemplate.java index 5a535bd79..c644eb7e4 100644 --- a/src/main/java/com/box/sdk/BoxSignTemplate.java +++ b/src/main/java/com/box/sdk/BoxSignTemplate.java @@ -7,408 +7,395 @@ import java.util.ArrayList; import java.util.List; - /** * Represents a Sign Template used in the Box Sign API. * - * @see Box Sign Templates - * - *

Unless otherwise noted, the methods in this class can throw an unchecked {@link BoxAPIException} (unchecked - * meaning that the compiler won't force you to handle it) if an error occurs. If you wish to implement custom error - * handling for errors related to the Box REST API, you should capture this exception explicitly.

+ * @see Box Sign + * Templates + *

Unless otherwise noted, the methods in this class can throw an unchecked {@link + * BoxAPIException} (unchecked meaning that the compiler won't force you to handle it) if an + * error occurs. If you wish to implement custom error handling for errors related to the Box + * REST API, you should capture this exception explicitly. */ @BoxResourceType("sign_template") public class BoxSignTemplate extends BoxResource { + /** The URL template for Sign Templates. */ + public static final URLTemplate SIGN_TEMPLATES_URL_TEMPLATE = new URLTemplate("sign_templates"); + + /** The URL template for Sign Templates operations with a given ID. */ + public static final URLTemplate SIGN_TEMPLATE_URL_TEMPLATE = new URLTemplate("sign_templates/%s"); + + /** The default limit of entries per response. */ + public static final int DEFAULT_LIMIT = 100; + + /** + * Constructs a BoxSignTemplate for a resource with a given ID. + * + * @param api the API connection to be used by the resource. + * @param id the ID of the resource. + */ + public BoxSignTemplate(BoxAPIConnection api, String id) { + super(api, id); + } + + /** + * Return all Sign Templates. + * + * @param api the API connection to be used by the resource. + * @return an iterable with all Sign Templates. + */ + public static Iterable getAll(BoxAPIConnection api) { + return getAll(api, DEFAULT_LIMIT); + } + + /** + * Return all Sign Templates. + * + * @param api the API connection to be used by the resource. + * @param limit the limit of entries per response. + * @return an iterable with all Sign Templates. + */ + public static Iterable getAll(BoxAPIConnection api, int limit) { + QueryStringBuilder builder = new QueryStringBuilder(); + URL url = SIGN_TEMPLATES_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString()); + return new BoxResourceIterable(api, url, limit) { + + @Override + protected BoxSignTemplate.Info factory(JsonObject jsonObject) { + BoxSignTemplate template = new BoxSignTemplate(api, jsonObject.get("id").asString()); + return template.new Info(jsonObject); + } + }; + } + + /** + * Return information about this Sign Template. + * + * @return information about this Sign Template. + */ + public BoxSignTemplate.Info getInfo() { + URL url = SIGN_TEMPLATE_URL_TEMPLATE.buildAlpha(this.getAPI().getBaseURL(), this.getID()); + BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); + try (BoxJSONResponse response = (BoxJSONResponse) request.send()) { + JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); + return new Info(jsonObject); + } + } + + /** Contains information about a BoxSignTemplate. */ + public class Info extends BoxResource.Info { + + private BoxSignTemplateAdditionalInfo additionalInfo; + private boolean areEmailSettingsLocked; + private boolean areFieldsLocked; + private boolean areOptionsLocked; + private boolean areFilesLocked; + private boolean areRecipientsLocked; + private BoxSignTemplateCustomBranding customBranding; + private Integer daysValid; + private String emailMessage; + private String emailSubject; + private String name; + private BoxFolder.Info parentFolder; + private BoxSignTemplateReadySignLink readySignLink; + private List signers; + private List sourceFiles; + + /** Constructs an empty Info object. */ + public Info() { + super(); + } + /** - * The URL template for Sign Templates. + * Constructs an Info object with the provided JSON string. + * + * @param json the JSON string representing the Sign Template. */ - public static final URLTemplate SIGN_TEMPLATES_URL_TEMPLATE = new URLTemplate("sign_templates"); + public Info(String json) { + super(json); + } /** - * The URL template for Sign Templates operations with a given ID. + * Constructs an Info object with the provided JSON object. + * + * @param jsonObject the JSON object representing the Sign Template. */ - public static final URLTemplate SIGN_TEMPLATE_URL_TEMPLATE = new URLTemplate("sign_templates/%s"); + Info(JsonObject jsonObject) { + super(jsonObject); + } + + /** {@inheritDoc} */ + @Override + public BoxSignTemplate getResource() { + return BoxSignTemplate.this; + } /** - * The default limit of entries per response. + * Gets the additional information about this Sign Template. + * + * @return the additional information about this Sign Template. */ - public static final int DEFAULT_LIMIT = 100; + public BoxSignTemplateAdditionalInfo getAdditionalInfo() { + return this.additionalInfo; + } /** - * Constructs a BoxSignTemplate for a resource with a given ID. + * Gets whether the templates email settings are editable or not. * - * @param api the API connection to be used by the resource. - * @param id the ID of the resource. + * @return true if the email settings are locked; otherwise false. */ - public BoxSignTemplate(BoxAPIConnection api, String id) { - super(api, id); + public boolean getAreEmailSettingsLocked() { + return this.areEmailSettingsLocked; } /** - * Return all Sign Templates. + * Gets whether the templates input fields are editable or not. This includes deleting or + * renaming template files. * - * @param api the API connection to be used by the resource. - * @return an iterable with all Sign Templates. + * @return true if the fields are locked; otherwise false. */ - public static Iterable getAll(BoxAPIConnection api) { - return getAll(api, DEFAULT_LIMIT); + public boolean getAreFieldsLocked() { + return this.areFieldsLocked; } /** - * Return all Sign Templates. + * Gets weather the templates input options are editable or not. * - * @param api the API connection to be used by the resource. - * @param limit the limit of entries per response. - * @return an iterable with all Sign Templates. + * @return true if the options are editable; otherwise false. */ - public static Iterable getAll(BoxAPIConnection api, int limit) { - QueryStringBuilder builder = new QueryStringBuilder(); - URL url = SIGN_TEMPLATES_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString()); - return new BoxResourceIterable(api, url, limit) { - - @Override - protected BoxSignTemplate.Info factory(JsonObject jsonObject) { - BoxSignTemplate template = new BoxSignTemplate(api, jsonObject.get("id").asString()); - return template.new Info(jsonObject); - } - }; - + public boolean getAreOptionsLocked() { + return this.areOptionsLocked; } /** - * Return information about this Sign Template. + * Gets whether the template document options are editable or not, for example renaming the + * document. * - * @return information about this Sign Template. + * @return true if the files are locked; otherwise false. */ - public BoxSignTemplate.Info getInfo() { - URL url = SIGN_TEMPLATE_URL_TEMPLATE.buildAlpha(this.getAPI().getBaseURL(), this.getID()); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); - try (BoxJSONResponse response = (BoxJSONResponse) request.send()) { - JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - return new Info(jsonObject); - } + public boolean getAreFilesLocked() { + return this.areFilesLocked; } /** - * Contains information about a BoxSignTemplate. + * Gets whether the template signers are editable or not. + * + * @return true if the recipients are locked; otherwise false. */ - public class Info extends BoxResource.Info { - - private BoxSignTemplateAdditionalInfo additionalInfo; - private boolean areEmailSettingsLocked; - private boolean areFieldsLocked; - private boolean areOptionsLocked; - private boolean areFilesLocked; - private boolean areRecipientsLocked; - private BoxSignTemplateCustomBranding customBranding; - private Integer daysValid; - private String emailMessage; - private String emailSubject; - private String name; - private BoxFolder.Info parentFolder; - private BoxSignTemplateReadySignLink readySignLink; - private List signers; - private List sourceFiles; - - /** - * Constructs an empty Info object. - */ - public Info() { - super(); - } - - /** - * Constructs an Info object with the provided JSON string. - * - * @param json the JSON string representing the Sign Template. - */ - public Info(String json) { - super(json); - } - - /** - * Constructs an Info object with the provided JSON object. - * - * @param jsonObject the JSON object representing the Sign Template. - */ - Info(JsonObject jsonObject) { - super(jsonObject); - } - - /** - * {@inheritDoc} - */ - @Override - public BoxSignTemplate getResource() { - return BoxSignTemplate.this; - } - - /** - * Gets the additional information about this Sign Template. - * - * @return the additional information about this Sign Template. - */ - public BoxSignTemplateAdditionalInfo getAdditionalInfo() { - return this.additionalInfo; - } - - /** - * Gets whether the templates email settings are editable or not. - * - * @return true if the email settings are locked; otherwise false. - */ - public boolean getAreEmailSettingsLocked() { - return this.areEmailSettingsLocked; - } - - /** - * Gets whether the templates input fields are editable or not. - * This includes deleting or renaming template files. - * - * @return true if the fields are locked; otherwise false. - */ - public boolean getAreFieldsLocked() { - return this.areFieldsLocked; - } - - /** - * Gets weather the templates input options are editable or not. - * - * @return true if the options are editable; otherwise false. - */ - public boolean getAreOptionsLocked() { - return this.areOptionsLocked; - } - - /** - * Gets whether the template document options are editable or not, - * for example renaming the document. - * - * @return true if the files are locked; otherwise false. - */ - public boolean getAreFilesLocked() { - return this.areFilesLocked; - } - - /** - * Gets whether the template signers are editable or not. - * - * @return true if the recipients are locked; otherwise false. - */ - public boolean getAreRecipientsLocked() { - return this.areRecipientsLocked; - } + public boolean getAreRecipientsLocked() { + return this.areRecipientsLocked; + } - /** - * Gets the custom branding applied to notifications and signature requests. - * - * @return the custom branding for this Sign Template. - */ - public BoxSignTemplateCustomBranding getCustomBranding() { - return this.customBranding; - } + /** + * Gets the custom branding applied to notifications and signature requests. + * + * @return the custom branding for this Sign Template. + */ + public BoxSignTemplateCustomBranding getCustomBranding() { + return this.customBranding; + } - /** - * Gets the number of days after which the created signature request - * will automatically expire if not completed. - * By default, we do not apply any expiration date on signature requests, - * and the signature request does not expire. - * - * @return the number of days the template is valid for. - */ - public Integer getDaysValid() { - return this.daysValid; - } + /** + * Gets the number of days after which the created signature request will automatically expire + * if not completed. By default, we do not apply any expiration date on signature requests, and + * the signature request does not expire. + * + * @return the number of days the template is valid for. + */ + public Integer getDaysValid() { + return this.daysValid; + } - /** - * Gets the email message that will be sent to all signers. - * - * @return the email message for this Sign Template. - */ - public String getEmailMessage() { - return this.emailMessage; - } + /** + * Gets the email message that will be sent to all signers. + * + * @return the email message for this Sign Template. + */ + public String getEmailMessage() { + return this.emailMessage; + } - /** - * Gets the email subject that will be sent to all signers. - * - * @return the email subject for this Sign Template. - */ - public String getEmailSubject() { - return this.emailSubject; - } + /** + * Gets the email subject that will be sent to all signers. + * + * @return the email subject for this Sign Template. + */ + public String getEmailSubject() { + return this.emailSubject; + } - /** - * Gets the name of this Sign Template. - * - * @return the name of this Sign Template. - */ - public String getName() { - return this.name; - } + /** + * Gets the name of this Sign Template. + * + * @return the name of this Sign Template. + */ + public String getName() { + return this.name; + } - /** - * Gets the parent folder of this Sign Template. - * - * @return the parent folder of this Sign Template. - */ - public BoxFolder.Info getParentFolder() { - return this.parentFolder; - } + /** + * Gets the parent folder of this Sign Template. + * + * @return the parent folder of this Sign Template. + */ + public BoxFolder.Info getParentFolder() { + return this.parentFolder; + } - /** - * Gets the ready sign link for this Sign Template. - * - * @return the ready sign link for this Sign Template. - */ - public BoxSignTemplateReadySignLink getReadySignLink() { - return this.readySignLink; - } + /** + * Gets the ready sign link for this Sign Template. + * + * @return the ready sign link for this Sign Template. + */ + public BoxSignTemplateReadySignLink getReadySignLink() { + return this.readySignLink; + } - /** - * Gets the signers for this Sign Template. - * - * @return the signers for this Sign Template. - */ - public List getSigners() { - return this.signers; - } + /** + * Gets the signers for this Sign Template. + * + * @return the signers for this Sign Template. + */ + public List getSigners() { + return this.signers; + } - /** - * Gets the source files for this Sign Template. - * - * @return the source files for this Sign Template. - */ - public List getSourceFiles() { - return this.sourceFiles; - } + /** + * Gets the source files for this Sign Template. + * + * @return the source files for this Sign Template. + */ + public List getSourceFiles() { + return this.sourceFiles; + } - /** - * {@inheritDoc} - */ - @Override - void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - String memberName = member.getName(); - JsonValue value = member.getValue(); - try { - switch (memberName) { - case "additional_info": - this.additionalInfo = this.parseAdditionalInfo(value.asObject()); - break; - case "are_email_settings_locked": - this.areEmailSettingsLocked = value.asBoolean(); - break; - case "are_fields_locked": - this.areFieldsLocked = value.asBoolean(); - break; - case "are_options_locked": - this.areOptionsLocked = value.asBoolean(); - break; - case "are_files_locked": - this.areFilesLocked = value.asBoolean(); - break; - case "are_recipients_locked": - this.areRecipientsLocked = value.asBoolean(); - break; - case "custom_branding": - this.customBranding = this.parseCustomBranding(value.asObject()); - break; - case "days_valid": - this.daysValid = value.asInt(); - break; - case "email_message": - this.emailMessage = value.asString(); - break; - case "email_subject": - this.emailSubject = value.asString(); - break; - case "name": - this.name = value.asString(); - break; - case "parent_folder": - JsonObject parentFolderJSON = value.asObject(); - String parentFolderID = parentFolderJSON.get("id").asString(); - BoxFolder parentFolder = new BoxFolder(getAPI(), parentFolderID); - this.parentFolder = parentFolder.new Info(parentFolderJSON); - break; - case "ready_sign_link": - this.readySignLink = this.parseReadySignLink(value.asObject()); - break; - case "signers": - this.signers = this.parseSigners(value.asArray()); - break; - case "source_files": - this.sourceFiles = this.parseSourceFiles(value.asArray()); - break; - default: - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); - } + /** {@inheritDoc} */ + @Override + void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + String memberName = member.getName(); + JsonValue value = member.getValue(); + try { + switch (memberName) { + case "additional_info": + this.additionalInfo = this.parseAdditionalInfo(value.asObject()); + break; + case "are_email_settings_locked": + this.areEmailSettingsLocked = value.asBoolean(); + break; + case "are_fields_locked": + this.areFieldsLocked = value.asBoolean(); + break; + case "are_options_locked": + this.areOptionsLocked = value.asBoolean(); + break; + case "are_files_locked": + this.areFilesLocked = value.asBoolean(); + break; + case "are_recipients_locked": + this.areRecipientsLocked = value.asBoolean(); + break; + case "custom_branding": + this.customBranding = this.parseCustomBranding(value.asObject()); + break; + case "days_valid": + this.daysValid = value.asInt(); + break; + case "email_message": + this.emailMessage = value.asString(); + break; + case "email_subject": + this.emailSubject = value.asString(); + break; + case "name": + this.name = value.asString(); + break; + case "parent_folder": + JsonObject parentFolderJSON = value.asObject(); + String parentFolderID = parentFolderJSON.get("id").asString(); + BoxFolder parentFolder = new BoxFolder(getAPI(), parentFolderID); + this.parentFolder = parentFolder.new Info(parentFolderJSON); + break; + case "ready_sign_link": + this.readySignLink = this.parseReadySignLink(value.asObject()); + break; + case "signers": + this.signers = this.parseSigners(value.asArray()); + break; + case "source_files": + this.sourceFiles = this.parseSourceFiles(value.asArray()); + break; + default: } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); + } + } - private BoxSignTemplateAdditionalInfo parseAdditionalInfo(JsonValue additionalInfoJSON) { - List nonEditableFields = new ArrayList(); - for (JsonValue fieldJSON : additionalInfoJSON.asObject().get("non_editable").asArray()) { - nonEditableFields.add(fieldJSON.asString()); - } - BoxSignTemplateAdditionalInfoRequired required = this.parseAdditionalInfoRequired( - additionalInfoJSON.asObject().get("required").asObject() - ); - return new BoxSignTemplateAdditionalInfo(nonEditableFields, required); - } + private BoxSignTemplateAdditionalInfo parseAdditionalInfo(JsonValue additionalInfoJSON) { + List nonEditableFields = new ArrayList(); + for (JsonValue fieldJSON : additionalInfoJSON.asObject().get("non_editable").asArray()) { + nonEditableFields.add(fieldJSON.asString()); + } + BoxSignTemplateAdditionalInfoRequired required = + this.parseAdditionalInfoRequired( + additionalInfoJSON.asObject().get("required").asObject()); + return new BoxSignTemplateAdditionalInfo(nonEditableFields, required); + } - private BoxSignTemplateAdditionalInfoRequired parseAdditionalInfoRequired(JsonObject requiredJSON) { - List> signers = new ArrayList>(); - for (JsonValue signerJSON : requiredJSON.get("signers").asArray()) { - List signer = new ArrayList(); - for (JsonValue fieldJSON : signerJSON.asArray()) { - signer.add(fieldJSON.asString()); - } - signers.add(signer); - } - return new BoxSignTemplateAdditionalInfoRequired(signers); + private BoxSignTemplateAdditionalInfoRequired parseAdditionalInfoRequired( + JsonObject requiredJSON) { + List> signers = new ArrayList>(); + for (JsonValue signerJSON : requiredJSON.get("signers").asArray()) { + List signer = new ArrayList(); + for (JsonValue fieldJSON : signerJSON.asArray()) { + signer.add(fieldJSON.asString()); } + signers.add(signer); + } + return new BoxSignTemplateAdditionalInfoRequired(signers); + } - private List parseSourceFiles(JsonValue filesArray) { - List files = new ArrayList(); - for (JsonValue fileJSON : filesArray.asArray()) { - JsonObject fileObj = fileJSON.asObject(); - String fileID = fileObj.get("id").asString(); - BoxFile file = new BoxFile(getAPI(), fileID); - files.add(file.new Info(fileObj)); - } - return files; - } + private List parseSourceFiles(JsonValue filesArray) { + List files = new ArrayList(); + for (JsonValue fileJSON : filesArray.asArray()) { + JsonObject fileObj = fileJSON.asObject(); + String fileID = fileObj.get("id").asString(); + BoxFile file = new BoxFile(getAPI(), fileID); + files.add(file.new Info(fileObj)); + } + return files; + } - private List parseSigners(JsonValue signersArray) { - List signers = new ArrayList(); - for (JsonValue signerJSON : signersArray.asArray()) { - JsonObject signerObj = signerJSON.asObject(); - signers.add(new BoxSignTemplateSigner(signerObj, getAPI())); - } - return signers; - } + private List parseSigners(JsonValue signersArray) { + List signers = new ArrayList(); + for (JsonValue signerJSON : signersArray.asArray()) { + JsonObject signerObj = signerJSON.asObject(); + signers.add(new BoxSignTemplateSigner(signerObj, getAPI())); + } + return signers; + } - private BoxSignTemplateCustomBranding parseCustomBranding(JsonObject customBrandingJSON) { - String brandingColor = customBrandingJSON.get("branding_color").asString(); - String companyName = customBrandingJSON.get("company_name").asString(); - String emailFooterText = customBrandingJSON.get("email_footer_text").asString(); - String logoUri = customBrandingJSON.get("logo_uri").asString(); - return new BoxSignTemplateCustomBranding(brandingColor, companyName, emailFooterText, logoUri); - } + private BoxSignTemplateCustomBranding parseCustomBranding(JsonObject customBrandingJSON) { + String brandingColor = customBrandingJSON.get("branding_color").asString(); + String companyName = customBrandingJSON.get("company_name").asString(); + String emailFooterText = customBrandingJSON.get("email_footer_text").asString(); + String logoUri = customBrandingJSON.get("logo_uri").asString(); + return new BoxSignTemplateCustomBranding( + brandingColor, companyName, emailFooterText, logoUri); + } - private BoxSignTemplateReadySignLink parseReadySignLink(JsonObject readySignLinkJSON) { - String folderID = readySignLinkJSON.get("folder_id").asString(); - String instructions = readySignLinkJSON.get("instructions").asString(); - boolean isActive = readySignLinkJSON.get("is_active").asBoolean(); - boolean isNofiticationDisabled = readySignLinkJSON.get("is_notification_disabled").asBoolean(); - String name = readySignLinkJSON.get("name").asString(); - String url = readySignLinkJSON.get("url").asString(); - return new BoxSignTemplateReadySignLink(folderID, instructions, isActive, - isNofiticationDisabled, name, url); - } + private BoxSignTemplateReadySignLink parseReadySignLink(JsonObject readySignLinkJSON) { + String folderID = readySignLinkJSON.get("folder_id").asString(); + String instructions = readySignLinkJSON.get("instructions").asString(); + boolean isActive = readySignLinkJSON.get("is_active").asBoolean(); + boolean isNofiticationDisabled = + readySignLinkJSON.get("is_notification_disabled").asBoolean(); + String name = readySignLinkJSON.get("name").asString(); + String url = readySignLinkJSON.get("url").asString(); + return new BoxSignTemplateReadySignLink( + folderID, instructions, isActive, isNofiticationDisabled, name, url); } + } } diff --git a/src/main/java/com/box/sdk/BoxSignTemplateAdditionalInfo.java b/src/main/java/com/box/sdk/BoxSignTemplateAdditionalInfo.java index b12513432..79e4bdf75 100644 --- a/src/main/java/com/box/sdk/BoxSignTemplateAdditionalInfo.java +++ b/src/main/java/com/box/sdk/BoxSignTemplateAdditionalInfo.java @@ -2,36 +2,35 @@ import java.util.List; - /** - * Box Sign Template additional information on which fields are required - * and which fields are not editable. + * Box Sign Template additional information on which fields are required and which fields are not + * editable. */ public class BoxSignTemplateAdditionalInfo { - private final List nonEditable; - private final BoxSignTemplateAdditionalInfoRequired required; + private final List nonEditable; + private final BoxSignTemplateAdditionalInfoRequired required; - public BoxSignTemplateAdditionalInfo(List nonEditable, - BoxSignTemplateAdditionalInfoRequired required) { - this.nonEditable = nonEditable; - this.required = required; - } + public BoxSignTemplateAdditionalInfo( + List nonEditable, BoxSignTemplateAdditionalInfoRequired required) { + this.nonEditable = nonEditable; + this.required = required; + } - /** - * Get non-editable fields. - * - * @return list of non-editable fields.\ - */ - public List getNonEditable() { - return this.nonEditable; - } + /** + * Get non-editable fields. + * + * @return list of non-editable fields.\ + */ + public List getNonEditable() { + return this.nonEditable; + } - /** - * Gets the required fields. - * - * @return the required fields. - */ - public BoxSignTemplateAdditionalInfoRequired getRequired() { - return this.required; - } + /** + * Gets the required fields. + * + * @return the required fields. + */ + public BoxSignTemplateAdditionalInfoRequired getRequired() { + return this.required; + } } diff --git a/src/main/java/com/box/sdk/BoxSignTemplateAdditionalInfoRequired.java b/src/main/java/com/box/sdk/BoxSignTemplateAdditionalInfoRequired.java index 67d0948d0..583e7dc8e 100644 --- a/src/main/java/com/box/sdk/BoxSignTemplateAdditionalInfoRequired.java +++ b/src/main/java/com/box/sdk/BoxSignTemplateAdditionalInfoRequired.java @@ -2,26 +2,23 @@ import java.util.List; - -/** - * Box Sign Template additional information on which fields are required. - */ +/** Box Sign Template additional information on which fields are required. */ public class BoxSignTemplateAdditionalInfoRequired { - private final List> signers; + private final List> signers; - /** - * Constructs a BoxSignTemplateAdditionalInfoRequired object with the provided list of signers. - */ - public BoxSignTemplateAdditionalInfoRequired(List> signers) { - this.signers = signers; - } + /** + * Constructs a BoxSignTemplateAdditionalInfoRequired object with the provided list of signers. + */ + public BoxSignTemplateAdditionalInfoRequired(List> signers) { + this.signers = signers; + } - /** - * Gets the required signer fields. - * - * @return the required signer fields. - */ - public List> getSigners() { - return this.signers; - } + /** + * Gets the required signer fields. + * + * @return the required signer fields. + */ + public List> getSigners() { + return this.signers; + } } diff --git a/src/main/java/com/box/sdk/BoxSignTemplateCustomBranding.java b/src/main/java/com/box/sdk/BoxSignTemplateCustomBranding.java index c1c1425a8..24fe22a6a 100644 --- a/src/main/java/com/box/sdk/BoxSignTemplateCustomBranding.java +++ b/src/main/java/com/box/sdk/BoxSignTemplateCustomBranding.java @@ -1,63 +1,61 @@ package com.box.sdk; -/** - * Custom branding applied to notifications and signature requests. - */ +/** Custom branding applied to notifications and signature requests. */ public class BoxSignTemplateCustomBranding { - private final String brandingColor; - private final String companyName; - private final String emailFooterText; - private final String logoUri; + private final String brandingColor; + private final String companyName; + private final String emailFooterText; + private final String logoUri; - /** - * Constructs a BoxSignTemplateCustomBranding object with the provided information. - * - * @param brandingColor the branding color. - * @param companyName the company name. - * @param emailFooterText the email footer text. - * @param logoUri the logo URI. - */ - public BoxSignTemplateCustomBranding(String brandingColor, String companyName, String emailFooterText, - String logoUri) { - this.brandingColor = brandingColor; - this.companyName = companyName; - this.emailFooterText = emailFooterText; - this.logoUri = logoUri; - } + /** + * Constructs a BoxSignTemplateCustomBranding object with the provided information. + * + * @param brandingColor the branding color. + * @param companyName the company name. + * @param emailFooterText the email footer text. + * @param logoUri the logo URI. + */ + public BoxSignTemplateCustomBranding( + String brandingColor, String companyName, String emailFooterText, String logoUri) { + this.brandingColor = brandingColor; + this.companyName = companyName; + this.emailFooterText = emailFooterText; + this.logoUri = logoUri; + } - /** - * Gets the branding color. - * - * @return the branding color. - */ - public String getBrandingColor() { - return this.brandingColor; - } + /** + * Gets the branding color. + * + * @return the branding color. + */ + public String getBrandingColor() { + return this.brandingColor; + } - /** - * Gets the company name. - * - * @return the company name. - */ - public String getCompanyName() { - return this.companyName; - } + /** + * Gets the company name. + * + * @return the company name. + */ + public String getCompanyName() { + return this.companyName; + } - /** - * Gets the email footer text. - * - * @return the email footer text. - */ - public String getEmailFooterText() { - return this.emailFooterText; - } + /** + * Gets the email footer text. + * + * @return the email footer text. + */ + public String getEmailFooterText() { + return this.emailFooterText; + } - /** - * Gets the logo URI. - * - * @return the logo URI. - */ - public String getLogoUri() { - return this.logoUri; - } + /** + * Gets the logo URI. + * + * @return the logo URI. + */ + public String getLogoUri() { + return this.logoUri; + } } diff --git a/src/main/java/com/box/sdk/BoxSignTemplateReadySignLink.java b/src/main/java/com/box/sdk/BoxSignTemplateReadySignLink.java index d331363ce..e947f464b 100644 --- a/src/main/java/com/box/sdk/BoxSignTemplateReadySignLink.java +++ b/src/main/java/com/box/sdk/BoxSignTemplateReadySignLink.java @@ -1,90 +1,96 @@ package com.box.sdk; /** - * Box's ready-sign link feature enables you to create a link to a signature request that you've created from a template. - * Use this link when you want to post a signature request on a public form — such as an email, - * social media post, or web page — without knowing who the signers will be. - * Note: The ready-sign link feature is limited to Enterprise Plus customers and not available to Box Verified Enterprises. + * Box's ready-sign link feature enables you to create a link to a signature request that you've + * created from a template. Use this link when you want to post a signature request on a public form + * — such as an email, social media post, or web page — without knowing who the signers will be. + * Note: The ready-sign link feature is limited to Enterprise Plus customers and not available to + * Box Verified Enterprises. */ public class BoxSignTemplateReadySignLink { - private final String folderID; - private final String instructions; - private final boolean isActive; - private final boolean isNofiticationDisabled; - private final String name; - private final String url; + private final String folderID; + private final String instructions; + private final boolean isActive; + private final boolean isNofiticationDisabled; + private final String name; + private final String url; - /** - * Constructs a BoxSignTemplateReadySignLink object with the provided information. - * - * @param folderID the folder ID. - * @param instructions the instructions. - * @param isActive whether the link is active or not. - * @param isNofiticationDisabled whether the notification is disabled or not. - * @param name the name. - * @param url the URL. - */ - public BoxSignTemplateReadySignLink(String folderID, String instructions, boolean isActive, - boolean isNofiticationDisabled, String name, String url) { - this.folderID = folderID; - this.instructions = instructions; - this.isActive = isActive; - this.isNofiticationDisabled = isNofiticationDisabled; - this.name = name; - this.url = url; - } + /** + * Constructs a BoxSignTemplateReadySignLink object with the provided information. + * + * @param folderID the folder ID. + * @param instructions the instructions. + * @param isActive whether the link is active or not. + * @param isNofiticationDisabled whether the notification is disabled or not. + * @param name the name. + * @param url the URL. + */ + public BoxSignTemplateReadySignLink( + String folderID, + String instructions, + boolean isActive, + boolean isNofiticationDisabled, + String name, + String url) { + this.folderID = folderID; + this.instructions = instructions; + this.isActive = isActive; + this.isNofiticationDisabled = isNofiticationDisabled; + this.name = name; + this.url = url; + } - /** - * Gets the folder ID. - * - * @return the folder ID. - */ - public String getFolderID() { - return this.folderID; - } + /** + * Gets the folder ID. + * + * @return the folder ID. + */ + public String getFolderID() { + return this.folderID; + } - /** - * Gets the instructions. - * - * @return the instructions. - */ - public String getInstructions() { - return this.instructions; - } + /** + * Gets the instructions. + * + * @return the instructions. + */ + public String getInstructions() { + return this.instructions; + } - /** - * Gets whether the link is active or not. - * - * @return true if the link is active; otherwise false. - */ - public boolean getIsActive() { - return this.isActive; - } + /** + * Gets whether the link is active or not. + * + * @return true if the link is active; otherwise false. + */ + public boolean getIsActive() { + return this.isActive; + } - /** - * Gets whether the notification is disabled or not. - * - * @return true if the notification is disabled; otherwise false. - */ - public boolean getIsNofiticationDisabled() { - return this.isNofiticationDisabled; - } + /** + * Gets whether the notification is disabled or not. + * + * @return true if the notification is disabled; otherwise false. + */ + public boolean getIsNofiticationDisabled() { + return this.isNofiticationDisabled; + } - /** - * Gets the name of the ready-sign link. - * - * @return the name. - */ - public String getName() { - return this.name; - } + /** + * Gets the name of the ready-sign link. + * + * @return the name. + */ + public String getName() { + return this.name; + } - /** - * Gets the URL of the ready-sign link. - * - * @return the URL. - */ - public String getUrl() { - return this.url; - } + /** + * Gets the URL of the ready-sign link. + * + * @return the URL. + */ + public String getUrl() { + return this.url; + } } diff --git a/src/main/java/com/box/sdk/BoxSignTemplateSigner.java b/src/main/java/com/box/sdk/BoxSignTemplateSigner.java index 0c18101e3..90ba4f50c 100644 --- a/src/main/java/com/box/sdk/BoxSignTemplateSigner.java +++ b/src/main/java/com/box/sdk/BoxSignTemplateSigner.java @@ -8,668 +8,627 @@ import java.util.Date; import java.util.List; - -/** - * Box Sign Template signer. - */ +/** Box Sign Template signer. */ public class BoxSignTemplateSigner extends BoxJSONObject { - private String email; - private List inputs; - private Boolean isInPerson; - private int order; - private BoxSignRequestSignerRole role; - private String signerGroupId; + private String email; + private List inputs; + private Boolean isInPerson; + private int order; + private BoxSignRequestSignerRole role; + private String signerGroupId; + private BoxAPIConnection api; + + /** + * Constructs a BoxSignTemplateSigner object with the provided information. + * + * @param email the email. + * @param inputs the inputs. + * @param isInPerson whether the signer is in person or not. + * @param order the order. + * @param role the role. + */ + public BoxSignTemplateSigner( + String email, + List inputs, + Boolean isInPerson, + int order, + BoxSignRequestSignerRole role) { + this(email, inputs, isInPerson, order, role, null); + } + + /** + * Constructs a BoxSignTemplateSigner object with the provided information. + * + * @param email the email. + * @param inputs the inputs. + * @param isInPerson whether the signer is in person or not. + * @param order the order. + * @param role the role. + * @param signerGroupId the signer group id. + */ + public BoxSignTemplateSigner( + String email, + List inputs, + Boolean isInPerson, + int order, + BoxSignRequestSignerRole role, + String signerGroupId) { + this.email = email; + this.inputs = inputs; + this.isInPerson = isInPerson; + this.order = order; + this.role = role; + this.signerGroupId = signerGroupId; + } + + /** + * Constructs a BoxSignTemplateSigner object with the provided JSON object. + * + * @param jsonObject the JSON object representing the Sign Template Signer. + */ + public BoxSignTemplateSigner(JsonObject jsonObject, BoxAPIConnection api) { + super(jsonObject); + this.api = api; + } + + /** + * Gets the email of the signer. + * + * @return the email of the signer. + */ + public String getEmail() { + return this.email; + } + + /** + * Gets the inputs of the signer. + * + * @return the inputs of the signer. + */ + public List getInputs() { + return this.inputs; + } + + /** + * Used in combination with an embed URL for a sender. After the sender signs, they will be + * redirected to the next in_person signer. + * + * @return true if the signer is in person; otherwise false. + */ + public Boolean getIsInPerson() { + return this.isInPerson; + } + + /** + * Gets the order of the signer. + * + * @return the order of the signer. + */ + public int getOrder() { + return this.order; + } + + /** + * Gets the role of the signer. + * + * @return the role of the signer. + */ + public BoxSignRequestSignerRole getRole() { + return this.role; + } + + /** + * Gets the signer group id. It is sufficient for only one signer from the group to sign the + * document. + * + * @return the id of the group signer. + */ + public String getSignerGroupId() { + return this.signerGroupId; + } + + /** {@inheritDoc} */ + @Override + void parseJSONMember(JsonObject.Member member) { + JsonValue value = member.getValue(); + String memberName = member.getName(); + try { + switch (memberName) { + case "email": + this.email = value.asString(); + break; + case "inputs": + this.inputs = new ArrayList(); + for (JsonValue inputJSON : value.asArray()) { + this.inputs.add(new BoxSignTemplateSignerInput(inputJSON.asObject(), this.api)); + } + break; + case "is_in_person": + this.isInPerson = value.asBoolean(); + break; + case "order": + this.order = value.asInt(); + break; + case "role": + this.role = BoxSignRequestSignerRole.fromJSONString(value.asString()); + break; + case "signer_group_id": + this.signerGroupId = value.asString(); + break; + default: + return; + } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); + } + } + + /** Box Sign Template signer input. */ + public class BoxSignTemplateSignerInput extends BoxJSONObject { + private BoxSignTemplateSignerInputType type; + private Boolean checkboxValue; + private BoxSignTemplateSignerInputContentType contentType; + private BoxSignTemplateSignerInputCoordinates coordinates; + private Date dateValue; + private BoxSignTemplatesSignerInputDimensions dimensions; + private String documentId; + private String documentTagId; + private List dropdownChoices; + private String groupId; + private Boolean isRequired; + private int pageIndex; + private String textValue; + private String label; private BoxAPIConnection api; /** - * Constructs a BoxSignTemplateSigner object with the provided information. + * Constructs a BoxSignTemplateSignerInput object with the provided information. * - * @param email the email. - * @param inputs the inputs. - * @param isInPerson whether the signer is in person or not. - * @param order the order. - * @param role the role. + * @param type the type. + * @param checkboxValue the checkbox value. + * @param contentType the content type. + * @param coordinates the coordinates. + * @param dateValue the date value. + * @param dimensions the dimensions. + * @param documentId the document ID. + * @param documentTagId the document tag ID. + * @param dropdownChoices the dropdown choices. + * @param groupId the group ID. + * @param isRequired whether the input is required or not. + * @param pageIndex the page index. + * @param textValue the text value. + * @param label the label. */ - public BoxSignTemplateSigner(String email, List inputs, Boolean isInPerson, - int order, BoxSignRequestSignerRole role) { - this(email, inputs, isInPerson, order, role, null); + public BoxSignTemplateSignerInput( + BoxSignTemplateSignerInputType type, + Boolean checkboxValue, + BoxSignTemplateSignerInputContentType contentType, + BoxSignTemplateSignerInputCoordinates coordinates, + Date dateValue, + BoxSignTemplatesSignerInputDimensions dimensions, + String documentId, + String documentTagId, + List dropdownChoices, + String groupId, + Boolean isRequired, + int pageIndex, + String textValue, + String label) { + this.type = type; + this.checkboxValue = checkboxValue; + this.contentType = contentType; + this.coordinates = coordinates; + this.dateValue = dateValue; + this.dimensions = dimensions; + this.documentId = documentId; + this.documentTagId = documentTagId; + this.dropdownChoices = dropdownChoices; + this.groupId = groupId; + this.isRequired = isRequired; + this.pageIndex = pageIndex; + this.textValue = textValue; + this.label = label; } /** - * Constructs a BoxSignTemplateSigner object with the provided information. + * Constructs a BoxSignTemplateSignerInput object with the provided JSON object. * - * @param email the email. - * @param inputs the inputs. - * @param isInPerson whether the signer is in person or not. - * @param order the order. - * @param role the role. - * @param signerGroupId the signer group id. + * @param jsonObject the JSON object representing the Sign Template Signer Input. */ - public BoxSignTemplateSigner(String email, List inputs, Boolean isInPerson, - int order, BoxSignRequestSignerRole role, String signerGroupId) { - this.email = email; - this.inputs = inputs; - this.isInPerson = isInPerson; - this.order = order; - this.role = role; - this.signerGroupId = signerGroupId; + public BoxSignTemplateSignerInput(JsonObject jsonObject, BoxAPIConnection api) { + super(jsonObject); + this.api = api; } /** - * Constructs a BoxSignTemplateSigner object with the provided JSON object. + * Gets the type of the input. * - * @param jsonObject the JSON object representing the Sign Template Signer. + * @return the type of the input. */ - public BoxSignTemplateSigner(JsonObject jsonObject, BoxAPIConnection api) { - super(jsonObject); - this.api = api; + public BoxSignTemplateSignerInputType getType() { + return this.type; } /** - * Gets the email of the signer. + * Gets the checkbox value. * - * @return the email of the signer. + * @return the checkbox value. */ - public String getEmail() { - return this.email; + public Boolean getCheckboxValue() { + return this.checkboxValue; } /** - * Gets the inputs of the signer. + * Gets the content type. * - * @return the inputs of the signer. + * @return the content type. */ - public List getInputs() { - return this.inputs; + public BoxSignTemplateSignerInputContentType getContentType() { + return this.contentType; } /** - * Used in combination with an embed URL for a sender. - * After the sender signs, they will be redirected to the next in_person signer. + * Gets the coordinates. * - * @return true if the signer is in person; otherwise false. + * @return the coordinates. */ - public Boolean getIsInPerson() { - return this.isInPerson; + public BoxSignTemplateSignerInputCoordinates getCoordinates() { + return this.coordinates; } /** - * Gets the order of the signer. + * Gets the date value. * - * @return the order of the signer. + * @return the date value. */ - public int getOrder() { - return this.order; + public Date getDateValue() { + return this.dateValue; } /** - * Gets the role of the signer. + * Gets the dimensions. * - * @return the role of the signer. + * @return the dimensions. */ - public BoxSignRequestSignerRole getRole() { - return this.role; + public BoxSignTemplatesSignerInputDimensions getDimensions() { + return this.dimensions; } /** - * Gets the signer group id. It is sufficient for only one signer from the group to sign the document. + * Gets the document ID. * - * @return the id of the group signer. + * @return the document ID. */ - public String getSignerGroupId() { - return this.signerGroupId; + public String getDocumentId() { + return this.documentId; } /** - * {@inheritDoc} + * Gets the document tag ID. + * + * @return the document tag ID. */ - @Override - void parseJSONMember(JsonObject.Member member) { - JsonValue value = member.getValue(); - String memberName = member.getName(); - try { - switch (memberName) { - case "email": - this.email = value.asString(); - break; - case "inputs": - this.inputs = new ArrayList(); - for (JsonValue inputJSON : value.asArray()) { - this.inputs.add(new BoxSignTemplateSignerInput(inputJSON.asObject(), this.api)); - } - break; - case "is_in_person": - this.isInPerson = value.asBoolean(); - break; - case "order": - this.order = value.asInt(); - break; - case "role": - this.role = BoxSignRequestSignerRole.fromJSONString(value.asString()); - break; - case "signer_group_id": - this.signerGroupId = value.asString(); - break; - default: - return; - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); - } + public String getDocumentTagId() { + return this.documentTagId; } /** - * Box Sign Template signer input. + * Gets the dropdown choices. + * + * @return the dropdown choices. */ - public class BoxSignTemplateSignerInput extends BoxJSONObject { - private BoxSignTemplateSignerInputType type; - private Boolean checkboxValue; - private BoxSignTemplateSignerInputContentType contentType; - private BoxSignTemplateSignerInputCoordinates coordinates; - private Date dateValue; - private BoxSignTemplatesSignerInputDimensions dimensions; - private String documentId; - private String documentTagId; - private List dropdownChoices; - private String groupId; - private Boolean isRequired; - private int pageIndex; - private String textValue; - private String label; - private BoxAPIConnection api; - - /** - * Constructs a BoxSignTemplateSignerInput object with the provided information. - * - * @param type the type. - * @param checkboxValue the checkbox value. - * @param contentType the content type. - * @param coordinates the coordinates. - * @param dateValue the date value. - * @param dimensions the dimensions. - * @param documentId the document ID. - * @param documentTagId the document tag ID. - * @param dropdownChoices the dropdown choices. - * @param groupId the group ID. - * @param isRequired whether the input is required or not. - * @param pageIndex the page index. - * @param textValue the text value. - * @param label the label. - */ - public BoxSignTemplateSignerInput(BoxSignTemplateSignerInputType type, Boolean checkboxValue, - BoxSignTemplateSignerInputContentType contentType, - BoxSignTemplateSignerInputCoordinates coordinates, Date dateValue, - BoxSignTemplatesSignerInputDimensions dimensions, String documentId, - String documentTagId, List dropdownChoices, String groupId, - Boolean isRequired, int pageIndex, String textValue, String label) { - this.type = type; - this.checkboxValue = checkboxValue; - this.contentType = contentType; - this.coordinates = coordinates; - this.dateValue = dateValue; - this.dimensions = dimensions; - this.documentId = documentId; - this.documentTagId = documentTagId; - this.dropdownChoices = dropdownChoices; - this.groupId = groupId; - this.isRequired = isRequired; - this.pageIndex = pageIndex; - this.textValue = textValue; - this.label = label; - } - - /** - * Constructs a BoxSignTemplateSignerInput object with the provided JSON object. - * - * @param jsonObject the JSON object representing the Sign Template Signer Input. - */ - public BoxSignTemplateSignerInput(JsonObject jsonObject, BoxAPIConnection api) { - super(jsonObject); - this.api = api; - } - - /** - * Gets the type of the input. - * - * @return the type of the input. - */ - public BoxSignTemplateSignerInputType getType() { - return this.type; - } - - /** - * Gets the checkbox value. - * - * @return the checkbox value. - */ - public Boolean getCheckboxValue() { - return this.checkboxValue; - } - - /** - * Gets the content type. - * - * @return the content type. - */ - public BoxSignTemplateSignerInputContentType getContentType() { - return this.contentType; - } - - /** - * Gets the coordinates. - * - * @return the coordinates. - */ - public BoxSignTemplateSignerInputCoordinates getCoordinates() { - return this.coordinates; - } - - /** - * Gets the date value. - * - * @return the date value. - */ - public Date getDateValue() { - return this.dateValue; - } - - /** - * Gets the dimensions. - * - * @return the dimensions. - */ - public BoxSignTemplatesSignerInputDimensions getDimensions() { - return this.dimensions; - } - - /** - * Gets the document ID. - * - * @return the document ID. - */ - public String getDocumentId() { - return this.documentId; - } - - /** - * Gets the document tag ID. - * - * @return the document tag ID. - */ - public String getDocumentTagId() { - return this.documentTagId; - } - - /** - * Gets the dropdown choices. - * - * @return the dropdown choices. - */ - public List getDropdownChoices() { - return this.dropdownChoices; - } + public List getDropdownChoices() { + return this.dropdownChoices; + } - /** - * Gets the group ID. - * - * @return the group ID. - */ - public String getGroupId() { - return this.groupId; - } + /** + * Gets the group ID. + * + * @return the group ID. + */ + public String getGroupId() { + return this.groupId; + } - /** - * Gets whether the input is required or not. - * - * @return true if the input is required; otherwise false. - */ - public Boolean getIsRequired() { - return this.isRequired; - } + /** + * Gets whether the input is required or not. + * + * @return true if the input is required; otherwise false. + */ + public Boolean getIsRequired() { + return this.isRequired; + } - /** - * Gets the page index. - * - * @return the page index. - */ - public int getPageIndex() { - return this.pageIndex; - } + /** + * Gets the page index. + * + * @return the page index. + */ + public int getPageIndex() { + return this.pageIndex; + } - /** - * Gets the text value. - * - * @return the text value. - */ - public String getTextValue() { - return this.textValue; - } + /** + * Gets the text value. + * + * @return the text value. + */ + public String getTextValue() { + return this.textValue; + } - /** - * Gets the label. - * - * @return the label. - */ - public String getLabel() { - return this.label; - } + /** + * Gets the label. + * + * @return the label. + */ + public String getLabel() { + return this.label; + } - /** - * {@inheritDoc} - */ - @Override - void parseJSONMember(JsonObject.Member member) { - JsonValue value = member.getValue(); - String memberName = member.getName(); - try { - switch (memberName) { - case "type": - this.type = BoxSignTemplateSignerInputType.fromJSONString(value.asString()); - break; - case "checkbox_value": - this.checkboxValue = value.asBoolean(); - break; - case "content_type": - this.contentType = BoxSignTemplateSignerInputContentType.fromJSONString(value.asString()); - break; - case "coordinates": - JsonObject coordinatesJSON = value.asObject(); - double x = coordinatesJSON.get("x").asFloat(); - double y = coordinatesJSON.get("y").asFloat(); - this.coordinates = new BoxSignTemplateSignerInputCoordinates(x, y); - break; - case "date_value": - this.dateValue = BoxDateFormat.parse(value.asString()); - break; - case "dimensions": - JsonObject dimensionsJSON = value.asObject(); - double height = dimensionsJSON.get("height").asFloat(); - double width = dimensionsJSON.get("width").asFloat(); - this.dimensions = new BoxSignTemplatesSignerInputDimensions(height, width); - break; - case "document_id": - this.documentId = value.asString(); - break; - case "document_tag_id": - this.documentTagId = value.asString(); - break; - case "dropdown_choices": - this.dropdownChoices = new ArrayList(); - for (JsonValue choiceJSON : value.asArray()) { - this.dropdownChoices.add(choiceJSON.asString()); - } - break; - case "group_id": - this.groupId = value.asString(); - break; - case "is_required": - this.isRequired = value.asBoolean(); - break; - case "page_index": - this.pageIndex = value.asInt(); - break; - case "text_value": - this.textValue = value.asString(); - break; - case "label": - this.label = value.asString(); - break; - default: - return; - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); + /** {@inheritDoc} */ + @Override + void parseJSONMember(JsonObject.Member member) { + JsonValue value = member.getValue(); + String memberName = member.getName(); + try { + switch (memberName) { + case "type": + this.type = BoxSignTemplateSignerInputType.fromJSONString(value.asString()); + break; + case "checkbox_value": + this.checkboxValue = value.asBoolean(); + break; + case "content_type": + this.contentType = + BoxSignTemplateSignerInputContentType.fromJSONString(value.asString()); + break; + case "coordinates": + JsonObject coordinatesJSON = value.asObject(); + double x = coordinatesJSON.get("x").asFloat(); + double y = coordinatesJSON.get("y").asFloat(); + this.coordinates = new BoxSignTemplateSignerInputCoordinates(x, y); + break; + case "date_value": + this.dateValue = BoxDateFormat.parse(value.asString()); + break; + case "dimensions": + JsonObject dimensionsJSON = value.asObject(); + double height = dimensionsJSON.get("height").asFloat(); + double width = dimensionsJSON.get("width").asFloat(); + this.dimensions = new BoxSignTemplatesSignerInputDimensions(height, width); + break; + case "document_id": + this.documentId = value.asString(); + break; + case "document_tag_id": + this.documentTagId = value.asString(); + break; + case "dropdown_choices": + this.dropdownChoices = new ArrayList(); + for (JsonValue choiceJSON : value.asArray()) { + this.dropdownChoices.add(choiceJSON.asString()); } + break; + case "group_id": + this.groupId = value.asString(); + break; + case "is_required": + this.isRequired = value.asBoolean(); + break; + case "page_index": + this.pageIndex = value.asInt(); + break; + case "text_value": + this.textValue = value.asString(); + break; + case "label": + this.label = value.asString(); + break; + default: + return; } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); + } } + } + + /** Box Sign Template signer input coordinates. */ + public class BoxSignTemplateSignerInputCoordinates { + private final double x; + private final double y; /** - * Box Sign Template signer input coordinates. + * Constructs a BoxSignTemplateSignerInputCoordinates object with the provided information. + * + * @param x the x coordinate. + * @param y the y coordinate. */ - public class BoxSignTemplateSignerInputCoordinates { - private final double x; - private final double y; - - /** - * Constructs a BoxSignTemplateSignerInputCoordinates object with the provided information. - * - * @param x the x coordinate. - * @param y the y coordinate. - */ - public BoxSignTemplateSignerInputCoordinates(double x, double y) { - this.x = x; - this.y = y; - } - - /** - * Gets the x coordinate. - * - * @return the x coordinate. - */ - public double getX() { - return this.x; - } + public BoxSignTemplateSignerInputCoordinates(double x, double y) { + this.x = x; + this.y = y; + } - /** - * Gets the y coordinate. - * - * @return the y coordinate. - */ - public double getY() { - return this.y; - } + /** + * Gets the x coordinate. + * + * @return the x coordinate. + */ + public double getX() { + return this.x; } /** - * Box Sign Template signer input dimensions. + * Gets the y coordinate. + * + * @return the y coordinate. */ - public class BoxSignTemplatesSignerInputDimensions { - private final double height; - private final double width; - - /** - * Constructs a BoxSignTemplatesSignerInputDimensions object with the provided information. - * - * @param height the height. - * @param width the width. - */ - public BoxSignTemplatesSignerInputDimensions(double height, double width) { - this.height = height; - this.width = width; - } + public double getY() { + return this.y; + } + } - /** - * Gets the height. - * - * @return the height. - */ - public double getHeight() { - return this.height; - } + /** Box Sign Template signer input dimensions. */ + public class BoxSignTemplatesSignerInputDimensions { + private final double height; + private final double width; - /** - * Gets the width. - * - * @return the width. - */ - public double getWidth() { - return this.width; - } + /** + * Constructs a BoxSignTemplatesSignerInputDimensions object with the provided information. + * + * @param height the height. + * @param width the width. + */ + public BoxSignTemplatesSignerInputDimensions(double height, double width) { + this.height = height; + this.width = width; } /** - * Box Sign Template signer input type. + * Gets the height. + * + * @return the height. */ - public enum BoxSignTemplateSignerInputType { - /** - * Signature input type. - */ - Signature("signature"), - /** - * Date input type. - */ - Date("date"), - /** - * Text input type. - */ - Text("text"), - /** - * Checkbox input type. - */ - Checkbox("checkbox"), - /** - * Attachment input type. - */ - Attachment("attachment"), - /** - * Radio input type. - */ - Radio("radio"), - /** - * Dropdown input type. - */ - Dropdown("dropdown"); - - private final String jsonValue; - - BoxSignTemplateSignerInputType(String jsonValue) { - this.jsonValue = jsonValue; - } - - static BoxSignTemplateSignerInputType fromJSONString(String jsonValue) { - switch (jsonValue) { - case "signature": - return Signature; - case "date": - return Date; - case "text": - return Text; - case "checkbox": - return Checkbox; - case "attachment": - return Attachment; - case "radio": - return Radio; - case "dropdown": - return Dropdown; - default: - throw new IllegalArgumentException( - format("The provided JSON value '%s' isn't a valid BoxSignTemplateSignerInputType.", - jsonValue) - ); - } - } + public double getHeight() { + return this.height; } /** - * Box Sign Template signer input content type. + * Gets the width. + * + * @return the width. */ - public enum BoxSignTemplateSignerInputContentType { - /** - * Initial content type - */ - Initial("initial"), - /** - * Stamp content type - */ - Stamp("stamp"), - /** - * Signature content type - */ - Signature("signature"), - /** - * Company content type - */ - Company("company"), - /** - * Title content type - */ - Title("title"), - /** - * Email content type - */ - Email("email"), - /** - * Full name content type - */ - FullName("full_name"), - /** - * First name content type - */ - FirstName("first_name"), - /** - * Last name content type - */ - LastName("last_name"), - /** - * Text content type - */ - Text("text"), - /** - * Date content type - */ - Date("date"), - /** - * Checkbox content type - */ - Checkbox("checkbox"), - /** - * Attachement content type - */ - Attachement("attachment"), - /** - * Radio content type - */ - Radio("radio"), - /** - * Dropdown content type - */ - Dropdown("dropdown"); - - private final String jsonValue; - - BoxSignTemplateSignerInputContentType(String jsonValue) { - this.jsonValue = jsonValue; - } + public double getWidth() { + return this.width; + } + } + + /** Box Sign Template signer input type. */ + public enum BoxSignTemplateSignerInputType { + /** Signature input type. */ + Signature("signature"), + /** Date input type. */ + Date("date"), + /** Text input type. */ + Text("text"), + /** Checkbox input type. */ + Checkbox("checkbox"), + /** Attachment input type. */ + Attachment("attachment"), + /** Radio input type. */ + Radio("radio"), + /** Dropdown input type. */ + Dropdown("dropdown"); + + private final String jsonValue; + + BoxSignTemplateSignerInputType(String jsonValue) { + this.jsonValue = jsonValue; + } - static BoxSignTemplateSignerInputContentType fromJSONString(String jsonValue) { - switch (jsonValue) { - case "initial": - return Initial; - case "stamp": - return Stamp; - case "signature": - return Signature; - case "company": - return Company; - case "title": - return Title; - case "email": - return Email; - case "full_name": - return FullName; - case "first_name": - return FirstName; - case "last_name": - return LastName; - case "text": - return Text; - case "date": - return Date; - case "checkbox": - return Checkbox; - case "attachment": - return Attachement; - case "radio": - return Radio; - case "dropdown": - return Dropdown; - default: - throw new IllegalArgumentException( - format("The provided JSON value '%s' isn't a valid BoxSignTemplateSignerInputContentType.", - jsonValue) - ); - } - } + static BoxSignTemplateSignerInputType fromJSONString(String jsonValue) { + switch (jsonValue) { + case "signature": + return Signature; + case "date": + return Date; + case "text": + return Text; + case "checkbox": + return Checkbox; + case "attachment": + return Attachment; + case "radio": + return Radio; + case "dropdown": + return Dropdown; + default: + throw new IllegalArgumentException( + format( + "The provided JSON value '%s' isn't a valid BoxSignTemplateSignerInputType.", + jsonValue)); + } + } + } + + /** Box Sign Template signer input content type. */ + public enum BoxSignTemplateSignerInputContentType { + /** Initial content type */ + Initial("initial"), + /** Stamp content type */ + Stamp("stamp"), + /** Signature content type */ + Signature("signature"), + /** Company content type */ + Company("company"), + /** Title content type */ + Title("title"), + /** Email content type */ + Email("email"), + /** Full name content type */ + FullName("full_name"), + /** First name content type */ + FirstName("first_name"), + /** Last name content type */ + LastName("last_name"), + /** Text content type */ + Text("text"), + /** Date content type */ + Date("date"), + /** Checkbox content type */ + Checkbox("checkbox"), + /** Attachement content type */ + Attachement("attachment"), + /** Radio content type */ + Radio("radio"), + /** Dropdown content type */ + Dropdown("dropdown"); + + private final String jsonValue; + + BoxSignTemplateSignerInputContentType(String jsonValue) { + this.jsonValue = jsonValue; + } + + static BoxSignTemplateSignerInputContentType fromJSONString(String jsonValue) { + switch (jsonValue) { + case "initial": + return Initial; + case "stamp": + return Stamp; + case "signature": + return Signature; + case "company": + return Company; + case "title": + return Title; + case "email": + return Email; + case "full_name": + return FullName; + case "first_name": + return FirstName; + case "last_name": + return LastName; + case "text": + return Text; + case "date": + return Date; + case "checkbox": + return Checkbox; + case "attachment": + return Attachement; + case "radio": + return Radio; + case "dropdown": + return Dropdown; + default: + throw new IllegalArgumentException( + format( + "The provided JSON value '%s' isn't a valid BoxSignTemplateSignerInputContentType.", + jsonValue)); + } } + } } diff --git a/src/main/java/com/box/sdk/BoxStoragePolicy.java b/src/main/java/com/box/sdk/BoxStoragePolicy.java index 25ddcfe7c..fb15824b7 100644 --- a/src/main/java/com/box/sdk/BoxStoragePolicy.java +++ b/src/main/java/com/box/sdk/BoxStoragePolicy.java @@ -4,168 +4,154 @@ import com.eclipsesource.json.JsonValue; import java.net.URL; -/** - * Represents a BoxStoragePolicy. - */ +/** Represents a BoxStoragePolicy. */ @BoxResourceType("storage_policy") public class BoxStoragePolicy extends BoxResource { - /** - * Storage Policies URL Template. - */ - public static final URLTemplate STORAGE_POLICY_URL_TEMPLATE = new URLTemplate("storage_policies"); - - /** - * Storage Policies URL Template. - */ - public static final URLTemplate STORAGE_POLICY_WITH_ID_URL_TEMPLATE = new URLTemplate("storage_policies/%s"); - - /** - * The default limit of entries per response. - */ - private static final int DEFAULT_LIMIT = 100; - - /** - * Constructs a BoxStoragePolicy with a given ID. - * - * @param api the API connection to be used by the BoxStoragePolicy. - * @param id the ID of the BoxStoragePolicy. - */ - public BoxStoragePolicy(BoxAPIConnection api, String id) { - super(api, id); + /** Storage Policies URL Template. */ + public static final URLTemplate STORAGE_POLICY_URL_TEMPLATE = new URLTemplate("storage_policies"); + + /** Storage Policies URL Template. */ + public static final URLTemplate STORAGE_POLICY_WITH_ID_URL_TEMPLATE = + new URLTemplate("storage_policies/%s"); + + /** The default limit of entries per response. */ + private static final int DEFAULT_LIMIT = 100; + + /** + * Constructs a BoxStoragePolicy with a given ID. + * + * @param api the API connection to be used by the BoxStoragePolicy. + * @param id the ID of the BoxStoragePolicy. + */ + public BoxStoragePolicy(BoxAPIConnection api, String id) { + super(api, id); + } + + /** + * Returns all BoxStoragePolicy with specified fields. + * + * @param api the API connection to be used by the resource. + * @param fields the fields to retrieve. + * @return an iterable with all the storage policies met search conditions. + */ + public static Iterable getAll( + final BoxAPIConnection api, String... fields) { + + return getAll(api, DEFAULT_LIMIT, fields); + } + + /** + * Returns all BoxStoragePolicy with specified fields. + * + * @param api the API connection to be used by the resource. + * @param limit the limit of items per single response. The default is 100. + * @param fields the fields to retrieve. + * @return an iterable with all the storage policies met search conditions. + */ + public static Iterable getAll( + final BoxAPIConnection api, int limit, String... fields) { + + QueryStringBuilder builder = new QueryStringBuilder(); + if (fields.length > 0) { + builder.appendParam("fields", fields); } - /** - * Returns all BoxStoragePolicy with specified fields. - * - * @param api the API connection to be used by the resource. - * @param fields the fields to retrieve. - * @return an iterable with all the storage policies met search conditions. - */ - public static Iterable getAll(final BoxAPIConnection api, String... fields) { - - return getAll(api, DEFAULT_LIMIT, fields); + URL url = STORAGE_POLICY_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString()); + return new BoxResourceIterable(api, url, limit) { + + @Override + protected BoxStoragePolicy.Info factory(JsonObject jsonObject) { + BoxStoragePolicy storagePolicy = new BoxStoragePolicy(api, jsonObject.get("id").asString()); + + return storagePolicy.new Info(jsonObject); + } + }; + } + + /** + * Gets information for a Box Storage Policy with optional fields. + * + * @param fields the fields to retrieve. + * @return info about this item containing only the specified fields, including storage policy. + */ + public BoxStoragePolicy.Info getInfo(String... fields) { + QueryStringBuilder builder = new QueryStringBuilder(); + if (fields.length > 0) { + builder.appendParam("fields", fields); } + URL url = + STORAGE_POLICY_WITH_ID_URL_TEMPLATE.buildWithQuery( + this.getAPI().getBaseURL(), builder.toString(), this.getID()); - /** - * Returns all BoxStoragePolicy with specified fields. - * - * @param api the API connection to be used by the resource. - * @param limit the limit of items per single response. The default is 100. - * @param fields the fields to retrieve. - * @return an iterable with all the storage policies met search conditions. - */ - public static Iterable getAll(final BoxAPIConnection api, int limit, String... fields) { - - QueryStringBuilder builder = new QueryStringBuilder(); - if (fields.length > 0) { - builder.appendParam("fields", fields); - } - - URL url = STORAGE_POLICY_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString()); - return new BoxResourceIterable(api, url, limit) { - - @Override - protected BoxStoragePolicy.Info factory(JsonObject jsonObject) { - BoxStoragePolicy storagePolicy = new BoxStoragePolicy(api, jsonObject.get("id").asString()); - - return storagePolicy.new Info(jsonObject); - } - }; + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); + try (BoxJSONResponse response = request.send()) { + return new Info(response.getJSON()); + } + } + + /** + * Checks if there is already a Storage Policy Assignment and creates one if one does not exist. + * + * @param userID the ID of the user you want to assign the Storage Policy to. + * @return information about this {@link BoxStoragePolicyAssignment}. + */ + public BoxStoragePolicyAssignment.Info assign(String userID) { + return BoxStoragePolicyAssignment.assign(this.getAPI(), this.getID(), userID); + } + + /** Contains information about the BoxStoragePolicy. */ + public class Info extends BoxResource.Info { + + /** @see #getStoragePolicyName() */ + private String storagePolicyName; + + /** Constructs an empty Info object. */ + public Info() { + super(); } /** - * Gets information for a Box Storage Policy with optional fields. + * Constructs an Info object by parsing information from a JSON string. * - * @param fields the fields to retrieve. - * @return info about this item containing only the specified fields, including storage policy. + * @param json the JSON string to parse. */ - public BoxStoragePolicy.Info getInfo(String... fields) { - QueryStringBuilder builder = new QueryStringBuilder(); - if (fields.length > 0) { - builder.appendParam("fields", fields); - } - URL url = STORAGE_POLICY_WITH_ID_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), builder.toString(), - this.getID()); - - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); - try (BoxJSONResponse response = request.send()) { - return new Info(response.getJSON()); - } + public Info(String json) { + super(json); } /** - * Checks if there is already a Storage Policy Assignment and creates one if one does not exist. + * Constructs an Info object using an already parsed JSON object. * - * @param userID the ID of the user you want to assign the Storage Policy to. - * @return information about this {@link BoxStoragePolicyAssignment}. + * @param jsonObject the parsed JSON object. */ - public BoxStoragePolicyAssignment.Info assign(String userID) { - return BoxStoragePolicyAssignment.assign(this.getAPI(), this.getID(), userID); + Info(JsonObject jsonObject) { + super(jsonObject); } - /** - * Contains information about the BoxStoragePolicy. - */ - public class Info extends BoxResource.Info { - - /** - * @see #getStoragePolicyName() - */ - private String storagePolicyName; - - /** - * Constructs an empty Info object. - */ - public Info() { - super(); - } - - /** - * Constructs an Info object by parsing information from a JSON string. - * - * @param json the JSON string to parse. - */ - public Info(String json) { - super(json); - } - - /** - * Constructs an Info object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - Info(JsonObject jsonObject) { - super(jsonObject); - } - - /** - * {@inheritDoc} - */ - @Override - public BoxStoragePolicy getResource() { - return BoxStoragePolicy.this; - } + /** {@inheritDoc} */ + @Override + public BoxStoragePolicy getResource() { + return BoxStoragePolicy.this; + } - /** - * @return the name of the storage policy. - */ - public String getStoragePolicyName() { - return this.storagePolicyName; - } + /** @return the name of the storage policy. */ + public String getStoragePolicyName() { + return this.storagePolicyName; + } - @Override - void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - String memberName = member.getName(); - JsonValue value = member.getValue(); - try { - if (memberName.equals("name")) { - this.storagePolicyName = value.asString(); - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); - } + @Override + void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + String memberName = member.getName(); + JsonValue value = member.getValue(); + try { + if (memberName.equals("name")) { + this.storagePolicyName = value.asString(); } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); + } } + } } diff --git a/src/main/java/com/box/sdk/BoxStoragePolicyAssignment.java b/src/main/java/com/box/sdk/BoxStoragePolicyAssignment.java index 2c3fb4613..ad04c96f9 100644 --- a/src/main/java/com/box/sdk/BoxStoragePolicyAssignment.java +++ b/src/main/java/com/box/sdk/BoxStoragePolicyAssignment.java @@ -6,270 +6,257 @@ import com.eclipsesource.json.JsonValue; import java.net.URL; -/** - * Represents a BoxStoragePolicyAssignment. - */ +/** Represents a BoxStoragePolicyAssignment. */ @BoxResourceType("storage_policy_assignment") public class BoxStoragePolicyAssignment extends BoxResource { - /** - * Storage Policies Assignment URL Template. - */ - public static final URLTemplate STORAGE_POLICY_ASSIGNMENT_URL_TEMPLATE = new - URLTemplate("storage_policy_assignments"); - - /** - * Storage Policy Assignment URL Template. - */ - public static final URLTemplate STORAGE_POLICY_ASSIGNMENT_WITH_ID_URL_TEMPLATE = new - URLTemplate("storage_policy_assignments/%s"); - - /** - * Constructs a BoxStoragePolicyAssignment for a BoxStoragePolicy with a givenID. - * - * @param api the API connection to be used by the file. - * @param id the ID of the file. - */ - public BoxStoragePolicyAssignment(BoxAPIConnection api, String id) { - super(api, id); + /** Storage Policies Assignment URL Template. */ + public static final URLTemplate STORAGE_POLICY_ASSIGNMENT_URL_TEMPLATE = + new URLTemplate("storage_policy_assignments"); + + /** Storage Policy Assignment URL Template. */ + public static final URLTemplate STORAGE_POLICY_ASSIGNMENT_WITH_ID_URL_TEMPLATE = + new URLTemplate("storage_policy_assignments/%s"); + + /** + * Constructs a BoxStoragePolicyAssignment for a BoxStoragePolicy with a givenID. + * + * @param api the API connection to be used by the file. + * @param id the ID of the file. + */ + public BoxStoragePolicyAssignment(BoxAPIConnection api, String id) { + super(api, id); + } + + /** + * Create a BoxStoragePolicyAssignment for a BoxStoragePolicy. + * + * @param api the API connection to be used by the resource. + * @param policyID the policy ID of the BoxStoragePolicy. + * @param userID the user ID of the to assign the BoxStoragePolicy to. + * @return the information about the BoxStoragePolicyAssignment created. + */ + public static BoxStoragePolicyAssignment.Info create( + BoxAPIConnection api, String policyID, String userID) { + URL url = STORAGE_POLICY_ASSIGNMENT_URL_TEMPLATE.build(api.getBaseURL()); + BoxJSONRequest request = new BoxJSONRequest(api, url, HttpMethod.POST); + JsonObject requestJSON = + new JsonObject() + .add( + "storage_policy", + new JsonObject().add("type", "storage_policy").add("id", policyID)) + .add("assigned_to", new JsonObject().add("type", "user").add("id", userID)); + + request.setBody(requestJSON.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + + BoxStoragePolicyAssignment storagePolicyAssignment = + new BoxStoragePolicyAssignment(api, responseJSON.get("id").asString()); + + return storagePolicyAssignment.new Info(responseJSON); + } + } + + /** + * Returns a BoxStoragePolicyAssignment information. + * + * @param api the API connection to be used by the resource. + * @param resolvedForType the assigned entity type for the storage policy. + * @param resolvedForID the assigned entity id for the storage policy. + * @return information about this {@link BoxStoragePolicyAssignment}. + */ + public static BoxStoragePolicyAssignment.Info getAssignmentForTarget( + final BoxAPIConnection api, String resolvedForType, String resolvedForID) { + QueryStringBuilder builder = new QueryStringBuilder(); + builder + .appendParam("resolved_for_type", resolvedForType) + .appendParam("resolved_for_id", resolvedForID); + URL url = + STORAGE_POLICY_ASSIGNMENT_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString()); + BoxJSONRequest request = new BoxJSONRequest(api, url, HttpMethod.GET); + try (BoxJSONResponse response = request.send()) { + + BoxStoragePolicyAssignment storagePolicyAssignment = + new BoxStoragePolicyAssignment( + api, + response + .getJsonObject() + .get("entries") + .asArray() + .get(0) + .asObject() + .get("id") + .asString()); + + return storagePolicyAssignment + .new Info(response.getJsonObject().get("entries").asArray().get(0).asObject()); + } + } + + /** + * Checks if there is already a Storage Policy Assignment and creates one if one does not exist. + * + * @param api the API connection to be used by the resource. + * @param storagePolicyID the ID of the Storage Policy you want to assign to user. + * @param userID the ID of the user you want to assign the Storage Policy to. + * @return information about this {@link BoxStoragePolicyAssignment}. + */ + public static BoxStoragePolicyAssignment.Info assign( + BoxAPIConnection api, String storagePolicyID, String userID) { + BoxStoragePolicyAssignment.Info assignmentInfo; + assignmentInfo = getAssignmentForTarget(api, "user", userID); + + if (assignmentInfo.getStoragePolicyID().equals(storagePolicyID)) { + return assignmentInfo; } - /** - * Create a BoxStoragePolicyAssignment for a BoxStoragePolicy. - * - * @param api the API connection to be used by the resource. - * @param policyID the policy ID of the BoxStoragePolicy. - * @param userID the user ID of the to assign the BoxStoragePolicy to. - * @return the information about the BoxStoragePolicyAssignment created. - */ - public static BoxStoragePolicyAssignment.Info create(BoxAPIConnection api, String policyID, String userID) { - URL url = STORAGE_POLICY_ASSIGNMENT_URL_TEMPLATE.build(api.getBaseURL()); - BoxJSONRequest request = new BoxJSONRequest(api, url, HttpMethod.POST); - JsonObject requestJSON = new JsonObject() - .add("storage_policy", new JsonObject() - .add("type", "storage_policy") - .add("id", policyID)) - .add("assigned_to", new JsonObject() - .add("type", "user") - .add("id", userID)); - - request.setBody(requestJSON.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - - BoxStoragePolicyAssignment storagePolicyAssignment = new BoxStoragePolicyAssignment(api, - responseJSON.get("id").asString()); - - return storagePolicyAssignment.new Info(responseJSON); - } + if (assignmentInfo.getAssignedToType().equals("enterprise")) { + return create(api, storagePolicyID, userID); } - /** - * Returns a BoxStoragePolicyAssignment information. - * - * @param api the API connection to be used by the resource. - * @param resolvedForType the assigned entity type for the storage policy. - * @param resolvedForID the assigned entity id for the storage policy. - * @return information about this {@link BoxStoragePolicyAssignment}. - */ - public static BoxStoragePolicyAssignment.Info getAssignmentForTarget(final BoxAPIConnection api, - String resolvedForType, String resolvedForID) { - QueryStringBuilder builder = new QueryStringBuilder(); - builder.appendParam("resolved_for_type", resolvedForType) - .appendParam("resolved_for_id", resolvedForID); - URL url = STORAGE_POLICY_ASSIGNMENT_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString()); - BoxJSONRequest request = new BoxJSONRequest(api, url, HttpMethod.GET); - try (BoxJSONResponse response = request.send()) { - - BoxStoragePolicyAssignment storagePolicyAssignment = new BoxStoragePolicyAssignment(api, - response.getJsonObject().get("entries").asArray().get(0).asObject().get("id").asString()); - - return storagePolicyAssignment - .new Info(response.getJsonObject().get("entries").asArray().get(0).asObject()); - } + assignmentInfo.setStoragePolicyID(storagePolicyID); + BoxStoragePolicyAssignment assignment = + new BoxStoragePolicyAssignment(api, assignmentInfo.getID()); + assignment.updateInfo(assignmentInfo); + return assignmentInfo; + } + + /** + * Updates the information about the BoxStoragePolicyAssignment with any info fields that have + * been modified locally. + * + * @param info the updated info. + */ + public void updateInfo(BoxStoragePolicyAssignment.Info info) { + URL url = + STORAGE_POLICY_ASSIGNMENT_WITH_ID_URL_TEMPLATE.buildAlpha( + this.getAPI().getBaseURL(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); + request.setBody(info.getPendingChanges()); + + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + info.update(responseJSON); + } + } + + /** @return information about this {@link BoxStoragePolicyAssignment}. */ + public BoxStoragePolicyAssignment.Info getInfo() { + URL url = + STORAGE_POLICY_ASSIGNMENT_WITH_ID_URL_TEMPLATE.buildAlpha( + this.getAPI().getBaseURL(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, HttpMethod.GET); + try (BoxJSONResponse response = request.send()) { + return new Info(Json.parse(response.getJSON()).asObject()); } + } - /** - * Checks if there is already a Storage Policy Assignment and creates one if one does not exist. - * - * @param api the API connection to be used by the resource. - * @param storagePolicyID the ID of the Storage Policy you want to assign to user. - * @param userID the ID of the user you want to assign the Storage Policy to. - * @return information about this {@link BoxStoragePolicyAssignment}. - */ - public static BoxStoragePolicyAssignment.Info assign(BoxAPIConnection api, String storagePolicyID, String userID) { - BoxStoragePolicyAssignment.Info assignmentInfo; - assignmentInfo = getAssignmentForTarget(api, "user", userID); + /** Deletes this BoxStoragePolicyAssignment. */ + public void delete() { + URL url = + STORAGE_POLICY_ASSIGNMENT_WITH_ID_URL_TEMPLATE.buildAlpha( + this.getAPI().getBaseURL(), this.getID()); + BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, HttpMethod.DELETE); + request.send().close(); + } - if (assignmentInfo.getStoragePolicyID().equals(storagePolicyID)) { - return assignmentInfo; - } + /** Contains information about a BoxStoragePolicyAssignment. */ + public class Info extends BoxResource.Info { - if (assignmentInfo.getAssignedToType().equals("enterprise")) { - return create(api, storagePolicyID, userID); - } + /** @see #getStoragePolicyID() */ + private String storagePolicyID; + + /** @see #getStoragePolicyType() */ + private String storagePolicyType; + + /** @see #getAssignedToID() */ + private String assignedToID; + + /** @see #getAssignedToType() */ + private String assignedToType; - assignmentInfo.setStoragePolicyID(storagePolicyID); - BoxStoragePolicyAssignment assignment = new BoxStoragePolicyAssignment(api, assignmentInfo.getID()); - assignment.updateInfo(assignmentInfo); - return assignmentInfo; + /** Constructs an empty Info object. */ + public Info() { + super(); } /** - * Updates the information about the BoxStoragePolicyAssignment with any info fields that have been - * modified locally. + * Constructs an Info object by parsing information from a JSON string. * - * @param info the updated info. + * @param json the JSON string to parse. */ - public void updateInfo(BoxStoragePolicyAssignment.Info info) { - URL url = STORAGE_POLICY_ASSIGNMENT_WITH_ID_URL_TEMPLATE.buildAlpha(this.getAPI().getBaseURL(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); - request.setBody(info.getPendingChanges()); - - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - info.update(responseJSON); - } + public Info(String json) { + super(json); } /** - * @return information about this {@link BoxStoragePolicyAssignment}. + * Constructs an Info object using an already parsed JSON object. + * + * @param jsonObject the parsed JSON object. */ - public BoxStoragePolicyAssignment.Info getInfo() { - URL url = STORAGE_POLICY_ASSIGNMENT_WITH_ID_URL_TEMPLATE.buildAlpha(this.getAPI().getBaseURL(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, HttpMethod.GET); - try (BoxJSONResponse response = request.send()) { - return new Info(Json.parse(response.getJSON()).asObject()); - } + Info(JsonObject jsonObject) { + super(jsonObject); } - /** - * Deletes this BoxStoragePolicyAssignment. - */ - public void delete() { - URL url = STORAGE_POLICY_ASSIGNMENT_WITH_ID_URL_TEMPLATE.buildAlpha(this.getAPI().getBaseURL(), this.getID()); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, HttpMethod.DELETE); - request.send().close(); + @Override + public BoxResource getResource() { + return BoxStoragePolicyAssignment.this; } - /** - * Contains information about a BoxStoragePolicyAssignment. - */ - public class Info extends BoxResource.Info { - - /** - * @see #getStoragePolicyID() - */ - private String storagePolicyID; - - /** - * @see #getStoragePolicyType() - */ - private String storagePolicyType; - - /** - * @see #getAssignedToID() - */ - private String assignedToID; - - /** - * @see #getAssignedToType() - */ - private String assignedToType; - - /** - * Constructs an empty Info object. - */ - public Info() { - super(); - } - - /** - * Constructs an Info object by parsing information from a JSON string. - * - * @param json the JSON string to parse. - */ - public Info(String json) { - super(json); - } - - /** - * Constructs an Info object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - Info(JsonObject jsonObject) { - super(jsonObject); - } - - @Override - public BoxResource getResource() { - return BoxStoragePolicyAssignment.this; - } + /** @return the entity type that this is assigned to. */ + public String getAssignedToType() { + return this.assignedToType; + } - /** - * @return the entity type that this is assigned to. - */ - public String getAssignedToType() { - return this.assignedToType; - } + /** @return the entity id that this is assigned to. */ + public String getAssignedToID() { + return this.assignedToID; + } - /** - * @return the entity id that this is assigned to. - */ - public String getAssignedToID() { - return this.assignedToID; - } + /** @return storage policy id that is assigned to. */ + public String getStoragePolicyID() { + return this.storagePolicyID; + } - /** - * @return storage policy id that is assigned to. - */ - public String getStoragePolicyID() { - return this.storagePolicyID; - } + /** + * Sets the storage policy of the storage policy assignment. + * + * @param storagePolicyID the Id of the storage policy you wish to assign. + */ + public void setStoragePolicyID(String storagePolicyID) { + this.storagePolicyID = storagePolicyID; + JsonObject storagePolicyObject = new JsonObject(); + storagePolicyObject.add("type", "storage_policy"); + storagePolicyObject.add("id", storagePolicyID); - /** - * Sets the storage policy of the storage policy assignment. - * - * @param storagePolicyID the Id of the storage policy you wish to assign. - */ - public void setStoragePolicyID(String storagePolicyID) { - this.storagePolicyID = storagePolicyID; - JsonObject storagePolicyObject = new JsonObject(); - storagePolicyObject.add("type", "storage_policy"); - storagePolicyObject.add("id", storagePolicyID); - - this.addPendingChange("storage_policy", storagePolicyObject); - } + this.addPendingChange("storage_policy", storagePolicyObject); + } - /** - * @return storage policy type that is assigned to. - */ - public String getStoragePolicyType() { - return this.storagePolicyType; - } + /** @return storage policy type that is assigned to. */ + public String getStoragePolicyType() { + return this.storagePolicyType; + } - /** - * {@inheritDoc} - */ - @Override - void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - String memberName = member.getName(); - JsonValue value = member.getValue(); - try { - if (memberName.equals("assigned_to")) { - JsonObject assignmentJSON = value.asObject(); - this.assignedToType = assignmentJSON.get("type").asString(); - this.assignedToID = assignmentJSON.get("id").asString(); - } else if (memberName.equals("storage_policy")) { - JsonObject storagePolicyJSON = value.asObject(); - this.storagePolicyID = storagePolicyJSON.get("id").asString(); - this.storagePolicyType = storagePolicyJSON.get("type").asString(); - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); - } + /** {@inheritDoc} */ + @Override + void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + String memberName = member.getName(); + JsonValue value = member.getValue(); + try { + if (memberName.equals("assigned_to")) { + JsonObject assignmentJSON = value.asObject(); + this.assignedToType = assignmentJSON.get("type").asString(); + this.assignedToID = assignmentJSON.get("id").asString(); + } else if (memberName.equals("storage_policy")) { + JsonObject storagePolicyJSON = value.asObject(); + this.storagePolicyID = storagePolicyJSON.get("id").asString(); + this.storagePolicyType = storagePolicyJSON.get("type").asString(); } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); + } } + } } diff --git a/src/main/java/com/box/sdk/BoxTask.java b/src/main/java/com/box/sdk/BoxTask.java index 79f9a6adb..15374d85b 100644 --- a/src/main/java/com/box/sdk/BoxTask.java +++ b/src/main/java/com/box/sdk/BoxTask.java @@ -9,467 +9,447 @@ import java.util.Date; import java.util.List; -/** - * Represents a task on Box. Tasks can have a due date and can be assigned to a specific user. - */ +/** Represents a task on Box. Tasks can have a due date and can be assigned to a specific user. */ @BoxResourceType("task") public class BoxTask extends BoxResource { + /** Task URL Template. */ + public static final URLTemplate TASK_URL_TEMPLATE = new URLTemplate("tasks/%s"); + /** Get Assignments URL Template. */ + public static final URLTemplate GET_ASSIGNMENTS_URL_TEMPLATE = + new URLTemplate("tasks/%s/assignments"); + /** Add Task Assignment URL Template. */ + public static final URLTemplate ADD_TASK_ASSIGNMENT_URL_TEMPLATE = + new URLTemplate("task_assignments"); + + /** + * Constructs a BoxTask for a task with a given ID. + * + * @param api the API connection to be used by the task. + * @param id the ID of the task. + */ + public BoxTask(BoxAPIConnection api, String id) { + super(api, id); + } + + /** Deletes this task. */ + public void delete() { + URL url = TASK_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); + request.send().close(); + } + + /** + * Adds a new assignment to this task. + * + * @param assignTo the user to assign the assignment to. + * @return information about the newly added task assignment. + */ + public BoxTaskAssignment.Info addAssignment(BoxUser assignTo) { + JsonObject taskJSON = new JsonObject(); + taskJSON.add("type", "task"); + taskJSON.add("id", this.getID()); + + JsonObject assignToJSON = new JsonObject(); + assignToJSON.add("id", assignTo.getID()); + + JsonObject requestJSON = new JsonObject(); + requestJSON.add("task", taskJSON); + requestJSON.add("assign_to", assignToJSON); + + URL url = ADD_TASK_ASSIGNMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); + request.setBody(requestJSON.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + + BoxTaskAssignment addedAssignment = + new BoxTaskAssignment(this.getAPI(), responseJSON.get("id").asString()); + return addedAssignment.new Info(responseJSON); + } + } + + /** + * Adds a new assignment to this task using user's login as identifier. + * + * @param assignToLogin the login of user to assign the task to. + * @return information about the newly added task assignment. + */ + public BoxTaskAssignment.Info addAssignmentByLogin(String assignToLogin) { + JsonObject taskJSON = new JsonObject(); + taskJSON.add("type", "task"); + taskJSON.add("id", this.getID()); + + JsonObject assignToJSON = new JsonObject(); + assignToJSON.add("login", assignToLogin); + + JsonObject requestJSON = new JsonObject(); + requestJSON.add("task", taskJSON); + requestJSON.add("assign_to", assignToJSON); + + URL url = ADD_TASK_ASSIGNMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); + request.setBody(requestJSON.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + + BoxTaskAssignment addedAssignment = + new BoxTaskAssignment(this.getAPI(), responseJSON.get("id").asString()); + return addedAssignment.new Info(responseJSON); + } + } + + /** + * Gets any assignments for this task. + * + * @return a list of assignments for this task. + */ + public List getAssignments() { + URL url = GET_ASSIGNMENTS_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + + int totalCount = responseJSON.get("total_count").asInt(); + List assignments = new ArrayList<>(totalCount); + JsonArray entries = responseJSON.get("entries").asArray(); + for (JsonValue value : entries) { + JsonObject assignmentJSON = value.asObject(); + BoxTaskAssignment assignment = + new BoxTaskAssignment(this.getAPI(), assignmentJSON.get("id").asString()); + BoxTaskAssignment.Info info = assignment.new Info(assignmentJSON); + assignments.add(info); + } + + return assignments; + } + } + + /** + * Gets an iterable of all the assignments of this task. + * + * @param fields the fields to retrieve. + * @return an iterable containing info about all the assignments. + */ + public Iterable getAllAssignments(String... fields) { + final QueryStringBuilder builder = new QueryStringBuilder(); + if (fields.length > 0) { + builder.appendParam("fields", fields); + } + return () -> { + URL url = + GET_ASSIGNMENTS_URL_TEMPLATE.buildWithQuery( + BoxTask.this.getAPI().getBaseURL(), builder.toString(), BoxTask.this.getID()); + return new BoxTaskAssignmentIterator(BoxTask.this.getAPI(), url); + }; + } + + /** + * Gets information about this task. + * + * @param fields the fields to retrieve. + * @return info about this task. + */ + public Info getInfo(String... fields) { + URL url = TASK_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + if (fields.length > 0) { + QueryStringBuilder builder = new QueryStringBuilder().appendParam("fields", fields); + url = + TASK_URL_TEMPLATE.buildWithQuery( + this.getAPI().getBaseURL(), builder.toString(), this.getID()); + } + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + return new Info(responseJSON); + } + } + + /** + * Updates the information about this task with any info fields that have been modified locally. + * + *

The only fields that will be updated are the ones that have been modified locally. For + * example, the following code won't update any information (or even send a network request) since + * none of the info's fields were changed: + * + *

BoxTask task = new BoxTask(api, id);
+   * BoxTask.Info info = task.getInfo();
+   * task.updateInfo(info);
+ * + * @param info the updated info. + */ + public void updateInfo(BoxTask.Info info) { + URL url = TASK_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); + request.setBody(info.getPendingChanges()); + try (BoxJSONResponse response = request.send()) { + JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); + info.update(jsonObject); + } + } + + /** Enumerates the possible actions that a task can have. */ + public enum Action { + /** The task must be reviewed. */ + REVIEW("review"), + + /** The task must be completed. */ + COMPLETE("complete"); + + private final String jsonValue; + + Action(String jsonValue) { + this.jsonValue = jsonValue; + } + + static Action fromJSONString(String jsonValue) { + if (jsonValue.equals("review")) { + return REVIEW; + } else if (jsonValue.equals("complete")) { + return COMPLETE; + } else { + throw new IllegalArgumentException("The provided JSON value isn't a valid Action."); + } + } + + String toJSONString() { + return this.jsonValue; + } + } + + /** Enumerates the possible completion rules for a task. */ + public enum CompletionRule { + + /** The task must be completed by all assignees. */ + ALL_ASSIGNEES("all_assignees"), + + /** The task must be completed by at least one assignee. */ + ANY_ASSIGNEE("any_assignee"); + + private final String jsonValue; + + CompletionRule(String jsonValue) { + this.jsonValue = jsonValue; + } + + String toJSONString() { + return this.jsonValue; + } + } + + /** Contains information about a BoxTask. */ + public class Info extends BoxResource.Info { + private BoxFile.Info item; + private Date dueAt; + private String action; + private String completionRule; + private String message; + private List taskAssignments; + private boolean completed; + private BoxUser.Info createdBy; + private Date createdAt; + + /** Constructs an empty Info object. */ + public Info() { + super(); + } + /** - * Task URL Template. + * Constructs an Info object by parsing information from a JSON string. + * + * @param json the JSON string to parse. */ - public static final URLTemplate TASK_URL_TEMPLATE = new URLTemplate("tasks/%s"); + public Info(String json) { + super(json); + } + /** - * Get Assignments URL Template. + * Constructs an Info object using an already parsed JSON object. + * + * @param jsonObject the parsed JSON object. */ - public static final URLTemplate GET_ASSIGNMENTS_URL_TEMPLATE = new URLTemplate("tasks/%s/assignments"); + Info(JsonObject jsonObject) { + super(jsonObject); + } + + @Override + public BoxTask getResource() { + return BoxTask.this; + } + /** - * Add Task Assignment URL Template. + * Gets the file associated with this task. + * + * @return the file associated with this task. */ - public static final URLTemplate ADD_TASK_ASSIGNMENT_URL_TEMPLATE = new URLTemplate("task_assignments"); + public BoxFile.Info getItem() { + return this.item; + } /** - * Constructs a BoxTask for a task with a given ID. + * Gets the date at which this task is due. * - * @param api the API connection to be used by the task. - * @param id the ID of the task. + * @return the date at which this task is due. */ - public BoxTask(BoxAPIConnection api, String id) { - super(api, id); + public Date getDueAt() { + return this.dueAt; } /** - * Deletes this task. + * Sets the task's due date. + * + * @param dueAt the task's due date. */ - public void delete() { - URL url = TASK_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); - request.send().close(); + public void setDueAt(Date dueAt) { + this.dueAt = dueAt; + this.addPendingChange("due_at", BoxDateFormat.format(dueAt)); } /** - * Adds a new assignment to this task. + * Gets the action the task assignee will be prompted to do. * - * @param assignTo the user to assign the assignment to. - * @return information about the newly added task assignment. + * @return the action the task assignee will be prompted to do. */ - public BoxTaskAssignment.Info addAssignment(BoxUser assignTo) { - JsonObject taskJSON = new JsonObject(); - taskJSON.add("type", "task"); - taskJSON.add("id", this.getID()); - - JsonObject assignToJSON = new JsonObject(); - assignToJSON.add("id", assignTo.getID()); - - JsonObject requestJSON = new JsonObject(); - requestJSON.add("task", taskJSON); - requestJSON.add("assign_to", assignToJSON); - - URL url = ADD_TASK_ASSIGNMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); - request.setBody(requestJSON.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - - BoxTaskAssignment addedAssignment = new BoxTaskAssignment(this.getAPI(), responseJSON.get("id").asString()); - return addedAssignment.new Info(responseJSON); - } + public String getTaskType() { + return this.action; } /** - * Adds a new assignment to this task using user's login as identifier. + * Returns the completion rule for the task. * - * @param assignToLogin the login of user to assign the task to. - * @return information about the newly added task assignment. + * @return the task completion rule. */ - public BoxTaskAssignment.Info addAssignmentByLogin(String assignToLogin) { - JsonObject taskJSON = new JsonObject(); - taskJSON.add("type", "task"); - taskJSON.add("id", this.getID()); - - JsonObject assignToJSON = new JsonObject(); - assignToJSON.add("login", assignToLogin); - - JsonObject requestJSON = new JsonObject(); - requestJSON.add("task", taskJSON); - requestJSON.add("assign_to", assignToJSON); - - URL url = ADD_TASK_ASSIGNMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); - request.setBody(requestJSON.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - - BoxTaskAssignment addedAssignment = new BoxTaskAssignment(this.getAPI(), responseJSON.get("id").asString()); - return addedAssignment.new Info(responseJSON); - } + public String getCompletionRule() { + return this.completionRule; } /** - * Gets any assignments for this task. + * Sets the task's completion rule. * - * @return a list of assignments for this task. + * @param completionRule the new completion rule. */ - public List getAssignments() { - URL url = GET_ASSIGNMENTS_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - - int totalCount = responseJSON.get("total_count").asInt(); - List assignments = new ArrayList<>(totalCount); - JsonArray entries = responseJSON.get("entries").asArray(); - for (JsonValue value : entries) { - JsonObject assignmentJSON = value.asObject(); - BoxTaskAssignment assignment = - new BoxTaskAssignment(this.getAPI(), assignmentJSON.get("id").asString()); - BoxTaskAssignment.Info info = assignment.new Info(assignmentJSON); - assignments.add(info); - } - - return assignments; - } + public void setCompletionRule(CompletionRule completionRule) { + this.completionRule = completionRule.toJSONString(); + this.addPendingChange("completion_rule", completionRule.toJSONString()); } /** - * Gets an iterable of all the assignments of this task. + * Gets the message that will be included with this task. * - * @param fields the fields to retrieve. - * @return an iterable containing info about all the assignments. + * @return the message that will be included with this task. */ - public Iterable getAllAssignments(String... fields) { - final QueryStringBuilder builder = new QueryStringBuilder(); - if (fields.length > 0) { - builder.appendParam("fields", fields); - } - return () -> { - URL url = GET_ASSIGNMENTS_URL_TEMPLATE.buildWithQuery( - BoxTask.this.getAPI().getBaseURL(), builder.toString(), BoxTask.this.getID()); - return new BoxTaskAssignmentIterator(BoxTask.this.getAPI(), url); - }; + public String getMessage() { + return this.message; } - /** - * Gets information about this task. + * Sets the task's message. * - * @param fields the fields to retrieve. - * @return info about this task. + * @param message the task's new message. */ - public Info getInfo(String... fields) { - URL url = TASK_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - if (fields.length > 0) { - QueryStringBuilder builder = new QueryStringBuilder().appendParam("fields", fields); - url = TASK_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), builder.toString(), this.getID()); - } - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - return new Info(responseJSON); - } + public void setMessage(String message) { + this.message = message; + this.addPendingChange("message", message); } /** - * Updates the information about this task with any info fields that have been modified locally. - * - *

The only fields that will be updated are the ones that have been modified locally. For example, the following - * code won't update any information (or even send a network request) since none of the info's fields were - * changed:

- * - *
BoxTask task = new BoxTask(api, id);
-     * BoxTask.Info info = task.getInfo();
-     * task.updateInfo(info);
+ * Gets the collection of task assignments associated with this task. * - * @param info the updated info. + * @return the collection of task assignments associated with this task. */ - public void updateInfo(BoxTask.Info info) { - URL url = TASK_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); - request.setBody(info.getPendingChanges()); - try (BoxJSONResponse response = request.send()) { - JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - info.update(jsonObject); - } + public List getTaskAssignments() { + return this.taskAssignments; } /** - * Enumerates the possible actions that a task can have. + * Gets whether or not this task has been completed. + * + * @return whether or not this task has been completed. */ - public enum Action { - /** - * The task must be reviewed. - */ - REVIEW("review"), - - /** - * The task must be completed. - */ - COMPLETE("complete"); - - private final String jsonValue; - - Action(String jsonValue) { - this.jsonValue = jsonValue; - } - - static Action fromJSONString(String jsonValue) { - if (jsonValue.equals("review")) { - return REVIEW; - } else if (jsonValue.equals("complete")) { - return COMPLETE; - } else { - throw new IllegalArgumentException("The provided JSON value isn't a valid Action."); - } - } - - String toJSONString() { - return this.jsonValue; - } + public boolean isCompleted() { + return this.completed; } /** - * Enumerates the possible completion rules for a task. + * Gets the user who created this task. + * + * @return the user who created this task. */ - public enum CompletionRule { - - /** - * The task must be completed by all assignees. - */ - ALL_ASSIGNEES("all_assignees"), - - /** - * The task must be completed by at least one assignee. - */ - ANY_ASSIGNEE("any_assignee"); - - private final String jsonValue; - - CompletionRule(String jsonValue) { - this.jsonValue = jsonValue; - } - - String toJSONString() { - return this.jsonValue; - } + public BoxUser.Info getCreatedBy() { + return this.createdBy; } /** - * Contains information about a BoxTask. + * Gets when this task was created. + * + * @return when this task was created. */ - public class Info extends BoxResource.Info { - private BoxFile.Info item; - private Date dueAt; - private String action; - private String completionRule; - private String message; - private List taskAssignments; - private boolean completed; - private BoxUser.Info createdBy; - private Date createdAt; - - /** - * Constructs an empty Info object. - */ - public Info() { - super(); - } - - /** - * Constructs an Info object by parsing information from a JSON string. - * - * @param json the JSON string to parse. - */ - public Info(String json) { - super(json); - } - - /** - * Constructs an Info object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - Info(JsonObject jsonObject) { - super(jsonObject); - } - - @Override - public BoxTask getResource() { - return BoxTask.this; - } - - /** - * Gets the file associated with this task. - * - * @return the file associated with this task. - */ - public BoxFile.Info getItem() { - return this.item; - } - - /** - * Gets the date at which this task is due. - * - * @return the date at which this task is due. - */ - public Date getDueAt() { - return this.dueAt; - } - - /** - * Sets the task's due date. - * - * @param dueAt the task's due date. - */ - public void setDueAt(Date dueAt) { - this.dueAt = dueAt; - this.addPendingChange("due_at", BoxDateFormat.format(dueAt)); - } - - /** - * Gets the action the task assignee will be prompted to do. - * - * @return the action the task assignee will be prompted to do. - */ - public String getTaskType() { - return this.action; - } - - /** - * Returns the completion rule for the task. - * - * @return the task completion rule. - */ - public String getCompletionRule() { - return this.completionRule; - } - - /** - * Sets the task's completion rule. - * - * @param completionRule the new completion rule. - */ - public void setCompletionRule(CompletionRule completionRule) { - this.completionRule = completionRule.toJSONString(); - this.addPendingChange("completion_rule", completionRule.toJSONString()); - } - - /** - * Gets the message that will be included with this task. - * - * @return the message that will be included with this task. - */ - public String getMessage() { - return this.message; - } - - /** - * Sets the task's message. - * - * @param message the task's new message. - */ - public void setMessage(String message) { - this.message = message; - this.addPendingChange("message", message); - } - - /** - * Gets the collection of task assignments associated with this task. - * - * @return the collection of task assignments associated with this task. - */ - public List getTaskAssignments() { - return this.taskAssignments; - } - - /** - * Gets whether or not this task has been completed. - * - * @return whether or not this task has been completed. - */ - public boolean isCompleted() { - return this.completed; - } - - /** - * Gets the user who created this task. - * - * @return the user who created this task. - */ - public BoxUser.Info getCreatedBy() { - return this.createdBy; - } + public Date getCreatedAt() { + return this.createdAt; + } - /** - * Gets when this task was created. - * - * @return when this task was created. - */ - public Date getCreatedAt() { - return this.createdAt; + @Override + void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + + String memberName = member.getName(); + JsonValue value = member.getValue(); + try { + switch (memberName) { + case "item": + JsonObject itemJSON = value.asObject(); + String itemID = itemJSON.get("id").asString(); + BoxFile file = new BoxFile(getAPI(), itemID); + this.item = file.new Info(itemJSON); + break; + case "due_at": + this.dueAt = BoxDateFormat.parse(value.asString()); + break; + case "action": + this.action = value.asString(); + break; + case "completion_rule": + this.completionRule = value.asString(); + break; + case "message": + this.message = value.asString(); + break; + case "task_assignment_collection": + this.taskAssignments = this.parseTaskAssignmentCollection(value.asObject()); + break; + case "is_completed": + this.completed = value.asBoolean(); + break; + case "created_by": + JsonObject userJSON = value.asObject(); + String userID = userJSON.get("id").asString(); + BoxUser user = new BoxUser(getAPI(), userID); + this.createdBy = user.new Info(userJSON); + break; + case "created_at": + this.createdAt = BoxDateFormat.parse(value.asString()); + break; + default: + break; } - @Override - void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - - String memberName = member.getName(); - JsonValue value = member.getValue(); - try { - switch (memberName) { - case "item": - JsonObject itemJSON = value.asObject(); - String itemID = itemJSON.get("id").asString(); - BoxFile file = new BoxFile(getAPI(), itemID); - this.item = file.new Info(itemJSON); - break; - case "due_at": - this.dueAt = BoxDateFormat.parse(value.asString()); - break; - case "action": - this.action = value.asString(); - break; - case "completion_rule": - this.completionRule = value.asString(); - break; - case "message": - this.message = value.asString(); - break; - case "task_assignment_collection": - this.taskAssignments = this.parseTaskAssignmentCollection(value.asObject()); - break; - case "is_completed": - this.completed = value.asBoolean(); - break; - case "created_by": - JsonObject userJSON = value.asObject(); - String userID = userJSON.get("id").asString(); - BoxUser user = new BoxUser(getAPI(), userID); - this.createdBy = user.new Info(userJSON); - break; - case "created_at": - this.createdAt = BoxDateFormat.parse(value.asString()); - break; - default: - break; - } - - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); - } - } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); + } + } - private List parseTaskAssignmentCollection(JsonObject jsonObject) { - int count = jsonObject.get("total_count").asInt(); - List taskAssignmentCollection = new ArrayList<>(count); - JsonArray entries = jsonObject.get("entries").asArray(); - for (JsonValue value : entries) { - JsonObject entry = value.asObject(); - String id = entry.get("id").asString(); - BoxTaskAssignment assignment = new BoxTaskAssignment(getAPI(), id); - taskAssignmentCollection.add(assignment.new Info(entry)); - } - - return taskAssignmentCollection; - } + private List parseTaskAssignmentCollection(JsonObject jsonObject) { + int count = jsonObject.get("total_count").asInt(); + List taskAssignmentCollection = new ArrayList<>(count); + JsonArray entries = jsonObject.get("entries").asArray(); + for (JsonValue value : entries) { + JsonObject entry = value.asObject(); + String id = entry.get("id").asString(); + BoxTaskAssignment assignment = new BoxTaskAssignment(getAPI(), id); + taskAssignmentCollection.add(assignment.new Info(entry)); + } + + return taskAssignmentCollection; } + } } diff --git a/src/main/java/com/box/sdk/BoxTaskAssignment.java b/src/main/java/com/box/sdk/BoxTaskAssignment.java index 073c59c88..40080a78f 100644 --- a/src/main/java/com/box/sdk/BoxTaskAssignment.java +++ b/src/main/java/com/box/sdk/BoxTaskAssignment.java @@ -7,335 +7,321 @@ import java.util.Date; /** - * Represents a task assignment on Box, which can be used to assign a task to a single user. There can be multiple - * assignments on a single task. + * Represents a task assignment on Box, which can be used to assign a task to a single user. There + * can be multiple assignments on a single task. */ @BoxResourceType("task_assignment") public class BoxTaskAssignment extends BoxResource { + /** Task Assignment URL Template. */ + public static final URLTemplate TASK_ASSIGNMENT_URL_TEMPLATE = + new URLTemplate("task_assignments/%s"); + + /** + * Constructs a BoxTaskAssignment for a task assignment with a given ID. + * + * @param api the API connection to be used by the resource. + * @param id the ID of the task assignment. + */ + public BoxTaskAssignment(BoxAPIConnection api, String id) { + super(api, id); + } + + /** Deletes this task assignment. */ + public void delete() { + URL url = TASK_ASSIGNMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); + request.send().close(); + } + + /** + * Gets information about this task assignment. + * + * @return info about this task assignment. + */ + public Info getInfo() { + URL url = TASK_ASSIGNMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + return new Info(responseJSON); + } + } + + /** + * Gets information about this task assignment. + * + * @param fields the fields to retrieve. + * @return info about this task assignment. + */ + public Info getInfo(String... fields) { + QueryStringBuilder builder = new QueryStringBuilder(); + if (fields.length > 0) { + builder.appendParam("fields", fields); + } + URL url = + TASK_ASSIGNMENT_URL_TEMPLATE.buildWithQuery( + this.getAPI().getBaseURL(), builder.toString(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + return new Info(responseJSON); + } + } + + /** + * Updates the information about this task assignment with any info fields that have been modified + * locally. + * + *

The only fields that will be updated are the ones that have been modified locally. For + * example, the following code won't update any information (or even send a network request) since + * none of the info's fields were changed: + * + *

BoxTaskAssignment taskAssignment = new BoxTaskAssignment(api, id);
+   * BoxTaskAssignment.Info info = taskAssignment.getInfo();
+   * taskAssignment.updateInfo(info);
+ * + * @param info the updated info. + */ + public void updateInfo(BoxTaskAssignment.Info info) { + URL url = TASK_ASSIGNMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); + request.setBody(info.getPendingChanges()); + try (BoxJSONResponse response = request.send()) { + JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); + info.update(jsonObject); + } + } + + /** Enumerates the possible resolution states that a task assignment can have. */ + public enum ResolutionState { + /** The task assignment has been completed. */ + COMPLETED("completed"), + + /** The task assignment is incomplete. */ + INCOMPLETE("incomplete"), + + /** The task assignment has been approved. */ + APPROVED("approved"), + + /** The task assignment has been rejected. */ + REJECTED("rejected"); + + private final String jsonValue; + + ResolutionState(String jsonValue) { + this.jsonValue = jsonValue; + } + + static ResolutionState fromJSONString(String jsonValue) { + if (jsonValue.equals("completed")) { + return COMPLETED; + } else if (jsonValue.equals("incomplete")) { + return INCOMPLETE; + } else if (jsonValue.equals("approved")) { + return APPROVED; + } else if (jsonValue.equals("rejected")) { + return REJECTED; + } else { + throw new IllegalArgumentException( + "The provided JSON value isn't a valid ResolutionState."); + } + } + + String toJSONString() { + return this.jsonValue; + } + } + + /** Contains information about a task assignment. */ + public class Info extends BoxResource.Info { + private BoxItem.Info item; + private BoxUser.Info assignedTo; + private String message; + private Date completedAt; + private Date assignedAt; + private Date remindedAt; + private ResolutionState resolutionState; + private String status; + private BoxUser.Info assignedBy; + + /** Constructs an empty Info object. */ + public Info() { + super(); + } + /** - * Task Assignment URL Template. + * Constructs an Info object by parsing information from a JSON string. + * + * @param json the JSON string to parse. */ - public static final URLTemplate TASK_ASSIGNMENT_URL_TEMPLATE = new URLTemplate("task_assignments/%s"); + public Info(String json) { + super(json); + } /** - * Constructs a BoxTaskAssignment for a task assignment with a given ID. + * Constructs an Info object using an already parsed JSON object. * - * @param api the API connection to be used by the resource. - * @param id the ID of the task assignment. + * @param jsonObject the parsed JSON object. */ - public BoxTaskAssignment(BoxAPIConnection api, String id) { - super(api, id); + Info(JsonObject jsonObject) { + super(jsonObject); + } + + @Override + public BoxResource getResource() { + return BoxTaskAssignment.this; } /** - * Deletes this task assignment. + * Gets the item associated with this task. + * + * @return the item associated with this task. */ - public void delete() { - URL url = TASK_ASSIGNMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); - request.send().close(); + public BoxItem.Info getItem() { + return this.item; } /** - * Gets information about this task assignment. + * Gets the user the assignment is assigned to. * - * @return info about this task assignment. + * @return the user assigned to this assignment. */ - public Info getInfo() { - URL url = TASK_ASSIGNMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - return new Info(responseJSON); - } + public BoxUser.Info getAssignedTo() { + return this.assignedTo; } /** - * Gets information about this task assignment. + * Gets the message that will be included with this task assignment. * - * @param fields the fields to retrieve. - * @return info about this task assignment. + * @return the message that will be included with this task assignment. */ - public Info getInfo(String... fields) { - QueryStringBuilder builder = new QueryStringBuilder(); - if (fields.length > 0) { - builder.appendParam("fields", fields); - } - URL url = TASK_ASSIGNMENT_URL_TEMPLATE.buildWithQuery( - this.getAPI().getBaseURL(), builder.toString(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - return new Info(responseJSON); - } + public String getMessage() { + return this.message; } /** - * Updates the information about this task assignment with any info fields that have been modified locally. - * - *

The only fields that will be updated are the ones that have been modified locally. For example, the following - * code won't update any information (or even send a network request) since none of the info's fields were - * changed:

+ * Sets the message for the assignment. * - *
BoxTaskAssignment taskAssignment = new BoxTaskAssignment(api, id);
-     * BoxTaskAssignment.Info info = taskAssignment.getInfo();
-     * taskAssignment.updateInfo(info);
- * - * @param info the updated info. + * @param message the message to be set on the assignment. */ - public void updateInfo(BoxTaskAssignment.Info info) { - URL url = TASK_ASSIGNMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); - request.setBody(info.getPendingChanges()); - try (BoxJSONResponse response = request.send()) { - JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - info.update(jsonObject); - } + public void setMessage(String message) { + this.message = message; + this.addPendingChange("message", message); } /** - * Enumerates the possible resolution states that a task assignment can have. + * Gets the date the assignment is to be completed at. + * + * @return the date the assignment is to be completed at. */ - public enum ResolutionState { - /** - * The task assignment has been completed. - */ - COMPLETED("completed"), - - /** - * The task assignment is incomplete. - */ - INCOMPLETE("incomplete"), - - /** - * The task assignment has been approved. - */ - APPROVED("approved"), - - /** - * The task assignment has been rejected. - */ - REJECTED("rejected"); - - private final String jsonValue; - - ResolutionState(String jsonValue) { - this.jsonValue = jsonValue; - } - - static ResolutionState fromJSONString(String jsonValue) { - if (jsonValue.equals("completed")) { - return COMPLETED; - } else if (jsonValue.equals("incomplete")) { - return INCOMPLETE; - } else if (jsonValue.equals("approved")) { - return APPROVED; - } else if (jsonValue.equals("rejected")) { - return REJECTED; - } else { - throw new IllegalArgumentException("The provided JSON value isn't a valid ResolutionState."); - } - } - - String toJSONString() { - return this.jsonValue; - } + public Date getCompletedAt() { + return this.completedAt; } /** - * Contains information about a task assignment. + * Gets the date the assignment was assigned at. + * + * @return the date the assignment was assigned at. */ - public class Info extends BoxResource.Info { - private BoxItem.Info item; - private BoxUser.Info assignedTo; - private String message; - private Date completedAt; - private Date assignedAt; - private Date remindedAt; - private ResolutionState resolutionState; - private String status; - private BoxUser.Info assignedBy; - - /** - * Constructs an empty Info object. - */ - public Info() { - super(); - } - - /** - * Constructs an Info object by parsing information from a JSON string. - * - * @param json the JSON string to parse. - */ - public Info(String json) { - super(json); - } - - /** - * Constructs an Info object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - Info(JsonObject jsonObject) { - super(jsonObject); - } - - @Override - public BoxResource getResource() { - return BoxTaskAssignment.this; - } - - /** - * Gets the item associated with this task. - * - * @return the item associated with this task. - */ - public BoxItem.Info getItem() { - return this.item; - } - - /** - * Gets the user the assignment is assigned to. - * - * @return the user assigned to this assignment. - */ - public BoxUser.Info getAssignedTo() { - return this.assignedTo; - } - - /** - * Gets the message that will be included with this task assignment. - * - * @return the message that will be included with this task assignment. - */ - public String getMessage() { - return this.message; - } - - /** - * Sets the message for the assignment. - * - * @param message the message to be set on the assignment. - */ - public void setMessage(String message) { - this.message = message; - this.addPendingChange("message", message); - } - - /** - * Gets the date the assignment is to be completed at. - * - * @return the date the assignment is to be completed at. - */ - public Date getCompletedAt() { - return this.completedAt; - } - - /** - * Gets the date the assignment was assigned at. - * - * @return the date the assignment was assigned at. - */ - public Date getAssignedAt() { - return this.assignedAt; - } + public Date getAssignedAt() { + return this.assignedAt; + } - /** - * Gets the date the assignee is to be reminded at. - * - * @return the date the assignee is to be reminded at. - */ - public Date getRemindedAt() { - return this.remindedAt; - } + /** + * Gets the date the assignee is to be reminded at. + * + * @return the date the assignee is to be reminded at. + */ + public Date getRemindedAt() { + return this.remindedAt; + } - /** - * Gets the current resolution state of the assignment. - * - * @return the current resolution state of the assignment. - */ - public ResolutionState getResolutionState() { - return this.resolutionState; - } + /** + * Gets the current resolution state of the assignment. + * + * @return the current resolution state of the assignment. + */ + public ResolutionState getResolutionState() { + return this.resolutionState; + } - /** - * Sets the resolution state for the assignment. - * - * @param resolutionState the resolution state to be set on the assignment. - */ - public void setResolutionState(ResolutionState resolutionState) { - this.resolutionState = resolutionState; - this.addPendingChange("resolution_state", resolutionState.toJSONString()); - } + /** + * Sets the resolution state for the assignment. + * + * @param resolutionState the resolution state to be set on the assignment. + */ + public void setResolutionState(ResolutionState resolutionState) { + this.resolutionState = resolutionState; + this.addPendingChange("resolution_state", resolutionState.toJSONString()); + } - /** - * Gets the current status of the assignment. - * - * @return the current status of the assignment. - */ - public String getStatus() { - return this.status; - } + /** + * Gets the current status of the assignment. + * + * @return the current status of the assignment. + */ + public String getStatus() { + return this.status; + } - /** - * Sets the status for the assignment. - * - * @param status the status to be set on the assignment. - */ - public void setStatus(String status) { - this.status = status; - this.addPendingChange("status", status); - } + /** + * Sets the status for the assignment. + * + * @param status the status to be set on the assignment. + */ + public void setStatus(String status) { + this.status = status; + this.addPendingChange("status", status); + } - /** - * Gets the user that assigned the assignment. - * - * @return the user that assigned the assignment. - */ - public BoxUser.Info getAssignedBy() { - return this.assignedBy; - } + /** + * Gets the user that assigned the assignment. + * + * @return the user that assigned the assignment. + */ + public BoxUser.Info getAssignedBy() { + return this.assignedBy; + } - @Override - void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - - String memberName = member.getName(); - JsonValue value = member.getValue(); - try { - if (memberName.equals("item")) { - JsonObject itemJSON = value.asObject(); - String itemID = itemJSON.get("id").asString(); - BoxFile file = new BoxFile(getAPI(), itemID); - this.item = file.new Info(itemJSON); - } else if (memberName.equals("assigned_to")) { - JsonObject userJSON = value.asObject(); - String userID = userJSON.get("id").asString(); - BoxUser user = new BoxUser(getAPI(), userID); - this.assignedTo = user.new Info(userJSON); - } else if (memberName.equals("message")) { - this.message = value.asString(); - } else if (memberName.equals("completed_at")) { - this.completedAt = BoxDateFormat.parse(value.asString()); - } else if (memberName.equals("assigned_at")) { - this.assignedAt = BoxDateFormat.parse(value.asString()); - } else if (memberName.equals("reminded_at")) { - this.remindedAt = BoxDateFormat.parse(value.asString()); - } else if (memberName.equals("resolution_state")) { - this.resolutionState = ResolutionState.fromJSONString(value.asString()); - } else if (memberName.equals("status")) { - this.status = value.asString(); - } else if (memberName.equals("assigned_by")) { - JsonObject userJSON = value.asObject(); - String userID = userJSON.get("id").asString(); - BoxUser user = new BoxUser(getAPI(), userID); - this.assignedBy = user.new Info(userJSON); - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); - } + @Override + void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + + String memberName = member.getName(); + JsonValue value = member.getValue(); + try { + if (memberName.equals("item")) { + JsonObject itemJSON = value.asObject(); + String itemID = itemJSON.get("id").asString(); + BoxFile file = new BoxFile(getAPI(), itemID); + this.item = file.new Info(itemJSON); + } else if (memberName.equals("assigned_to")) { + JsonObject userJSON = value.asObject(); + String userID = userJSON.get("id").asString(); + BoxUser user = new BoxUser(getAPI(), userID); + this.assignedTo = user.new Info(userJSON); + } else if (memberName.equals("message")) { + this.message = value.asString(); + } else if (memberName.equals("completed_at")) { + this.completedAt = BoxDateFormat.parse(value.asString()); + } else if (memberName.equals("assigned_at")) { + this.assignedAt = BoxDateFormat.parse(value.asString()); + } else if (memberName.equals("reminded_at")) { + this.remindedAt = BoxDateFormat.parse(value.asString()); + } else if (memberName.equals("resolution_state")) { + this.resolutionState = ResolutionState.fromJSONString(value.asString()); + } else if (memberName.equals("status")) { + this.status = value.asString(); + } else if (memberName.equals("assigned_by")) { + JsonObject userJSON = value.asObject(); + String userID = userJSON.get("id").asString(); + BoxUser user = new BoxUser(getAPI(), userID); + this.assignedBy = user.new Info(userJSON); } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); + } } + } } diff --git a/src/main/java/com/box/sdk/BoxTaskAssignmentIterator.java b/src/main/java/com/box/sdk/BoxTaskAssignmentIterator.java index a0dd5c6bd..0c5bddd18 100644 --- a/src/main/java/com/box/sdk/BoxTaskAssignmentIterator.java +++ b/src/main/java/com/box/sdk/BoxTaskAssignmentIterator.java @@ -6,64 +6,47 @@ import java.net.URL; import java.util.Iterator; - -/** - * An iterator object for {@link BoxTaskAssignment} object. - * Supports offset-based paging. - */ +/** An iterator object for {@link BoxTaskAssignment} object. Supports offset-based paging. */ class BoxTaskAssignmentIterator implements Iterator { - /** - * The limit of entries per response. - */ - private static final long LIMIT = 100; - - /** - * The API connection to be used. - */ - private final BoxAPIConnection api; - - /** - * Iterator object with paging support. - */ - private final JsonIterator jsonIterator; - - /** - * Creates new BoxTaskAssignment iterator. - * - * @param api The API connection to be used by the iterator. - * @param url The endpoint url. - */ - BoxTaskAssignmentIterator(BoxAPIConnection api, URL url) { - this.api = api; - this.jsonIterator = new JsonIterator(api, url, offset(0, LIMIT)); - } - - /** - * @return false if current element is the last. - */ - @Override - public boolean hasNext() { - return this.jsonIterator.hasNext(); - } - - - /** - * @return next BoxTaskAssignment.Info object in the list. - */ - @Override - public BoxTaskAssignment.Info next() { - JsonObject nextJSONObject = this.jsonIterator.next(); - String id = nextJSONObject.get("id").asString(); - - BoxTaskAssignment assignment = new BoxTaskAssignment(this.api, id); - return assignment.new Info(nextJSONObject); - } - - /** - * Remove operation is not supported. - */ - public void remove() { - throw new UnsupportedOperationException(); - } + /** The limit of entries per response. */ + private static final long LIMIT = 100; + + /** The API connection to be used. */ + private final BoxAPIConnection api; + + /** Iterator object with paging support. */ + private final JsonIterator jsonIterator; + + /** + * Creates new BoxTaskAssignment iterator. + * + * @param api The API connection to be used by the iterator. + * @param url The endpoint url. + */ + BoxTaskAssignmentIterator(BoxAPIConnection api, URL url) { + this.api = api; + this.jsonIterator = new JsonIterator(api, url, offset(0, LIMIT)); + } + + /** @return false if current element is the last. */ + @Override + public boolean hasNext() { + return this.jsonIterator.hasNext(); + } + + /** @return next BoxTaskAssignment.Info object in the list. */ + @Override + public BoxTaskAssignment.Info next() { + JsonObject nextJSONObject = this.jsonIterator.next(); + String id = nextJSONObject.get("id").asString(); + + BoxTaskAssignment assignment = new BoxTaskAssignment(this.api, id); + return assignment.new Info(nextJSONObject); + } + + /** Remove operation is not supported. */ + public void remove() { + throw new UnsupportedOperationException(); + } } diff --git a/src/main/java/com/box/sdk/BoxTermsOfService.java b/src/main/java/com/box/sdk/BoxTermsOfService.java index 672c6f1dc..2b2b018dd 100644 --- a/src/main/java/com/box/sdk/BoxTermsOfService.java +++ b/src/main/java/com/box/sdk/BoxTermsOfService.java @@ -9,390 +9,346 @@ import java.util.Date; import java.util.List; -/** - * Represents a custom Box Terms of Service object. - */ +/** Represents a custom Box Terms of Service object. */ @BoxResourceType("terms_of_service") public class BoxTermsOfService extends BoxResource { - /** - * Terms of Services URL Template. - */ - public static final URLTemplate TERMS_OF_SERVICE_URL_TEMPLATE = new URLTemplate("terms_of_services/%s"); - /** - * All Terms of Services URL Template. - */ - public static final URLTemplate ALL_TERMS_OF_SERVICES_URL_TEMPLATE = new URLTemplate("terms_of_services"); - - /** - * Constructs a BoxTermsOfService for a Box Enterprise with a given ID. - * - * @param api the API connection to be used by the resource. - * @param id the ID of the resource. - */ - public BoxTermsOfService(BoxAPIConnection api, String id) { - super(api, id); - } - - /** - * Creates a new Terms of Services. - * - * @param api the API connection to be used by the resource. - * @param termsOfServiceStatus the current status of the terms of services. Set to "enabled" or "disabled". - * @param termsOfServiceType the scope of terms of service. Set to "external" or "managed". - * @param text the text field of terms of service containing terms of service agreement info. - * @return information about the Terms of Service created. - */ - public static BoxTermsOfService.Info create(BoxAPIConnection api, - BoxTermsOfService.TermsOfServiceStatus termsOfServiceStatus, - BoxTermsOfService.TermsOfServiceType termsOfServiceType, String text) { - URL url = ALL_TERMS_OF_SERVICES_URL_TEMPLATE.build(api.getBaseURL()); - BoxJSONRequest request = new BoxJSONRequest(api, url, "POST"); - JsonObject requestJSON = new JsonObject() + /** Terms of Services URL Template. */ + public static final URLTemplate TERMS_OF_SERVICE_URL_TEMPLATE = + new URLTemplate("terms_of_services/%s"); + /** All Terms of Services URL Template. */ + public static final URLTemplate ALL_TERMS_OF_SERVICES_URL_TEMPLATE = + new URLTemplate("terms_of_services"); + + /** + * Constructs a BoxTermsOfService for a Box Enterprise with a given ID. + * + * @param api the API connection to be used by the resource. + * @param id the ID of the resource. + */ + public BoxTermsOfService(BoxAPIConnection api, String id) { + super(api, id); + } + + /** + * Creates a new Terms of Services. + * + * @param api the API connection to be used by the resource. + * @param termsOfServiceStatus the current status of the terms of services. Set to "enabled" or + * "disabled". + * @param termsOfServiceType the scope of terms of service. Set to "external" or "managed". + * @param text the text field of terms of service containing terms of service agreement info. + * @return information about the Terms of Service created. + */ + public static BoxTermsOfService.Info create( + BoxAPIConnection api, + BoxTermsOfService.TermsOfServiceStatus termsOfServiceStatus, + BoxTermsOfService.TermsOfServiceType termsOfServiceType, + String text) { + URL url = ALL_TERMS_OF_SERVICES_URL_TEMPLATE.build(api.getBaseURL()); + BoxJSONRequest request = new BoxJSONRequest(api, url, "POST"); + JsonObject requestJSON = + new JsonObject() .add("status", termsOfServiceStatus.toString()) .add("tos_type", termsOfServiceType.toString()) .add("text", text); - request.setBody(requestJSON.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - BoxTermsOfService createdTermsOfServices = new BoxTermsOfService(api, responseJSON.get("id").asString()); + request.setBody(requestJSON.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + BoxTermsOfService createdTermsOfServices = + new BoxTermsOfService(api, responseJSON.get("id").asString()); - return createdTermsOfServices.new Info(responseJSON); - } + return createdTermsOfServices.new Info(responseJSON); + } + } + + /** + * Retrieves a list of Terms of Services that belong to your Enterprise as an Iterable. + * + * @param api the API connection to be used by the resource. + * @return the Iterable of Terms of Service in your Enterprise. + */ + public static List getAllTermsOfServices(final BoxAPIConnection api) { + return getAllTermsOfServices(api, null); + } + + /** + * Retrieves a list of Terms of Service that belong to your Enterprise as an Iterable. + * + * @param api api the API connection to be used by the resource. + * @param termsOfServiceType the type of terms of service to be retrieved. Can be set to "managed" + * or "external" + * @return the Iterable of Terms of Service in an Enterprise that match the filter parameters. + */ + public static List getAllTermsOfServices( + final BoxAPIConnection api, BoxTermsOfService.TermsOfServiceType termsOfServiceType) { + QueryStringBuilder builder = new QueryStringBuilder(); + if (termsOfServiceType != null) { + builder.appendParam("tos_type", termsOfServiceType.toString()); } - /** - * Retrieves a list of Terms of Services that belong to your Enterprise as an Iterable. - * - * @param api the API connection to be used by the resource. - * @return the Iterable of Terms of Service in your Enterprise. - */ - public static List getAllTermsOfServices(final BoxAPIConnection api) { - return getAllTermsOfServices(api, null); + URL url = + ALL_TERMS_OF_SERVICES_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString()); + BoxJSONRequest request = new BoxJSONRequest(api, url, "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + + int totalCount = responseJSON.get("total_count").asInt(); + List termsOfServices = new ArrayList<>(totalCount); + JsonArray entries = responseJSON.get("entries").asArray(); + for (JsonValue value : entries) { + JsonObject termsOfServiceJSON = value.asObject(); + BoxTermsOfService termsOfService = + new BoxTermsOfService(api, termsOfServiceJSON.get("id").asString()); + BoxTermsOfService.Info info = termsOfService.new Info(termsOfServiceJSON); + termsOfServices.add(info); + } + + return termsOfServices; } + } + + /** + * Updates the information about this terms of service with modified locally info. Only status and + * text can be modified. + * + * @param info the updated info. + */ + public void updateInfo(BoxTermsOfService.Info info) { + URL url = TERMS_OF_SERVICE_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); + request.setBody(info.getPendingChanges()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + info.update(responseJSON); + } + } + + /** @return Gets information about this {@link BoxTermsOfService}. */ + public BoxTermsOfService.Info getInfo() { + URL url = TERMS_OF_SERVICE_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); + try (BoxJSONResponse response = request.send()) { + return new Info(Json.parse(response.getJSON()).asObject()); + } + } - /** - * Retrieves a list of Terms of Service that belong to your Enterprise as an Iterable. - * - * @param api api the API connection to be used by the resource. - * @param termsOfServiceType the type of terms of service to be retrieved. Can be set to "managed" or "external" - * @return the Iterable of Terms of Service in an Enterprise that match the filter parameters. - */ - public static List getAllTermsOfServices(final BoxAPIConnection api, - BoxTermsOfService.TermsOfServiceType - termsOfServiceType) { - QueryStringBuilder builder = new QueryStringBuilder(); - if (termsOfServiceType != null) { - builder.appendParam("tos_type", termsOfServiceType.toString()); - } + /** Enumerates the possible types of terms of service. */ + public enum TermsOfServiceType { + /** The terms of service is managed by an enterprise. */ + MANAGED("managed"), - URL url = ALL_TERMS_OF_SERVICES_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString()); - BoxJSONRequest request = new BoxJSONRequest(api, url, "GET"); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - - int totalCount = responseJSON.get("total_count").asInt(); - List termsOfServices = new ArrayList<>(totalCount); - JsonArray entries = responseJSON.get("entries").asArray(); - for (JsonValue value : entries) { - JsonObject termsOfServiceJSON = value.asObject(); - BoxTermsOfService termsOfService = new BoxTermsOfService(api, termsOfServiceJSON.get("id").asString()); - BoxTermsOfService.Info info = termsOfService.new Info(termsOfServiceJSON); - termsOfServices.add(info); - } - - return termsOfServices; - } - } + /** The terms of service is external to an enterprise. */ + EXTERNAL("external"); - /** - * Updates the information about this terms of service with modified locally info. - * Only status and text can be modified. - * - * @param info the updated info. - */ - public void updateInfo(BoxTermsOfService.Info info) { - URL url = TERMS_OF_SERVICE_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); - request.setBody(info.getPendingChanges()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - info.update(responseJSON); - } + private final String tosType; + + TermsOfServiceType(String tosType) { + this.tosType = tosType; } - /** - * @return Gets information about this {@link BoxTermsOfService}. - */ - public BoxTermsOfService.Info getInfo() { - URL url = TERMS_OF_SERVICE_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); - try (BoxJSONResponse response = request.send()) { - return new Info(Json.parse(response.getJSON()).asObject()); - } + static TermsOfServiceType fromTosType(String tosType) { + if (tosType.equals("managed")) { + return TermsOfServiceType.MANAGED; + } else if (tosType.equals("external")) { + return TermsOfServiceType.EXTERNAL; + } else { + System.out.print("Invalid Terms of Service Type"); + return null; + } } /** - * Enumerates the possible types of terms of service. + * Returns a String containing terms of service type. + * + * @return a String containing information about terms of service type. */ - public enum TermsOfServiceType { - /** - * The terms of service is managed by an enterprise. - */ - MANAGED("managed"), + public String toString() { + return this.tosType; + } + } - /** - * The terms of service is external to an enterprise. - */ - EXTERNAL("external"); + /** Enumerates the possible status that a terms of service can have. */ + public enum TermsOfServiceStatus { + /** The terms of service is enabled. */ + ENABLED("enabled"), - private final String tosType; + /** The terms of service is disabled. */ + DISABLED("disabled"); - TermsOfServiceType(String tosType) { - this.tosType = tosType; - } + private final String status; - static TermsOfServiceType fromTosType(String tosType) { - if (tosType.equals("managed")) { - return TermsOfServiceType.MANAGED; - } else if (tosType.equals("external")) { - return TermsOfServiceType.EXTERNAL; - } else { - System.out.print("Invalid Terms of Service Type"); - return null; - } - } + TermsOfServiceStatus(String status) { + this.status = status; + } - /** - * Returns a String containing terms of service type. - * - * @return a String containing information about terms of service type. - */ - public String toString() { - return this.tosType; - } + static TermsOfServiceStatus fromStatus(String status) { + if (status.equals("enabled")) { + return TermsOfServiceStatus.ENABLED; + } else if (status.equals("disabled")) { + return TermsOfServiceStatus.DISABLED; + } else { + System.out.print("Invalid Terms of Service Status"); + return null; + } } /** - * Enumerates the possible status that a terms of service can have. + * Returns a String containing current status of the terms of service. + * + * @return a String containing information about the status of the terms of service. */ - public enum TermsOfServiceStatus { - /** - * The terms of service is enabled. - */ - ENABLED("enabled"), + public String toString() { + return this.status; + } + } - /** - * The terms of service is disabled. - */ - DISABLED("disabled"); + /** Contains information about the terms of service. */ + public class Info extends BoxResource.Info { - private final String status; + /** @see #getStatus() */ + private TermsOfServiceStatus status; - TermsOfServiceStatus(String status) { - this.status = status; - } + /** @see #getType() */ + private String type; - static TermsOfServiceStatus fromStatus(String status) { - if (status.equals("enabled")) { - return TermsOfServiceStatus.ENABLED; - } else if (status.equals("disabled")) { - return TermsOfServiceStatus.DISABLED; - } else { - System.out.print("Invalid Terms of Service Status"); - return null; - } - } + /** @see #getTosType() */ + private TermsOfServiceType tosType; - /** - * Returns a String containing current status of the terms of service. - * - * @return a String containing information about the status of the terms of service. - */ - public String toString() { - return this.status; - } - } + /** @see #getEnterprise() */ + private BoxEnterprise enterprise; - /** - * Contains information about the terms of service. - */ - public class Info extends BoxResource.Info { - - /** - * @see #getStatus() - */ - private TermsOfServiceStatus status; - - /** - * @see #getType() - */ - private String type; - - /** - * @see #getTosType() - */ - private TermsOfServiceType tosType; - - /** - * @see #getEnterprise() - */ - private BoxEnterprise enterprise; - - /** - * @see #getText() - */ - private String text; - - /** - * @see #getCreatedAt() - */ - private Date createdAt; - - /** - * @see #getModifiedAt() - */ - private Date modifiedAt; - - /** - * Constructs an empty Info object. - */ - public Info() { - super(); - } + /** @see #getText() */ + private String text; - /** - * Constructs an Info object by parsing information from a JSON string. - * - * @param json the JSON string to parse. - */ - public Info(String json) { - super(json); - } + /** @see #getCreatedAt() */ + private Date createdAt; - /** - * Constructs an Info object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - Info(JsonObject jsonObject) { - super(jsonObject); - } + /** @see #getModifiedAt() */ + private Date modifiedAt; - /** - * {@inheritDoc} - */ - @Override - public BoxResource getResource() { - return BoxTermsOfService.this; - } + /** Constructs an empty Info object. */ + public Info() { + super(); + } - /** - * TermsOfServiceStatus can be "enabled" or "disabled". - * - * @return the status of the terms of service. - */ - public TermsOfServiceStatus getStatus() { - return this.status; - } + /** + * Constructs an Info object by parsing information from a JSON string. + * + * @param json the JSON string to parse. + */ + public Info(String json) { + super(json); + } - /** - * Sets the status of the terms of service in order to enable or disable it. - * - * @param status the new status of the terms of service. - */ - public void setStatus(TermsOfServiceStatus status) { - this.status = status; - this.addPendingChange("status", status.toString()); - } + /** + * Constructs an Info object using an already parsed JSON object. + * + * @param jsonObject the parsed JSON object. + */ + Info(JsonObject jsonObject) { + super(jsonObject); + } - /** - * The type is terms_of_service. - * - * @return the type terms_of_service. - */ - public String getType() { - return this.type; - } + /** {@inheritDoc} */ + @Override + public BoxResource getResource() { + return BoxTermsOfService.this; + } - /** - * TermsOfServiceType can be "managed" or "external". - * - * @return the type of the terms of service. - */ - public TermsOfServiceType getTosType() { - return this.tosType; - } + /** + * TermsOfServiceStatus can be "enabled" or "disabled". + * + * @return the status of the terms of service. + */ + public TermsOfServiceStatus getStatus() { + return this.status; + } + /** + * Sets the status of the terms of service in order to enable or disable it. + * + * @param status the new status of the terms of service. + */ + public void setStatus(TermsOfServiceStatus status) { + this.status = status; + this.addPendingChange("status", status.toString()); + } - /** - * @return the enterprise for the terms of service. - */ - public BoxEnterprise getEnterprise() { - return this.enterprise; - } + /** + * The type is terms_of_service. + * + * @return the type terms_of_service. + */ + public String getType() { + return this.type; + } + /** + * TermsOfServiceType can be "managed" or "external". + * + * @return the type of the terms of service. + */ + public TermsOfServiceType getTosType() { + return this.tosType; + } - /** - * @return the text of the terms of service. - */ - public String getText() { - return this.text; - } + /** @return the enterprise for the terms of service. */ + public BoxEnterprise getEnterprise() { + return this.enterprise; + } - /** - * Sets the text of the terms of service. - * - * @param text the new text of the terms of service. - */ - public void setText(String text) { - this.text = text; - this.addPendingChange("text", text); - } + /** @return the text of the terms of service. */ + public String getText() { + return this.text; + } + /** + * Sets the text of the terms of service. + * + * @param text the new text of the terms of service. + */ + public void setText(String text) { + this.text = text; + this.addPendingChange("text", text); + } - /** - * @return time the policy was created. - */ - public Date getCreatedAt() { - return this.createdAt; - } + /** @return time the policy was created. */ + public Date getCreatedAt() { + return this.createdAt; + } - /** - * @return time the policy was modified. - */ - public Date getModifiedAt() { - return this.modifiedAt; - } + /** @return time the policy was modified. */ + public Date getModifiedAt() { + return this.modifiedAt; + } - /** - * {@inheritDoc} - */ - @Override - void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - String memberName = member.getName(); - JsonValue value = member.getValue(); - try { - if (memberName.equals("status")) { - this.status = TermsOfServiceStatus.fromStatus(value.asString()); - } else if (memberName.equals("enterprise")) { - JsonObject jsonObject = value.asObject(); - this.enterprise = new BoxEnterprise(jsonObject); - } else if (memberName.equals("type")) { - this.type = value.asString(); - } else if (memberName.equals("tos_type")) { - this.tosType = TermsOfServiceType.fromTosType(value.asString()); - } else if (memberName.equals("text")) { - this.text = value.asString(); - } else if (memberName.equals("created_at")) { - this.createdAt = BoxDateFormat.parse(value.asString()); - } else if (memberName.equals("modified_at")) { - this.modifiedAt = BoxDateFormat.parse(value.asString()); - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); - } + /** {@inheritDoc} */ + @Override + void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + String memberName = member.getName(); + JsonValue value = member.getValue(); + try { + if (memberName.equals("status")) { + this.status = TermsOfServiceStatus.fromStatus(value.asString()); + } else if (memberName.equals("enterprise")) { + JsonObject jsonObject = value.asObject(); + this.enterprise = new BoxEnterprise(jsonObject); + } else if (memberName.equals("type")) { + this.type = value.asString(); + } else if (memberName.equals("tos_type")) { + this.tosType = TermsOfServiceType.fromTosType(value.asString()); + } else if (memberName.equals("text")) { + this.text = value.asString(); + } else if (memberName.equals("created_at")) { + this.createdAt = BoxDateFormat.parse(value.asString()); + } else if (memberName.equals("modified_at")) { + this.modifiedAt = BoxDateFormat.parse(value.asString()); } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); + } } + } } diff --git a/src/main/java/com/box/sdk/BoxTermsOfServiceUserStatus.java b/src/main/java/com/box/sdk/BoxTermsOfServiceUserStatus.java index 8aae5b682..eca72aa1b 100644 --- a/src/main/java/com/box/sdk/BoxTermsOfServiceUserStatus.java +++ b/src/main/java/com/box/sdk/BoxTermsOfServiceUserStatus.java @@ -9,297 +9,261 @@ import java.util.Date; import java.util.List; -/** - * Represents a user status on a custom Box Terms of Service object. - */ +/** Represents a user status on a custom Box Terms of Service object. */ @BoxResourceType("terms_of_service_user_status") public class BoxTermsOfServiceUserStatus extends BoxResource { - /** - * All Terms of Services User Statuses URL Template. - */ - public static final URLTemplate TERMS_OF_SERVICE_USER_STATUSES_TEMPLATE = - new URLTemplate("terms_of_service_user_statuses/%s"); - /** - * Terms of Services User Statuses URL Template. - */ - public static final URLTemplate ALL_TERMS_OF_SERVICE_USER_STATUSES_TEMPLATE = - new URLTemplate("terms_of_service_user_statuses"); + /** All Terms of Services User Statuses URL Template. */ + public static final URLTemplate TERMS_OF_SERVICE_USER_STATUSES_TEMPLATE = + new URLTemplate("terms_of_service_user_statuses/%s"); + /** Terms of Services User Statuses URL Template. */ + public static final URLTemplate ALL_TERMS_OF_SERVICE_USER_STATUSES_TEMPLATE = + new URLTemplate("terms_of_service_user_statuses"); + + /** + * Constructs a BoxTermsOfServiceUserStatus for a resource with a given ID. + * + * @param api the API connection to be used by the resource. + * @param id the ID of the resource. + */ + public BoxTermsOfServiceUserStatus(BoxAPIConnection api, String id) { + super(api, id); + } + + /** + * Creates a User Status on a custom Terms of Service. + * + * @param api the API connection to be used by the resource. + * @param termsOfServiceID the ID of the terms of service. + * @param isAccepted the indicator for whether the terms of service has been accepted. + * @return information about the User Status for Terms of Service created. + */ + public static BoxTermsOfServiceUserStatus.Info create( + final BoxAPIConnection api, String termsOfServiceID, Boolean isAccepted) { + return create(api, termsOfServiceID, isAccepted, null); + } + + /** + * Creates a User Status on a custom Terms of Service. + * + * @param api the API connection to be used by the resource. + * @param termsOfServiceID the ID of the terms of service. + * @param isAccepted the indicator for whether the terms of service has been accepted. + * @param userID the ID of the user for the terms of service. + * @return information about the User Status for Terms of Service created. + */ + public static BoxTermsOfServiceUserStatus.Info create( + final BoxAPIConnection api, String termsOfServiceID, Boolean isAccepted, String userID) { + URL url = ALL_TERMS_OF_SERVICE_USER_STATUSES_TEMPLATE.build(api.getBaseURL()); + BoxJSONRequest request = new BoxJSONRequest(api, url, "POST"); + JsonObject requestJSON = + new JsonObject() + .add( + "tos", new JsonObject().add("type", "terms_of_service").add("id", termsOfServiceID)) + .add("is_accepted", isAccepted); - /** - * Constructs a BoxTermsOfServiceUserStatus for a resource with a given ID. - * - * @param api the API connection to be used by the resource. - * @param id the ID of the resource. - */ - public BoxTermsOfServiceUserStatus(BoxAPIConnection api, String id) { - super(api, id); + if (userID != null) { + requestJSON.add("user", new JsonObject().add("type", "user").add("id", userID)); } - /** - * Creates a User Status on a custom Terms of Service. - * - * @param api the API connection to be used by the resource. - * @param termsOfServiceID the ID of the terms of service. - * @param isAccepted the indicator for whether the terms of service has been accepted. - * @return information about the User Status for Terms of Service created. - */ - public static BoxTermsOfServiceUserStatus.Info create(final BoxAPIConnection api, String termsOfServiceID, - Boolean isAccepted) { - return create(api, termsOfServiceID, isAccepted, null); + request.setBody(requestJSON.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + BoxTermsOfServiceUserStatus termsOfServiceUserStatus = + new BoxTermsOfServiceUserStatus(api, responseJSON.get("id").asString()); + + return termsOfServiceUserStatus.new Info(responseJSON); + } + } + + /** + * Retrieves a list of User Status for Terms of Service as an Iterable. + * + * @param api the API connection to be used by the resource. + * @param termsOfServiceID the ID of the terms of service. + * @return the Iterable of User Status for Terms of Service. + */ + public static List getInfo( + final BoxAPIConnection api, String termsOfServiceID) { + return getInfo(api, termsOfServiceID, null); + } + + /** + * Retrieves a list of User Status for Terms of Service as an Iterable. + * + * @param api the API connection to be used by the resource. + * @param termsOfServiceID the ID of the terms of service. + * @param userID the ID of the user to retrieve terms of service for. + * @return the Iterable of User Status for Terms of Service. + */ + public static List getInfo( + final BoxAPIConnection api, String termsOfServiceID, String userID) { + QueryStringBuilder builder = new QueryStringBuilder(); + builder.appendParam("tos_id", termsOfServiceID); + if (userID != null) { + builder.appendParam("user_id", userID); } - /** - * Creates a User Status on a custom Terms of Service. - * - * @param api the API connection to be used by the resource. - * @param termsOfServiceID the ID of the terms of service. - * @param isAccepted the indicator for whether the terms of service has been accepted. - * @param userID the ID of the user for the terms of service. - * @return information about the User Status for Terms of Service created. - */ - public static BoxTermsOfServiceUserStatus.Info create(final BoxAPIConnection api, String termsOfServiceID, - Boolean isAccepted, String userID) { - URL url = ALL_TERMS_OF_SERVICE_USER_STATUSES_TEMPLATE.build(api.getBaseURL()); - BoxJSONRequest request = new BoxJSONRequest(api, url, "POST"); - JsonObject requestJSON = new JsonObject() - .add("tos", new JsonObject() - .add("type", "terms_of_service") - .add("id", termsOfServiceID)) - .add("is_accepted", isAccepted); + URL url = + ALL_TERMS_OF_SERVICE_USER_STATUSES_TEMPLATE.buildWithQuery( + api.getBaseURL(), builder.toString()); + BoxJSONRequest request = new BoxJSONRequest(api, url, "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + + int totalCount = responseJSON.get("total_count").asInt(); + List termsOfServiceUserStatuses = + new ArrayList<>(totalCount); + JsonArray entries = responseJSON.get("entries").asArray(); + for (JsonValue value : entries) { + JsonObject termsOfServiceUserStatusJSON = value.asObject(); + BoxTermsOfServiceUserStatus termsOfServiceUserStatus = + new BoxTermsOfServiceUserStatus(api, termsOfServiceUserStatusJSON.get("id").asString()); + BoxTermsOfServiceUserStatus.Info info = + termsOfServiceUserStatus.new Info(termsOfServiceUserStatusJSON); + termsOfServiceUserStatuses.add(info); + } + + return termsOfServiceUserStatuses; + } + } + + /** + * Updates the information about the user status for this terms of service with any info fields + * that have been modified locally. + * + * @param info the updated info. + */ + public void updateInfo(BoxTermsOfServiceUserStatus.Info info) { + URL url = + TERMS_OF_SERVICE_USER_STATUSES_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); + request.setBody(info.getPendingChanges()); + + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + info.update(responseJSON); + } + } - if (userID != null) { - requestJSON.add("user", new JsonObject() - .add("type", "user") - .add("id", userID)); - } + /** Contains information about the user status on a terms of service. */ + public class Info extends BoxResource.Info { - request.setBody(requestJSON.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - BoxTermsOfServiceUserStatus termsOfServiceUserStatus = new BoxTermsOfServiceUserStatus(api, - responseJSON.get("id").asString()); + /** @see #getTermsOfService() */ + private BoxTermsOfService.Info termsOfService; - return termsOfServiceUserStatus.new Info(responseJSON); - } - } + /** @see #getUser() */ + private BoxUser.Info user; - /** - * Retrieves a list of User Status for Terms of Service as an Iterable. - * - * @param api the API connection to be used by the resource. - * @param termsOfServiceID the ID of the terms of service. - * @return the Iterable of User Status for Terms of Service. - */ - public static List getInfo(final BoxAPIConnection api, String termsOfServiceID) { - return getInfo(api, termsOfServiceID, null); - } + /** @see #getType() */ + private String termsOfServiceUserStatusType; - /** - * Retrieves a list of User Status for Terms of Service as an Iterable. - * - * @param api the API connection to be used by the resource. - * @param termsOfServiceID the ID of the terms of service. - * @param userID the ID of the user to retrieve terms of service for. - * @return the Iterable of User Status for Terms of Service. - */ - public static List getInfo(final BoxAPIConnection api, - String termsOfServiceID, String userID) { - QueryStringBuilder builder = new QueryStringBuilder(); - builder.appendParam("tos_id", termsOfServiceID); - if (userID != null) { - builder.appendParam("user_id", userID); - } + /** @see #getIsAccepted() () */ + private Boolean isAccepted; - URL url = ALL_TERMS_OF_SERVICE_USER_STATUSES_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString()); - BoxJSONRequest request = new BoxJSONRequest(api, url, "GET"); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - - int totalCount = responseJSON.get("total_count").asInt(); - List termsOfServiceUserStatuses = new - ArrayList<>(totalCount); - JsonArray entries = responseJSON.get("entries").asArray(); - for (JsonValue value : entries) { - JsonObject termsOfServiceUserStatusJSON = value.asObject(); - BoxTermsOfServiceUserStatus termsOfServiceUserStatus = new - BoxTermsOfServiceUserStatus(api, termsOfServiceUserStatusJSON.get("id").asString()); - BoxTermsOfServiceUserStatus.Info info = termsOfServiceUserStatus.new Info(termsOfServiceUserStatusJSON); - termsOfServiceUserStatuses.add(info); - } - - return termsOfServiceUserStatuses; - } + /** @see #getCreatedAt() */ + private Date createdAt; + + /** @see #getModifiedAt() */ + private Date modifiedAt; + + /** Constructs an empty Info object. */ + public Info() { + super(); } /** - * Updates the information about the user status for this terms of service with any info fields that have - * been modified locally. + * Constructs an Info object by parsing information from a JSON string. * - * @param info the updated info. + * @param json the JSON string to parse. */ - public void updateInfo(BoxTermsOfServiceUserStatus.Info info) { - URL url = TERMS_OF_SERVICE_USER_STATUSES_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); - request.setBody(info.getPendingChanges()); - - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - info.update(responseJSON); - } + public Info(String json) { + super(json); } /** - * Contains information about the user status on a terms of service. + * Constructs an Info object using an already parsed JSON object. + * + * @param jsonObject the parsed JSON object. */ - public class Info extends BoxResource.Info { - - /** - * @see #getTermsOfService() - */ - private BoxTermsOfService.Info termsOfService; - - /** - * @see #getUser() - */ - private BoxUser.Info user; - - /** - * @see #getType() - */ - private String termsOfServiceUserStatusType; - - - /** - * @see #getIsAccepted() () - */ - private Boolean isAccepted; - - /** - * @see #getCreatedAt() - */ - private Date createdAt; - - /** - * @see #getModifiedAt() - */ - private Date modifiedAt; - - /** - * Constructs an empty Info object. - */ - public Info() { - super(); - } - - /** - * Constructs an Info object by parsing information from a JSON string. - * - * @param json the JSON string to parse. - */ - public Info(String json) { - super(json); - } - - /** - * Constructs an Info object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - Info(JsonObject jsonObject) { - super(jsonObject); - } + Info(JsonObject jsonObject) { + super(jsonObject); + } - /** - * {@inheritDoc} - */ - @Override - public BoxResource getResource() { - return BoxTermsOfServiceUserStatus.this; - } + /** {@inheritDoc} */ + @Override + public BoxResource getResource() { + return BoxTermsOfServiceUserStatus.this; + } - /** - * @return the terms of service. - */ - public BoxTermsOfService.Info getTermsOfService() { - return this.termsOfService; - } + /** @return the terms of service. */ + public BoxTermsOfService.Info getTermsOfService() { + return this.termsOfService; + } - /** - * @return the user. - */ - public BoxUser.Info getUser() { - return this.user; - } + /** @return the user. */ + public BoxUser.Info getUser() { + return this.user; + } - /** - * @return the is_accepted state of the terms of service. - */ - public Boolean getIsAccepted() { - return this.isAccepted; - } + /** @return the is_accepted state of the terms of service. */ + public Boolean getIsAccepted() { + return this.isAccepted; + } - /** - * Accept or decline the terms of service. - * - * @param enabled the new user status of the terms of service. - */ - public void setIsAccepted(Boolean enabled) { - this.isAccepted = enabled; - this.addPendingChange("is_accepted", this.isAccepted); - } + /** + * Accept or decline the terms of service. + * + * @param enabled the new user status of the terms of service. + */ + public void setIsAccepted(Boolean enabled) { + this.isAccepted = enabled; + this.addPendingChange("is_accepted", this.isAccepted); + } - /** - * @return the type of the terms of service user status. - */ - public String getType() { - return this.termsOfServiceUserStatusType; - } + /** @return the type of the terms of service user status. */ + public String getType() { + return this.termsOfServiceUserStatusType; + } - /** - * @return time the policy was created. - */ - public Date getCreatedAt() { - return this.createdAt; - } + /** @return time the policy was created. */ + public Date getCreatedAt() { + return this.createdAt; + } - /** - * @return time the policy was modified. - */ - public Date getModifiedAt() { - return this.modifiedAt; - } + /** @return time the policy was modified. */ + public Date getModifiedAt() { + return this.modifiedAt; + } - /** - * {@inheritDoc} - */ - @Override - void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - String memberName = member.getName(); - JsonValue value = member.getValue(); - try { - if (memberName.equals("tos")) { - JsonObject tosJSON = value.asObject(); - String termsOfServiceID = tosJSON.get("id").asString(); - BoxTermsOfService termsOfService = new BoxTermsOfService(getAPI(), termsOfServiceID); - this.termsOfService = termsOfService.new Info(tosJSON); - } else if (memberName.equals("user")) { - JsonObject userJSON = value.asObject(); - String userID = userJSON.get("id").asString(); - BoxUser user = new BoxUser(getAPI(), userID); - this.user = user.new Info(userJSON); - } else if (memberName.equals("is_accepted")) { - this.isAccepted = value.asBoolean(); - } else if (memberName.equals("created_at")) { - this.createdAt = BoxDateFormat.parse(value.asString()); - } else if (memberName.equals("modified_at")) { - this.modifiedAt = BoxDateFormat.parse(value.asString()); - } else if (memberName.equals("type")) { - this.termsOfServiceUserStatusType = value.asString(); - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); - } + /** {@inheritDoc} */ + @Override + void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + String memberName = member.getName(); + JsonValue value = member.getValue(); + try { + if (memberName.equals("tos")) { + JsonObject tosJSON = value.asObject(); + String termsOfServiceID = tosJSON.get("id").asString(); + BoxTermsOfService termsOfService = new BoxTermsOfService(getAPI(), termsOfServiceID); + this.termsOfService = termsOfService.new Info(tosJSON); + } else if (memberName.equals("user")) { + JsonObject userJSON = value.asObject(); + String userID = userJSON.get("id").asString(); + BoxUser user = new BoxUser(getAPI(), userID); + this.user = user.new Info(userJSON); + } else if (memberName.equals("is_accepted")) { + this.isAccepted = value.asBoolean(); + } else if (memberName.equals("created_at")) { + this.createdAt = BoxDateFormat.parse(value.asString()); + } else if (memberName.equals("modified_at")) { + this.modifiedAt = BoxDateFormat.parse(value.asString()); + } else if (memberName.equals("type")) { + this.termsOfServiceUserStatusType = value.asString(); } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); + } } + } } diff --git a/src/main/java/com/box/sdk/BoxTransactionalAPIConnection.java b/src/main/java/com/box/sdk/BoxTransactionalAPIConnection.java index 6f06be179..f6cc6501e 100644 --- a/src/main/java/com/box/sdk/BoxTransactionalAPIConnection.java +++ b/src/main/java/com/box/sdk/BoxTransactionalAPIConnection.java @@ -10,130 +10,135 @@ /** * Represents an authenticated transactional connection to the Box API. * - *

This class handles everything for transactional API that isn't already handled by BoxAPIConnection.

+ *

This class handles everything for transactional API that isn't already handled by + * BoxAPIConnection. */ public class BoxTransactionalAPIConnection extends BoxAPIConnection { - private static final String SUBJECT_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token"; - private static final String GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange"; - - /** - * Constructs a new BoxTransactionalAPIConnection that authenticates with an access token. - * - * @param accessToken a transactional auth access token. - */ - public BoxTransactionalAPIConnection(String accessToken) { - super(accessToken); - super.setAutoRefresh(false); + private static final String SUBJECT_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token"; + private static final String GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange"; + + /** + * Constructs a new BoxTransactionalAPIConnection that authenticates with an access token. + * + * @param accessToken a transactional auth access token. + */ + public BoxTransactionalAPIConnection(String accessToken) { + super(accessToken); + super.setAutoRefresh(false); + } + + /** + * Request a scoped transactional token. + * + * @param accessToken application access token. + * @param scope scope of transactional token. + * @return a BoxAPIConnection which can be used to perform transactional requests. + */ + public static BoxAPIConnection getTransactionConnection(String accessToken, String scope) { + return BoxTransactionalAPIConnection.getTransactionConnection(accessToken, scope, null); + } + + /** + * Request a scoped transactional token for a particular resource. + * + * @param accessToken application access token. + * @param scope scope of transactional token. + * @param resource resource transactional token has access to. + * @return a BoxAPIConnection which can be used to perform transactional requests. + */ + public static BoxAPIConnection getTransactionConnection( + String accessToken, String scope, String resource) { + BoxAPIConnection apiConnection = new BoxAPIConnection(accessToken); + + URL url; + try { + url = new URL(apiConnection.getTokenURL()); + } catch (MalformedURLException e) { + assert false : "An invalid token URL indicates a bug in the SDK."; + throw new RuntimeException("An invalid token URL indicates a bug in the SDK.", e); } - /** - * Request a scoped transactional token. - * - * @param accessToken application access token. - * @param scope scope of transactional token. - * @return a BoxAPIConnection which can be used to perform transactional requests. - */ - public static BoxAPIConnection getTransactionConnection(String accessToken, String scope) { - return BoxTransactionalAPIConnection.getTransactionConnection(accessToken, scope, null); + String urlParameters; + try { + urlParameters = + String.format( + "grant_type=%s&subject_token=%s&subject_token_type=%s&scope=%s", + GRANT_TYPE, + URLEncoder.encode(accessToken, "UTF-8"), + SUBJECT_TOKEN_TYPE, + URLEncoder.encode(scope, "UTF-8")); + + if (resource != null) { + urlParameters += "&resource=" + URLEncoder.encode(resource, "UTF-8"); + } + } catch (UnsupportedEncodingException e) { + throw new BoxAPIException( + "An error occurred while attempting to encode url parameters for a transactional token request"); } - /** - * Request a scoped transactional token for a particular resource. - * - * @param accessToken application access token. - * @param scope scope of transactional token. - * @param resource resource transactional token has access to. - * @return a BoxAPIConnection which can be used to perform transactional requests. - */ - public static BoxAPIConnection getTransactionConnection(String accessToken, String scope, String resource) { - BoxAPIConnection apiConnection = new BoxAPIConnection(accessToken); - - URL url; - try { - url = new URL(apiConnection.getTokenURL()); - } catch (MalformedURLException e) { - assert false : "An invalid token URL indicates a bug in the SDK."; - throw new RuntimeException("An invalid token URL indicates a bug in the SDK.", e); - } - - String urlParameters; - try { - urlParameters = String.format("grant_type=%s&subject_token=%s&subject_token_type=%s&scope=%s", GRANT_TYPE, - URLEncoder.encode(accessToken, "UTF-8"), SUBJECT_TOKEN_TYPE, URLEncoder.encode(scope, "UTF-8")); - - if (resource != null) { - urlParameters += "&resource=" + URLEncoder.encode(resource, "UTF-8"); - } - } catch (UnsupportedEncodingException e) { - throw new BoxAPIException( - "An error occurred while attempting to encode url parameters for a transactional token request" - ); - } - - // authentication uses form url encoded params but response is JSON - BoxAPIRequest request = new BoxAPIRequest(apiConnection, url, "POST"); - request.shouldAuthenticate(false); - request.setBody(urlParameters); - - try (BoxJSONResponse response = (BoxJSONResponse) request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - - final String fileToken = responseJSON.get("access_token").asString(); - BoxTransactionalAPIConnection transactionConnection = new BoxTransactionalAPIConnection(fileToken); - transactionConnection.setExpires(responseJSON.get("expires_in").asLong() * 1000); - - return transactionConnection; - } - } + // authentication uses form url encoded params but response is JSON + BoxAPIRequest request = new BoxAPIRequest(apiConnection, url, "POST"); + request.shouldAuthenticate(false); + request.setBody(urlParameters); - /** - * Disabling the non-Box Developer Edition authenticate method. - * - * @param authCode an auth code obtained from the first half of the OAuth process. - * @throws UnsupportedOperationException Box Transactional API does not support authentication with an auth code - */ - @Override - public void authenticate(String authCode) { - throw new UnsupportedOperationException( - "BoxTransactionalAPIConnection does not support the authenticate method." - ); - } + try (BoxJSONResponse response = (BoxJSONResponse) request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - /** - * BoxTransactionalAPIConnection can never refresh. - * - * @return false always. - */ - @Override - public boolean canRefresh() { - return false; - } - - /** - * Auto refresh is not available for transactional auth. - * - * @param autoRefresh true to enable auto token refresh; otherwise false. - * @throws UnsupportedOperationException Box Transactional API tokens can not be refreshed - */ - @Override - public void setAutoRefresh(boolean autoRefresh) { - throw new UnsupportedOperationException( - "BoxTransactionalAPIConnection does not support token refreshing, " - + "access tokens can be generated in the developer console." - ); - } + final String fileToken = responseJSON.get("access_token").asString(); + BoxTransactionalAPIConnection transactionConnection = + new BoxTransactionalAPIConnection(fileToken); + transactionConnection.setExpires(responseJSON.get("expires_in").asLong() * 1000); - /** - * Transactional auth does not support token refreshes. - * - * @throws UnsupportedOperationException Box Transactional API tokens can not be refreshed - */ - @Override - public void refresh() { - throw new UnsupportedOperationException( - "BoxTransactionalAPIConnection does not support token refreshing, " - + "access tokens can be generated in the developer console." - ); + return transactionConnection; } + } + + /** + * Disabling the non-Box Developer Edition authenticate method. + * + * @param authCode an auth code obtained from the first half of the OAuth process. + * @throws UnsupportedOperationException Box Transactional API does not support authentication + * with an auth code + */ + @Override + public void authenticate(String authCode) { + throw new UnsupportedOperationException( + "BoxTransactionalAPIConnection does not support the authenticate method."); + } + + /** + * BoxTransactionalAPIConnection can never refresh. + * + * @return false always. + */ + @Override + public boolean canRefresh() { + return false; + } + + /** + * Auto refresh is not available for transactional auth. + * + * @param autoRefresh true to enable auto token refresh; otherwise false. + * @throws UnsupportedOperationException Box Transactional API tokens can not be refreshed + */ + @Override + public void setAutoRefresh(boolean autoRefresh) { + throw new UnsupportedOperationException( + "BoxTransactionalAPIConnection does not support token refreshing, " + + "access tokens can be generated in the developer console."); + } + + /** + * Transactional auth does not support token refreshes. + * + * @throws UnsupportedOperationException Box Transactional API tokens can not be refreshed + */ + @Override + public void refresh() { + throw new UnsupportedOperationException( + "BoxTransactionalAPIConnection does not support token refreshing, " + + "access tokens can be generated in the developer console."); + } } diff --git a/src/main/java/com/box/sdk/BoxTrash.java b/src/main/java/com/box/sdk/BoxTrash.java index d60f5de57..54655b1d8 100644 --- a/src/main/java/com/box/sdk/BoxTrash.java +++ b/src/main/java/com/box/sdk/BoxTrash.java @@ -12,296 +12,284 @@ /** * Provides methods for deleting, recovering, and viewing a user's trashed files and folders. * - *

Unless otherwise noted, the methods in this class can throw an unchecked {@link BoxAPIException} (unchecked - * meaning that the compiler won't force you to handle it) if an error occurs. If you wish to implement custom error - * handling for errors related to the Box REST API, you should capture this exception explicitly.

+ *

Unless otherwise noted, the methods in this class can throw an unchecked {@link + * BoxAPIException} (unchecked meaning that the compiler won't force you to handle it) if an error + * occurs. If you wish to implement custom error handling for errors related to the Box REST API, + * you should capture this exception explicitly. */ public class BoxTrash implements Iterable { - /** - * Get Item URL Template. - */ - public static final URLTemplate GET_ITEMS_URL = new URLTemplate("folders/trash/items/"); - /** - * Folder Info URL Template. - */ - public static final URLTemplate FOLDER_INFO_URL_TEMPLATE = new URLTemplate("folders/%s/trash"); - /** - * File Info URL Template. - */ - public static final URLTemplate FILE_INFO_URL_TEMPLATE = new URLTemplate("files/%s/trash"); - /** - * Restore File URL Template. - */ - public static final URLTemplate RESTORE_FILE_URL_TEMPLATE = new URLTemplate("files/%s"); - /** - * Restore Folder URL Template. - */ - public static final URLTemplate RESTORE_FOLDER_URL_TEMPLATE = new URLTemplate("folders/%s"); - - private final BoxAPIConnection api; - - /** - * Constructs a BoxTrash using a given API connection. - * - * @param api the API connection to be used by the trash. - */ - public BoxTrash(BoxAPIConnection api) { - this.api = api; + /** Get Item URL Template. */ + public static final URLTemplate GET_ITEMS_URL = new URLTemplate("folders/trash/items/"); + /** Folder Info URL Template. */ + public static final URLTemplate FOLDER_INFO_URL_TEMPLATE = new URLTemplate("folders/%s/trash"); + /** File Info URL Template. */ + public static final URLTemplate FILE_INFO_URL_TEMPLATE = new URLTemplate("files/%s/trash"); + /** Restore File URL Template. */ + public static final URLTemplate RESTORE_FILE_URL_TEMPLATE = new URLTemplate("files/%s"); + /** Restore Folder URL Template. */ + public static final URLTemplate RESTORE_FOLDER_URL_TEMPLATE = new URLTemplate("folders/%s"); + + private final BoxAPIConnection api; + + /** + * Constructs a BoxTrash using a given API connection. + * + * @param api the API connection to be used by the trash. + */ + public BoxTrash(BoxAPIConnection api) { + this.api = api; + } + + /** + * Permanently deletes a trashed folder. + * + * @param folderID the ID of the trashed folder to permanently delete. + */ + public void deleteFolder(String folderID) { + URL url = FOLDER_INFO_URL_TEMPLATE.build(this.api.getBaseURL(), folderID); + BoxAPIRequest request = new BoxAPIRequest(this.api, url, "DELETE"); + request.send().close(); + } + + /** + * Gets information about a trashed folder. + * + * @param folderID the ID of the trashed folder. + * @return info about the trashed folder. + */ + public BoxFolder.Info getFolderInfo(String folderID) { + URL url = FOLDER_INFO_URL_TEMPLATE.build(this.api.getBaseURL(), folderID); + BoxJSONRequest request = new BoxJSONRequest(this.api, url, "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); + + BoxFolder folder = new BoxFolder(this.api, jsonObject.get("id").asString()); + return folder.new Info(response.getJSON()); } - - /** - * Permanently deletes a trashed folder. - * - * @param folderID the ID of the trashed folder to permanently delete. - */ - public void deleteFolder(String folderID) { - URL url = FOLDER_INFO_URL_TEMPLATE.build(this.api.getBaseURL(), folderID); - BoxAPIRequest request = new BoxAPIRequest(this.api, url, "DELETE"); - request.send().close(); - } - - /** - * Gets information about a trashed folder. - * - * @param folderID the ID of the trashed folder. - * @return info about the trashed folder. - */ - public BoxFolder.Info getFolderInfo(String folderID) { - URL url = FOLDER_INFO_URL_TEMPLATE.build(this.api.getBaseURL(), folderID); - BoxJSONRequest request = new BoxJSONRequest(this.api, url, "GET"); - try (BoxJSONResponse response = request.send()) { - JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - - BoxFolder folder = new BoxFolder(this.api, jsonObject.get("id").asString()); - return folder.new Info(response.getJSON()); - } + } + + /** + * Gets information about a trashed folder that's limited to a list of specified fields. + * + * @param folderID the ID of the trashed folder. + * @param fields the fields to retrieve. + * @return info about the trashed folder containing only the specified fields. + */ + public BoxFolder.Info getFolderInfo(String folderID, String... fields) { + String queryString = new QueryStringBuilder().appendParam("fields", fields).toString(); + URL url = FOLDER_INFO_URL_TEMPLATE.buildWithQuery(this.api.getBaseURL(), queryString, folderID); + BoxJSONRequest request = new BoxJSONRequest(this.api, url, "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); + + BoxFolder folder = new BoxFolder(this.api, jsonObject.get("id").asString()); + return folder.new Info(response.getJSON()); } - - /** - * Gets information about a trashed folder that's limited to a list of specified fields. - * - * @param folderID the ID of the trashed folder. - * @param fields the fields to retrieve. - * @return info about the trashed folder containing only the specified fields. - */ - public BoxFolder.Info getFolderInfo(String folderID, String... fields) { - String queryString = new QueryStringBuilder().appendParam("fields", fields).toString(); - URL url = FOLDER_INFO_URL_TEMPLATE.buildWithQuery(this.api.getBaseURL(), queryString, folderID); - BoxJSONRequest request = new BoxJSONRequest(this.api, url, "GET"); - try (BoxJSONResponse response = request.send()) { - JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - - BoxFolder folder = new BoxFolder(this.api, jsonObject.get("id").asString()); - return folder.new Info(response.getJSON()); - } + } + + /** + * Restores a trashed folder back to its original location. + * + * @param folderID the ID of the trashed folder. + * @return info about the restored folder. + */ + public BoxFolder.Info restoreFolder(String folderID) { + URL url = RESTORE_FOLDER_URL_TEMPLATE.build(this.api.getBaseURL(), folderID); + BoxJSONRequest request = new BoxJSONRequest(this.api, url, "POST"); + JsonObject requestJSON = new JsonObject().add("", ""); + request.setBody(requestJSON.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + + BoxFolder restoredFolder = new BoxFolder(this.api, responseJSON.get("id").asString()); + return restoredFolder.new Info(responseJSON); } - - /** - * Restores a trashed folder back to its original location. - * - * @param folderID the ID of the trashed folder. - * @return info about the restored folder. - */ - public BoxFolder.Info restoreFolder(String folderID) { - URL url = RESTORE_FOLDER_URL_TEMPLATE.build(this.api.getBaseURL(), folderID); - BoxJSONRequest request = new BoxJSONRequest(this.api, url, "POST"); - JsonObject requestJSON = new JsonObject() - .add("", ""); - request.setBody(requestJSON.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - - BoxFolder restoredFolder = new BoxFolder(this.api, responseJSON.get("id").asString()); - return restoredFolder.new Info(responseJSON); - } + } + + /** + * Restores a trashed folder to a new location with a new name. + * + * @param folderID the ID of the trashed folder. + * @param newName an optional new name to give the folder. This can be null to use the folder's + * original name. + * @param newParentID an optional new parent ID for the folder. This can be null to use the + * folder's original parent. + * @return info about the restored folder. + */ + public BoxFolder.Info restoreFolder(String folderID, String newName, String newParentID) { + JsonObject requestJSON = new JsonObject(); + + if (newName != null) { + requestJSON.add("name", newName); } - /** - * Restores a trashed folder to a new location with a new name. - * - * @param folderID the ID of the trashed folder. - * @param newName an optional new name to give the folder. This can be null to use the folder's original name. - * @param newParentID an optional new parent ID for the folder. This can be null to use the folder's original - * parent. - * @return info about the restored folder. - */ - public BoxFolder.Info restoreFolder(String folderID, String newName, String newParentID) { - JsonObject requestJSON = new JsonObject(); - - if (newName != null) { - requestJSON.add("name", newName); - } - - if (newParentID != null) { - JsonObject parent = new JsonObject(); - parent.add("id", newParentID); - requestJSON.add("parent", parent); - } - - URL url = RESTORE_FOLDER_URL_TEMPLATE.build(this.api.getBaseURL(), folderID); - BoxJSONRequest request = new BoxJSONRequest(this.api, url, "POST"); - request.setBody(requestJSON.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - - BoxFolder restoredFolder = new BoxFolder(this.api, responseJSON.get("id").asString()); - return restoredFolder.new Info(responseJSON); - } + if (newParentID != null) { + JsonObject parent = new JsonObject(); + parent.add("id", newParentID); + requestJSON.add("parent", parent); } - /** - * Permanently deletes a trashed file. - * - * @param fileID the ID of the trashed folder to permanently delete. - */ - public void deleteFile(String fileID) { - URL url = FILE_INFO_URL_TEMPLATE.build(this.api.getBaseURL(), fileID); - BoxAPIRequest request = new BoxAPIRequest(this.api, url, "DELETE"); - request.send().close(); - } + URL url = RESTORE_FOLDER_URL_TEMPLATE.build(this.api.getBaseURL(), folderID); + BoxJSONRequest request = new BoxJSONRequest(this.api, url, "POST"); + request.setBody(requestJSON.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - /** - * Gets information about a trashed file. - * - * @param fileID the ID of the trashed file. - * @return info about the trashed file. - */ - public BoxFile.Info getFileInfo(String fileID) { - URL url = FILE_INFO_URL_TEMPLATE.build(this.api.getBaseURL(), fileID); - BoxJSONRequest request = new BoxJSONRequest(this.api, url, "GET"); - try (BoxJSONResponse response = request.send()) { - JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - - BoxFile file = new BoxFile(this.api, jsonObject.get("id").asString()); - return file.new Info(response.getJSON()); - } + BoxFolder restoredFolder = new BoxFolder(this.api, responseJSON.get("id").asString()); + return restoredFolder.new Info(responseJSON); } - - /** - * Gets information about a trashed file that's limited to a list of specified fields. - * - * @param fileID the ID of the trashed file. - * @param fields the fields to retrieve. - * @return info about the trashed file containing only the specified fields. - */ - public BoxFile.Info getFileInfo(String fileID, String... fields) { - String queryString = new QueryStringBuilder().appendParam("fields", fields).toString(); - URL url = FILE_INFO_URL_TEMPLATE.buildWithQuery(this.api.getBaseURL(), queryString, fileID); - BoxJSONRequest request = new BoxJSONRequest(this.api, url, "GET"); - try (BoxJSONResponse response = request.send()) { - JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - - BoxFile file = new BoxFile(this.api, jsonObject.get("id").asString()); - return file.new Info(response.getJSON()); - } + } + + /** + * Permanently deletes a trashed file. + * + * @param fileID the ID of the trashed folder to permanently delete. + */ + public void deleteFile(String fileID) { + URL url = FILE_INFO_URL_TEMPLATE.build(this.api.getBaseURL(), fileID); + BoxAPIRequest request = new BoxAPIRequest(this.api, url, "DELETE"); + request.send().close(); + } + + /** + * Gets information about a trashed file. + * + * @param fileID the ID of the trashed file. + * @return info about the trashed file. + */ + public BoxFile.Info getFileInfo(String fileID) { + URL url = FILE_INFO_URL_TEMPLATE.build(this.api.getBaseURL(), fileID); + BoxJSONRequest request = new BoxJSONRequest(this.api, url, "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); + + BoxFile file = new BoxFile(this.api, jsonObject.get("id").asString()); + return file.new Info(response.getJSON()); } - - /** - * Restores a trashed file back to its original location. - * - * @param fileID the ID of the trashed file. - * @return info about the restored file. - */ - public BoxFile.Info restoreFile(String fileID) { - URL url = RESTORE_FILE_URL_TEMPLATE.build(this.api.getBaseURL(), fileID); - BoxJSONRequest request = new BoxJSONRequest(this.api, url, "POST"); - JsonObject requestJSON = new JsonObject() - .add("", ""); - return getInfo(requestJSON, request); + } + + /** + * Gets information about a trashed file that's limited to a list of specified fields. + * + * @param fileID the ID of the trashed file. + * @param fields the fields to retrieve. + * @return info about the trashed file containing only the specified fields. + */ + public BoxFile.Info getFileInfo(String fileID, String... fields) { + String queryString = new QueryStringBuilder().appendParam("fields", fields).toString(); + URL url = FILE_INFO_URL_TEMPLATE.buildWithQuery(this.api.getBaseURL(), queryString, fileID); + BoxJSONRequest request = new BoxJSONRequest(this.api, url, "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); + + BoxFile file = new BoxFile(this.api, jsonObject.get("id").asString()); + return file.new Info(response.getJSON()); } - - /** - * Restores a trashed file to a new location with a new name. - * - * @param fileID the ID of the trashed file. - * @param newName an optional new name to give the file. This can be null to use the file's original name. - * @param newParentID an optional new parent ID for the file. This can be null to use the file's original - * parent. - * @return info about the restored file. - */ - public BoxFile.Info restoreFile(String fileID, String newName, String newParentID) { - JsonObject requestJSON = new JsonObject(); - - if (newName != null) { - requestJSON.add("name", newName); - } - - if (newParentID != null) { - JsonObject parent = new JsonObject(); - parent.add("id", newParentID); - requestJSON.add("parent", parent); - } - - URL url = RESTORE_FILE_URL_TEMPLATE.build(this.api.getBaseURL(), fileID); - BoxJSONRequest request = new BoxJSONRequest(this.api, url, "POST"); - return getInfo(requestJSON, request); + } + + /** + * Restores a trashed file back to its original location. + * + * @param fileID the ID of the trashed file. + * @return info about the restored file. + */ + public BoxFile.Info restoreFile(String fileID) { + URL url = RESTORE_FILE_URL_TEMPLATE.build(this.api.getBaseURL(), fileID); + BoxJSONRequest request = new BoxJSONRequest(this.api, url, "POST"); + JsonObject requestJSON = new JsonObject().add("", ""); + return getInfo(requestJSON, request); + } + + /** + * Restores a trashed file to a new location with a new name. + * + * @param fileID the ID of the trashed file. + * @param newName an optional new name to give the file. This can be null to use the file's + * original name. + * @param newParentID an optional new parent ID for the file. This can be null to use the file's + * original parent. + * @return info about the restored file. + */ + public BoxFile.Info restoreFile(String fileID, String newName, String newParentID) { + JsonObject requestJSON = new JsonObject(); + + if (newName != null) { + requestJSON.add("name", newName); } - /** - * Returns an iterator over the items in the trash. - * - * @return an iterator over the items in the trash. - */ - public Iterator iterator() { - return items(none(), marker(DEFAULT_LIMIT)).iterator(); + if (newParentID != null) { + JsonObject parent = new JsonObject(); + parent.add("id", newParentID); + requestJSON.add("parent", parent); } - /** - * Returns an iterable containing the items in trash. You can specify sort order, limit of files requested, ofset - * or use marker based pagination. - * - * @param sortParameters describes sorting parameters. - * Sort parameters are supported only with offset based pagination. - * Use {@link SortParameters#none()} to ignore sorting. - * @param pagingParameters describes paging parameters - * @param fields the fields to retrieve. - * @return an iterable containing the items in the trash. - */ - public Iterable items( - SortParameters sortParameters, - PagingParameters pagingParameters, - String... fields - ) { - QueryStringBuilder builder = sortParameters.asQueryStringBuilder(); - validateSortIsSelectedWithOffsetPaginationOnly(pagingParameters, builder); - - if (fields.length > 0) { - builder.appendParam("fields", fields); - } - final String query = builder.toString(); - return () -> { - URL url = GET_ITEMS_URL.buildWithQuery(this.api.getBaseURL(), query); - if (pagingParameters == null) { - return new BoxItemIterator(this.api, url, marker(DEFAULT_LIMIT)); - } else { - return new BoxItemIterator(this.api, url, pagingParameters); - } - }; + URL url = RESTORE_FILE_URL_TEMPLATE.build(this.api.getBaseURL(), fileID); + BoxJSONRequest request = new BoxJSONRequest(this.api, url, "POST"); + return getInfo(requestJSON, request); + } + + /** + * Returns an iterator over the items in the trash. + * + * @return an iterator over the items in the trash. + */ + public Iterator iterator() { + return items(none(), marker(DEFAULT_LIMIT)).iterator(); + } + + /** + * Returns an iterable containing the items in trash. You can specify sort order, limit of files + * requested, ofset or use marker based pagination. + * + * @param sortParameters describes sorting parameters. Sort parameters are supported only with + * offset based pagination. Use {@link SortParameters#none()} to ignore sorting. + * @param pagingParameters describes paging parameters + * @param fields the fields to retrieve. + * @return an iterable containing the items in the trash. + */ + public Iterable items( + SortParameters sortParameters, PagingParameters pagingParameters, String... fields) { + QueryStringBuilder builder = sortParameters.asQueryStringBuilder(); + validateSortIsSelectedWithOffsetPaginationOnly(pagingParameters, builder); + + if (fields.length > 0) { + builder.appendParam("fields", fields); } - - private BoxFile.Info getInfo(JsonObject requestJSON, BoxJSONRequest request) { - request.setBody(requestJSON.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - - BoxFile restoredFile = new BoxFile(this.api, responseJSON.get("id").asString()); - return restoredFile.new Info(responseJSON); - } + final String query = builder.toString(); + return () -> { + URL url = GET_ITEMS_URL.buildWithQuery(this.api.getBaseURL(), query); + if (pagingParameters == null) { + return new BoxItemIterator(this.api, url, marker(DEFAULT_LIMIT)); + } else { + return new BoxItemIterator(this.api, url, pagingParameters); + } + }; + } + + private BoxFile.Info getInfo(JsonObject requestJSON, BoxJSONRequest request) { + request.setBody(requestJSON.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + + BoxFile restoredFile = new BoxFile(this.api, responseJSON.get("id").asString()); + return restoredFile.new Info(responseJSON); } - - /** - * Throws IllegalArgumentException exception when sorting and marker pagination is selected. - * - * @param pagingParameters paging definition to check - * @param sortQuery builder containing sort query - */ - private void validateSortIsSelectedWithOffsetPaginationOnly( - PagingParameters pagingParameters, - QueryStringBuilder sortQuery - ) { - if (pagingParameters != null && pagingParameters.isMarkerBasedPaging() && sortQuery.toString().length() > 0) { - throw new IllegalArgumentException("Sorting is not supported when using marker based pagination."); - } + } + + /** + * Throws IllegalArgumentException exception when sorting and marker pagination is selected. + * + * @param pagingParameters paging definition to check + * @param sortQuery builder containing sort query + */ + private void validateSortIsSelectedWithOffsetPaginationOnly( + PagingParameters pagingParameters, QueryStringBuilder sortQuery) { + if (pagingParameters != null + && pagingParameters.isMarkerBasedPaging() + && sortQuery.toString().length() > 0) { + throw new IllegalArgumentException( + "Sorting is not supported when using marker based pagination."); } + } } diff --git a/src/main/java/com/box/sdk/BoxUploadEmail.java b/src/main/java/com/box/sdk/BoxUploadEmail.java index f4516ddcc..dbf853a4a 100644 --- a/src/main/java/com/box/sdk/BoxUploadEmail.java +++ b/src/main/java/com/box/sdk/BoxUploadEmail.java @@ -3,101 +3,90 @@ import com.eclipsesource.json.JsonObject; import com.eclipsesource.json.JsonValue; -/** - * Represents an email address that can be used to upload files to a folder on Box. - */ +/** Represents an email address that can be used to upload files to a folder on Box. */ public class BoxUploadEmail extends BoxJSONObject { - private Access access; - private String email; + private Access access; + private String email; - /** - * Constructs a BoxUploadEmail with default settings. - */ - public BoxUploadEmail() { - } + /** Constructs a BoxUploadEmail with default settings. */ + public BoxUploadEmail() {} - /** - * Constructs a BoxUploadEmail from a JSON string. - * - * @param json the JSON encoded upload email. - */ - public BoxUploadEmail(String json) { - super(json); - } + /** + * Constructs a BoxUploadEmail from a JSON string. + * + * @param json the JSON encoded upload email. + */ + public BoxUploadEmail(String json) { + super(json); + } - BoxUploadEmail(JsonObject jsonObject) { - super(jsonObject); - } + BoxUploadEmail(JsonObject jsonObject) { + super(jsonObject); + } - /** - * Gets the access level of this upload email. - * - * @return the access level of this upload email. - */ - public Access getAccess() { - return this.access; - } + /** + * Gets the access level of this upload email. + * + * @return the access level of this upload email. + */ + public Access getAccess() { + return this.access; + } - /** - * Sets the access level of this upload email. - * - * @param access the new access level of this upload email. - */ - public void setAccess(Access access) { - this.access = access; - this.addPendingChange("access", access.toJSONValue()); - } + /** + * Sets the access level of this upload email. + * + * @param access the new access level of this upload email. + */ + public void setAccess(Access access) { + this.access = access; + this.addPendingChange("access", access.toJSONValue()); + } - /** - * Gets the email address of this upload email. - * - * @return the email address of this upload email. - */ - public String getEmail() { - return this.email; - } + /** + * Gets the email address of this upload email. + * + * @return the email address of this upload email. + */ + public String getEmail() { + return this.email; + } - @Override - void parseJSONMember(JsonObject.Member member) { - JsonValue value = member.getValue(); - String memberName = member.getName(); - try { - if (memberName.equals("access")) { - this.access = Access.fromJSONValue(value.asString()); - } else if (memberName.equals("email")) { - this.email = value.asString(); - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); - } + @Override + void parseJSONMember(JsonObject.Member member) { + JsonValue value = member.getValue(); + String memberName = member.getName(); + try { + if (memberName.equals("access")) { + this.access = Access.fromJSONValue(value.asString()); + } else if (memberName.equals("email")) { + this.email = value.asString(); + } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); } + } - /** - * Enumerates the possible access levels that can be set on an upload email. - */ - public enum Access { - /** - * Anyone can send an upload to this email address. - */ - OPEN("open"), + /** Enumerates the possible access levels that can be set on an upload email. */ + public enum Access { + /** Anyone can send an upload to this email address. */ + OPEN("open"), - /** - * Only collaborators can send an upload to this email address. - */ - COLLABORATORS("collaborators"); + /** Only collaborators can send an upload to this email address. */ + COLLABORATORS("collaborators"); - private final String jsonValue; + private final String jsonValue; - Access(String jsonValue) { - this.jsonValue = jsonValue; - } + Access(String jsonValue) { + this.jsonValue = jsonValue; + } - static Access fromJSONValue(String jsonValue) { - return Access.valueOf(jsonValue.toUpperCase(java.util.Locale.ROOT)); - } + static Access fromJSONValue(String jsonValue) { + return Access.valueOf(jsonValue.toUpperCase(java.util.Locale.ROOT)); + } - String toJSONValue() { - return this.jsonValue; - } + String toJSONValue() { + return this.jsonValue; } + } } diff --git a/src/main/java/com/box/sdk/BoxUser.java b/src/main/java/com/box/sdk/BoxUser.java index 8da41e9a1..fb2d226ae 100644 --- a/src/main/java/com/box/sdk/BoxUser.java +++ b/src/main/java/com/box/sdk/BoxUser.java @@ -27,1444 +27,1446 @@ /** * Represents a Box user account. * - *

Unless otherwise noted, the methods in this class can throw an unchecked {@link BoxAPIException} (unchecked - * meaning that the compiler won't force you to handle it) if an error occurs. If you wish to implement custom error - * handling for errors related to the Box REST API, you should capture this exception explicitly.

+ *

Unless otherwise noted, the methods in this class can throw an unchecked {@link + * BoxAPIException} (unchecked meaning that the compiler won't force you to handle it) if an error + * occurs. If you wish to implement custom error handling for errors related to the Box REST API, + * you should capture this exception explicitly. */ @BoxResourceType("user") public class BoxUser extends BoxCollaborator { - /** - * An array of all possible file fields that can be requested when calling {@link #getInfo(String...)}. - */ - public static final String[] ALL_FIELDS = {"type", "id", "name", "login", "created_at", "modified_at", "role", - "language", "timezone", "space_amount", "space_used", "max_upload_size", "tracking_codes", - "can_see_managed_users", "is_sync_enabled", "is_external_collab_restricted", "status", "job_title", "phone", - "address", "avatar_url", "is_exempt_from_device_limits", "is_exempt_from_login_verification", "enterprise", - "my_tags", "hostname", "is_platform_access_only", "external_app_user_id", "notification_email"}; + /** + * An array of all possible file fields that can be requested when calling {@link + * #getInfo(String...)}. + */ + public static final String[] ALL_FIELDS = { + "type", + "id", + "name", + "login", + "created_at", + "modified_at", + "role", + "language", + "timezone", + "space_amount", + "space_used", + "max_upload_size", + "tracking_codes", + "can_see_managed_users", + "is_sync_enabled", + "is_external_collab_restricted", + "status", + "job_title", + "phone", + "address", + "avatar_url", + "is_exempt_from_device_limits", + "is_exempt_from_login_verification", + "enterprise", + "my_tags", + "hostname", + "is_platform_access_only", + "external_app_user_id", + "notification_email" + }; + + /** User URL Template. */ + public static final URLTemplate USER_URL_TEMPLATE = new URLTemplate("users/%s"); + /** Get Me URL Template. */ + public static final URLTemplate GET_ME_URL = new URLTemplate("users/me"); + /** Users URL Template. */ + public static final URLTemplate USERS_URL_TEMPLATE = new URLTemplate("users"); + /** User Memberships URL Template. */ + public static final URLTemplate USER_MEMBERSHIPS_URL_TEMPLATE = + new URLTemplate("users/%s/memberships"); + /** E-Mail Alias URL Template. */ + public static final URLTemplate EMAIL_ALIAS_URL_TEMPLATE = + new URLTemplate("users/%s/email_aliases/%s"); + /** E-Mail Aliases URL Template. */ + public static final URLTemplate EMAIL_ALIASES_URL_TEMPLATE = + new URLTemplate("users/%s/email_aliases"); + /** Move Folder To User Template. */ + public static final URLTemplate MOVE_FOLDER_TO_USER_TEMPLATE = + new URLTemplate("users/%s/folders/%s"); + /** User Avatar Template. */ + public static final URLTemplate USER_AVATAR_TEMPLATE = new URLTemplate("users/%s/avatar"); + + /** + * Constructs a BoxUser for a user with a given ID. + * + * @param api the API connection to be used by the user. + * @param id the ID of the user. + */ + public BoxUser(BoxAPIConnection api, String id) { + super(api, id); + } + + /** + * Provisions a new app user in an enterprise using Box Developer Edition. + * + * @param api the API connection to be used by the created user. + * @param name the name of the user. + * @param fields the fields to retrieve. Leave this out for the standard fields. + * @return the created user's info. + */ + public static BoxUser.Info createAppUser(BoxAPIConnection api, String name, String... fields) { + return createAppUser(api, name, new CreateUserParams(), fields); + } + + /** + * Provisions a new app user in an enterprise with additional user information using Box Developer + * Edition. + * + * @param api the API connection to be used by the created user. + * @param name the name of the user. + * @param params additional user information. + * @param fields the fields to retrieve. Leave this out for the standard fields. + * @return the created user's info. + */ + public static BoxUser.Info createAppUser( + BoxAPIConnection api, String name, CreateUserParams params, String... fields) { + + params.setIsPlatformAccessOnly(true); + return createEnterpriseUser(api, null, name, params, fields); + } + + /** + * Provisions a new user in an enterprise. + * + * @param api the API connection to be used by the created user. + * @param login the email address the user will use to login. + * @param name the name of the user. + * @param fields the fields to retrieve. Leave this out for the standard fields. + * @return the created user's info. + */ + public static BoxUser.Info createEnterpriseUser( + BoxAPIConnection api, String login, String name, String... fields) { + return createEnterpriseUser(api, login, name, null, fields); + } + + /** + * Provisions a new user in an enterprise with additional user information. + * + * @param api the API connection to be used by the created user. + * @param login the email address the user will use to login. + * @param name the name of the user. + * @param params additional user information. + * @param fields the fields to retrieve. Leave this out for the standard fields. + * @return the created user's info. + */ + public static BoxUser.Info createEnterpriseUser( + BoxAPIConnection api, String login, String name, CreateUserParams params, String... fields) { + + JsonObject requestJSON = new JsonObject(); + requestJSON.add("login", login); + requestJSON.add("name", name); + + if (params != null) { + if (params.getRole() != null) { + requestJSON.add("role", params.getRole().toJSONValue()); + } + + if (params.getStatus() != null) { + requestJSON.add("status", params.getStatus().toJSONValue()); + } + + 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()); + } + + QueryStringBuilder queryString = new QueryStringBuilder(); + if (fields.length > 0) { + queryString.appendParam("fields", fields); + } + URL url = USERS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), queryString.toString()); + BoxJSONRequest request = new BoxJSONRequest(api, url, "POST"); + request.setBody(requestJSON.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + + BoxUser createdUser = new BoxUser(api, responseJSON.get("id").asString()); + return createdUser.new Info(responseJSON); + } + } + + /** + * Gets the current user. + * + * @param api the API connection of the current user. + * @return the current user. + */ + public static BoxUser getCurrentUser(BoxAPIConnection api) { + URL url = GET_ME_URL.build(api.getBaseURL()); + BoxJSONRequest request = new BoxJSONRequest(api, url, "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); + return new BoxUser(api, jsonObject.get("id").asString()); + } + } + + /** + * Returns an iterable containing all the enterprise users. + * + * @param api the API connection to be used when retrieving the users. + * @return an iterable containing all the enterprise users. + */ + public static Iterable getAllEnterpriseUsers(final BoxAPIConnection api) { + return getAllEnterpriseUsers(api, false, null); + } + + /** + * Returns an iterable containing all the enterprise users. Uses marker based pagination. + * + * @param api the API connection to be used when retrieving the users. + * @param usemarker Boolean that determines whether to use marker based pagination. + * @param marker The marker at which the iterator will begin. + * @return an iterable containing all the enterprise users. + */ + public static Iterable getAllEnterpriseUsers( + final BoxAPIConnection api, final boolean usemarker, final String marker) { + return getUsersInfoForType(api, null, null, null, usemarker, marker); + } + + /** + * Returns an iterable containing all the enterprise users that matches the filter and specifies + * which child fields to retrieve from the API. + * + * @param api the API connection to be used when retrieving the users. + * @param filterTerm used to filter the results to only users starting with this string in either + * the name or the login. Can be null to not filter the results. + * @param fields the fields to retrieve. Leave this out for the standard fields. + * @return an iterable containing all the enterprise users that matches the filter. + */ + public static Iterable getAllEnterpriseUsers( + final BoxAPIConnection api, final String filterTerm, final String... fields) { + return getUsersInfoForType(api, filterTerm, null, null, false, null, fields); + } + + /** + * Returns an iterable containing all the enterprise users that matches the filter and specifies + * which child fields to retrieve from the API. Uses marker based pagination. + * + * @param api the API connection to be used when retrieving the users. + * @param filterTerm used to filter the results to only users starting with this string in either + * the name or the login. Can be null to not filter the results. + * @param usemarker Boolean that determines whether to use marker based pagination. + * @param marker The marker at which the iterator will begin. + * @param fields the fields to retrieve. Leave this out for the standard fields. + * @return an iterable containing all the enterprise users that matches the filter. + */ + public static Iterable getAllEnterpriseUsers( + final BoxAPIConnection api, + final String filterTerm, + final boolean usemarker, + final String marker, + final String... fields) { + return getUsersInfoForType(api, filterTerm, null, null, usemarker, marker, fields); + } + + /** + * Gets a limited set of information about an external user. (A user collaborating on content + * owned by the enterprise). Note: Only fields the user has permission to see will be returned + * with values. Other fields will return a value of null. + * + * @param api the API connection to be used when retrieving the users. + * @param filterTerm used to filter the results to only users matching the given login. This does + * exact match only, so if no filter term is passed in, nothing will be returned. + * @param fields the fields to retrieve. Leave this out for the standard fields. + * @return an iterable containing external users matching the given email + */ + public static Iterable getExternalUsers( + final BoxAPIConnection api, final String filterTerm, final String... fields) { + return getUsersInfoForType(api, filterTerm, "external", null, false, null, fields); + } + + /** + * Gets a limited set of information about an external user. (A user collaborating on content + * owned by the enterprise). Note: Only fields the user has permission to see will be returned + * with values. Other fields will return a value of null. Uses marker based pagination. + * + * @param api the API connection to be used when retrieving the users. + * @param filterTerm used to filter the results to only users matching the given login. This does + * exact match only, so if no filter term is passed in, nothing will be returned. + * @param usemarker Boolean that determines whether to use marker based pagination. + * @param marker The marker at which the iterator will begin. + * @param fields the fields to retrieve. Leave this out for the standard fields. + * @return an iterable containing external users matching the given email + */ + public static Iterable getExternalUsers( + final BoxAPIConnection api, + final String filterTerm, + final boolean usemarker, + final String marker, + final String... fields) { + return getUsersInfoForType(api, filterTerm, "external", null, usemarker, marker, fields); + } + + /** + * Gets any managed users that match the filter term as well as any external users that match the + * filter term. For managed users it matches any users names or emails that start with the term. + * For external, it only does full match on email. This method is ideal to use in the case where + * you have a full email for a user and you don't know if they're managed or external. + * + * @param api the API connection to be used when retrieving the users. + * @param filterTerm The filter term to lookup users by (login for external, login or name for + * managed) + * @param fields the fields to retrieve. Leave this out for the standard fields. + * @return an iterable containing users matching the given email + */ + public static Iterable getAllEnterpriseOrExternalUsers( + final BoxAPIConnection api, final String filterTerm, final String... fields) { + return getUsersInfoForType(api, filterTerm, "all", null, false, null, fields); + } + + /** + * Gets any managed users that match the filter term as well as any external users that match the + * filter term. For managed users it matches any users names or emails that start with the term. + * For external, it only does full match on email. This method is ideal to use in the case where + * you have a full email for a user and you don't know if they're managed or external. Uses marker + * based pagination. + * + * @param api the API connection to be used when retrieving the users. + * @param filterTerm The filter term to lookup users by (login for external, login or name for + * managed) + * @param usemarker Boolean that determines whether to use marker based pagination. + * @param marker The marker at which the iterator will begin. + * @param fields the fields to retrieve. Leave this out for the standard fields. + * @return an iterable containing users matching the given email + */ + public static Iterable getAllEnterpriseOrExternalUsers( + final BoxAPIConnection api, + final String filterTerm, + final boolean usemarker, + final String marker, + final String... fields) { + return getUsersInfoForType(api, filterTerm, "all", null, usemarker, marker, fields); + } + + /** + * Gets any app users that has an exact match with the externalAppUserId term. + * + * @param api the API connection to be used when retrieving the users. + * @param externalAppUserId the external app user id that has been set for app user + * @param fields the fields to retrieve. Leave this out for the standard fields. + * @return an iterable containing users matching the given email + */ + public static Iterable getAppUsersByExternalAppUserID( + final BoxAPIConnection api, final String externalAppUserId, final String... fields) { + return getUsersInfoForType(api, null, null, externalAppUserId, false, null, fields); + } + + /** + * Gets any app users that has an exact match with the externalAppUserId term using marker based + * pagination. + * + * @param api the API connection to be used when retrieving the users. + * @param externalAppUserId the external app user id that has been set for app user + * @param usemarker Boolean that determines whether to use marker based pagination. + * @param marker The marker at which the iterator will begin. + * @param fields the fields to retrieve. Leave this out for the standard fields. + * @return an iterable containing users matching the given email + */ + public static Iterable getAppUsersByExternalAppUserID( + final BoxAPIConnection api, + final String externalAppUserId, + final boolean usemarker, + String marker, + final String... fields) { + return getUsersInfoForType(api, null, null, externalAppUserId, usemarker, marker, fields); + } + + /** + * Helper method to abstract out the common logic from the various users methods. + * + * @param api the API connection to be used when retrieving the users. + * @param filterTerm The filter term to lookup users by (login for external, login or name for + * managed) + * @param userType The type of users we want to search with this request. Valid values are + * 'managed' (enterprise users), 'external' or 'all' + * @param externalAppUserId the external app user id that has been set for an app user + * @param usemarker Boolean that determines whether to use marker based pagination. + * @param marker The marker at which the iterator will begin. + * @param fields the fields to retrieve. Leave this out for the standard fields. + * @return An iterator over the selected users. + */ + private static Iterable getUsersInfoForType( + final BoxAPIConnection api, + final String filterTerm, + final String userType, + final String externalAppUserId, + final boolean usemarker, + final String marker, + final String... fields) { + + final QueryStringBuilder builder = new QueryStringBuilder(); + if (filterTerm != null) { + builder.appendParam("filter_term", filterTerm); + } + if (userType != null) { + builder.appendParam("user_type", userType); + } + if (externalAppUserId != null) { + builder.appendParam("external_app_user_id", externalAppUserId); + } + if (usemarker) { + builder.appendParam("usemarker", "true"); + } + if (fields.length > 0) { + builder.appendParam("fields", fields); + } + final URL url = USERS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString()); + + if (usemarker) { + return new BoxResourceIterable(api, url, 100, null, marker) { + @Override + protected BoxUser.Info factory(JsonObject jsonObject) { + BoxUser user = new BoxUser(api, jsonObject.get("id").asString()); + return user.new Info(jsonObject); + } + }; + } else { + return () -> new BoxUserIterator(api, url); + } + } + + private static JsonArray toTrackingCodesJson(Map trackingCodes) { + JsonArray trackingCodesJsonArray = new JsonArray(); + for (String attrKey : trackingCodes.keySet()) { + JsonObject trackingCode = new JsonObject(); + trackingCode.set("type", "tracking_code"); + trackingCode.set("name", attrKey); + trackingCode.set("value", trackingCodes.get(attrKey)); + trackingCodesJsonArray.add(trackingCode); + } + return trackingCodesJsonArray; + } + + /** + * Gets information about this user. + * + * @param fields the optional fields to retrieve. + * @return info about this user. + */ + public BoxUser.Info getInfo(String... fields) { + URL url; + if (fields.length > 0) { + String queryString = new QueryStringBuilder().appendParam("fields", fields).toString(); + url = USER_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID()); + } else { + url = USER_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + } + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); + return new Info(jsonObject); + } + } + + /** + * Gets information about all of the group memberships for this user. Does not support paging. + * + *

Note: This method is only available to enterprise admins. + * + * @return a collection of information about the group memberships for this user. + */ + public Collection getMemberships() { + BoxAPIConnection api = this.getAPI(); + URL url = USER_MEMBERSHIPS_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + + BoxJSONRequest request = new BoxJSONRequest(api, url, "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + + int entriesCount = responseJSON.get("total_count").asInt(); + Collection memberships = new ArrayList<>(entriesCount); + JsonArray entries = responseJSON.get("entries").asArray(); + for (JsonValue entry : entries) { + JsonObject entryObject = entry.asObject(); + BoxGroupMembership membership = + new BoxGroupMembership(api, entryObject.get("id").asString()); + BoxGroupMembership.Info info = membership.new Info(entryObject); + memberships.add(info); + } + + return memberships; + } + } + + /** + * Gets information about all of the group memberships for this user as iterable with paging + * support. + * + * @param fields the fields to retrieve. + * @return an iterable with information about the group memberships for this user. + */ + public Iterable getAllMemberships(String... fields) { + final QueryStringBuilder builder = new QueryStringBuilder(); + if (fields.length > 0) { + builder.appendParam("fields", fields); + } + return () -> { + URL url = + USER_MEMBERSHIPS_URL_TEMPLATE.buildWithQuery( + BoxUser.this.getAPI().getBaseURL(), builder.toString(), BoxUser.this.getID()); + return new BoxGroupMembershipIterator(BoxUser.this.getAPI(), url); + }; + } + + /** + * Adds a new email alias to this user's account. + * + * @param email the email address to add as an alias. + * @return the newly created email alias. + */ + public EmailAlias addEmailAlias(String email) { + return this.addEmailAlias(email, false); + } + + /** + * Adds a new email alias to this user's account and confirms it without user interaction. This + * functionality is only available for enterprise admins. + * + * @param email the email address to add as an alias. + * @param isConfirmed whether or not the email alias should be automatically confirmed. + * @return the newly created email alias. + */ + public EmailAlias addEmailAlias(String email, boolean isConfirmed) { + URL url = EMAIL_ALIASES_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); + + JsonObject requestJSON = new JsonObject().add("email", email); + + if (isConfirmed) { + requestJSON.add("is_confirmed", isConfirmed); + } + + request.setBody(requestJSON.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + return new EmailAlias(responseJSON); + } + } + + /** + * Deletes an email alias from this user's account. + * + *

The IDs of the user's email aliases can be found by calling {@link #getEmailAliases}. + * + * @param emailAliasID the ID of the email alias to delete. + */ + public void deleteEmailAlias(String emailAliasID) { + URL url = + EMAIL_ALIAS_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), emailAliasID); + BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); + request.send().close(); + } + + /** + * Gets a collection of all the email aliases for this user. + * + *

Note that the user's primary login email is not included in the collection of email aliases. + * + * @return a collection of all the email aliases for this user. + */ + public Collection getEmailAliases() { + URL url = EMAIL_ALIASES_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + + int totalCount = responseJSON.get("total_count").asInt(); + Collection emailAliases = new ArrayList<>(totalCount); + JsonArray entries = responseJSON.get("entries").asArray(); + for (JsonValue value : entries) { + JsonObject emailAliasJSON = value.asObject(); + emailAliases.add(new EmailAlias(emailAliasJSON)); + } + + return emailAliases; + } + } + + /** + * Deletes a user from an enterprise account. + * + * @param notifyUser whether or not to send an email notification to the user that their account + * has been deleted. + * @param force whether or not this user should be deleted even if they still own files. + */ + public void delete(boolean notifyUser, boolean force) { + String queryString = + new QueryStringBuilder() + .appendParam("notify", String.valueOf(notifyUser)) + .appendParam("force", String.valueOf(force)) + .toString(); + + performUserDelete(queryString); + } + + /** + * Deletes a user from an enterprise account. Uses API default values to determine if request + * should be forced and if user should be notified. + */ + public void delete() { + performUserDelete(""); + } + + private void performUserDelete(String queryString) { + URL url = + USER_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID()); + BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); + request.send().close(); + } + + /** + * Updates the information about this user with any info fields that have been modified locally. + * + *

Note: This method is only available to enterprise admins. + * + * @param info info the updated info. + * @param fields the fields to retrieve. Leave this out for the standard fields. + */ + public void updateInfo(BoxUser.Info info, String... fields) { + QueryStringBuilder builder = new QueryStringBuilder(); + if (fields.length > 0) { + builder.appendParam("fields", fields); + } + URL url = + USER_URL_TEMPLATE.buildWithQuery( + this.getAPI().getBaseURL(), builder.toString(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); + request.setBody(info.getPendingChanges()); + try (BoxJSONResponse response = request.send()) { + JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); + info.update(jsonObject); + } + } + + /** + * Moves all the owned content from within one user’s folder into a new folder in another user's + * account. You can move folders across users as long as the you have administrative permissions + * and the 'source' user owns the folders. Per the documentation at the link below, this will move + * everything from the root folder, as this is currently the only mode of operation supported. + * + *

See also https://developer.box.com/en/reference/put-users-id-folders-id/ + * + * @param destinationUserID the user id of the user that you wish to transfer content to. + * @return info for the newly created folder. + */ + public BoxFolder.Info transferContent(String destinationUserID) { + URL url = MOVE_FOLDER_TO_USER_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), "0"); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); + JsonObject destinationUser = new JsonObject(); + destinationUser.add("id", destinationUserID); + JsonObject ownedBy = new JsonObject(); + ownedBy.add("owned_by", destinationUser); + request.setBody(ownedBy.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + BoxFolder movedFolder = new BoxFolder(this.getAPI(), responseJSON.get("id").asString()); + + return movedFolder.new Info(responseJSON); + } + } + + /** + * Writes avatar into specified {@link OutputStream} + * + * @param outputStream Stream where to write avatar. + */ + public void downloadAvatar(OutputStream outputStream) { + URL url = USER_AVATAR_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); + writeStream(request.send(), outputStream); + } + + /** + * Retrieves the avatar of a user as an InputStream. + * + * @return InputStream representing the user avater. + * @deprecated This method loads whole avatar image to memory. Use {@link + * BoxUser#downloadAvatar(OutputStream)} to store avatar in file or memory. That method uses + * very small buffer to store bytes in memory. + */ + public InputStream getAvatar() { + URL url = USER_AVATAR_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); + BoxAPIResponse response = request.send(); + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { + writeStream(response, outputStream); + return new ByteArrayInputStream(outputStream.toByteArray()); + } catch (IOException e) { + throw new RuntimeException("Error while closing stream", e); + } + } + + /** + * Upload avatar image to user account. Supported formats are JPG and PNG. The image size cannot + * exceed 1024 * 1024 pixels or 1MB. + * + * @param file File containg avatar image. + * @return Avatar creation response. + */ + public AvatarUploadResponse uploadAvatar(File file) { + try { + return uploadAvatar(new FileInputStream(file), file.getName()); + } catch (FileNotFoundException e) { + throw new RuntimeException(e); + } + } + + /** + * Upload avatar image to user account. Supported formats are JPG and PNG. The image size cannot + * exceed 1024 * 1024 pixels or 1MB. + * + * @param file {@link File} containg avatar image. + * @param progressListener {@link ProgressListener} set if you want to track upload progress + * @return Avatar creation response. + */ + public AvatarUploadResponse uploadAvatar(File file, ProgressListener progressListener) { + try { + return uploadAvatar(new FileInputStream(file), file.getName(), progressListener); + } catch (FileNotFoundException e) { + throw new RuntimeException(e); + } + } + + /** + * Upload avatar image to user account. Supported formats are JPG and PNG. The image size cannot + * exceed 1024 * 1024 pixels or 1MB. + * + * @param content {@link InputStream} containing image data + * @param fileName file name with extention what will be used to determine content type + * @return Avatar creation response. + */ + public AvatarUploadResponse uploadAvatar(InputStream content, String fileName) { + return uploadAvatar(content, fileName, null); + } + + /** + * Upload avatar image to user account. Supported formats are JPG and PNG. The image size cannot + * exceed 1024 * 1024 pixels or 1MB. + * + * @param content {@link InputStream} containing image data + * @param fileName file name with extention what will be used to determine content type + * @param progressListener {@link ProgressListener} set if you want to track upload progress + * @return Avatar creation response. + */ + public AvatarUploadResponse uploadAvatar( + InputStream content, String fileName, ProgressListener progressListener) { + URL url = USER_AVATAR_TEMPLATE.build(getAPI().getBaseURL(), this.getID()); + BoxImageMultipartRequest request = new BoxImageMultipartRequest(getAPI(), url, "pic"); + request.setFile(content, fileName); + + BoxAPIResponse response = null; + try { + if (progressListener != null) { + response = request.send(progressListener); + } else { + response = request.send(); + } + + return parseUploadAvatarResponse(response); + } finally { + Optional.ofNullable(response).ifPresent(BoxAPIResponse::close); + } + } + + /** Removes avatar from user account. */ + public void deleteAvatar() { + URL url = USER_AVATAR_TEMPLATE.build(getAPI().getBaseURL(), this.getID()); + BoxAPIRequest request = new BoxAPIRequest(getAPI(), url, DELETE); + request.send().close(); + } + + private AvatarUploadResponse parseUploadAvatarResponse(BoxAPIResponse response) { + JsonObject responseObject = Json.parse(response.bodyToString()).asObject(); + JsonObject picUrls = responseObject.get("pic_urls").asObject(); + return new AvatarUploadResponse( + picUrls.getString("small", null), + picUrls.getString("large", null), + picUrls.getString("preview", null)); + } + + /** Enumerates the possible roles that a user can have within an enterprise. */ + public enum Role { + /** The user is an administrator of their enterprise. */ + ADMIN("admin"), + + /** The user is a co-administrator of their enterprise. */ + COADMIN("coadmin"), + + /** The user is a regular user within their enterprise. */ + USER("user"); + + private final String jsonValue; + + Role(String jsonValue) { + this.jsonValue = jsonValue; + } + + static Role fromJSONValue(String jsonValue) { + return Role.valueOf(jsonValue.toUpperCase(java.util.Locale.ROOT)); + } + + String toJSONValue() { + return this.jsonValue; + } + } + + /** Enumerates the possible statuses that a user's account can have. */ + public enum Status { + /** The user's account is active. */ + ACTIVE("active"), + + /** The user's account is inactive. */ + INACTIVE("inactive"), + + /** The user's account cannot delete or edit content. */ + CANNOT_DELETE_EDIT("cannot_delete_edit"), + + /** The user's account cannot delete, edit, or upload content. */ + CANNOT_DELETE_EDIT_UPLOAD("cannot_delete_edit_upload"); + + private final String jsonValue; + + Status(String jsonValue) { + this.jsonValue = jsonValue; + } + + static Status fromJSONValue(String jsonValue) { + return Status.valueOf(jsonValue.toUpperCase(java.util.Locale.ROOT)); + } + + String toJSONValue() { + return this.jsonValue; + } + } + + /** Contains information about a BoxUser. */ + public class Info extends BoxCollaborator.Info { + private String login; + private Role role; + private String language; + private String timezone; + private long spaceAmount; + private long spaceUsed; + private long maxUploadSize; + private boolean canSeeManagedUsers; + private boolean isSyncEnabled; + private boolean isExternalCollabRestricted; + private Status status; + private String jobTitle; + private String phone; + private String address; + private String avatarURL; + private BoxNotificationEmail notificationEmail; + private boolean isExemptFromDeviceLimits; + private boolean isExemptFromLoginVerification; + private boolean isPasswordResetRequired; + private boolean isPlatformAccessOnly; + private String externalAppUserId; + private BoxEnterprise enterprise; + private List myTags; + private String hostname; + private Map trackingCodes; + + /** Constructs an empty Info object. */ + public Info() { + super(); + } /** - * User URL Template. - */ - public static final URLTemplate USER_URL_TEMPLATE = new URLTemplate("users/%s"); - /** - * Get Me URL Template. - */ - public static final URLTemplate GET_ME_URL = new URLTemplate("users/me"); - /** - * Users URL Template. - */ - public static final URLTemplate USERS_URL_TEMPLATE = new URLTemplate("users"); - /** - * User Memberships URL Template. + * Constructs an Info object by parsing information from a JSON string. + * + * @param json the JSON string to parse. */ - public static final URLTemplate USER_MEMBERSHIPS_URL_TEMPLATE = new URLTemplate("users/%s/memberships"); + public Info(String json) { + super(json); + } + + Info(JsonObject jsonObject) { + super(jsonObject); + } + + @Override + public BoxUser getResource() { + return BoxUser.this; + } + /** - * E-Mail Alias URL Template. + * Gets the email address the user uses to login. + * + * @return the email address the user uses to login. */ - public static final URLTemplate EMAIL_ALIAS_URL_TEMPLATE = new URLTemplate("users/%s/email_aliases/%s"); + public String getLogin() { + return this.login; + } + /** - * E-Mail Aliases URL Template. + * Sets the email address the user uses to login. The new login must be one of the user's + * already confirmed email aliases. + * + * @param login one of the user's confirmed email aliases. */ - public static final URLTemplate EMAIL_ALIASES_URL_TEMPLATE = new URLTemplate("users/%s/email_aliases"); + public void setLogin(String login) { + this.login = login; + this.addPendingChange("login", login); + } + /** - * Move Folder To User Template. + * Gets the user's enterprise role. + * + * @return the user's enterprise role. */ - public static final URLTemplate MOVE_FOLDER_TO_USER_TEMPLATE = new URLTemplate("users/%s/folders/%s"); + public Role getRole() { + return this.role; + } + /** - * User Avatar Template. + * Sets the user's role in their enterprise. + * + * @param role the user's new role in their enterprise. */ - public static final URLTemplate USER_AVATAR_TEMPLATE = new URLTemplate("users/%s/avatar"); + public void setRole(Role role) { + this.role = role; + this.addPendingChange("role", role.name().toLowerCase(java.util.Locale.ROOT)); + } /** - * Constructs a BoxUser for a user with a given ID. + * Gets the language of the user. * - * @param api the API connection to be used by the user. - * @param id the ID of the user. + * @return the language of the user. */ - public BoxUser(BoxAPIConnection api, String id) { - super(api, id); + public String getLanguage() { + return this.language; } /** - * Provisions a new app user in an enterprise using Box Developer Edition. + * Sets the language of the user. * - * @param api the API connection to be used by the created user. - * @param name the name of the user. - * @param fields the fields to retrieve. Leave this out for the standard fields. - * @return the created user's info. + * @param language the new language of the user. */ - public static BoxUser.Info createAppUser(BoxAPIConnection api, String name, String... fields) { - return createAppUser(api, name, new CreateUserParams(), fields); + public void setLanguage(String language) { + this.language = language; + this.addPendingChange("language", language); } /** - * Provisions a new app user in an enterprise with additional user information using Box Developer Edition. + * Gets the timezone of the user. * - * @param api the API connection to be used by the created user. - * @param name the name of the user. - * @param params additional user information. - * @param fields the fields to retrieve. Leave this out for the standard fields. - * @return the created user's info. + * @return the timezone of the user. */ - public static BoxUser.Info createAppUser(BoxAPIConnection api, String name, - CreateUserParams params, String... fields) { - - params.setIsPlatformAccessOnly(true); - return createEnterpriseUser(api, null, name, params, fields); + public String getTimezone() { + return this.timezone; } /** - * Provisions a new user in an enterprise. + * Sets the timezone of the user. * - * @param api the API connection to be used by the created user. - * @param login the email address the user will use to login. - * @param name the name of the user. - * @param fields the fields to retrieve. Leave this out for the standard fields. - * @return the created user's info. + * @param timezone the new timezone of the user. */ - public static BoxUser.Info createEnterpriseUser(BoxAPIConnection api, String login, String name, String... fields) { - return createEnterpriseUser(api, login, name, null, fields); + public void setTimezone(String timezone) { + this.timezone = timezone; + this.addPendingChange("timezone", timezone); } /** - * Provisions a new user in an enterprise with additional user information. + * Gets the user's total available space in bytes. * - * @param api the API connection to be used by the created user. - * @param login the email address the user will use to login. - * @param name the name of the user. - * @param params additional user information. - * @param fields the fields to retrieve. Leave this out for the standard fields. - * @return the created user's info. + * @return the user's total available space in bytes. */ - public static BoxUser.Info createEnterpriseUser(BoxAPIConnection api, String login, String name, - CreateUserParams params, String... fields) { - - JsonObject requestJSON = new JsonObject(); - requestJSON.add("login", login); - requestJSON.add("name", name); - - if (params != null) { - if (params.getRole() != null) { - requestJSON.add("role", params.getRole().toJSONValue()); - } - - if (params.getStatus() != null) { - requestJSON.add("status", params.getStatus().toJSONValue()); - } - - 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()); - } - - QueryStringBuilder queryString = new QueryStringBuilder(); - if (fields.length > 0) { - queryString.appendParam("fields", fields); - } - URL url = USERS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), queryString.toString()); - BoxJSONRequest request = new BoxJSONRequest(api, url, "POST"); - request.setBody(requestJSON.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - - BoxUser createdUser = new BoxUser(api, responseJSON.get("id").asString()); - return createdUser.new Info(responseJSON); - } + public long getSpaceAmount() { + return this.spaceAmount; } /** - * Gets the current user. + * Sets the user's total available space in bytes. * - * @param api the API connection of the current user. - * @return the current user. + * @param spaceAmount the new amount of space available to the user in bytes, or -1 for + * unlimited storage. */ - public static BoxUser getCurrentUser(BoxAPIConnection api) { - URL url = GET_ME_URL.build(api.getBaseURL()); - BoxJSONRequest request = new BoxJSONRequest(api, url, "GET"); - try (BoxJSONResponse response = request.send()) { - JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - return new BoxUser(api, jsonObject.get("id").asString()); - } + public void setSpaceAmount(long spaceAmount) { + this.spaceAmount = spaceAmount; + this.addPendingChange("space_amount", spaceAmount); } /** - * Returns an iterable containing all the enterprise users. + * Gets the amount of space the user has used in bytes. * - * @param api the API connection to be used when retrieving the users. - * @return an iterable containing all the enterprise users. + * @return the amount of space the user has used in bytes. */ - public static Iterable getAllEnterpriseUsers(final BoxAPIConnection api) { - return getAllEnterpriseUsers(api, false, null); + public long getSpaceUsed() { + return this.spaceUsed; } - /** - * Returns an iterable containing all the enterprise users. Uses marker based pagination. + * Gets the maximum individual file size in bytes the user can have. * - * @param api the API connection to be used when retrieving the users. - * @param usemarker Boolean that determines whether to use marker based pagination. - * @param marker The marker at which the iterator will begin. - * @return an iterable containing all the enterprise users. + * @return the maximum individual file size in bytes the user can have. */ - public static Iterable getAllEnterpriseUsers(final BoxAPIConnection api, final boolean usemarker, - final String marker) { - return getUsersInfoForType(api, null, null, null, usemarker, marker); + public long getMaxUploadSize() { + return this.maxUploadSize; } /** - * Returns an iterable containing all the enterprise users that matches the filter and specifies which child fields - * to retrieve from the API. + * Gets the user's current account status. * - * @param api the API connection to be used when retrieving the users. - * @param filterTerm used to filter the results to only users starting with this string in either the name or the - * login. Can be null to not filter the results. - * @param fields the fields to retrieve. Leave this out for the standard fields. - * @return an iterable containing all the enterprise users that matches the filter. + * @return the user's current account status. */ - public static Iterable getAllEnterpriseUsers(final BoxAPIConnection api, final String filterTerm, - final String... fields) { - return getUsersInfoForType(api, filterTerm, null, null, false, null, fields); + public Status getStatus() { + return this.status; } /** - * Returns an iterable containing all the enterprise users that matches the filter and specifies which child fields - * to retrieve from the API. Uses marker based pagination. + * Sets the user's current account status. * - * @param api the API connection to be used when retrieving the users. - * @param filterTerm used to filter the results to only users starting with this string in either the name or the - * login. Can be null to not filter the results. - * @param usemarker Boolean that determines whether to use marker based pagination. - * @param marker The marker at which the iterator will begin. - * @param fields the fields to retrieve. Leave this out for the standard fields. - * @return an iterable containing all the enterprise users that matches the filter. + * @param status the user's new account status. */ - public static Iterable getAllEnterpriseUsers( - final BoxAPIConnection api, - final String filterTerm, - final boolean usemarker, - final String marker, - final String... fields - ) { - return getUsersInfoForType(api, filterTerm, null, null, usemarker, marker, fields); + public void setStatus(Status status) { + this.status = status; + this.addPendingChange("status", status.name().toLowerCase(java.util.Locale.ROOT)); } /** - * Gets a limited set of information about an external user. (A user collaborating - * on content owned by the enterprise). Note: Only fields the user has permission to - * see will be returned with values. Other fields will return a value of null. + * Gets the job title of the user. * - * @param api the API connection to be used when retrieving the users. - * @param filterTerm used to filter the results to only users matching the given login. - * This does exact match only, so if no filter term is passed in, nothing - * will be returned. - * @param fields the fields to retrieve. Leave this out for the standard fields. - * @return an iterable containing external users matching the given email + * @return the job title of the user. */ - public static Iterable getExternalUsers(final BoxAPIConnection api, final String filterTerm, - final String... fields) { - return getUsersInfoForType(api, filterTerm, "external", null, false, null, fields); + public String getJobTitle() { + return this.jobTitle; } /** - * Gets a limited set of information about an external user. (A user collaborating - * on content owned by the enterprise). Note: Only fields the user has permission to - * see will be returned with values. Other fields will return a value of null. Uses marker based pagination. + * Sets the job title of the user. * - * @param api the API connection to be used when retrieving the users. - * @param filterTerm used to filter the results to only users matching the given login. - * This does exact match only, so if no filter term is passed in, nothing - * will be returned. - * @param usemarker Boolean that determines whether to use marker based pagination. - * @param marker The marker at which the iterator will begin. - * @param fields the fields to retrieve. Leave this out for the standard fields. - * @return an iterable containing external users matching the given email + * @param jobTitle the new job title of the user. */ - public static Iterable getExternalUsers( - final BoxAPIConnection api, - final String filterTerm, - final boolean usemarker, - final String marker, - final String... fields - ) { - return getUsersInfoForType(api, filterTerm, "external", null, usemarker, marker, fields); + public void setJobTitle(String jobTitle) { + this.jobTitle = jobTitle; + this.addPendingChange("job_title", jobTitle); } /** - * Gets any managed users that match the filter term as well as any external users that - * match the filter term. For managed users it matches any users names or emails that - * start with the term. For external, it only does full match on email. This method - * is ideal to use in the case where you have a full email for a user and you don't - * know if they're managed or external. + * Gets the phone number of the user. * - * @param api the API connection to be used when retrieving the users. - * @param filterTerm The filter term to lookup users by (login for external, login or name for managed) - * @param fields the fields to retrieve. Leave this out for the standard fields. - * @return an iterable containing users matching the given email + * @return the phone number of the user. */ - public static Iterable getAllEnterpriseOrExternalUsers( - final BoxAPIConnection api, - final String filterTerm, - final String... fields - ) { - return getUsersInfoForType(api, filterTerm, "all", null, false, null, fields); + public String getPhone() { + return this.phone; } /** - * Gets any managed users that match the filter term as well as any external users that - * match the filter term. For managed users it matches any users names or emails that - * start with the term. For external, it only does full match on email. This method - * is ideal to use in the case where you have a full email for a user and you don't - * know if they're managed or external. Uses marker based pagination. + * Sets the phone number of the user. * - * @param api the API connection to be used when retrieving the users. - * @param filterTerm The filter term to lookup users by (login for external, login or name for managed) - * @param usemarker Boolean that determines whether to use marker based pagination. - * @param marker The marker at which the iterator will begin. - * @param fields the fields to retrieve. Leave this out for the standard fields. - * @return an iterable containing users matching the given email + * @param phone the new phone number of the user. */ - public static Iterable getAllEnterpriseOrExternalUsers( - final BoxAPIConnection api, - final String filterTerm, - final boolean usemarker, - final String marker, - final String... fields - ) { - return getUsersInfoForType(api, filterTerm, "all", null, usemarker, marker, fields); + public void setPhone(String phone) { + this.phone = phone; + this.addPendingChange("phone", phone); } /** - * Gets any app users that has an exact match with the externalAppUserId term. + * Gets the address of the user. * - * @param api the API connection to be used when retrieving the users. - * @param externalAppUserId the external app user id that has been set for app user - * @param fields the fields to retrieve. Leave this out for the standard fields. - * @return an iterable containing users matching the given email + * @return the address of the user. */ - public static Iterable getAppUsersByExternalAppUserID( - final BoxAPIConnection api, - final String externalAppUserId, - final String... fields - ) { - return getUsersInfoForType(api, null, null, externalAppUserId, false, null, fields); + public String getAddress() { + return this.address; } /** - * Gets any app users that has an exact match with the externalAppUserId term using marker based pagination. + * Sets the address of the user. * - * @param api the API connection to be used when retrieving the users. - * @param externalAppUserId the external app user id that has been set for app user - * @param usemarker Boolean that determines whether to use marker based pagination. - * @param marker The marker at which the iterator will begin. - * @param fields the fields to retrieve. Leave this out for the standard fields. - * @return an iterable containing users matching the given email + * @param address the new address of the user. */ - public static Iterable getAppUsersByExternalAppUserID( - final BoxAPIConnection api, - final String externalAppUserId, - final boolean usemarker, - String marker, - final String... fields - ) { - return getUsersInfoForType(api, null, null, externalAppUserId, usemarker, marker, fields); + public void setAddress(String address) { + this.address = address; + this.addPendingChange("address", address); } /** - * Helper method to abstract out the common logic from the various users methods. + * Gets the URL of the user's avatar. * - * @param api the API connection to be used when retrieving the users. - * @param filterTerm The filter term to lookup users by (login for external, login or name for managed) - * @param userType The type of users we want to search with this request. - * Valid values are 'managed' (enterprise users), 'external' or 'all' - * @param externalAppUserId the external app user id that has been set for an app user - * @param usemarker Boolean that determines whether to use marker based pagination. - * @param marker The marker at which the iterator will begin. - * @param fields the fields to retrieve. Leave this out for the standard fields. - * @return An iterator over the selected users. + * @return the URL of the user's avatar. */ - private static Iterable getUsersInfoForType( - final BoxAPIConnection api, - final String filterTerm, - final String userType, - final String externalAppUserId, - final boolean usemarker, - final String marker, - final String... fields - ) { - - final QueryStringBuilder builder = new QueryStringBuilder(); - if (filterTerm != null) { - builder.appendParam("filter_term", filterTerm); - } - if (userType != null) { - builder.appendParam("user_type", userType); - } - if (externalAppUserId != null) { - builder.appendParam("external_app_user_id", externalAppUserId); - } - if (usemarker) { - builder.appendParam("usemarker", "true"); - } - if (fields.length > 0) { - builder.appendParam("fields", fields); - } - final URL url = USERS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString()); - - if (usemarker) { - return new BoxResourceIterable(api, url, 100, null, marker) { - @Override - protected BoxUser.Info factory(JsonObject jsonObject) { - BoxUser user = new BoxUser(api, jsonObject.get("id").asString()); - return user.new Info(jsonObject); - } - }; - } else { - return () -> new BoxUserIterator(api, url); - } + public String getAvatarURL() { + return this.avatarURL; } - private static JsonArray toTrackingCodesJson(Map trackingCodes) { - JsonArray trackingCodesJsonArray = new JsonArray(); - for (String attrKey : trackingCodes.keySet()) { - JsonObject trackingCode = new JsonObject(); - trackingCode.set("type", "tracking_code"); - trackingCode.set("name", attrKey); - trackingCode.set("value", trackingCodes.get(attrKey)); - trackingCodesJsonArray.add(trackingCode); - } - return trackingCodesJsonArray; + /** + * Gets the user's alternate notification email address to which email notifications are sent. + * + * @return the user's notification email address. + */ + public BoxNotificationEmail getNotificationEmail() { + return this.notificationEmail; } /** - * Gets information about this user. + * Sets the user's notification email address. * - * @param fields the optional fields to retrieve. - * @return info about this user. + * @param notificationEmail the user's new notification email address. */ - public BoxUser.Info getInfo(String... fields) { - URL url; - if (fields.length > 0) { - String queryString = new QueryStringBuilder().appendParam("fields", fields).toString(); - url = USER_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID()); - } else { - url = USER_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - } - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); - try (BoxJSONResponse response = request.send()) { - JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - return new Info(jsonObject); - } + public void setNotificationEmail(BoxNotificationEmail notificationEmail) { + this.notificationEmail = notificationEmail; } /** - * Gets information about all of the group memberships for this user. - * Does not support paging. - * - *

Note: This method is only available to enterprise admins.

+ * Gets the enterprise that the user belongs to. * - * @return a collection of information about the group memberships for this user. + * @return the enterprise that the user belongs to. */ - public Collection getMemberships() { - BoxAPIConnection api = this.getAPI(); - URL url = USER_MEMBERSHIPS_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - - BoxJSONRequest request = new BoxJSONRequest(api, url, "GET"); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - - int entriesCount = responseJSON.get("total_count").asInt(); - Collection memberships = new ArrayList<>(entriesCount); - JsonArray entries = responseJSON.get("entries").asArray(); - for (JsonValue entry : entries) { - JsonObject entryObject = entry.asObject(); - BoxGroupMembership membership = new BoxGroupMembership(api, entryObject.get("id").asString()); - BoxGroupMembership.Info info = membership.new Info(entryObject); - memberships.add(info); - } + public BoxEnterprise getEnterprise() { + return this.enterprise; + } - return memberships; - } + /** Removes the user from their enterprise and converts them to a standalone free user. */ + public void removeEnterprise() { + this.removeChildObject("enterprise"); + this.enterprise = null; + this.addChildObject("enterprise", null); } /** - * Gets information about all of the group memberships for this user as iterable with paging support. + * Gets whether or not the user can use Box Sync. * - * @param fields the fields to retrieve. - * @return an iterable with information about the group memberships for this user. + * @return true if the user can use Box Sync; otherwise false. */ - public Iterable getAllMemberships(String... fields) { - final QueryStringBuilder builder = new QueryStringBuilder(); - if (fields.length > 0) { - builder.appendParam("fields", fields); - } - return () -> { - URL url = USER_MEMBERSHIPS_URL_TEMPLATE.buildWithQuery( - BoxUser.this.getAPI().getBaseURL(), builder.toString(), BoxUser.this.getID()); - return new BoxGroupMembershipIterator(BoxUser.this.getAPI(), url); - }; + public boolean getIsSyncEnabled() { + return this.isSyncEnabled; } /** - * Adds a new email alias to this user's account. + * Sets whether or not the user can use Box Sync. * - * @param email the email address to add as an alias. - * @return the newly created email alias. + * @param enabled whether or not the user can use Box Sync. */ - public EmailAlias addEmailAlias(String email) { - return this.addEmailAlias(email, false); + public void setIsSyncEnabled(boolean enabled) { + this.isSyncEnabled = enabled; + this.addPendingChange("is_sync_enabled", enabled); } /** - * Adds a new email alias to this user's account and confirms it without user interaction. - * This functionality is only available for enterprise admins. + * Gets whether this user is allowed or not to collaborate with users outside their enterprise. * - * @param email the email address to add as an alias. - * @param isConfirmed whether or not the email alias should be automatically confirmed. - * @return the newly created email alias. + * @return true if this user is not allowed to collaborate with users outside their enterprise; + * otherwise false. */ - public EmailAlias addEmailAlias(String email, boolean isConfirmed) { - URL url = EMAIL_ALIASES_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); - - JsonObject requestJSON = new JsonObject() - .add("email", email); - - if (isConfirmed) { - requestJSON.add("is_confirmed", isConfirmed); - } - - request.setBody(requestJSON.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - return new EmailAlias(responseJSON); - } + public boolean getIsExternalCollabRestricted() { + return this.isExternalCollabRestricted; } /** - * Deletes an email alias from this user's account. - * - *

The IDs of the user's email aliases can be found by calling {@link #getEmailAliases}.

+ * Sets whether this user is allowed or not to collaborate with users outside their enterprise. * - * @param emailAliasID the ID of the email alias to delete. + * @param isExternalCollabRestricted whether the user is allowed to collaborate outside their + * enterprise. */ - public void deleteEmailAlias(String emailAliasID) { - URL url = EMAIL_ALIAS_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), emailAliasID); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); - request.send().close(); + public void setIsExternalCollabRestricted(boolean isExternalCollabRestricted) { + this.isExternalCollabRestricted = isExternalCollabRestricted; + this.addPendingChange("is_external_collab_restricted", isExternalCollabRestricted); } /** - * Gets a collection of all the email aliases for this user. + * Gets whether or not the user can see other enterprise users in their contact list. * - *

Note that the user's primary login email is not included in the collection of email aliases.

- * - * @return a collection of all the email aliases for this user. + * @return true if the user can see other enterprise users in their contact list; otherwise + * false. */ - public Collection getEmailAliases() { - URL url = EMAIL_ALIASES_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - - int totalCount = responseJSON.get("total_count").asInt(); - Collection emailAliases = new ArrayList<>(totalCount); - JsonArray entries = responseJSON.get("entries").asArray(); - for (JsonValue value : entries) { - JsonObject emailAliasJSON = value.asObject(); - emailAliases.add(new EmailAlias(emailAliasJSON)); - } - - return emailAliases; - } + public boolean getCanSeeManagedUsers() { + return this.canSeeManagedUsers; } /** - * Deletes a user from an enterprise account. + * Sets whether or not the user can see other enterprise users in their contact list. * - * @param notifyUser whether or not to send an email notification to the user that their account has been deleted. - * @param force whether or not this user should be deleted even if they still own files. + * @param canSeeManagedUsers whether or not the user can see other enterprise users in their + * contact list. */ - public void delete(boolean notifyUser, boolean force) { - String queryString = new QueryStringBuilder() - .appendParam("notify", String.valueOf(notifyUser)) - .appendParam("force", String.valueOf(force)) - .toString(); - - performUserDelete(queryString); + public void setCanSeeManagedUsers(boolean canSeeManagedUsers) { + this.canSeeManagedUsers = canSeeManagedUsers; + this.addPendingChange("can_see_managed_users", canSeeManagedUsers); } /** - * Deletes a user from an enterprise account. Uses API default values to determine if request should - * be forced and if user should be notified. + * Gets whether or not the user is exempt from enterprise device limits. + * + * @return true if the user is exempt from enterprise device limits; otherwise false. */ - public void delete() { - performUserDelete(""); - } - - private void performUserDelete(String queryString) { - URL url = USER_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID()); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); - request.send().close(); + public boolean getIsExemptFromDeviceLimits() { + return this.isExemptFromDeviceLimits; } /** - * Updates the information about this user with any info fields that have been modified locally. - * - *

Note: This method is only available to enterprise admins.

+ * Sets whether or not the user is exempt from enterprise device limits. * - * @param info info the updated info. - * @param fields the fields to retrieve. Leave this out for the standard fields. + * @param isExemptFromDeviceLimits whether or not the user is exempt from enterprise device + * limits. */ - public void updateInfo(BoxUser.Info info, String... fields) { - QueryStringBuilder builder = new QueryStringBuilder(); - if (fields.length > 0) { - builder.appendParam("fields", fields); - } - URL url = USER_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), builder.toString(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); - request.setBody(info.getPendingChanges()); - try (BoxJSONResponse response = request.send()) { - JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - info.update(jsonObject); - } + public void setIsExemptFromDeviceLimits(boolean isExemptFromDeviceLimits) { + this.isExemptFromDeviceLimits = isExemptFromDeviceLimits; + this.addPendingChange("is_exempt_from_device_limits", isExemptFromDeviceLimits); } /** - * Moves all the owned content from within one user’s folder into a new folder in another user's account. - * You can move folders across users as long as the you have administrative permissions and the 'source' - * user owns the folders. Per the documentation at the link below, this will move everything from the root - * folder, as this is currently the only mode of operation supported. - *

- * See also https://developer.box.com/en/reference/put-users-id-folders-id/ + * Gets whether or not the user must use two-factor authentication. * - * @param destinationUserID the user id of the user that you wish to transfer content to. - * @return info for the newly created folder. + * @return true if the user must use two-factor authentication; otherwise false. */ - public BoxFolder.Info transferContent(String destinationUserID) { - URL url = MOVE_FOLDER_TO_USER_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), "0"); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); - JsonObject destinationUser = new JsonObject(); - destinationUser.add("id", destinationUserID); - JsonObject ownedBy = new JsonObject(); - ownedBy.add("owned_by", destinationUser); - request.setBody(ownedBy.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - BoxFolder movedFolder = new BoxFolder(this.getAPI(), responseJSON.get("id").asString()); - - return movedFolder.new Info(responseJSON); - } + public boolean getIsExemptFromLoginVerification() { + return this.isExemptFromLoginVerification; } /** - * Writes avatar into specified {@link OutputStream} + * Sets whether or not the user must use two-factor authentication. * - * @param outputStream Stream where to write avatar. + * @param isExemptFromLoginVerification whether or not the user must use two-factor + * authentication. */ - public void downloadAvatar(OutputStream outputStream) { - URL url = USER_AVATAR_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); - writeStream(request.send(), outputStream); + public void setIsExemptFromLoginVerification(boolean isExemptFromLoginVerification) { + this.isExemptFromLoginVerification = isExemptFromLoginVerification; + this.addPendingChange("is_exempt_from_login_verification", isExemptFromLoginVerification); } /** - * Retrieves the avatar of a user as an InputStream. + * Gets whether or not the user is required to reset password. * - * @return InputStream representing the user avater. - * @deprecated This method loads whole avatar image to memory. - * Use {@link BoxUser#downloadAvatar(OutputStream)} to store avatar in file or memory. - * That method uses very small buffer to store bytes in memory. + * @return true if the user is required to reset password; otherwise false. */ - public InputStream getAvatar() { - URL url = USER_AVATAR_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); - BoxAPIResponse response = request.send(); - try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { - writeStream(response, outputStream); - return new ByteArrayInputStream(outputStream.toByteArray()); - } catch (IOException e) { - throw new RuntimeException("Error while closing stream", e); - } + public boolean getIsPasswordResetRequired() { + return this.isPasswordResetRequired; } /** - * Upload avatar image to user account. Supported formats are JPG and PNG. - * The image size cannot exceed 1024 * 1024 pixels or 1MB. + * Sets whether or not the user is required to reset password. * - * @param file File containg avatar image. - * @return Avatar creation response. + * @param isPasswordResetRequired whether or not the user is required to reset password. */ - public AvatarUploadResponse uploadAvatar(File file) { - try { - return uploadAvatar(new FileInputStream(file), file.getName()); - } catch (FileNotFoundException e) { - throw new RuntimeException(e); - } + public void setIsPasswordResetRequired(boolean isPasswordResetRequired) { + this.isPasswordResetRequired = isPasswordResetRequired; + this.addPendingChange("is_password_reset_required", isPasswordResetRequired); } /** - * Upload avatar image to user account. Supported formats are JPG and PNG. - * The image size cannot exceed 1024 * 1024 pixels or 1MB. + * Gets whether or not the user we are creating is an app user with Box Developer Edition. * - * @param file {@link File} containg avatar image. - * @param progressListener {@link ProgressListener} set if you want to track upload progress - * @return Avatar creation response. + * @return true if the new user is an app user for Box Developer Addition; otherwise false. */ - public AvatarUploadResponse uploadAvatar(File file, ProgressListener progressListener) { - try { - return uploadAvatar(new FileInputStream(file), file.getName(), progressListener); - } catch (FileNotFoundException e) { - throw new RuntimeException(e); - } + public boolean getIsPlatformAccessOnly() { + return this.isPlatformAccessOnly; } /** - * Upload avatar image to user account. Supported formats are JPG and PNG. - * The image size cannot exceed 1024 * 1024 pixels or 1MB. + * Gets the external app user id that has been set for the app user. * - * @param content {@link InputStream} containing image data - * @param fileName file name with extention what will be used to determine content type - * @return Avatar creation response. + * @return the external app user id. */ - public AvatarUploadResponse uploadAvatar(InputStream content, String fileName) { - return uploadAvatar(content, fileName, null); + public String getExternalAppUserId() { + return this.externalAppUserId; } /** - * Upload avatar image to user account. Supported formats are JPG and PNG. - * The image size cannot exceed 1024 * 1024 pixels or 1MB. + * Sets the external app user id. * - * @param content {@link InputStream} containing image data - * @param fileName file name with extention what will be used to determine content type - * @param progressListener {@link ProgressListener} set if you want to track upload progress - * @return Avatar creation response. + * @param externalAppUserId external app user id. */ - public AvatarUploadResponse uploadAvatar(InputStream content, String fileName, ProgressListener progressListener) { - URL url = USER_AVATAR_TEMPLATE.build(getAPI().getBaseURL(), this.getID()); - BoxImageMultipartRequest request = new BoxImageMultipartRequest(getAPI(), url, "pic"); - request.setFile(content, fileName); - - BoxAPIResponse response = null; - try { - if (progressListener != null) { - response = request.send(progressListener); - } else { - response = request.send(); - } - - return parseUploadAvatarResponse(response); - } finally { - Optional.ofNullable(response).ifPresent(BoxAPIResponse::close); - } + public void setExternalAppUserId(String externalAppUserId) { + this.externalAppUserId = externalAppUserId; + this.addPendingChange("external_app_user_id", externalAppUserId); } /** - * Removes avatar from user account. + * Gets the tags for all files and folders owned by this user. + * + * @return the tags for all files and folders owned by this user. */ - public void deleteAvatar() { - URL url = USER_AVATAR_TEMPLATE.build(getAPI().getBaseURL(), this.getID()); - BoxAPIRequest request = new BoxAPIRequest(getAPI(), url, DELETE); - request.send().close(); + public List getMyTags() { + return this.myTags; } - private AvatarUploadResponse parseUploadAvatarResponse(BoxAPIResponse response) { - JsonObject responseObject = Json.parse(response.bodyToString()).asObject(); - JsonObject picUrls = responseObject.get("pic_urls").asObject(); - return new AvatarUploadResponse( - picUrls.getString("small", null), - picUrls.getString("large", null), - picUrls.getString("preview", null) - ); + /** + * Gets the root (protocol, subdomain, domain) of any links that need to be generated for this + * user. + * + * @return the root (protocol, subdomain, domain) of any links that need to be generated for + * this user. + */ + public String getHostname() { + return this.hostname; } /** - * Enumerates the possible roles that a user can have within an enterprise. + * Gets the tracking defined for each entity. + * + * @return a Map with tracking codes. */ - public enum Role { - /** - * The user is an administrator of their enterprise. - */ - ADMIN("admin"), - - /** - * The user is a co-administrator of their enterprise. - */ - COADMIN("coadmin"), - - /** - * The user is a regular user within their enterprise. - */ - USER("user"); - - private final String jsonValue; - - Role(String jsonValue) { - this.jsonValue = jsonValue; - } - - static Role fromJSONValue(String jsonValue) { - return Role.valueOf(jsonValue.toUpperCase(java.util.Locale.ROOT)); - } - - String toJSONValue() { - return this.jsonValue; - } + public Map getTrackingCodes() { + return this.trackingCodes; } /** - * Enumerates the possible statuses that a user's account can have. + * Allows admin to set attributes specific for a group of users. + * + * @param trackingCodes a Map representing the user's new tracking codes */ - public enum Status { - /** - * The user's account is active. - */ - ACTIVE("active"), - - /** - * The user's account is inactive. - */ - INACTIVE("inactive"), - - /** - * The user's account cannot delete or edit content. - */ - CANNOT_DELETE_EDIT("cannot_delete_edit"), - - /** - * The user's account cannot delete, edit, or upload content. - */ - CANNOT_DELETE_EDIT_UPLOAD("cannot_delete_edit_upload"); - - private final String jsonValue; - - Status(String jsonValue) { - this.jsonValue = jsonValue; - } - - static Status fromJSONValue(String jsonValue) { - return Status.valueOf(jsonValue.toUpperCase(java.util.Locale.ROOT)); - } - - String toJSONValue() { - return this.jsonValue; - } + public void setTrackingCodes(Map trackingCodes) { + this.trackingCodes = trackingCodes; + this.addPendingChange("tracking_codes", toTrackingCodesJson(this.trackingCodes)); } /** - * Contains information about a BoxUser. + * Allows the admin to append new tracking codes to the previous existing list. + * + * @param name the name or `key` of the attribute to set. + * @param value the value of the attribute to set. */ - public class Info extends BoxCollaborator.Info { - private String login; - private Role role; - private String language; - private String timezone; - private long spaceAmount; - private long spaceUsed; - private long maxUploadSize; - private boolean canSeeManagedUsers; - private boolean isSyncEnabled; - private boolean isExternalCollabRestricted; - private Status status; - private String jobTitle; - private String phone; - private String address; - private String avatarURL; - private BoxNotificationEmail notificationEmail; - private boolean isExemptFromDeviceLimits; - private boolean isExemptFromLoginVerification; - private boolean isPasswordResetRequired; - private boolean isPlatformAccessOnly; - private String externalAppUserId; - private BoxEnterprise enterprise; - private List myTags; - private String hostname; - private Map trackingCodes; - - /** - * Constructs an empty Info object. - */ - public Info() { - super(); - } - - /** - * Constructs an Info object by parsing information from a JSON string. - * - * @param json the JSON string to parse. - */ - public Info(String json) { - super(json); - } - - Info(JsonObject jsonObject) { - super(jsonObject); - } - - @Override - public BoxUser getResource() { - return BoxUser.this; - } - - /** - * Gets the email address the user uses to login. - * - * @return the email address the user uses to login. - */ - public String getLogin() { - return this.login; - } - - /** - * Sets the email address the user uses to login. The new login must be one of the user's already confirmed - * email aliases. - * - * @param login one of the user's confirmed email aliases. - */ - public void setLogin(String login) { - this.login = login; - this.addPendingChange("login", login); - } - - /** - * Gets the user's enterprise role. - * - * @return the user's enterprise role. - */ - public Role getRole() { - return this.role; - } - - /** - * Sets the user's role in their enterprise. - * - * @param role the user's new role in their enterprise. - */ - public void setRole(Role role) { - this.role = role; - this.addPendingChange("role", role.name().toLowerCase(java.util.Locale.ROOT)); - } - - /** - * Gets the language of the user. - * - * @return the language of the user. - */ - public String getLanguage() { - return this.language; - } - - /** - * Sets the language of the user. - * - * @param language the new language of the user. - */ - public void setLanguage(String language) { - this.language = language; - this.addPendingChange("language", language); - } - - /** - * Gets the timezone of the user. - * - * @return the timezone of the user. - */ - public String getTimezone() { - return this.timezone; - } - - /** - * Sets the timezone of the user. - * - * @param timezone the new timezone of the user. - */ - public void setTimezone(String timezone) { - this.timezone = timezone; - this.addPendingChange("timezone", timezone); - } - - /** - * Gets the user's total available space in bytes. - * - * @return the user's total available space in bytes. - */ - public long getSpaceAmount() { - return this.spaceAmount; - } - - /** - * Sets the user's total available space in bytes. - * - * @param spaceAmount the new amount of space available to the user in bytes, or -1 for unlimited storage. - */ - public void setSpaceAmount(long spaceAmount) { - this.spaceAmount = spaceAmount; - this.addPendingChange("space_amount", spaceAmount); - } - - /** - * Gets the amount of space the user has used in bytes. - * - * @return the amount of space the user has used in bytes. - */ - public long getSpaceUsed() { - return this.spaceUsed; - } - - /** - * Gets the maximum individual file size in bytes the user can have. - * - * @return the maximum individual file size in bytes the user can have. - */ - public long getMaxUploadSize() { - return this.maxUploadSize; - } - - /** - * Gets the user's current account status. - * - * @return the user's current account status. - */ - public Status getStatus() { - return this.status; - } - - /** - * Sets the user's current account status. - * - * @param status the user's new account status. - */ - public void setStatus(Status status) { - this.status = status; - this.addPendingChange("status", status.name().toLowerCase(java.util.Locale.ROOT)); - } - - /** - * Gets the job title of the user. - * - * @return the job title of the user. - */ - public String getJobTitle() { - return this.jobTitle; - } - - /** - * Sets the job title of the user. - * - * @param jobTitle the new job title of the user. - */ - public void setJobTitle(String jobTitle) { - this.jobTitle = jobTitle; - this.addPendingChange("job_title", jobTitle); - } - - /** - * Gets the phone number of the user. - * - * @return the phone number of the user. - */ - public String getPhone() { - return this.phone; - } - - /** - * Sets the phone number of the user. - * - * @param phone the new phone number of the user. - */ - public void setPhone(String phone) { - this.phone = phone; - this.addPendingChange("phone", phone); - } - - /** - * Gets the address of the user. - * - * @return the address of the user. - */ - public String getAddress() { - return this.address; - } - - /** - * Sets the address of the user. - * - * @param address the new address of the user. - */ - public void setAddress(String address) { - this.address = address; - this.addPendingChange("address", address); - } - - /** - * Gets the URL of the user's avatar. - * - * @return the URL of the user's avatar. - */ - public String getAvatarURL() { - return this.avatarURL; - } - - /** - * Gets the user's alternate notification email address to which email notifications are sent. - * - * @return the user's notification email address. - */ - public BoxNotificationEmail getNotificationEmail() { - return this.notificationEmail; - } - - /** - * Sets the user's notification email address. - * - * @param notificationEmail the user's new notification email address. - */ - public void setNotificationEmail(BoxNotificationEmail notificationEmail) { - this.notificationEmail = notificationEmail; - } - - /** - * Gets the enterprise that the user belongs to. - * - * @return the enterprise that the user belongs to. - */ - public BoxEnterprise getEnterprise() { - return this.enterprise; - } - - /** - * Removes the user from their enterprise and converts them to a standalone free user. - */ - public void removeEnterprise() { - this.removeChildObject("enterprise"); - this.enterprise = null; - this.addChildObject("enterprise", null); - } - - /** - * Gets whether or not the user can use Box Sync. - * - * @return true if the user can use Box Sync; otherwise false. - */ - public boolean getIsSyncEnabled() { - return this.isSyncEnabled; - } - - /** - * Sets whether or not the user can use Box Sync. - * - * @param enabled whether or not the user can use Box Sync. - */ - public void setIsSyncEnabled(boolean enabled) { - this.isSyncEnabled = enabled; - this.addPendingChange("is_sync_enabled", enabled); - } - - /** - * Gets whether this user is allowed or not to collaborate with users outside their enterprise. - * - * @return true if this user is not allowed to collaborate with users outside their enterprise; otherwise false. - */ - public boolean getIsExternalCollabRestricted() { - return this.isExternalCollabRestricted; - } - - /** - * Sets whether this user is allowed or not to collaborate with users outside their enterprise. - * - * @param isExternalCollabRestricted whether the user is allowed to collaborate outside their enterprise. - */ - public void setIsExternalCollabRestricted(boolean isExternalCollabRestricted) { - this.isExternalCollabRestricted = isExternalCollabRestricted; - this.addPendingChange("is_external_collab_restricted", isExternalCollabRestricted); - } - - /** - * Gets whether or not the user can see other enterprise users in their contact list. - * - * @return true if the user can see other enterprise users in their contact list; otherwise false. - */ - public boolean getCanSeeManagedUsers() { - return this.canSeeManagedUsers; - } - - /** - * Sets whether or not the user can see other enterprise users in their contact list. - * - * @param canSeeManagedUsers whether or not the user can see other enterprise users in their contact list. - */ - public void setCanSeeManagedUsers(boolean canSeeManagedUsers) { - this.canSeeManagedUsers = canSeeManagedUsers; - this.addPendingChange("can_see_managed_users", canSeeManagedUsers); - } - - /** - * Gets whether or not the user is exempt from enterprise device limits. - * - * @return true if the user is exempt from enterprise device limits; otherwise false. - */ - public boolean getIsExemptFromDeviceLimits() { - return this.isExemptFromDeviceLimits; - } - - /** - * Sets whether or not the user is exempt from enterprise device limits. - * - * @param isExemptFromDeviceLimits whether or not the user is exempt from enterprise device limits. - */ - public void setIsExemptFromDeviceLimits(boolean isExemptFromDeviceLimits) { - this.isExemptFromDeviceLimits = isExemptFromDeviceLimits; - this.addPendingChange("is_exempt_from_device_limits", isExemptFromDeviceLimits); - } - - /** - * Gets whether or not the user must use two-factor authentication. - * - * @return true if the user must use two-factor authentication; otherwise false. - */ - public boolean getIsExemptFromLoginVerification() { - return this.isExemptFromLoginVerification; - } - - /** - * Sets whether or not the user must use two-factor authentication. - * - * @param isExemptFromLoginVerification whether or not the user must use two-factor authentication. - */ - public void setIsExemptFromLoginVerification(boolean isExemptFromLoginVerification) { - this.isExemptFromLoginVerification = isExemptFromLoginVerification; - this.addPendingChange("is_exempt_from_login_verification", isExemptFromLoginVerification); - } - - /** - * Gets whether or not the user is required to reset password. - * - * @return true if the user is required to reset password; otherwise false. - */ - public boolean getIsPasswordResetRequired() { - return this.isPasswordResetRequired; - } - - /** - * Sets whether or not the user is required to reset password. - * - * @param isPasswordResetRequired whether or not the user is required to reset password. - */ - public void setIsPasswordResetRequired(boolean isPasswordResetRequired) { - this.isPasswordResetRequired = isPasswordResetRequired; - this.addPendingChange("is_password_reset_required", isPasswordResetRequired); - } - - /** - * Gets whether or not the user we are creating is an app user with Box Developer Edition. - * - * @return true if the new user is an app user for Box Developer Addition; otherwise false. - */ - public boolean getIsPlatformAccessOnly() { - return this.isPlatformAccessOnly; - } - - /** - * Gets the external app user id that has been set for the app user. - * - * @return the external app user id. - */ - public String getExternalAppUserId() { - return this.externalAppUserId; - } - - /** - * Sets the external app user id. - * - * @param externalAppUserId external app user id. - */ - public void setExternalAppUserId(String externalAppUserId) { - this.externalAppUserId = externalAppUserId; - this.addPendingChange("external_app_user_id", externalAppUserId); - } - - /** - * Gets the tags for all files and folders owned by this user. - * - * @return the tags for all files and folders owned by this user. - */ - public List getMyTags() { - return this.myTags; - } - - /** - * Gets the root (protocol, subdomain, domain) of any links that need to be generated for this user. - * - * @return the root (protocol, subdomain, domain) of any links that need to be generated for this user. - */ - public String getHostname() { - return this.hostname; - } - - /** - * Gets the tracking defined for each entity. - * - * @return a Map with tracking codes. - */ - public Map getTrackingCodes() { - return this.trackingCodes; - } - - /** - * Allows admin to set attributes specific for a group of users. - * - * @param trackingCodes a Map representing the user's new tracking codes - */ - public void setTrackingCodes(Map trackingCodes) { - this.trackingCodes = trackingCodes; - this.addPendingChange("tracking_codes", toTrackingCodesJson(this.trackingCodes)); - } - - /** - * Allows the admin to append new tracking codes to the previous existing list. - * - * @param name the name or `key` of the attribute to set. - * @param value the value of the attribute to set. - */ - public void appendTrackingCodes(String name, String value) { - this.getTrackingCodes().put(name, value); - this.addPendingChange("tracking_codes", toTrackingCodesJson(this.trackingCodes)); - } + public void appendTrackingCodes(String name, String value) { + this.getTrackingCodes().put(name, value); + this.addPendingChange("tracking_codes", toTrackingCodesJson(this.trackingCodes)); + } - @SuppressWarnings("checkstyle:MissingSwitchDefault") - @Override - protected void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - - JsonValue value = member.getValue(); - String memberName = member.getName(); - try { - switch (memberName) { - case "login": - this.login = value.asString(); - break; - case "role": - this.role = Role.fromJSONValue(value.asString()); - break; - case "language": - this.language = value.asString(); - break; - case "timezone": - this.timezone = value.asString(); - break; - case "space_amount": - this.spaceAmount = Double.valueOf(value.toString()).longValue(); - break; - case "space_used": - this.spaceUsed = Double.valueOf(value.toString()).longValue(); - break; - case "max_upload_size": - this.maxUploadSize = Double.valueOf(value.toString()).longValue(); - break; - case "status": - this.status = Status.fromJSONValue(value.asString()); - break; - case "job_title": - this.jobTitle = value.asString(); - break; - case "phone": - this.phone = value.asString(); - break; - case "address": - this.address = value.asString(); - break; - case "avatar_url": - this.avatarURL = value.asString(); - break; - case "notification_email": - if (value.isObject()) { - this.notificationEmail = new BoxNotificationEmail(value.asObject()); - } else { - this.notificationEmail = null; - } - break; - case "can_see_managed_users": - this.canSeeManagedUsers = value.asBoolean(); - break; - case "is_sync_enabled": - this.isSyncEnabled = value.asBoolean(); - break; - case "is_external_collab_restricted": - this.isExternalCollabRestricted = value.asBoolean(); - break; - case "is_exempt_from_device_limits": - this.isExemptFromDeviceLimits = value.asBoolean(); - break; - case "is_exempt_from_login_verification": - this.isExemptFromLoginVerification = value.asBoolean(); - break; - case "is_password_reset_required": - this.isPasswordResetRequired = value.asBoolean(); - break; - case "is_platform_access_only": - this.isPlatformAccessOnly = value.asBoolean(); - break; - case "external_app_user_id": - this.externalAppUserId = value.asString(); - break; - case "enterprise": - JsonObject jsonObject = value.asObject(); - if (this.enterprise == null) { - this.enterprise = new BoxEnterprise(jsonObject); - } else { - this.enterprise.update(jsonObject); - } - break; - case "my_tags": - this.myTags = this.parseMyTags(value.asArray()); - break; - case "hostname": - this.hostname = value.asString(); - break; - case "tracking_codes": - this.trackingCodes = this.parseTrackingCodes(value.asArray()); - break; - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); + @SuppressWarnings("checkstyle:MissingSwitchDefault") + @Override + protected void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + + JsonValue value = member.getValue(); + String memberName = member.getName(); + try { + switch (memberName) { + case "login": + this.login = value.asString(); + break; + case "role": + this.role = Role.fromJSONValue(value.asString()); + break; + case "language": + this.language = value.asString(); + break; + case "timezone": + this.timezone = value.asString(); + break; + case "space_amount": + this.spaceAmount = Double.valueOf(value.toString()).longValue(); + break; + case "space_used": + this.spaceUsed = Double.valueOf(value.toString()).longValue(); + break; + case "max_upload_size": + this.maxUploadSize = Double.valueOf(value.toString()).longValue(); + break; + case "status": + this.status = Status.fromJSONValue(value.asString()); + break; + case "job_title": + this.jobTitle = value.asString(); + break; + case "phone": + this.phone = value.asString(); + break; + case "address": + this.address = value.asString(); + break; + case "avatar_url": + this.avatarURL = value.asString(); + break; + case "notification_email": + if (value.isObject()) { + this.notificationEmail = new BoxNotificationEmail(value.asObject()); + } else { + this.notificationEmail = null; } - - } - - private List parseMyTags(JsonArray jsonArray) { - List myTags = new ArrayList<>(jsonArray.size()); - for (JsonValue value : jsonArray) { - myTags.add(value.asString()); + break; + case "can_see_managed_users": + this.canSeeManagedUsers = value.asBoolean(); + break; + case "is_sync_enabled": + this.isSyncEnabled = value.asBoolean(); + break; + case "is_external_collab_restricted": + this.isExternalCollabRestricted = value.asBoolean(); + break; + case "is_exempt_from_device_limits": + this.isExemptFromDeviceLimits = value.asBoolean(); + break; + case "is_exempt_from_login_verification": + this.isExemptFromLoginVerification = value.asBoolean(); + break; + case "is_password_reset_required": + this.isPasswordResetRequired = value.asBoolean(); + break; + case "is_platform_access_only": + this.isPlatformAccessOnly = value.asBoolean(); + break; + case "external_app_user_id": + this.externalAppUserId = value.asString(); + break; + case "enterprise": + JsonObject jsonObject = value.asObject(); + if (this.enterprise == null) { + this.enterprise = new BoxEnterprise(jsonObject); + } else { + this.enterprise.update(jsonObject); } + break; + case "my_tags": + this.myTags = this.parseMyTags(value.asArray()); + break; + case "hostname": + this.hostname = value.asString(); + break; + case "tracking_codes": + this.trackingCodes = this.parseTrackingCodes(value.asArray()); + break; + } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); + } + } - return myTags; - } + private List parseMyTags(JsonArray jsonArray) { + List myTags = new ArrayList<>(jsonArray.size()); + for (JsonValue value : jsonArray) { + myTags.add(value.asString()); + } - private Map parseTrackingCodes(JsonArray jsonArray) { - Map result = new HashMap<>(); - if (jsonArray == null) { - return null; - } - List valuesList = jsonArray.values(); - for (JsonValue jsonValue : valuesList) { - JsonObject object = jsonValue.asObject(); - result.put(object.get("name").asString(), object.get("value").asString()); - } - return result; - } + return myTags; + } + + private Map parseTrackingCodes(JsonArray jsonArray) { + Map result = new HashMap<>(); + if (jsonArray == null) { + return null; + } + List valuesList = jsonArray.values(); + for (JsonValue jsonValue : valuesList) { + JsonObject object = jsonValue.asObject(); + result.put(object.get("name").asString(), object.get("value").asString()); + } + return result; } + } } diff --git a/src/main/java/com/box/sdk/BoxUserIterator.java b/src/main/java/com/box/sdk/BoxUserIterator.java index 03ec69b03..29a9bce63 100644 --- a/src/main/java/com/box/sdk/BoxUserIterator.java +++ b/src/main/java/com/box/sdk/BoxUserIterator.java @@ -7,29 +7,29 @@ import java.util.Iterator; class BoxUserIterator implements Iterator { - private static final long LIMIT = 1000; + private static final long LIMIT = 1000; - private final BoxAPIConnection api; - private final JsonIterator jsonIterator; + private final BoxAPIConnection api; + private final JsonIterator jsonIterator; - BoxUserIterator(BoxAPIConnection api, URL url) { - this.api = api; - this.jsonIterator = new JsonIterator(api, url, offset(0, LIMIT)); - } + BoxUserIterator(BoxAPIConnection api, URL url) { + this.api = api; + this.jsonIterator = new JsonIterator(api, url, offset(0, LIMIT)); + } - public boolean hasNext() { - return this.jsonIterator.hasNext(); - } + public boolean hasNext() { + return this.jsonIterator.hasNext(); + } - public BoxUser.Info next() { - JsonObject nextJSONObject = this.jsonIterator.next(); - String id = nextJSONObject.get("id").asString(); + public BoxUser.Info next() { + JsonObject nextJSONObject = this.jsonIterator.next(); + String id = nextJSONObject.get("id").asString(); - BoxUser user = new BoxUser(this.api, id); - return user.new Info(nextJSONObject); - } + BoxUser user = new BoxUser(this.api, id); + return user.new Info(nextJSONObject); + } - public void remove() { - throw new UnsupportedOperationException(); - } + public void remove() { + throw new UnsupportedOperationException(); + } } diff --git a/src/main/java/com/box/sdk/BoxWatermark.java b/src/main/java/com/box/sdk/BoxWatermark.java index bb8792211..a72f460d8 100644 --- a/src/main/java/com/box/sdk/BoxWatermark.java +++ b/src/main/java/com/box/sdk/BoxWatermark.java @@ -5,116 +5,97 @@ import java.util.Date; /** - * Represents a watermark. - * Watermarks are used to protect sensitive information in the Box account. + * Represents a watermark. Watermarks are used to protect sensitive information in the Box account. * * @see Watermarking */ public class BoxWatermark extends BoxJSONObject { - /** - * Default imprint for watermarks. - */ - public static final String WATERMARK_DEFAULT_IMPRINT = "default"; - - /** - * Json key for watermark. - * - * @see BoxWatermark#parseJSONMember(JsonObject.Member) - */ - public static final String WATERMARK_JSON_KEY = "watermark"; - - /** - * Json key for created_at param. - * - * @see BoxWatermark#parseJSONMember(JsonObject.Member) - */ - public static final String CREATED_AT_JSON_KEY = "created_at"; - - /** - * Json key for modified_at param. - * - * @see BoxWatermark#parseJSONMember(JsonObject.Member) - */ - public static final String MODIFIED_AT_JSON_KEY = "modified_at"; - - /** - * Json key for watermark param. - */ - public static final String WATERMARK_IMPRINT_JSON_KEY = "imprint"; - - /** - * @see #getCreatedAt() - */ - private Date createdAt; - - /** - * @see #getModifiedAt() - */ - private Date modifiedAt; - - /** - * Constructs an empty watermark object. - */ - public BoxWatermark() { - super(); + /** Default imprint for watermarks. */ + public static final String WATERMARK_DEFAULT_IMPRINT = "default"; + + /** + * Json key for watermark. + * + * @see BoxWatermark#parseJSONMember(JsonObject.Member) + */ + public static final String WATERMARK_JSON_KEY = "watermark"; + + /** + * Json key for created_at param. + * + * @see BoxWatermark#parseJSONMember(JsonObject.Member) + */ + public static final String CREATED_AT_JSON_KEY = "created_at"; + + /** + * Json key for modified_at param. + * + * @see BoxWatermark#parseJSONMember(JsonObject.Member) + */ + public static final String MODIFIED_AT_JSON_KEY = "modified_at"; + + /** Json key for watermark param. */ + public static final String WATERMARK_IMPRINT_JSON_KEY = "imprint"; + + /** @see #getCreatedAt() */ + private Date createdAt; + + /** @see #getModifiedAt() */ + private Date modifiedAt; + + /** Constructs an empty watermark object. */ + public BoxWatermark() { + super(); + } + + /** + * Constructs a watermark object by parsing information from a JSON string. + * + * @param json the JSON string to parse. + */ + public BoxWatermark(String json) { + super(json); + } + + /** + * Constructs a watermark object using an already parsed JSON object. + * + * @param jsonObject the parsed JSON object. + */ + BoxWatermark(JsonObject jsonObject) { + super(jsonObject); + } + + /** @return the time that the watermark was created. */ + public Date getCreatedAt() { + return this.createdAt; + } + + /** @return the time that the watermark was last modified. */ + public Date getModifiedAt() { + return this.modifiedAt; + } + + /** {@inheritDoc} */ + public BoxWatermark getResource() { + return BoxWatermark.this; + } + + /** {@inheritDoc} */ + @Override + void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + String memberName = member.getName(); + JsonValue value = member.getValue(); + if (memberName.equals(WATERMARK_JSON_KEY)) { + try { + this.createdAt = BoxDateFormat.parse(value.asObject().get(CREATED_AT_JSON_KEY).asString()); + this.modifiedAt = + BoxDateFormat.parse(value.asObject().get(MODIFIED_AT_JSON_KEY).asString()); + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); + } } - - /** - * Constructs a watermark object by parsing information from a JSON string. - * - * @param json the JSON string to parse. - */ - public BoxWatermark(String json) { - super(json); - } - - /** - * Constructs a watermark object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - BoxWatermark(JsonObject jsonObject) { - super(jsonObject); - } - - /** - * @return the time that the watermark was created. - */ - public Date getCreatedAt() { - return this.createdAt; - } - - /** - * @return the time that the watermark was last modified. - */ - public Date getModifiedAt() { - return this.modifiedAt; - } - - /** - * {@inheritDoc} - */ - public BoxWatermark getResource() { - return BoxWatermark.this; - } - - /** - * {@inheritDoc} - */ - @Override - void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - String memberName = member.getName(); - JsonValue value = member.getValue(); - if (memberName.equals(WATERMARK_JSON_KEY)) { - try { - this.createdAt = BoxDateFormat.parse(value.asObject().get(CREATED_AT_JSON_KEY).asString()); - this.modifiedAt = BoxDateFormat.parse(value.asObject().get(MODIFIED_AT_JSON_KEY).asString()); - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); - } - } - } - + } } diff --git a/src/main/java/com/box/sdk/BoxWebHook.java b/src/main/java/com/box/sdk/BoxWebHook.java index 1025675b7..89d4692ab 100644 --- a/src/main/java/com/box/sdk/BoxWebHook.java +++ b/src/main/java/com/box/sdk/BoxWebHook.java @@ -24,820 +24,723 @@ @BoxResourceType("webhook") public class BoxWebHook extends BoxResource { - /** - * {@link URLTemplate} for {@link BoxWebHook}s resource. - */ - public static final URLTemplate WEBHOOKS_URL_TEMPLATE = new URLTemplate("webhooks"); - /** - * {@link URLTemplate} for single {@link BoxWebHook} resource. - */ - public static final URLTemplate WEBHOOK_URL_TEMPLATE = new URLTemplate("webhooks/%s"); + /** {@link URLTemplate} for {@link BoxWebHook}s resource. */ + public static final URLTemplate WEBHOOKS_URL_TEMPLATE = new URLTemplate("webhooks"); + /** {@link URLTemplate} for single {@link BoxWebHook} resource. */ + public static final URLTemplate WEBHOOK_URL_TEMPLATE = new URLTemplate("webhooks/%s"); + + /** JSON Key for {@link BoxWebHook} {@link #getID()}. */ + private static final String JSON_KEY_ID = "id"; + + /** JSON Key for {@link BoxWebHook.Info#getTarget()}. */ + private static final String JSON_KEY_TARGET = "target"; + + /** JSON Key for {@link BoxWebHook.Target#getType()}. */ + private static final String JSON_KEY_TARGET_TYPE = "type"; + + /** JSON Key for {@link BoxWebHook.Target#getId()}. */ + private static final String JSON_KEY_TARGET_ID = "id"; + + /** JSON Key for {@link BoxWebHook.Info#getAddress()}. */ + private static final String JSON_KEY_ADDRESS = "address"; + + /** JSON Key for {@link BoxWebHook.Info#getTriggers()}. */ + private static final String JSON_KEY_TRIGGERS = "triggers"; + + /** JSON Key for {@link BoxWebHook.Info#getCreatedBy()}. */ + private static final String JSON_KEY_CREATED_BY = "created_by"; + + /** JSON Key for {@link BoxWebHook.Info#getCreatedAt()}. */ + private static final String JSON_KEY_CREATED_AT = "created_at"; + + /** Maps a {@link Trigger} to its {@link Trigger#getValue()}. */ + private static final Mapper TRIGGER_TO_VALUE = Trigger::getValue; + + private static final Mapper JSON_VALUE_TO_TRIGGER = + value -> Trigger.fromValue(value.asString()); + + /** + * Constructor. + * + * @param api {@link #getAPI()} + * @param id {@link #getID()} + */ + public BoxWebHook(BoxAPIConnection api, String id) { + super(api, id); + } + + /** + * Adds a {@link BoxWebHook} to a provided {@link BoxResource}. + * + * @param target {@link BoxResource} web resource + * @param address {@link URL} where the notification should send to + * @param triggers events this {@link BoxWebHook} is interested in + * @return created {@link BoxWebHook} + * @see #create(BoxResource, URL, Set) + */ + public static BoxWebHook.Info create( + BoxResource target, URL address, BoxWebHook.Trigger... triggers) { + return create(target, address, new HashSet<>(Arrays.asList(triggers))); + } + + /** + * Adds a {@link BoxWebHook} to a provided {@link BoxResource}. + * + * @param target {@link BoxResource} web resource + * @param address {@link URL} where the notification should send to + * @param triggers events this {@link BoxWebHook} is interested in + * @return created {@link BoxWebHook} + * @see #create(BoxResource, URL, Trigger...) + */ + public static BoxWebHook.Info create( + BoxResource target, URL address, Set triggers) { + BoxAPIConnection api = target.getAPI(); + + String type = BoxResource.getResourceType(target.getClass()); + validateTriggers(type, triggers); + + JsonObject targetJSON = + new JsonObject().add(JSON_KEY_TARGET_TYPE, type).add(JSON_KEY_TARGET_ID, target.getID()); + + JsonObject requestJSON = + new JsonObject() + .add(JSON_KEY_TARGET, targetJSON) + .add(JSON_KEY_ADDRESS, address.toExternalForm()) + .add(JSON_KEY_TRIGGERS, toJsonArray(CollectionUtils.map(triggers, TRIGGER_TO_VALUE))); - /** - * JSON Key for {@link BoxWebHook} {@link #getID()}. - */ - private static final String JSON_KEY_ID = "id"; + URL url = WEBHOOKS_URL_TEMPLATE.build(api.getBaseURL()); + BoxJSONRequest request = new BoxJSONRequest(api, url, "POST"); + request.setBody(requestJSON.toString()); - /** - * JSON Key for {@link BoxWebHook.Info#getTarget()}. - */ - private static final String JSON_KEY_TARGET = "target"; + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - /** - * JSON Key for {@link BoxWebHook.Target#getType()}. - */ - private static final String JSON_KEY_TARGET_TYPE = "type"; + BoxWebHook webHook = new BoxWebHook(api, responseJSON.get(JSON_KEY_ID).asString()); + return webHook.new Info(responseJSON); + } + } + + /** + * Helper function to create JsonArray from collection. + * + * @param values collection of values to convert to JsonArray + * @return JsonArray with collection values + */ + private static JsonArray toJsonArray(Collection values) { + JsonArray array = new JsonArray(); + for (String value : values) { + array.add(value); + } + return array; + } + + /** + * Returns iterator over all {@link BoxWebHook}-s. + * + * @param api the API connection to be used by the resource + * @return existing {@link BoxWebHook.Info}-s + */ + public static Iterable all(final BoxAPIConnection api) { + return new BoxResourceIterable( + api, WEBHOOKS_URL_TEMPLATE.build(api.getBaseURL()), 64) { + + @Override + protected BoxWebHook.Info factory(JsonObject jsonObject) { + BoxWebHook webHook = new BoxWebHook(api, jsonObject.get("id").asString()); + return webHook.new Info(jsonObject); + } + }; + } + + /** + * Returns iterator over all {@link BoxWebHook}-s. + * + * @param api the API connection to be used by the resource + * @param fields the fields to retrieve. + * @return existing {@link BoxWebHook.Info}-s + */ + public static Iterable all(final BoxAPIConnection api, String... fields) { + QueryStringBuilder builder = new QueryStringBuilder(); + if (fields.length > 0) { + builder.appendParam("fields", fields); + } + return new BoxResourceIterable( + api, WEBHOOKS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString()), 64) { + + @Override + protected BoxWebHook.Info factory(JsonObject jsonObject) { + BoxWebHook webHook = new BoxWebHook(api, jsonObject.get("id").asString()); + return webHook.new Info(jsonObject); + } + }; + } + + /** + * Validates that provided {@link BoxWebHook.Trigger}-s can be applied on the provided {@link + * BoxResourceType}. + * + * @param targetType on which target the triggers should be applied to + * @param triggers for check + * @see #validateTrigger(String, Trigger) + */ + public static void validateTriggers(String targetType, Collection triggers) { + for (BoxWebHook.Trigger trigger : triggers) { + validateTrigger(targetType, trigger); + } + } + + /** + * Validates that provided {@link BoxWebHook.Trigger} can be applied on the provided {@link + * BoxResourceType}. + * + * @param targetType on which targets the trigger should be applied to + * @param trigger for check + * @see #validateTriggers(String, Collection) + */ + private static void validateTrigger(String targetType, BoxWebHook.Trigger trigger) { + for (String type : trigger.getTypes()) { + if (targetType.equals(type)) { + return; + } + } + throw new IllegalArgumentException( + String.format( + "Provided trigger '%s' is not supported on provided target '%s'.", + trigger.name(), targetType)); + } + + /** + * @param fields the fields to retrieve. + * @return Gets information about this {@link BoxWebHook}. + */ + public BoxWebHook.Info getInfo(String... fields) { + URL url = WEBHOOK_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + if (fields.length > 0) { + QueryStringBuilder builder = new QueryStringBuilder().appendParam("fields", fields); + url = + WEBHOOK_URL_TEMPLATE.buildWithQuery( + this.getAPI().getBaseURL(), builder.toString(), this.getID()); + } + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); + try (BoxJSONResponse response = request.send()) { + return new Info(Json.parse(response.getJSON()).asObject()); + } + } + + /** + * Updates {@link BoxWebHook} information. + * + * @param info new state + */ + public void updateInfo(BoxWebHook.Info info) { + URL url = WEBHOOK_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(getAPI(), url, "PUT"); + request.setBody(info.getPendingChanges()); + + try (BoxJSONResponse response = request.send()) { + JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); + info.update(jsonObject); + } + } + + /** Deletes this webhook. */ + public void delete() { + URL url = WEBHOOK_URL_TEMPLATE.build(getAPI().getBaseURL(), this.getID()); + BoxAPIRequest request = new BoxAPIRequest(getAPI(), url, "DELETE"); + request.send().close(); + } + + /** A Box related triggers. */ + public enum Trigger { + + // BoxFolder related triggers. + + /** Triggered when a {@link BoxFolder} gets created. */ + FOLDER_CREATED("FOLDER.CREATED", BoxResource.getResourceType(BoxFolder.class)), + + /** Triggered when a {@link BoxFolder} gets copied. */ + FOLDER_COPIED("FOLDER.COPIED", BoxResource.getResourceType(BoxFolder.class)), + + /** Triggered when a {@link BoxFolder} gets moved. */ + FOLDER_MOVED("FOLDER.MOVED", BoxResource.getResourceType(BoxFolder.class)), + + /** Triggered when a {@link BoxFolder} is downloaded. */ + FOLDER_DOWNLOADED("FOLDER.DOWNLOADED", BoxResource.getResourceType(BoxFolder.class)), + + /** Triggered when a {@link BoxFolder} is trashed. */ + FOLDER_TRASHED("FOLDER.TRASHED", BoxResource.getResourceType(BoxFolder.class)), + + /** Triggered when a {@link BoxFolder} gets restored. */ + FOLDER_RESTORED("FOLDER.RESTORED", BoxResource.getResourceType(BoxFolder.class)), + + /** Triggered when a {@link BoxFolder} gets deleted. */ + FOLDER_DELETED("FOLDER.DELETED", BoxResource.getResourceType(BoxFolder.class)), + + /** Triggered when a {@link BoxFolder} is renamed. */ + FOLDER_RENAMED("FOLDER.RENAMED", BoxResource.getResourceType(BoxFolder.class)), + + // BoxFile related triggers. + + /** Triggered when a {@link BoxFile} gets uploaded. */ + FILE_UPLOADED("FILE.UPLOADED", BoxResource.getResourceType(BoxFolder.class)), + + /** Triggered when a {@link BoxFile} gets copied. */ + FILE_COPIED( + "FILE.COPIED", + BoxResource.getResourceType(BoxFolder.class), + BoxResource.getResourceType(BoxFile.class)), + + /** Triggered when a {@link BoxFile} gets copied. */ + FILE_MOVED( + "FILE.MOVED", + BoxResource.getResourceType(BoxFolder.class), + BoxResource.getResourceType(BoxFile.class)), + + /** Triggered when a {@link BoxFile} is previewed. */ + FILE_PREVIEWED( + "FILE.PREVIEWED", + BoxResource.getResourceType(BoxFolder.class), + BoxResource.getResourceType(BoxFile.class)), + + /** Triggered when a {@link BoxFile} is downloaded. */ + FILE_DOWNLOADED( + "FILE.DOWNLOADED", + BoxResource.getResourceType(BoxFolder.class), + BoxResource.getResourceType(BoxFile.class)), + + /** Triggered when a {@link BoxFile} gets locked. */ + FILE_LOCKED( + "FILE.LOCKED", + BoxResource.getResourceType(BoxFolder.class), + BoxResource.getResourceType(BoxFile.class)), + + /** Triggered when a {@link BoxFile} gets unlocked. */ + FILE_UNLOCKED( + "FILE.UNLOCKED", + BoxResource.getResourceType(BoxFolder.class), + BoxResource.getResourceType(BoxFile.class)), + + /** Triggered when a {@link BoxFile} is trashed. Do not include file versions for now. */ + FILE_TRASHED( + "FILE.TRASHED", + BoxResource.getResourceType(BoxFolder.class), + BoxResource.getResourceType(BoxFile.class)), + + /** Triggered when a {@link BoxFile} gets restored. */ + FILE_RESTORED( + "FILE.RESTORED", + BoxResource.getResourceType(BoxFolder.class), + BoxResource.getResourceType(BoxFile.class)), + + /** Triggered when a {@link BoxFile} is permanently deleted. */ + FILE_DELETED( + "FILE.DELETED", + BoxResource.getResourceType(BoxFolder.class), + BoxResource.getResourceType(BoxFile.class)), + + /** Triggered when a {@link BoxFile} is renamed. */ + FILE_RENAMED( + "FILE.RENAMED", + BoxResource.getResourceType(BoxFolder.class), + BoxResource.getResourceType(BoxFile.class)), + + /** Triggered when a {@link BoxComment} was created. */ + COMMENT_CREATED( + "COMMENT.CREATED", + BoxResource.getResourceType(BoxFolder.class), + BoxResource.getResourceType(BoxFile.class)), + + /** Triggered when a {@link BoxComment} was updated. */ + COMMENT_UPDATED( + "COMMENT.UPDATED", + BoxResource.getResourceType(BoxFolder.class), + BoxResource.getResourceType(BoxFile.class)), + + /** Triggered when a {@link BoxComment} was deleted. */ + COMMENT_DELETED( + "COMMENT.DELETED", + BoxResource.getResourceType(BoxFolder.class), + BoxResource.getResourceType(BoxFile.class)), + + /** Triggered when a {@link BoxTaskAssignment} is created. */ + TASK_ASSIGNMENT_CREATED( + "TASK_ASSIGNMENT.CREATED", + BoxResource.getResourceType(BoxFolder.class), + BoxResource.getResourceType(BoxFile.class)), + + /** Triggered when a {@link BoxTaskAssignment} is updated. */ + TASK_ASSIGNMENT_UPDATED( + "TASK_ASSIGNMENT.UPDATED", + BoxResource.getResourceType(BoxFolder.class), + BoxResource.getResourceType(BoxFile.class)), /** - * JSON Key for {@link BoxWebHook.Target#getId()}. + * Triggered when a metadata template is associated to a {@link BoxFile} or {@link BoxFolder}. */ - private static final String JSON_KEY_TARGET_ID = "id"; + METADATA_INSTANCE_CREATED( + "METADATA_INSTANCE.CREATED", + BoxResource.getResourceType(BoxFolder.class), + BoxResource.getResourceType(BoxFile.class)), /** - * JSON Key for {@link BoxWebHook.Info#getAddress()}. + * Triggered when a field is updated in the metadata on a {@link BoxFile} or {@link BoxFolder}. */ - private static final String JSON_KEY_ADDRESS = "address"; + METADATA_INSTANCE_UPDATED( + "METADATA_INSTANCE.UPDATED", + BoxResource.getResourceType(BoxFolder.class), + BoxResource.getResourceType(BoxFile.class)), /** - * JSON Key for {@link BoxWebHook.Info#getTriggers()}. + * Triggered when a metadata template is removed from a {@link BoxFile} or {@link BoxFolder}. */ - private static final String JSON_KEY_TRIGGERS = "triggers"; + METADATA_INSTANCE_DELETED( + "METADATA_INSTANCE.DELETED", + BoxResource.getResourceType(BoxFolder.class), + BoxResource.getResourceType(BoxFile.class)), + + /** Triggered when a {@link BoxWebHook} is deleted. */ + WEBHOOK_DELETED("WEBHOOK.DELETED"), + + /** Triggered when a {@link BoxCollaboration} is created. */ + COLLABORATION_CREATED("COLLABORATION.CREATED", BoxResource.getResourceType(BoxFolder.class)), + + /** Triggered when a {@link BoxCollaboration} is accepted. */ + COLLABORATION_ACCEPTED("COLLABORATION.ACCEPTED", BoxResource.getResourceType(BoxFolder.class)), + + /** Triggered when a {@link BoxCollaboration} is rejected. */ + COLLABORATION_REJECTED("COLLABORATION.REJECTED", BoxResource.getResourceType(BoxFolder.class)), + + /** Triggered when a {@link BoxCollaboration} is removed. */ + COLLABORATION_REMOVED("COLLABORATION.REMOVED", BoxResource.getResourceType(BoxFolder.class)), + + /** Triggered when a {@link BoxCollaboration} is updated. */ + COLLABORATION_UPDATED("COLLABORATION.UPDATED", BoxResource.getResourceType(BoxFolder.class)), + + /** Triggered when a {@link BoxSharedLink} is created. */ + SHARED_LINK_CRATED( + "SHARED_LINK.CREATED", + BoxResource.getResourceType(BoxFolder.class), + BoxResource.getResourceType(BoxFile.class)), + + /** Triggered when a {@link BoxSharedLink} is updated. */ + SHARED_LINK_UPDATED( + "SHARED_LINK.UPDATED", + BoxResource.getResourceType(BoxFolder.class), + BoxResource.getResourceType(BoxFile.class)), + + /** Triggered when a {@link BoxSharedLink} is deleted. */ + SHARED_LINK_DELETED( + "SHARED_LINK.DELETED", + BoxResource.getResourceType(BoxFolder.class), + BoxResource.getResourceType(BoxFile.class)), + + /** Triggered when {@link BoxSignRequest} is completed. */ + SIGN_REQUEST_COMPLETED( + "SIGN_REQUEST.COMPLETED", + BoxResource.getResourceType(BoxFolder.class), + BoxResource.getResourceType(BoxFile.class)), + /** Triggered when {@link BoxFile} is declined. */ + SIGN_REQUEST_DECLINED( + "SIGN_REQUEST.DECLINED", + BoxResource.getResourceType(BoxFolder.class), + BoxResource.getResourceType(BoxFile.class)), + /** Triggered when {@link BoxFile} is expired. */ + SIGN_REQUEST_EXPIRED( + "SIGN_REQUEST.EXPIRED", + BoxResource.getResourceType(BoxFolder.class), + BoxResource.getResourceType(BoxFile.class)), + /** Triggered when a signer's email is bounced. */ + SIGN_REQUEST_SIGNER_EMAIL_BOUNCED( + "SIGN_REQUEST.SIGNER_EMAIL_BOUNCED", + BoxResource.getResourceType(BoxFolder.class), + BoxResource.getResourceType(BoxFile.class)), + /** Triggered when the signature request is signed. */ + SIGN_REQUEST_SIGNER_SIGNED( + "SIGN_REQUEST.SIGNER_SIGNED", + BoxResource.getResourceType(BoxFolder.class), + BoxResource.getResourceType(BoxFile.class)), + /** Triggered when the signature is requested from the signer. */ + SIGN_REQUEST_SIGNATURE_REQUESTED( + "SIGN_REQUEST.SIGNATURE_REQUESTED", + BoxResource.getResourceType(BoxFolder.class), + BoxResource.getResourceType(BoxFile.class)), + /** Triggered when the signature request could not be processed. */ + SIGN_REQUEST_ERROR_FINALIZING( + "SIGN_REQUEST.ERROR_FINALIZING", + BoxResource.getResourceType(BoxFolder.class), + BoxResource.getResourceType(BoxFile.class)); + + /** @see #getValue() */ + private final String value; + + /** @see #getTypes() */ + private final String[] types; /** - * JSON Key for {@link BoxWebHook.Info#getCreatedBy()}. + * Constructor. + * + * @param value {@link #getValue()} + * @param types {@link #getTypes()} */ - private static final String JSON_KEY_CREATED_BY = "created_by"; + Trigger(String value, String... types) { + this.value = value; + this.types = types; + } /** - * JSON Key for {@link BoxWebHook.Info#getCreatedAt()}. + * @param value value to get the Trigger enum value for + * @return Trigger for given value */ - private static final String JSON_KEY_CREATED_AT = "created_at"; + public static Trigger fromValue(String value) { + for (Trigger trigger : Trigger.values()) { + if (trigger.getValue().equals(value)) { + return trigger; + } + } + throw new IllegalArgumentException("No Trigger for value: " + value); + } - /** - * Maps a {@link Trigger} to its {@link Trigger#getValue()}. - */ - private static final Mapper TRIGGER_TO_VALUE = Trigger::getValue; + /** @return {@link String} representation for {@link Trigger}. */ + public String getValue() { + return this.value; + } - private static final Mapper JSON_VALUE_TO_TRIGGER = - value -> Trigger.fromValue(value.asString()); + /** @return Supported types for a web-hook. */ + public String[] getTypes() { + return this.types; + } + } + + /** WebHook target - file or folder. */ + public static class Target { + + /** @see #getType() */ + private final String type; + + /** @see #getId() */ + private final String id; /** * Constructor. * - * @param api {@link #getAPI()} - * @param id {@link #getID()} + * @param type {@link #getType()} + * @param id {@link #getId()} */ - public BoxWebHook(BoxAPIConnection api, String id) { - super(api, id); + public Target(String type, String id) { + this.type = type; + this.id = id; } /** - * Adds a {@link BoxWebHook} to a provided {@link BoxResource}. - * - * @param target {@link BoxResource} web resource - * @param address {@link URL} where the notification should send to - * @param triggers events this {@link BoxWebHook} is interested in - * @return created {@link BoxWebHook} - * @see #create(BoxResource, URL, Set) + * @return Type of target. + * @see BoxResourceType */ - public static BoxWebHook.Info create(BoxResource target, URL address, BoxWebHook.Trigger... triggers) { - return create(target, address, new HashSet<>(Arrays.asList(triggers))); + public String getType() { + return this.type; } - /** - * Adds a {@link BoxWebHook} to a provided {@link BoxResource}. - * - * @param target {@link BoxResource} web resource - * @param address {@link URL} where the notification should send to - * @param triggers events this {@link BoxWebHook} is interested in - * @return created {@link BoxWebHook} - * @see #create(BoxResource, URL, Trigger...) - */ - public static BoxWebHook.Info create(BoxResource target, URL address, Set triggers) { - BoxAPIConnection api = target.getAPI(); - - String type = BoxResource.getResourceType(target.getClass()); - validateTriggers(type, triggers); + /** @return {@link BoxResource#getID()} */ + public String getId() { + return this.id; + } + } - JsonObject targetJSON = new JsonObject() - .add(JSON_KEY_TARGET_TYPE, type) - .add(JSON_KEY_TARGET_ID, target.getID()); + /** Contains information for a {@link BoxWebHook} instance. */ + public class Info extends BoxResource.Info { - JsonObject requestJSON = new JsonObject() - .add(JSON_KEY_TARGET, targetJSON) - .add(JSON_KEY_ADDRESS, address.toExternalForm()) - .add(JSON_KEY_TRIGGERS, toJsonArray(CollectionUtils.map(triggers, TRIGGER_TO_VALUE))); + /** @see #getTarget() */ + private Target target; - URL url = WEBHOOKS_URL_TEMPLATE.build(api.getBaseURL()); - BoxJSONRequest request = new BoxJSONRequest(api, url, "POST"); - request.setBody(requestJSON.toString()); + /** @see #getAddress() */ + private URL address; - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + /** @see #getTriggers() */ + private Set triggers; - BoxWebHook webHook = new BoxWebHook(api, responseJSON.get(JSON_KEY_ID).asString()); - return webHook.new Info(responseJSON); - } - } + /** @see #getCreatedBy() */ + private BoxUser.Info createdBy; - /** - * Helper function to create JsonArray from collection. - * - * @param values collection of values to convert to JsonArray - * @return JsonArray with collection values - */ - private static JsonArray toJsonArray(Collection values) { - JsonArray array = new JsonArray(); - for (String value : values) { - array.add(value); - } - return array; + /** @see #getCreatedAt() */ + private Date createdAt; + /** Constructs an Info object with current target. */ + public Info() { + super(); + this.target = BoxWebHook.this.getInfo().getTarget(); } /** - * Returns iterator over all {@link BoxWebHook}-s. + * Constructs an Info object by parsing information from a JSON string. * - * @param api the API connection to be used by the resource - * @return existing {@link BoxWebHook.Info}-s + * @param json the JSON string to parse. */ - public static Iterable all(final BoxAPIConnection api) { - return new BoxResourceIterable(api, WEBHOOKS_URL_TEMPLATE.build(api.getBaseURL()), 64) { - - @Override - protected BoxWebHook.Info factory(JsonObject jsonObject) { - BoxWebHook webHook = new BoxWebHook(api, jsonObject.get("id").asString()); - return webHook.new Info(jsonObject); - } - - }; + public Info(String json) { + this(Json.parse(json).asObject()); } /** - * Returns iterator over all {@link BoxWebHook}-s. + * Constructor. * - * @param api the API connection to be used by the resource - * @param fields the fields to retrieve. - * @return existing {@link BoxWebHook.Info}-s + * @param jsonObject a parsed JSON object */ - public static Iterable all(final BoxAPIConnection api, String... fields) { - QueryStringBuilder builder = new QueryStringBuilder(); - if (fields.length > 0) { - builder.appendParam("fields", fields); + public Info(JsonObject jsonObject) { + super(jsonObject); + + if (jsonObject.get(JSON_KEY_TARGET) != null) { + JsonObject targetObject = jsonObject.get(JSON_KEY_TARGET).asObject(); + String targetType = targetObject.get(JSON_KEY_TARGET_TYPE).asString(); + String targetId = targetObject.get(JSON_KEY_TARGET_ID).asString(); + this.target = new Target(targetType, targetId); + } + + if (jsonObject.get(JSON_KEY_TRIGGERS) != null) { + this.triggers = + new HashSet<>( + CollectionUtils.map( + jsonObject.get(JSON_KEY_TRIGGERS).asArray().values(), JSON_VALUE_TO_TRIGGER)); + } + if (jsonObject.get(JSON_KEY_ADDRESS) != null) { + try { + this.address = new URL(jsonObject.get(JSON_KEY_ADDRESS).asString()); + } catch (MalformedURLException e) { + throw new RuntimeException(e); } - return new BoxResourceIterable( - api, WEBHOOKS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString()), 64) { - - @Override - protected BoxWebHook.Info factory(JsonObject jsonObject) { - BoxWebHook webHook = new BoxWebHook(api, jsonObject.get("id").asString()); - return webHook.new Info(jsonObject); - } + } + + if (jsonObject.get(JSON_KEY_CREATED_BY) != null) { + JsonObject userJSON = jsonObject.get(JSON_KEY_CREATED_BY).asObject(); + if (this.createdBy == null) { + BoxUser user = new BoxUser(getAPI(), userJSON.get(JSON_KEY_TARGET_ID).asString()); + this.createdBy = user.new Info(userJSON); + } else { + this.createdBy.update(userJSON); + } + } - }; + if (jsonObject.get(JSON_KEY_CREATED_AT) != null) { + try { + this.createdAt = BoxDateFormat.parse(jsonObject.get(JSON_KEY_CREATED_AT).asString()); + } catch (ParseException e) { + assert false : "A ParseException indicates a bug in the SDK."; + } + } } - /** - * Validates that provided {@link BoxWebHook.Trigger}-s can be applied on the provided {@link BoxResourceType}. - * - * @param targetType on which target the triggers should be applied to - * @param triggers for check - * @see #validateTrigger(String, Trigger) - */ - public static void validateTriggers(String targetType, Collection triggers) { - for (BoxWebHook.Trigger trigger : triggers) { - validateTrigger(targetType, trigger); - } + /** {@inheritDoc} */ + @Override + public BoxWebHook getResource() { + return BoxWebHook.this; } - /** - * Validates that provided {@link BoxWebHook.Trigger} can be applied on the provided {@link BoxResourceType}. - * - * @param targetType on which targets the trigger should be applied to - * @param trigger for check - * @see #validateTriggers(String, Collection) - */ - private static void validateTrigger(String targetType, BoxWebHook.Trigger trigger) { - for (String type : trigger.getTypes()) { - if (targetType.equals(type)) { - return; - } - } - throw new IllegalArgumentException(String.format( - "Provided trigger '%s' is not supported on provided target '%s'.", trigger.name(), targetType)); + /** @return WebHook target / {@link BoxResource}. */ + public Target getTarget() { + return this.target; } - /** - * @param fields the fields to retrieve. - * @return Gets information about this {@link BoxWebHook}. - */ - public BoxWebHook.Info getInfo(String... fields) { - URL url = WEBHOOK_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - if (fields.length > 0) { - QueryStringBuilder builder = new QueryStringBuilder().appendParam("fields", fields); - url = WEBHOOK_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), builder.toString(), this.getID()); - } - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); - try (BoxJSONResponse response = request.send()) { - return new Info(Json.parse(response.getJSON()).asObject()); - } + /** @return {@link URL} where the notification should send to. */ + public URL getAddress() { + return this.address; } /** - * Updates {@link BoxWebHook} information. + * Setter for {@link #getAddress()}. * - * @param info new state + * @param address {@link #getAddress()} + * @return itself */ - public void updateInfo(BoxWebHook.Info info) { - URL url = WEBHOOK_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(getAPI(), url, "PUT"); - request.setBody(info.getPendingChanges()); - - try (BoxJSONResponse response = request.send()) { - JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - info.update(jsonObject); - } + public Info setAddress(URL address) { + if (address == null) { + throw new IllegalArgumentException("Address cannot be null"); + } + if (this.address == null || !this.address.equals(address)) { + this.address = address; + this.addPendingChange(JSON_KEY_ADDRESS, address.toExternalForm()); + } + + return this; } - /** - * Deletes this webhook. - */ - public void delete() { - URL url = WEBHOOK_URL_TEMPLATE.build(getAPI().getBaseURL(), this.getID()); - BoxAPIRequest request = new BoxAPIRequest(getAPI(), url, "DELETE"); - request.send().close(); + /** @return Events this webhook is interested in. */ + public Set getTriggers() { + return this.triggers; } /** - * A Box related triggers. + * Sets {@link #getTriggers()}. + * + * @param triggers {@link #getTriggers()} + * @return itself */ - public enum Trigger { - - // BoxFolder related triggers. - - /** - * Triggered when a {@link BoxFolder} gets created. - */ - FOLDER_CREATED("FOLDER.CREATED", BoxResource.getResourceType(BoxFolder.class)), - - /** - * Triggered when a {@link BoxFolder} gets copied. - */ - FOLDER_COPIED("FOLDER.COPIED", BoxResource.getResourceType(BoxFolder.class)), - - /** - * Triggered when a {@link BoxFolder} gets moved. - */ - FOLDER_MOVED("FOLDER.MOVED", BoxResource.getResourceType(BoxFolder.class)), - - /** - * Triggered when a {@link BoxFolder} is downloaded. - */ - FOLDER_DOWNLOADED("FOLDER.DOWNLOADED", BoxResource.getResourceType(BoxFolder.class)), - - /** - * Triggered when a {@link BoxFolder} is trashed. - */ - FOLDER_TRASHED("FOLDER.TRASHED", BoxResource.getResourceType(BoxFolder.class)), - - /** - * Triggered when a {@link BoxFolder} gets restored. - */ - FOLDER_RESTORED("FOLDER.RESTORED", BoxResource.getResourceType(BoxFolder.class)), - - /** - * Triggered when a {@link BoxFolder} gets deleted. - */ - FOLDER_DELETED("FOLDER.DELETED", BoxResource.getResourceType(BoxFolder.class)), - - /** - * Triggered when a {@link BoxFolder} is renamed. - */ - FOLDER_RENAMED("FOLDER.RENAMED", BoxResource.getResourceType(BoxFolder.class)), - - // BoxFile related triggers. - - /** - * Triggered when a {@link BoxFile} gets uploaded. - */ - FILE_UPLOADED("FILE.UPLOADED", BoxResource.getResourceType(BoxFolder.class)), - - /** - * Triggered when a {@link BoxFile} gets copied. - */ - FILE_COPIED("FILE.COPIED", - BoxResource.getResourceType(BoxFolder.class), BoxResource.getResourceType(BoxFile.class)), - - /** - * Triggered when a {@link BoxFile} gets copied. - */ - FILE_MOVED("FILE.MOVED", - BoxResource.getResourceType(BoxFolder.class), BoxResource.getResourceType(BoxFile.class)), - - /** - * Triggered when a {@link BoxFile} is previewed. - */ - FILE_PREVIEWED("FILE.PREVIEWED", - BoxResource.getResourceType(BoxFolder.class), BoxResource.getResourceType(BoxFile.class)), - - /** - * Triggered when a {@link BoxFile} is downloaded. - */ - FILE_DOWNLOADED("FILE.DOWNLOADED", - BoxResource.getResourceType(BoxFolder.class), BoxResource.getResourceType(BoxFile.class)), - - /** - * Triggered when a {@link BoxFile} gets locked. - */ - FILE_LOCKED("FILE.LOCKED", - BoxResource.getResourceType(BoxFolder.class), BoxResource.getResourceType(BoxFile.class)), - - /** - * Triggered when a {@link BoxFile} gets unlocked. - */ - FILE_UNLOCKED("FILE.UNLOCKED", - BoxResource.getResourceType(BoxFolder.class), BoxResource.getResourceType(BoxFile.class)), - - /** - * Triggered when a {@link BoxFile} is trashed. Do not include file versions for now. - */ - FILE_TRASHED("FILE.TRASHED", - BoxResource.getResourceType(BoxFolder.class), BoxResource.getResourceType(BoxFile.class)), - - /** - * Triggered when a {@link BoxFile} gets restored. - */ - FILE_RESTORED("FILE.RESTORED", - BoxResource.getResourceType(BoxFolder.class), BoxResource.getResourceType(BoxFile.class)), - - /** - * Triggered when a {@link BoxFile} is permanently deleted. - */ - FILE_DELETED("FILE.DELETED", - BoxResource.getResourceType(BoxFolder.class), BoxResource.getResourceType(BoxFile.class)), - - /** - * Triggered when a {@link BoxFile} is renamed. - */ - FILE_RENAMED("FILE.RENAMED", - BoxResource.getResourceType(BoxFolder.class), BoxResource.getResourceType(BoxFile.class)), - - /** - * Triggered when a {@link BoxComment} was created. - */ - COMMENT_CREATED("COMMENT.CREATED", - BoxResource.getResourceType(BoxFolder.class), BoxResource.getResourceType(BoxFile.class)), - - /** - * Triggered when a {@link BoxComment} was updated. - */ - COMMENT_UPDATED("COMMENT.UPDATED", - BoxResource.getResourceType(BoxFolder.class), BoxResource.getResourceType(BoxFile.class)), - - /** - * Triggered when a {@link BoxComment} was deleted. - */ - COMMENT_DELETED("COMMENT.DELETED", - BoxResource.getResourceType(BoxFolder.class), BoxResource.getResourceType(BoxFile.class)), - - /** - * Triggered when a {@link BoxTaskAssignment} is created. - */ - TASK_ASSIGNMENT_CREATED("TASK_ASSIGNMENT.CREATED", - BoxResource.getResourceType(BoxFolder.class), BoxResource.getResourceType(BoxFile.class)), - - /** - * Triggered when a {@link BoxTaskAssignment} is updated. - */ - TASK_ASSIGNMENT_UPDATED("TASK_ASSIGNMENT.UPDATED", - BoxResource.getResourceType(BoxFolder.class), BoxResource.getResourceType(BoxFile.class)), - - /** - * Triggered when a metadata template is associated to a {@link BoxFile} or {@link BoxFolder}. - */ - METADATA_INSTANCE_CREATED("METADATA_INSTANCE.CREATED", - BoxResource.getResourceType(BoxFolder.class), BoxResource.getResourceType(BoxFile.class)), - - /** - * Triggered when a field is updated in the metadata on a {@link BoxFile} or {@link BoxFolder}. - */ - METADATA_INSTANCE_UPDATED("METADATA_INSTANCE.UPDATED", - BoxResource.getResourceType(BoxFolder.class), BoxResource.getResourceType(BoxFile.class)), - - /** - * Triggered when a metadata template is removed from a {@link BoxFile} or {@link BoxFolder}. - */ - METADATA_INSTANCE_DELETED("METADATA_INSTANCE.DELETED", - BoxResource.getResourceType(BoxFolder.class), BoxResource.getResourceType(BoxFile.class)), - - /** - * Triggered when a {@link BoxWebHook} is deleted. - */ - WEBHOOK_DELETED("WEBHOOK.DELETED"), - - /** - * Triggered when a {@link BoxCollaboration} is created. - */ - COLLABORATION_CREATED("COLLABORATION.CREATED", - BoxResource.getResourceType(BoxFolder.class)), - - /** - * Triggered when a {@link BoxCollaboration} is accepted. - */ - COLLABORATION_ACCEPTED("COLLABORATION.ACCEPTED", - BoxResource.getResourceType(BoxFolder.class)), - - /** - * Triggered when a {@link BoxCollaboration} is rejected. - */ - COLLABORATION_REJECTED("COLLABORATION.REJECTED", - BoxResource.getResourceType(BoxFolder.class)), - - /** - * Triggered when a {@link BoxCollaboration} is removed. - */ - COLLABORATION_REMOVED("COLLABORATION.REMOVED", - BoxResource.getResourceType(BoxFolder.class)), - - /** - * Triggered when a {@link BoxCollaboration} is updated. - */ - COLLABORATION_UPDATED("COLLABORATION.UPDATED", - BoxResource.getResourceType(BoxFolder.class)), - - /** - * Triggered when a {@link BoxSharedLink} is created. - */ - SHARED_LINK_CRATED("SHARED_LINK.CREATED", - BoxResource.getResourceType(BoxFolder.class), BoxResource.getResourceType(BoxFile.class)), - - /** - * Triggered when a {@link BoxSharedLink} is updated. - */ - SHARED_LINK_UPDATED("SHARED_LINK.UPDATED", - BoxResource.getResourceType(BoxFolder.class), BoxResource.getResourceType(BoxFile.class)), - - /** - * Triggered when a {@link BoxSharedLink} is deleted. - */ - SHARED_LINK_DELETED("SHARED_LINK.DELETED", - BoxResource.getResourceType(BoxFolder.class), BoxResource.getResourceType(BoxFile.class)), - - /** - * Triggered when {@link BoxSignRequest} is completed. - */ - SIGN_REQUEST_COMPLETED("SIGN_REQUEST.COMPLETED", - BoxResource.getResourceType(BoxFolder.class), BoxResource.getResourceType(BoxFile.class)), - /** - * Triggered when {@link BoxFile} is declined. - */ - SIGN_REQUEST_DECLINED("SIGN_REQUEST.DECLINED", - BoxResource.getResourceType(BoxFolder.class), BoxResource.getResourceType(BoxFile.class)), - /** - * Triggered when {@link BoxFile} is expired. - */ - SIGN_REQUEST_EXPIRED("SIGN_REQUEST.EXPIRED", - BoxResource.getResourceType(BoxFolder.class), BoxResource.getResourceType(BoxFile.class)), - /** - * Triggered when a signer's email is bounced. - */ - SIGN_REQUEST_SIGNER_EMAIL_BOUNCED("SIGN_REQUEST.SIGNER_EMAIL_BOUNCED", - BoxResource.getResourceType(BoxFolder.class), BoxResource.getResourceType(BoxFile.class)), - /** - * Triggered when the signature request is signed. - */ - SIGN_REQUEST_SIGNER_SIGNED("SIGN_REQUEST.SIGNER_SIGNED", - BoxResource.getResourceType(BoxFolder.class), BoxResource.getResourceType(BoxFile.class)), - /** - * Triggered when the signature is requested from the signer. - */ - SIGN_REQUEST_SIGNATURE_REQUESTED("SIGN_REQUEST.SIGNATURE_REQUESTED", - BoxResource.getResourceType(BoxFolder.class), BoxResource.getResourceType(BoxFile.class)), - /** - * Triggered when the signature request could not be processed. - */ - SIGN_REQUEST_ERROR_FINALIZING("SIGN_REQUEST.ERROR_FINALIZING", - BoxResource.getResourceType(BoxFolder.class), BoxResource.getResourceType(BoxFile.class)); - - /** - * @see #getValue() - */ - private final String value; - - /** - * @see #getTypes() - */ - private final String[] types; - - /** - * Constructor. - * - * @param value {@link #getValue()} - * @param types {@link #getTypes()} - */ - Trigger(String value, String... types) { - this.value = value; - this.types = types; - } - - /** - * @param value value to get the Trigger enum value for - * @return Trigger for given value - */ - public static Trigger fromValue(String value) { - for (Trigger trigger : Trigger.values()) { - if (trigger.getValue().equals(value)) { - return trigger; - } - } - throw new IllegalArgumentException("No Trigger for value: " + value); - } - - /** - * @return {@link String} representation for {@link Trigger}. - */ - public String getValue() { - return this.value; - } - - /** - * @return Supported types for a web-hook. - */ - public String[] getTypes() { - return this.types; - } - + public Info setTriggers(BoxWebHook.Trigger... triggers) { + return this.setTriggers(new HashSet<>(Arrays.asList(triggers))); } /** - * WebHook target - file or folder. + * Setter for {@link #getTriggers()}. + * + * @param triggers {@link #getTriggers()} + * @return itself */ - public static class Target { - - /** - * @see #getType() - */ - private final String type; - - /** - * @see #getId() - */ - private final String id; - - /** - * Constructor. - * - * @param type {@link #getType()} - * @param id {@link #getId()} - */ - public Target(String type, String id) { - this.type = type; - this.id = id; - } - - /** - * @return Type of target. - * @see BoxResourceType - */ - public String getType() { - return this.type; - } - - /** - * @return {@link BoxResource#getID()} - */ - public String getId() { - return this.id; - } - + public Info setTriggers(Set triggers) { + validateTriggers(this.target.getType(), triggers); + + JsonArray oldValue; + if (this.triggers != null) { + oldValue = toJsonArray(CollectionUtils.map(this.triggers, TRIGGER_TO_VALUE)); + } else { + oldValue = null; + } + JsonArray newValue = toJsonArray(CollectionUtils.map(triggers, TRIGGER_TO_VALUE)); + + if (!newValue.equals(oldValue)) { + this.triggers = Collections.unmodifiableSet(triggers); + this.addPendingChange(JSON_KEY_TRIGGERS, newValue); + } + + return this; } - /** - * Contains information for a {@link BoxWebHook} instance. - */ - public class Info extends BoxResource.Info { - - /** - * @see #getTarget() - */ - private Target target; - - /** - * @see #getAddress() - */ - private URL address; - - /** - * @see #getTriggers() - */ - private Set triggers; - - /** - * @see #getCreatedBy() - */ - private BoxUser.Info createdBy; - - /** - * @see #getCreatedAt() - */ - private Date createdAt; - - /** - * Constructs an Info object with current target. - */ - public Info() { - super(); - this.target = BoxWebHook.this.getInfo().getTarget(); - } - - /** - * Constructs an Info object by parsing information from a JSON string. - * - * @param json the JSON string to parse. - */ - public Info(String json) { - this(Json.parse(json).asObject()); - } - - /** - * Constructor. - * - * @param jsonObject a parsed JSON object - */ - public Info(JsonObject jsonObject) { - super(jsonObject); - - if (jsonObject.get(JSON_KEY_TARGET) != null) { - JsonObject targetObject = jsonObject.get(JSON_KEY_TARGET).asObject(); - String targetType = targetObject.get(JSON_KEY_TARGET_TYPE).asString(); - String targetId = targetObject.get(JSON_KEY_TARGET_ID).asString(); - this.target = new Target(targetType, targetId); - } - - if (jsonObject.get(JSON_KEY_TRIGGERS) != null) { - this.triggers = new HashSet<>( - CollectionUtils.map(jsonObject.get(JSON_KEY_TRIGGERS).asArray().values(), JSON_VALUE_TO_TRIGGER) - ); - } - if (jsonObject.get(JSON_KEY_ADDRESS) != null) { - try { - this.address = new URL(jsonObject.get(JSON_KEY_ADDRESS).asString()); - } catch (MalformedURLException e) { - throw new RuntimeException(e); - } - } - - if (jsonObject.get(JSON_KEY_CREATED_BY) != null) { - JsonObject userJSON = jsonObject.get(JSON_KEY_CREATED_BY).asObject(); - if (this.createdBy == null) { - BoxUser user = new BoxUser(getAPI(), userJSON.get(JSON_KEY_TARGET_ID).asString()); - this.createdBy = user.new Info(userJSON); - } else { - this.createdBy.update(userJSON); - } - } - - if (jsonObject.get(JSON_KEY_CREATED_AT) != null) { - try { - this.createdAt = BoxDateFormat.parse(jsonObject.get(JSON_KEY_CREATED_AT).asString()); - } catch (ParseException e) { - assert false : "A ParseException indicates a bug in the SDK."; - } - } - } - - /** - * {@inheritDoc} - */ - @Override - public BoxWebHook getResource() { - return BoxWebHook.this; - } - - /** - * @return WebHook target / {@link BoxResource}. - */ - public Target getTarget() { - return this.target; - } - - /** - * @return {@link URL} where the notification should send to. - */ - public URL getAddress() { - return this.address; - } - - /** - * Setter for {@link #getAddress()}. - * - * @param address {@link #getAddress()} - * @return itself - */ - public Info setAddress(URL address) { - if (address == null) { - throw new IllegalArgumentException("Address cannot be null"); - } - if (this.address == null || !this.address.equals(address)) { - this.address = address; - this.addPendingChange(JSON_KEY_ADDRESS, address.toExternalForm()); - } - - return this; - } - - /** - * @return Events this webhook is interested in. - */ - public Set getTriggers() { - return this.triggers; - } - - /** - * Sets {@link #getTriggers()}. - * - * @param triggers {@link #getTriggers()} - * @return itself - */ - public Info setTriggers(BoxWebHook.Trigger... triggers) { - return this.setTriggers(new HashSet<>(Arrays.asList(triggers))); - } - - /** - * Setter for {@link #getTriggers()}. - * - * @param triggers {@link #getTriggers()} - * @return itself - */ - public Info setTriggers(Set triggers) { - validateTriggers(this.target.getType(), triggers); - - JsonArray oldValue; - if (this.triggers != null) { - oldValue = toJsonArray(CollectionUtils.map(this.triggers, TRIGGER_TO_VALUE)); - } else { - oldValue = null; - } - JsonArray newValue = toJsonArray(CollectionUtils.map(triggers, TRIGGER_TO_VALUE)); - - if (!newValue.equals(oldValue)) { - this.triggers = Collections.unmodifiableSet(triggers); - this.addPendingChange(JSON_KEY_TRIGGERS, newValue); - } - - return this; - } - - /** - * @return Info about the user who created this webhook. - */ - public BoxUser.Info getCreatedBy() { - return this.createdBy; - } + /** @return Info about the user who created this webhook. */ + public BoxUser.Info getCreatedBy() { + return this.createdBy; + } - /** - * @return the time this webhook was created. - */ - public Date getCreatedAt() { - return this.createdAt; - } + /** @return the time this webhook was created. */ + public Date getCreatedAt() { + return this.createdAt; + } - /** - * {@inheritDoc} - */ - @Override - void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - String memberName = member.getName(); - JsonValue value = member.getValue(); - try { - if (memberName.equals(JSON_KEY_TARGET)) { - String targetType = value.asObject().get(JSON_KEY_TARGET_TYPE).asString(); - String targetId = value.asObject().get(JSON_KEY_TARGET_ID).asString(); - this.target = new Target(targetType, targetId); - } else if (memberName.equals(JSON_KEY_TRIGGERS)) { - this.triggers = new HashSet<>( - CollectionUtils.map(value.asArray().values(), JSON_VALUE_TO_TRIGGER) - ); - } else if (memberName.equals(JSON_KEY_ADDRESS)) { - this.address = new URL(value.asString()); - } else if (memberName.equals(JSON_KEY_CREATED_BY)) { - JsonObject userJSON = value.asObject(); - if (this.createdBy == null) { - String userID = userJSON.get(JSON_KEY_ID).asString(); - BoxUser user = new BoxUser(getAPI(), userID); - this.createdBy = user.new Info(userJSON); - } else { - this.createdBy.update(userJSON); - } - } else if (memberName.equals("created_at")) { - this.createdAt = BoxDateFormat.parse(value.asString()); - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); - } + /** {@inheritDoc} */ + @Override + void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + String memberName = member.getName(); + JsonValue value = member.getValue(); + try { + if (memberName.equals(JSON_KEY_TARGET)) { + String targetType = value.asObject().get(JSON_KEY_TARGET_TYPE).asString(); + String targetId = value.asObject().get(JSON_KEY_TARGET_ID).asString(); + this.target = new Target(targetType, targetId); + } else if (memberName.equals(JSON_KEY_TRIGGERS)) { + this.triggers = + new HashSet<>(CollectionUtils.map(value.asArray().values(), JSON_VALUE_TO_TRIGGER)); + } else if (memberName.equals(JSON_KEY_ADDRESS)) { + this.address = new URL(value.asString()); + } else if (memberName.equals(JSON_KEY_CREATED_BY)) { + JsonObject userJSON = value.asObject(); + if (this.createdBy == null) { + String userID = userJSON.get(JSON_KEY_ID).asString(); + BoxUser user = new BoxUser(getAPI(), userID); + this.createdBy = user.new Info(userJSON); + } else { + this.createdBy.update(userJSON); + } + } else if (memberName.equals("created_at")) { + this.createdAt = BoxDateFormat.parse(value.asString()); } - + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); + } } - + } } diff --git a/src/main/java/com/box/sdk/BoxWebHookSignatureVerifier.java b/src/main/java/com/box/sdk/BoxWebHookSignatureVerifier.java index 5f490ddd4..ac673b40f 100644 --- a/src/main/java/com/box/sdk/BoxWebHookSignatureVerifier.java +++ b/src/main/java/com/box/sdk/BoxWebHookSignatureVerifier.java @@ -19,206 +19,212 @@ */ public class BoxWebHookSignatureVerifier { - /** - * Reference to UTF_8 {@link Charset}. - */ - private static final Charset UTF_8 = Charset.forName("UTF-8"); - - /** - * Versions supported by this implementation. - */ - private static final Set SUPPORTED_VERSIONS = Collections.singleton("1"); - - /** - * Algorithms supported by this implementation. - */ - private static final Set SUPPORTED_ALGORITHMS = Collections.unmodifiableSet( - EnumSet.of(BoxSignatureAlgorithm.HMAC_SHA256)); + /** Reference to UTF_8 {@link Charset}. */ + private static final Charset UTF_8 = Charset.forName("UTF-8"); + + /** Versions supported by this implementation. */ + private static final Set SUPPORTED_VERSIONS = Collections.singleton("1"); + + /** Algorithms supported by this implementation. */ + private static final Set SUPPORTED_ALGORITHMS = + Collections.unmodifiableSet(EnumSet.of(BoxSignatureAlgorithm.HMAC_SHA256)); + + /** {@link Mac}-s pool. */ + private static final MacPool MAC_POOL = new MacPool(); + + /** Primary key setup within the Box. */ + private final String primarySignatureKey; + + /** Secondary key setup within the Box. */ + private final String secondarySignatureKey; + + /** + * Creates a new instance of verifier specified with given primary and secondary keys. Primary key + * and secondary key are needed for rotating purposes, at least at one has to be valid. + * + * @param primarySignatureKey primary signature key for web-hooks (can not be null) + * @param secondarySignatureKey secondary signature key for web-hooks (can be null) + * @throws IllegalArgumentException primary key can not be null + */ + public BoxWebHookSignatureVerifier(String primarySignatureKey, String secondarySignatureKey) { + if (primarySignatureKey == null && secondarySignatureKey == null) { + throw new IllegalArgumentException( + "At least primary or secondary signature key must be provided!"); + } - /** - * {@link Mac}-s pool. - */ - private static final MacPool MAC_POOL = new MacPool(); + this.primarySignatureKey = primarySignatureKey; + this.secondarySignatureKey = secondarySignatureKey; + } + + /** + * Verifies given web-hook information. + * + * @param signatureVersion signature version received from web-hook + * @param signatureAlgorithm signature algorithm received from web-hook + * @param primarySignature primary signature received from web-hook + * @param secondarySignature secondary signature received from web-hook + * @param webHookPayload payload of web-hook + * @param deliveryTimestamp devilery timestamp received from web-hook + * @return true, if given payload is successfully verified against primary and secondary + * signatures, false otherwise + */ + public boolean verify( + String signatureVersion, + String signatureAlgorithm, + String primarySignature, + String secondarySignature, + String webHookPayload, + String deliveryTimestamp) { + + // enforce versions supported by this implementation + if (!SUPPORTED_VERSIONS.contains(signatureVersion)) { + return false; + } - /** - * Primary key setup within the Box. - */ - private final String primarySignatureKey; + // enforce algorithms supported by this implementation + BoxSignatureAlgorithm algorithm = BoxSignatureAlgorithm.byName(signatureAlgorithm); + if (!SUPPORTED_ALGORITHMS.contains(algorithm)) { + return false; + } - /** - * Secondary key setup within the Box. - */ - private final String secondarySignatureKey; + // check primary key signature if primary key exists + if (this.primarySignatureKey != null + && this.verify( + this.primarySignatureKey, + algorithm, + primarySignature, + webHookPayload, + deliveryTimestamp)) { + return true; + } - /** - * Creates a new instance of verifier specified with given primary and secondary keys. Primary key and secondary key - * are needed for rotating purposes, at least at one has to be valid. - * - * @param primarySignatureKey primary signature key for web-hooks (can not be null) - * @param secondarySignatureKey secondary signature key for web-hooks (can be null) - * @throws IllegalArgumentException primary key can not be null - */ - public BoxWebHookSignatureVerifier(String primarySignatureKey, String secondarySignatureKey) { - if (primarySignatureKey == null && secondarySignatureKey == null) { - throw new IllegalArgumentException("At least primary or secondary signature key must be provided!"); - } + // check secondary key signature if secondary key exists + if (this.secondarySignatureKey != null + && this.verify( + this.secondarySignatureKey, + algorithm, + secondarySignature, + webHookPayload, + deliveryTimestamp)) { + return true; + } - this.primarySignatureKey = primarySignatureKey; - this.secondarySignatureKey = secondarySignatureKey; + // default strategy is false, to minimize security issues + return false; + } + + /** + * Verifies a provided signature. + * + * @param key for which signature key + * @param actualAlgorithm current signature algorithm + * @param actualSignature current signature + * @param webHookPayload for signing + * @param deliveryTimestamp for signing + * @return true if verification passed + */ + private boolean verify( + String key, + BoxSignatureAlgorithm actualAlgorithm, + String actualSignature, + String webHookPayload, + String deliveryTimestamp) { + if (actualSignature == null) { + return false; } - /** - * Verifies given web-hook information. - * - * @param signatureVersion signature version received from web-hook - * @param signatureAlgorithm signature algorithm received from web-hook - * @param primarySignature primary signature received from web-hook - * @param secondarySignature secondary signature received from web-hook - * @param webHookPayload payload of web-hook - * @param deliveryTimestamp devilery timestamp received from web-hook - * @return true, if given payload is successfully verified against primary and secondary signatures, false otherwise - */ - public boolean verify(String signatureVersion, String signatureAlgorithm, String primarySignature, - String secondarySignature, String webHookPayload, String deliveryTimestamp) { - - // enforce versions supported by this implementation - if (!SUPPORTED_VERSIONS.contains(signatureVersion)) { - return false; - } - - // enforce algorithms supported by this implementation - BoxSignatureAlgorithm algorithm = BoxSignatureAlgorithm.byName(signatureAlgorithm); - if (!SUPPORTED_ALGORITHMS.contains(algorithm)) { - return false; - } - - // check primary key signature if primary key exists - if (this.primarySignatureKey != null && this.verify(this.primarySignatureKey, algorithm, primarySignature, - webHookPayload, deliveryTimestamp)) { - return true; - } - - // check secondary key signature if secondary key exists - if (this.secondarySignatureKey != null && this.verify(this.secondarySignatureKey, algorithm, secondarySignature, - webHookPayload, deliveryTimestamp)) { - return true; - } - - // default strategy is false, to minimize security issues - return false; + byte[] actual = Base64.decode(actualSignature); + byte[] expected = this.signRaw(actualAlgorithm, key, webHookPayload, deliveryTimestamp); + + return MessageDigest.isEqual(expected, actual); + } + + /** + * Calculates signature for a provided information. + * + * @param algorithm for which algorithm + * @param key used by signing + * @param webHookPayload for singing + * @param deliveryTimestamp for signing + * @return calculated signature + */ + public String sign( + BoxSignatureAlgorithm algorithm, + String key, + String webHookPayload, + String deliveryTimestamp) { + return Base64.encode(this.signRaw(algorithm, key, webHookPayload, deliveryTimestamp)); + } + + /** + * Calculates signature for a provided information. + * + * @param algorithm for which algorithm + * @param key used by signing + * @param webHookPayload for singing + * @param deliveryTimestamp for signing + * @return calculated signature + */ + private byte[] signRaw( + BoxSignatureAlgorithm algorithm, + String key, + String webHookPayload, + String deliveryTimestamp) { + Mac mac = MAC_POOL.acquire(algorithm.javaProviderName); + try { + mac.init(new SecretKeySpec(key.getBytes(UTF_8), algorithm.javaProviderName)); + mac.update(UTF_8.encode(webHookPayload)); + mac.update(UTF_8.encode(deliveryTimestamp)); + return mac.doFinal(); + } catch (InvalidKeyException e) { + throw new IllegalArgumentException("Invalid key: ", e); + } finally { + MAC_POOL.release(mac); } + } - /** - * Verifies a provided signature. - * - * @param key for which signature key - * @param actualAlgorithm current signature algorithm - * @param actualSignature current signature - * @param webHookPayload for signing - * @param deliveryTimestamp for signing - * @return true if verification passed - */ - private boolean verify(String key, BoxSignatureAlgorithm actualAlgorithm, String actualSignature, - String webHookPayload, String deliveryTimestamp) { - if (actualSignature == null) { - return false; - } + /** Box Signature Algorithms. */ + public enum BoxSignatureAlgorithm { - byte[] actual = Base64.decode(actualSignature); - byte[] expected = this.signRaw(actualAlgorithm, key, webHookPayload, deliveryTimestamp); + /** HmacSHA256 algorithm. */ + HMAC_SHA256("HmacSHA256", "HmacSHA256"); - return MessageDigest.isEqual(expected, actual); - } + /** @see #byName(String) */ + private static final Map ALGORITHM_BY_NAME; - /** - * Calculates signature for a provided information. - * - * @param algorithm for which algorithm - * @param key used by signing - * @param webHookPayload for singing - * @param deliveryTimestamp for signing - * @return calculated signature - */ - public String sign(BoxSignatureAlgorithm algorithm, String key, String webHookPayload, String deliveryTimestamp) { - return Base64.encode(this.signRaw(algorithm, key, webHookPayload, deliveryTimestamp)); + static { + Map algorithmByName = + new ConcurrentHashMap(); + for (BoxSignatureAlgorithm algorithm : BoxSignatureAlgorithm.values()) { + algorithmByName.put(algorithm.name, algorithm); + } + ALGORITHM_BY_NAME = Collections.unmodifiableMap(algorithmByName); } + /** Algorithm name by Box. */ + private final String name; + /** Algorithm name according to the Java provider. */ + private final String javaProviderName; + /** - * Calculates signature for a provided information. + * Constructor. * - * @param algorithm for which algorithm - * @param key used by signing - * @param webHookPayload for singing - * @param deliveryTimestamp for signing - * @return calculated signature + * @param name algorithm name by Box + * @param javaProviderName algorithm name according to the Java provider */ - private byte[] signRaw(BoxSignatureAlgorithm algorithm, String key, String webHookPayload, - String deliveryTimestamp) { - Mac mac = MAC_POOL.acquire(algorithm.javaProviderName); - try { - mac.init(new SecretKeySpec(key.getBytes(UTF_8), algorithm.javaProviderName)); - mac.update(UTF_8.encode(webHookPayload)); - mac.update(UTF_8.encode(deliveryTimestamp)); - return mac.doFinal(); - } catch (InvalidKeyException e) { - throw new IllegalArgumentException("Invalid key: ", e); - } finally { - MAC_POOL.release(mac); - } + BoxSignatureAlgorithm(String name, String javaProviderName) { + this.name = javaProviderName; + this.javaProviderName = javaProviderName; } /** - * Box Signature Algorithms. + * Resolves {@link BoxSignatureAlgorithm} according to its name. + * + * @param name of algorithm + * @return resolved {@link BoxSignatureAlgorithm} or null if does not exist */ - public enum BoxSignatureAlgorithm { - - /** - * HmacSHA256 algorithm. - */ - HMAC_SHA256("HmacSHA256", "HmacSHA256"); - - /** - * @see #byName(String) - */ - private static final Map ALGORITHM_BY_NAME; - - static { - Map algorithmByName = new ConcurrentHashMap(); - for (BoxSignatureAlgorithm algorithm : BoxSignatureAlgorithm.values()) { - algorithmByName.put(algorithm.name, algorithm); - } - ALGORITHM_BY_NAME = Collections.unmodifiableMap(algorithmByName); - } - - /** - * Algorithm name by Box. - */ - private final String name; - /** - * Algorithm name according to the Java provider. - */ - private final String javaProviderName; - - /** - * Constructor. - * - * @param name algorithm name by Box - * @param javaProviderName algorithm name according to the Java provider - */ - BoxSignatureAlgorithm(String name, String javaProviderName) { - this.name = javaProviderName; - this.javaProviderName = javaProviderName; - } - - /** - * Resolves {@link BoxSignatureAlgorithm} according to its name. - * - * @param name of algorithm - * @return resolved {@link BoxSignatureAlgorithm} or null if does not exist - */ - private static BoxSignatureAlgorithm byName(String name) { - return ALGORITHM_BY_NAME.get(name); - } + private static BoxSignatureAlgorithm byName(String name) { + return ALGORITHM_BY_NAME.get(name); } - + } } diff --git a/src/main/java/com/box/sdk/BoxWebLink.java b/src/main/java/com/box/sdk/BoxWebLink.java index b596d33f5..1b90032fe 100644 --- a/src/main/java/com/box/sdk/BoxWebLink.java +++ b/src/main/java/com/box/sdk/BoxWebLink.java @@ -9,276 +9,289 @@ import java.net.URL; /** - * Represents an individual WebLink file on Box. This class can be used to retrieve the link's URL or perform other - * common file operations (move, copy, delete, etc.). + * Represents an individual WebLink file on Box. This class can be used to retrieve the link's URL + * or perform other common file operations (move, copy, delete, etc.). * - *

Unless otherwise noted, the methods in this class can throw an unchecked {@link BoxAPIException} (unchecked - * meaning that the compiler won't force you to handle it) if an error occurs. If you wish to implement custom error - * handling for errors related to the Box REST API, you should capture this exception explicitly.

+ *

Unless otherwise noted, the methods in this class can throw an unchecked {@link + * BoxAPIException} (unchecked meaning that the compiler won't force you to handle it) if an error + * occurs. If you wish to implement custom error handling for errors related to the Box REST API, + * you should capture this exception explicitly. */ @BoxResourceType("web_link") public class BoxWebLink extends BoxItem { - /** - * An array of all possible weblink fields that can be requested when calling {@link #getInfo(String...)}. - */ - public static final String[] ALL_FIELDS = {"type", "id", "sequence_id", "etag", "name", "url", "description", - "path_collection", "created_at", "modified_at", "trashed_at", "purged_at", "created_by", "modified_by", - "owned_by", "shared_link", "parent", "item_status", "collections"}; - - /** - * Copy URL Template. - */ - public static final URLTemplate COPY_URL_TEMPLATE = new URLTemplate("web_links/%s/copy"); - /** - * Web Link URL Template. - */ - public static final URLTemplate WEB_LINK_URL_TEMPLATE = new URLTemplate("web_links/%s"); - - /** - * Constructs a BoxWebLink for a weblink with a given ID. - * - * @param api the API connection to be used by the weblink. - * @param id the ID of the weblink. - */ - public BoxWebLink(BoxAPIConnection api, String id) { - super(api, id); + /** + * An array of all possible weblink fields that can be requested when calling {@link + * #getInfo(String...)}. + */ + public static final String[] ALL_FIELDS = { + "type", + "id", + "sequence_id", + "etag", + "name", + "url", + "description", + "path_collection", + "created_at", + "modified_at", + "trashed_at", + "purged_at", + "created_by", + "modified_by", + "owned_by", + "shared_link", + "parent", + "item_status", + "collections" + }; + + /** Copy URL Template. */ + public static final URLTemplate COPY_URL_TEMPLATE = new URLTemplate("web_links/%s/copy"); + /** Web Link URL Template. */ + public static final URLTemplate WEB_LINK_URL_TEMPLATE = new URLTemplate("web_links/%s"); + + /** + * Constructs a BoxWebLink for a weblink with a given ID. + * + * @param api the API connection to be used by the weblink. + * @param id the ID of the weblink. + */ + public BoxWebLink(BoxAPIConnection api, String id) { + super(api, id); + } + + /** + * Creates a shared link. + * + * @param sharedLinkRequest Shared link to create + * @return Created shared link. + */ + public BoxSharedLink createSharedLink(BoxSharedLinkWithoutPermissionsRequest sharedLinkRequest) { + return createSharedLink(sharedLinkRequest.asSharedLink()); + } + + private BoxSharedLink createSharedLink(BoxSharedLink sharedLink) { + BoxWebLink.Info info = new BoxWebLink.Info(); + info.setSharedLink(sharedLink); + + this.updateInfo(info); + return info.getSharedLink(); + } + + @Override + public BoxWebLink.Info copy(BoxFolder destination) { + return this.copy(destination, null); + } + + @Override + public BoxWebLink.Info copy(BoxFolder destination, String newName) { + URL url = COPY_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + + JsonObject parent = new JsonObject(); + parent.add("id", destination.getID()); + + JsonObject copyInfo = new JsonObject(); + copyInfo.add("parent", parent); + if (newName != null) { + copyInfo.add("name", newName); } - /** - * Creates a shared link. - * - * @param sharedLinkRequest Shared link to create - * @return Created shared link. - */ - public BoxSharedLink createSharedLink(BoxSharedLinkWithoutPermissionsRequest sharedLinkRequest) { - return createSharedLink(sharedLinkRequest.asSharedLink()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); + request.setBody(copyInfo.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + BoxWebLink copiedWebLink = new BoxWebLink(this.getAPI(), responseJSON.get("id").asString()); + return copiedWebLink.new Info(responseJSON); } - - private BoxSharedLink createSharedLink(BoxSharedLink sharedLink) { - BoxWebLink.Info info = new BoxWebLink.Info(); - info.setSharedLink(sharedLink); - - this.updateInfo(info); - return info.getSharedLink(); + } + + /** Deletes this weblink by moving it to the trash. */ + public void delete() { + URL url = WEB_LINK_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); + request.send().close(); + } + + @Override + public BoxItem.Info move(BoxFolder destination) { + return this.move(destination, null); + } + + @Override + public BoxItem.Info move(BoxFolder destination, String newName) { + URL url = WEB_LINK_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); + + JsonObject parent = new JsonObject(); + parent.add("id", destination.getID()); + + JsonObject updateInfo = new JsonObject(); + updateInfo.add("parent", parent); + if (newName != null) { + updateInfo.add("name", newName); } - - @Override - public BoxWebLink.Info copy(BoxFolder destination) { - return this.copy(destination, null); + request.setBody(updateInfo.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + BoxWebLink movedWebLink = new BoxWebLink(this.getAPI(), responseJSON.get("id").asString()); + return movedWebLink.new Info(responseJSON); } - - @Override - public BoxWebLink.Info copy(BoxFolder destination, String newName) { - URL url = COPY_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - - JsonObject parent = new JsonObject(); - parent.add("id", destination.getID()); - - JsonObject copyInfo = new JsonObject(); - copyInfo.add("parent", parent); - if (newName != null) { - copyInfo.add("name", newName); - } - - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); - request.setBody(copyInfo.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - BoxWebLink copiedWebLink = new BoxWebLink(this.getAPI(), responseJSON.get("id").asString()); - return copiedWebLink.new Info(responseJSON); - } + } + + /** + * Renames this weblink. + * + * @param newName the new name of the weblink. + */ + public void rename(String newName) { + URL url = WEB_LINK_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); + + JsonObject updateInfo = new JsonObject(); + updateInfo.add("name", newName); + + request.setBody(updateInfo.toString()); + request.send().close(); + } + + @Override + public BoxWebLink.Info getInfo(String... fields) { + URL url = WEB_LINK_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + if (fields.length > 0) { + String queryString = new QueryStringBuilder().appendParam("fields", fields).toString(); + url = + WEB_LINK_URL_TEMPLATE.buildWithQuery( + this.getAPI().getBaseURL(), queryString, this.getID()); } - /** - * Deletes this weblink by moving it to the trash. - */ - public void delete() { - URL url = WEB_LINK_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); - request.send().close(); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); + try (BoxJSONResponse response = request.send()) { + return new Info(response.getJSON()); } - - @Override - public BoxItem.Info move(BoxFolder destination) { - return this.move(destination, null); + } + + /** + * Updates the information about this weblink with any info fields that have been modified + * locally. + * + *

The only fields that will be updated are the ones that have been modified locally. For + * example, the following code won't update any information (or even send a network request) since + * none of the info's fields were changed: + * + *

BoxWebLink webLink = new BoxWebLink(api, id);
+   * BoxWebLink.Info info = webLink.getInfo();
+   * webLink.updateInfo(info);
+ * + * @param info the updated info. + */ + public void updateInfo(BoxWebLink.Info info) { + URL url = WEB_LINK_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); + request.setBody(info.getPendingChanges()); + try (BoxJSONResponse response = request.send()) { + JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); + info.update(jsonObject); } + } + + @Override + public BoxWebLink.Info setCollections(BoxCollection... collections) { + JsonArray jsonArray = new JsonArray(); + for (BoxCollection collection : collections) { + JsonObject collectionJSON = new JsonObject(); + collectionJSON.add("id", collection.getID()); + jsonArray.add(collectionJSON); + } + JsonObject infoJSON = new JsonObject(); + infoJSON.add("collections", jsonArray); + + String queryString = new QueryStringBuilder().appendParam("fields", ALL_FIELDS).toString(); + URL url = + WEB_LINK_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); + request.setBody(infoJSON.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); + return new Info(jsonObject); + } + } - @Override - public BoxItem.Info move(BoxFolder destination, String newName) { - URL url = WEB_LINK_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); - - JsonObject parent = new JsonObject(); - parent.add("id", destination.getID()); - - JsonObject updateInfo = new JsonObject(); - updateInfo.add("parent", parent); - if (newName != null) { - updateInfo.add("name", newName); - } + /** Contains information about a BoxWebLink. */ + public class Info extends BoxItem.Info { + private URL linkURL; + private String description; - request.setBody(updateInfo.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - BoxWebLink movedWebLink = new BoxWebLink(this.getAPI(), responseJSON.get("id").asString()); - return movedWebLink.new Info(responseJSON); - } + /** Constructs an empty Info object. */ + public Info() { + super(); } /** - * Renames this weblink. + * Constructs an Info object by parsing information from a JSON string. * - * @param newName the new name of the weblink. + * @param json the JSON string to parse. */ - public void rename(String newName) { - URL url = WEB_LINK_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); - - JsonObject updateInfo = new JsonObject(); - updateInfo.add("name", newName); - - request.setBody(updateInfo.toString()); - request.send().close(); - } - - @Override - public BoxWebLink.Info getInfo(String... fields) { - URL url = WEB_LINK_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - if (fields.length > 0) { - String queryString = new QueryStringBuilder().appendParam("fields", fields).toString(); - url = WEB_LINK_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID()); - } - - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "GET"); - try (BoxJSONResponse response = request.send()) { - return new Info(response.getJSON()); - } + public Info(String json) { + super(json); } /** - * Updates the information about this weblink with any info fields that have been modified locally. - * - *

The only fields that will be updated are the ones that have been modified locally. For example, the following - * code won't update any information (or even send a network request) since none of the info's fields were - * changed:

- * - *
BoxWebLink webLink = new BoxWebLink(api, id);
-     * BoxWebLink.Info info = webLink.getInfo();
-     * webLink.updateInfo(info);
+ * Constructs an Info object using an already parsed JSON object. * - * @param info the updated info. + * @param jsonObject the parsed JSON object. */ - public void updateInfo(BoxWebLink.Info info) { - URL url = WEB_LINK_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); - request.setBody(info.getPendingChanges()); - try (BoxJSONResponse response = request.send()) { - JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - info.update(jsonObject); - } + public Info(JsonObject jsonObject) { + super(jsonObject.toString()); } @Override - public BoxWebLink.Info setCollections(BoxCollection... collections) { - JsonArray jsonArray = new JsonArray(); - for (BoxCollection collection : collections) { - JsonObject collectionJSON = new JsonObject(); - collectionJSON.add("id", collection.getID()); - jsonArray.add(collectionJSON); - } - JsonObject infoJSON = new JsonObject(); - infoJSON.add("collections", jsonArray); - - String queryString = new QueryStringBuilder().appendParam("fields", ALL_FIELDS).toString(); - URL url = WEB_LINK_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "PUT"); - request.setBody(infoJSON.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - return new Info(jsonObject); - } + public BoxWebLink getResource() { + return BoxWebLink.this; } /** - * Contains information about a BoxWebLink. + * Gets the description of this weblink. + * + * @return the description of this weblink. */ - public class Info extends BoxItem.Info { - private URL linkURL; - private String description; - - /** - * Constructs an empty Info object. - */ - public Info() { - super(); - } - - /** - * Constructs an Info object by parsing information from a JSON string. - * - * @param json the JSON string to parse. - */ - public Info(String json) { - super(json); - } - - /** - * Constructs an Info object using an already parsed JSON object. - * - * @param jsonObject the parsed JSON object. - */ - public Info(JsonObject jsonObject) { - super(jsonObject.toString()); - } - - @Override - public BoxWebLink getResource() { - return BoxWebLink.this; - } - - /** - * Gets the description of this weblink. - * - * @return the description of this weblink. - */ - public String getDescription() { - return this.description; - } + public String getDescription() { + return this.description; + } - /** - * Gets the URL this weblink points to. - * - * @return the URL this weblink points to. - */ - public URL getLinkURL() { - return this.linkURL; - } + /** + * Gets the URL this weblink points to. + * + * @return the URL this weblink points to. + */ + public URL getLinkURL() { + return this.linkURL; + } - @Override - protected void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - - String memberName = member.getName(); - JsonValue value = member.getValue(); - try { - if (memberName.equals("url")) { - try { - if (value.asString().isEmpty()) { - this.linkURL = null; - } else { - this.linkURL = new URL(value.asString()); - } - } catch (MalformedURLException e) { - throw new BoxAPIException("Couldn't parse url for weblink", e); - } - } else if (memberName.equals("description")) { - this.description = value.asString(); - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); + @Override + protected void parseJSONMember(JsonObject.Member member) { + super.parseJSONMember(member); + + String memberName = member.getName(); + JsonValue value = member.getValue(); + try { + if (memberName.equals("url")) { + try { + if (value.asString().isEmpty()) { + this.linkURL = null; + } else { + this.linkURL = new URL(value.asString()); } + } catch (MalformedURLException e) { + throw new BoxAPIException("Couldn't parse url for weblink", e); + } + } else if (memberName.equals("description")) { + this.description = value.asString(); } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); + } } + } } diff --git a/src/main/java/com/box/sdk/BoxZip.java b/src/main/java/com/box/sdk/BoxZip.java index 901d193e5..83ba9ecee 100644 --- a/src/main/java/com/box/sdk/BoxZip.java +++ b/src/main/java/com/box/sdk/BoxZip.java @@ -10,91 +10,90 @@ import java.util.List; /** - * Provides methods to allow users to download multiple files and folders as a single zip file. Users can download - * up to either 32GB or 10,000 files in one batch (whichever limitation is hit first) as a single zip file. + * Provides methods to allow users to download multiple files and folders as a single zip file. + * Users can download up to either 32GB or 10,000 files in one batch (whichever limitation is hit + * first) as a single zip file. */ public class BoxZip { - /** - * Zip URL Template. - */ - public static final URLTemplate ZIP_URL_TEMPLATE = new URLTemplate("zip_downloads"); - private final BoxAPIConnection api; + /** Zip URL Template. */ + public static final URLTemplate ZIP_URL_TEMPLATE = new URLTemplate("zip_downloads"); - /** - * Constructs a Zip to be used by everything. - * - * @param api the API connection to be used by the Zip. - */ - public BoxZip(BoxAPIConnection api) { - this.api = api; - } + private final BoxAPIConnection api; - /** - * Creates a zip of multiple files and folders. - * - * @param name the name of the zip file to be created - * @param items list of files or folders to be part of the created zip - * @return information about the created zip file - */ - public BoxZipInfo create(String name, List items) { - JsonArray itemsArray = new JsonArray(); - for (BoxZipItem item : items) { - itemsArray.add(item.getJSONObject()); - } - JsonObject requestJSON = new JsonObject(); - requestJSON.add("items", itemsArray); - requestJSON.add("download_file_name", name); + /** + * Constructs a Zip to be used by everything. + * + * @param api the API connection to be used by the Zip. + */ + public BoxZip(BoxAPIConnection api) { + this.api = api; + } - URL url = ZIP_URL_TEMPLATE.build(this.getAPI().getBaseURL()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); - request.setBody(requestJSON.toString()); - try (BoxJSONResponse response = request.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - return new BoxZipInfo(responseJSON); - } + /** + * Creates a zip of multiple files and folders. + * + * @param name the name of the zip file to be created + * @param items list of files or folders to be part of the created zip + * @return information about the created zip file + */ + public BoxZipInfo create(String name, List items) { + JsonArray itemsArray = new JsonArray(); + for (BoxZipItem item : items) { + itemsArray.add(item.getJSONObject()); } + JsonObject requestJSON = new JsonObject(); + requestJSON.add("items", itemsArray); + requestJSON.add("download_file_name", name); - /** - * Creates a zip and downloads it to a given OutputStream. - * - * @param name the name of the zip file to be created - * @param items list of files or folders to be part of the created zip - * @param output the stream to where the zip file will be written. - * @return information about status of the download - */ - public BoxZipDownloadStatus download(String name, List items, OutputStream output) { - return this.download(name, items, output, null); + URL url = ZIP_URL_TEMPLATE.build(this.getAPI().getBaseURL()); + BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); + request.setBody(requestJSON.toString()); + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + return new BoxZipInfo(responseJSON); } + } - /** - * Creates a zip and downloads its contents its to a given OutputStream. - * - * @param name the name of the zip file to be created - * @param items list of files or folders to be part of the created zip - * @param output the stream to where the zip file will be written. - * @param listener a listener for monitoring the download's progress. - * @return information about status of the download - */ - public BoxZipDownloadStatus download( - String name, List items, OutputStream output, ProgressListener listener - ) { - BoxZipInfo zipInfo = this.create(name, items); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), zipInfo.getDownloadURL(), "GET"); - BoxAPIResponse response = request.send(); - writeStream(response, output, listener); - BoxJSONRequest statusRequest = new BoxJSONRequest(this.getAPI(), zipInfo.getStatusURL(), "GET"); - try (BoxJSONResponse statusResponse = statusRequest.send()) { - JsonObject statusResponseJSON = Json.parse(statusResponse.getJSON()).asObject(); - return new BoxZipDownloadStatus(statusResponseJSON); - } - } + /** + * Creates a zip and downloads it to a given OutputStream. + * + * @param name the name of the zip file to be created + * @param items list of files or folders to be part of the created zip + * @param output the stream to where the zip file will be written. + * @return information about status of the download + */ + public BoxZipDownloadStatus download(String name, List items, OutputStream output) { + return this.download(name, items, output, null); + } - /** - * Gets the API connection used by this resource. - * - * @return the API connection used by this resource. - */ - public BoxAPIConnection getAPI() { - return this.api; + /** + * Creates a zip and downloads its contents its to a given OutputStream. + * + * @param name the name of the zip file to be created + * @param items list of files or folders to be part of the created zip + * @param output the stream to where the zip file will be written. + * @param listener a listener for monitoring the download's progress. + * @return information about status of the download + */ + public BoxZipDownloadStatus download( + String name, List items, OutputStream output, ProgressListener listener) { + BoxZipInfo zipInfo = this.create(name, items); + BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), zipInfo.getDownloadURL(), "GET"); + BoxAPIResponse response = request.send(); + writeStream(response, output, listener); + BoxJSONRequest statusRequest = new BoxJSONRequest(this.getAPI(), zipInfo.getStatusURL(), "GET"); + try (BoxJSONResponse statusResponse = statusRequest.send()) { + JsonObject statusResponseJSON = Json.parse(statusResponse.getJSON()).asObject(); + return new BoxZipDownloadStatus(statusResponseJSON); } + } + + /** + * Gets the API connection used by this resource. + * + * @return the API connection used by this resource. + */ + public BoxAPIConnection getAPI() { + return this.api; + } } diff --git a/src/main/java/com/box/sdk/BoxZipConflict.java b/src/main/java/com/box/sdk/BoxZipConflict.java index fd333b5bf..76e18962e 100644 --- a/src/main/java/com/box/sdk/BoxZipConflict.java +++ b/src/main/java/com/box/sdk/BoxZipConflict.java @@ -6,47 +6,42 @@ import java.util.ArrayList; import java.util.List; -/** - * Represents a conflict that occurs between items that have the same name. - */ +/** Represents a conflict that occurs between items that have the same name. */ public class BoxZipConflict extends BoxJSONObject { - private List items; + private List items; - /** - * Constructs a BoxZipDownloadStatus with default settings. - */ - public BoxZipConflict() { - } + /** Constructs a BoxZipDownloadStatus with default settings. */ + public BoxZipConflict() {} - /** - * Constructs a BoxZipDownloadStatus from a JSON string. - * - * @param json the JSON encoded enterprise. - */ - public BoxZipConflict(String json) { - super(json); - } + /** + * Constructs a BoxZipDownloadStatus from a JSON string. + * + * @param json the JSON encoded enterprise. + */ + public BoxZipConflict(String json) { + super(json); + } - BoxZipConflict(JsonObject jsonObject) { - super(jsonObject); - } + BoxZipConflict(JsonObject jsonObject) { + super(jsonObject); + } - /** - * Gets the items that conflict because they have the same name. - * - * @return the items that conflict because they have the same name. - */ - public List getItems() { - return this.items; - } + /** + * Gets the items that conflict because they have the same name. + * + * @return the items that conflict because they have the same name. + */ + public List getItems() { + return this.items; + } - @Override - void parseJSONMember(JsonObject.Member member) { - JsonArray value = member.getValue().asArray(); - List conflictItems = new ArrayList(value.size()); - for (JsonValue item : value) { - conflictItems.add(new BoxZipConflictItem(item.asObject())); - } - this.items = conflictItems; + @Override + void parseJSONMember(JsonObject.Member member) { + JsonArray value = member.getValue().asArray(); + List conflictItems = new ArrayList(value.size()); + for (JsonValue item : value) { + conflictItems.add(new BoxZipConflictItem(item.asObject())); } + this.items = conflictItems; + } } diff --git a/src/main/java/com/box/sdk/BoxZipConflictItem.java b/src/main/java/com/box/sdk/BoxZipConflictItem.java index a16ee4ae0..2f65d3e8c 100644 --- a/src/main/java/com/box/sdk/BoxZipConflictItem.java +++ b/src/main/java/com/box/sdk/BoxZipConflictItem.java @@ -3,82 +3,77 @@ import com.eclipsesource.json.JsonObject; import com.eclipsesource.json.JsonValue; -/** - * Represents items that have naming conflicts when creating a zip file. - */ +/** Represents items that have naming conflicts when creating a zip file. */ public class BoxZipConflictItem extends BoxJSONObject { - private String id; - private String type; - private String originalName; - private String downloadName; + private String id; + private String type; + private String originalName; + private String downloadName; - /** - * Constructs a BoxZipNameConflict with default settings. - */ - public BoxZipConflictItem() { - } + /** Constructs a BoxZipNameConflict with default settings. */ + public BoxZipConflictItem() {} - /** - * Constructs a BoxZipNameConflict from a JSON string. - * - * @param json the JSON encoded enterprise. - */ - public BoxZipConflictItem(String json) { - super(json); - } + /** + * Constructs a BoxZipNameConflict from a JSON string. + * + * @param json the JSON encoded enterprise. + */ + public BoxZipConflictItem(String json) { + super(json); + } - BoxZipConflictItem(JsonObject jsonObject) { - super(jsonObject); - } + BoxZipConflictItem(JsonObject jsonObject) { + super(jsonObject); + } - /** - * Gets the ID of the item that has the conflict. - * - * @return the ID of the item that has the conflict. - */ - public String getID() { - return this.id; - } + /** + * Gets the ID of the item that has the conflict. + * + * @return the ID of the item that has the conflict. + */ + public String getID() { + return this.id; + } - /** - * Gets the type of the item that has the conflict. - * - * @return the type of the item that has the conflict. - */ - public String getType() { - return this.type; - } + /** + * Gets the type of the item that has the conflict. + * + * @return the type of the item that has the conflict. + */ + public String getType() { + return this.type; + } - /** - * Gets the original name of the item that has the conflict. - * - * @return the original name of the item that has the conflict. - */ - public String getOriginalName() { - return this.originalName; - } + /** + * Gets the original name of the item that has the conflict. + * + * @return the original name of the item that has the conflict. + */ + public String getOriginalName() { + return this.originalName; + } - /** - * Gets the new name of the item when it downloads that resolves the conflict. - * - * @return the new name of the item when it downloads that resolves the conflict. - */ - public String getDownloadName() { - return this.downloadName; - } + /** + * Gets the new name of the item when it downloads that resolves the conflict. + * + * @return the new name of the item when it downloads that resolves the conflict. + */ + public String getDownloadName() { + return this.downloadName; + } - @Override - void parseJSONMember(JsonObject.Member member) { - JsonValue value = member.getValue(); - String memberName = member.getName(); - if (memberName.equals("id")) { - this.id = value.asString(); - } else if (memberName.equals("type")) { - this.type = value.asString(); - } else if (memberName.equals("original_name")) { - this.originalName = value.asString(); - } else if (memberName.equals("download_name")) { - this.downloadName = value.asString(); - } + @Override + void parseJSONMember(JsonObject.Member member) { + JsonValue value = member.getValue(); + String memberName = member.getName(); + if (memberName.equals("id")) { + this.id = value.asString(); + } else if (memberName.equals("type")) { + this.type = value.asString(); + } else if (memberName.equals("original_name")) { + this.originalName = value.asString(); + } else if (memberName.equals("download_name")) { + this.downloadName = value.asString(); } + } } diff --git a/src/main/java/com/box/sdk/BoxZipDownloadStatus.java b/src/main/java/com/box/sdk/BoxZipDownloadStatus.java index f088530d9..3654de763 100644 --- a/src/main/java/com/box/sdk/BoxZipDownloadStatus.java +++ b/src/main/java/com/box/sdk/BoxZipDownloadStatus.java @@ -3,128 +3,115 @@ import com.eclipsesource.json.JsonObject; import com.eclipsesource.json.JsonValue; -/** - * Represents the download status of a zip file. - */ +/** Represents the download status of a zip file. */ public class BoxZipDownloadStatus extends BoxJSONObject { - private int totalFileCount; - private int downloadFileCount; - private int skippedFileCount; - private int skippedFolderCount; - private State state; - - /** - * Constructs a BoxZipDownloadStatus with default settings. - */ - public BoxZipDownloadStatus() { + private int totalFileCount; + private int downloadFileCount; + private int skippedFileCount; + private int skippedFolderCount; + private State state; + + /** Constructs a BoxZipDownloadStatus with default settings. */ + public BoxZipDownloadStatus() {} + + /** + * Constructs a BoxZipDownloadStatus from a JSON string. + * + * @param json the JSON encoded enterprise. + */ + public BoxZipDownloadStatus(String json) { + super(json); + } + + BoxZipDownloadStatus(JsonObject jsonObject) { + super(jsonObject); + } + + /** + * Gets the total number of files in the zip. + * + * @return the total number of files in the zip. + */ + public int getTotalFileCount() { + return this.totalFileCount; + } + + /** + * Gets the number of files in the zip that were downloaded. + * + * @return the number of files in the zip that were downloaded. + */ + public int getDownloadFileCount() { + return this.downloadFileCount; + } + + /** + * Gets the number of files in the zip that were skipped when downloading. + * + * @return the number of files in the zip that were skipped when downloading. + */ + public int getSkippedFileCount() { + return this.skippedFileCount; + } + + /** + * Gets the number of folders in the zip that were skipped when downloading. + * + * @return the number of folder in the zip that were skipped when downloading. + */ + public int getSkippedFolderCount() { + return this.skippedFolderCount; + } + + /** + * Gets the state of the download for the zip file. + * + * @return the state of the download for the zip file + */ + public State getState() { + return this.state; + } + + @Override + void parseJSONMember(JsonObject.Member member) { + JsonValue value = member.getValue(); + String memberName = member.getName(); + if (memberName.equals("total_file_count")) { + this.totalFileCount = value.asInt(); + } else if (memberName.equals("downloaded_file_count")) { + this.downloadFileCount = value.asInt(); + } else if (memberName.equals("skipped_file_count")) { + this.skippedFileCount = value.asInt(); + } else if (memberName.equals("skipped_folder_count")) { + this.skippedFolderCount = value.asInt(); + } else if (memberName.equals("state")) { + this.state = State.fromJSONValue(value.asString()); } + } - /** - * Constructs a BoxZipDownloadStatus from a JSON string. - * - * @param json the JSON encoded enterprise. - */ - public BoxZipDownloadStatus(String json) { - super(json); - } - - BoxZipDownloadStatus(JsonObject jsonObject) { - super(jsonObject); - } - - /** - * Gets the total number of files in the zip. - * - * @return the total number of files in the zip. - */ - public int getTotalFileCount() { - return this.totalFileCount; - } + /** Enumerates the possible download states of a zip. */ + public enum State { + /** Succeeded in downloading. */ + SUCCEEDED("succeeded"), - /** - * Gets the number of files in the zip that were downloaded. - * - * @return the number of files in the zip that were downloaded. - */ - public int getDownloadFileCount() { - return this.downloadFileCount; - } + /** Downloading in progress. */ + IN_PROGRESS("in_progress"), - /** - * Gets the number of files in the zip that were skipped when downloading. - * - * @return the number of files in the zip that were skipped when downloading. - */ - public int getSkippedFileCount() { - return this.skippedFileCount; - } + /** Failed when downloading. */ + FAILED("failed"); - /** - * Gets the number of folders in the zip that were skipped when downloading. - * - * @return the number of folder in the zip that were skipped when downloading. - */ - public int getSkippedFolderCount() { - return this.skippedFolderCount; - } + private final String jsonValue; - /** - * Gets the state of the download for the zip file. - * - * @return the state of the download for the zip file - */ - public State getState() { - return this.state; + State(String jsonValue) { + this.jsonValue = jsonValue; } - @Override - void parseJSONMember(JsonObject.Member member) { - JsonValue value = member.getValue(); - String memberName = member.getName(); - if (memberName.equals("total_file_count")) { - this.totalFileCount = value.asInt(); - } else if (memberName.equals("downloaded_file_count")) { - this.downloadFileCount = value.asInt(); - } else if (memberName.equals("skipped_file_count")) { - this.skippedFileCount = value.asInt(); - } else if (memberName.equals("skipped_folder_count")) { - this.skippedFolderCount = value.asInt(); - } else if (memberName.equals("state")) { - this.state = State.fromJSONValue(value.asString()); - } + static State fromJSONValue(String jsonValue) { + return State.valueOf(jsonValue.toUpperCase(java.util.Locale.ROOT)); } - /** - * Enumerates the possible download states of a zip. - */ - public enum State { - /** - * Succeeded in downloading. - */ - SUCCEEDED("succeeded"), - - /** - * Downloading in progress. - */ - IN_PROGRESS("in_progress"), - - /** - * Failed when downloading. - */ - FAILED("failed"); - - private final String jsonValue; - - State(String jsonValue) { - this.jsonValue = jsonValue; - } - - static State fromJSONValue(String jsonValue) { - return State.valueOf(jsonValue.toUpperCase(java.util.Locale.ROOT)); - } - - String toJSONValue() { - return this.jsonValue; - } + String toJSONValue() { + return this.jsonValue; } + } } diff --git a/src/main/java/com/box/sdk/BoxZipInfo.java b/src/main/java/com/box/sdk/BoxZipInfo.java index e3309ae62..003a1e322 100644 --- a/src/main/java/com/box/sdk/BoxZipInfo.java +++ b/src/main/java/com/box/sdk/BoxZipInfo.java @@ -9,107 +9,104 @@ import java.util.Date; import java.util.List; -/** - * Represents items that have naming conflicts when creating a zip file. - */ +/** Represents items that have naming conflicts when creating a zip file. */ public class BoxZipInfo extends BoxJSONObject { - private URL downloadURL; - private URL statusURL; - private Date expiresAt; - private List nameConflicts; + private URL downloadURL; + private URL statusURL; + private Date expiresAt; + private List nameConflicts; - /** - * Constructs a BoxZipDownloadStatus with default settings. - */ - public BoxZipInfo() { - } + /** Constructs a BoxZipDownloadStatus with default settings. */ + public BoxZipInfo() {} - /** - * Constructs a BoxZipDownloadStatus from a JSON string. - * - * @param json the JSON encoded enterprise. - */ - public BoxZipInfo(String json) { - super(json); - } + /** + * Constructs a BoxZipDownloadStatus from a JSON string. + * + * @param json the JSON encoded enterprise. + */ + public BoxZipInfo(String json) { + super(json); + } - BoxZipInfo(JsonObject jsonObject) { - super(jsonObject); - } + BoxZipInfo(JsonObject jsonObject) { + super(jsonObject); + } - /** - * Gets the ID of the item that has the conflict. - * - * @return the ID of the item that has the conflict. - */ - public URL getDownloadURL() { - return this.downloadURL; - } + /** + * Gets the ID of the item that has the conflict. + * + * @return the ID of the item that has the conflict. + */ + public URL getDownloadURL() { + return this.downloadURL; + } - /** - * Gets the type of the item that has the conflict. - * - * @return the type of the item that has the conflict. - */ - public URL getStatusURL() { - return this.statusURL; - } + /** + * Gets the type of the item that has the conflict. + * + * @return the type of the item that has the conflict. + */ + public URL getStatusURL() { + return this.statusURL; + } - /** - * Gets the original name of the item that has the conflict. - * - * @return the original name of the item that has the conflict. - */ - public Date getExpiresAt() { - return this.expiresAt; - } + /** + * Gets the original name of the item that has the conflict. + * + * @return the original name of the item that has the conflict. + */ + public Date getExpiresAt() { + return this.expiresAt; + } - /** - * Gets the new name of the item when it downloads that resolves the conflict. - * - * @return the new name of the item when it downloads that resolves the conflict. - */ - public List getNameConflicts() { - return this.nameConflicts; - } + /** + * Gets the new name of the item when it downloads that resolves the conflict. + * + * @return the new name of the item when it downloads that resolves the conflict. + */ + public List getNameConflicts() { + return this.nameConflicts; + } - @Override - void parseJSONMember(JsonObject.Member member) { - JsonValue value = member.getValue(); - String memberName = member.getName(); + @Override + void parseJSONMember(JsonObject.Member member) { + JsonValue value = member.getValue(); + String memberName = member.getName(); + try { + if (memberName.equals("download_url")) { try { - if (memberName.equals("download_url")) { - try { - String urlString = value.asString(); - this.downloadURL = new URL(urlString); - } catch (MalformedURLException e) { - throw new BoxAPIException("Couldn't parse download url for zip", e); - } - } else if (memberName.equals("status_url")) { - try { - String urlString = value.asString(); - this.statusURL = new URL(urlString); - } catch (MalformedURLException e) { - throw new BoxAPIException("Couldn't parse status url for zip", e); - } - } else if (memberName.equals("expires_at")) { - this.expiresAt = BoxDateFormat.parse(value.asString()); - } else if (memberName.equals("name_conflicts")) { - this.nameConflicts = this.parseNameConflicts(value.asArray()); - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); + String urlString = value.asString(); + this.downloadURL = new URL(urlString); + } catch (MalformedURLException e) { + throw new BoxAPIException("Couldn't parse download url for zip", e); } + } else if (memberName.equals("status_url")) { + try { + String urlString = value.asString(); + this.statusURL = new URL(urlString); + } catch (MalformedURLException e) { + throw new BoxAPIException("Couldn't parse status url for zip", e); + } + } else if (memberName.equals("expires_at")) { + this.expiresAt = BoxDateFormat.parse(value.asString()); + } else if (memberName.equals("name_conflicts")) { + this.nameConflicts = this.parseNameConflicts(value.asArray()); + } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); } + } - private List parseNameConflicts(JsonArray jsonArray) { - List nameConflicts = new ArrayList(jsonArray.size()); - for (JsonValue conflict : jsonArray) { - // We create a "conflictObj" with the arbitrary key name "conflict" in order to allow BoxZipConflict - // to later parse the object to create `List items` (since it can't take in an array) - JsonObject conflictObj = new JsonObject().add("conflict", conflict); - nameConflicts.add(new BoxZipConflict(conflictObj)); - } - return nameConflicts; + private List parseNameConflicts(JsonArray jsonArray) { + List nameConflicts = new ArrayList(jsonArray.size()); + for (JsonValue conflict : jsonArray) { + // We create a "conflictObj" with the arbitrary key name "conflict" in order to allow + // BoxZipConflict + // to later parse the object to create `List items` (since it can't take + // in an array) + JsonObject conflictObj = new JsonObject().add("conflict", conflict); + nameConflicts.add(new BoxZipConflict(conflictObj)); } + return nameConflicts; + } } diff --git a/src/main/java/com/box/sdk/BoxZipItem.java b/src/main/java/com/box/sdk/BoxZipItem.java index b46ffa34b..b3fec1d33 100644 --- a/src/main/java/com/box/sdk/BoxZipItem.java +++ b/src/main/java/com/box/sdk/BoxZipItem.java @@ -2,53 +2,48 @@ import com.eclipsesource.json.JsonObject; -/** - * Represents a Box item to be included when creating a zip file. - */ +/** Represents a Box item to be included when creating a zip file. */ public class BoxZipItem { - private String type; - private String id; + private String type; + private String id; - /** - * Constructs a base BoxZipItem object. - * - * @param type item type, "file" or "folder". - * @param id id of the the item. - */ - public BoxZipItem(String type, String id) { - super(); - this.type = type; - this.id = id; - } + /** + * Constructs a base BoxZipItem object. + * + * @param type item type, "file" or "folder". + * @param id id of the the item. + */ + public BoxZipItem(String type, String id) { + super(); + this.type = type; + this.id = id; + } - /** - * Gets the item type. - * - * @return the type of the zip item. - */ - public String getType() { - return this.type; - } + /** + * Gets the item type. + * + * @return the type of the zip item. + */ + public String getType() { + return this.type; + } - /** - * Gets the item ID. - * - * @return the ID fo the zip item. - */ - public String getID() { - return this.id; - } - - /** - * Gets a JSON object reprsenting this class. - * - * @return the JSON object reprsenting this class. - */ - public JsonObject getJSONObject() { - JsonObject jsonObj = new JsonObject() - .add("type", this.type) - .add("id", this.id); - return jsonObj; - } + /** + * Gets the item ID. + * + * @return the ID fo the zip item. + */ + public String getID() { + return this.id; + } + /** + * Gets a JSON object reprsenting this class. + * + * @return the JSON object reprsenting this class. + */ + public JsonObject getJSONObject() { + JsonObject jsonObj = new JsonObject().add("type", this.type).add("id", this.id); + return jsonObj; + } } diff --git a/src/main/java/com/box/sdk/CreateUserParams.java b/src/main/java/com/box/sdk/CreateUserParams.java index a2f75f3d8..1f9810329 100644 --- a/src/main/java/com/box/sdk/CreateUserParams.java +++ b/src/main/java/com/box/sdk/CreateUserParams.java @@ -3,367 +3,373 @@ import java.util.HashMap; import java.util.Map; -/** - * Contains optional parameters for creating a new enterprise user on Box. - */ +/** 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 BoxUser.Role role; - private BoxUser.Status status; - private Long spaceAmount; - private String address; - private String jobTitle; - private String language; - private String phone; - private String timezone; - private String externalAppUserId; - private Map trackingCodes; - - /** - * Gets whether or not the new user will be able to see other enterprise users in their contact list. - * - * @return true if the new user will be able to see other enterprise users in their contact list; otherwise false. - */ - public Boolean getCanSeeManagedUsers() { - return this.canSeeManagedUsers; - } - - /** - * Sets whether or not the new user will be able to see other enterprise users in their contact list. - * - * @param canSeeManagedUsers whether or not the new user will be able to see other enterprise users in their - * contact list. - * @return this CreateUserParams object for chaining. - */ - public CreateUserParams setCanSeeManagedUsers(boolean canSeeManagedUsers) { - this.canSeeManagedUsers = canSeeManagedUsers; - return this; - } - - /** - * Gets whether or not the new user will be exempt from Enterprise device limits. - * - * @return true if the new user will be exempt from Enterprise device limits; otherwise false. - */ - public Boolean getIsExemptFromDeviceLimits() { - return this.isExemptFromDeviceLimits; - } - - /** - * Sets whether or not the new user will be exempt from Enterprise device limits. - * - * @param isExemptFromDeviceLimits whether or not the new user will be exempt from Enterprise device limits. - * @return this CreateUserParams object for chaining. - */ - public CreateUserParams setIsExemptFromDeviceLimits(boolean isExemptFromDeviceLimits) { - this.isExemptFromDeviceLimits = isExemptFromDeviceLimits; - return this; - } - - /** - * Gets whether or not the new user will be required to use two-factor authentication. - * - * @return true if the new user will be required to use two-factor authentication; otherwise false. - */ - public Boolean getIsExemptFromLoginVerification() { - return this.isExemptFromLoginVerification; - } - - /** - * Sets whether or not the new user will be required to use two-factor authentication. - * - * @param isExemptFromLoginVerification whether or not the new user will be required to use two-factor - * authentication. - * @return this CreateUserParams object for chaining. - */ - public CreateUserParams setIsExemptFromLoginVerification(boolean isExemptFromLoginVerification) { - this.isExemptFromLoginVerification = isExemptFromLoginVerification; - return this; - } - - /** - * Gets whether or not the user we are creating is an app user with Box Developer Edition. - * - * @return true if the new user is an app user for Box Developer Addition; otherwise false. - */ - public Boolean getIsPlatformAccessOnly() { - return this.isPlatformAccessOnly; - } - - /** - * Sets whether or not the user we are creating is an app user with Box Developer Edition. - * - * @param isPlatformAccessOnly whether or not the user we are creating is an app user with Box Developer - * Edition. - * @return this CreateUserParams object for chaining. - */ - public CreateUserParams setIsPlatformAccessOnly(boolean isPlatformAccessOnly) { - this.isPlatformAccessOnly = isPlatformAccessOnly; - return this; - } - - /** - * Gets whether or not the new user will be able to use Box Sync. - * - * @return true if the new user will be able to use Box Sync; otherwise false. - */ - public Boolean getIsSyncEnabled() { - return this.isSyncEnabled; - } - - /** - * Sets whether or not the new user will be able to use Box Sync. - * - * @param isSyncEnabled whether or not the new user will be able to use Box Sync. - * @return this CreateUserParams object for chaining. - */ - public CreateUserParams setIsSyncEnabled(boolean isSyncEnabled) { - this.isSyncEnabled = isSyncEnabled; - return this; - } - - /** - * Gets what the new user's enterprise role will be. - * - * @return what the new user's enterprise role will be. - */ - public BoxUser.Role getRole() { - return this.role; - } - - /** - * Sets what the new user's enterprise role will be. - * - * @param role what the new user's enterprise role will be. - * @return this CreateUserParams object for chaining. - */ - public CreateUserParams setRole(BoxUser.Role role) { - this.role = role; - return this; - } - - /** - * Gets what the new user's account status will be. - * - * @return what the new user's account status will be. - */ - public BoxUser.Status getStatus() { - return this.status; - } - - /** - * Sets what the new user's account status will be. - * - * @param status what the new user's account status will be. - * @return this CreateUserParams object for chaining. - */ - public CreateUserParams setStatus(BoxUser.Status status) { - this.status = status; - return this; - } - - /** - * Gets what the new user's total available space will be in bytes. - * - * @return what the new user's total available space will be in bytes. - */ - public Long getSpaceAmount() { - return this.spaceAmount; - } - - /** - * Sets what the new user's total available space will be in bytes. - * - * @param spaceAmount what the new user's total available space will be in bytes. - * @return this CreateUserParams object for chaining. - */ - public CreateUserParams setSpaceAmount(long spaceAmount) { - this.spaceAmount = spaceAmount; - return this; - } - - /** - * Gets what the address of the new user will be. - * - * @return what the address of the new user will be. - */ - public String getAddress() { - return this.address; - } - - /** - * Sets what the address of the new user will be. - * - * @param address what the address of the new user will be. - * @return this CreateUserParams object for chaining. - */ - public CreateUserParams setAddress(String address) { - this.address = address; - return this; - } - - /** - * Gets what the job title of the new user will be. - * - * @return what the job title of the new user will be. - */ - public String getJobTitle() { - return this.jobTitle; - } - - /** - * Sets what the job title of the new user will be. - * - * @param jobTitle what the job title of the new user will be. - * @return this CreateUserParams object for chaining. - */ - public CreateUserParams setJobTitle(String jobTitle) { - this.jobTitle = jobTitle; - return this; - } - - /** - * Gets what the language of the new user will be. - * - * @return what the language of the new user will be. - */ - public String getLanguage() { - return this.language; - } - - /** - * Sets what the language of the new user will be. - * - * @param language what the language of the new user will be. - * @return this CreateUserParams object for chaining. - */ - public CreateUserParams setLanguage(String language) { - this.language = language; - return this; - } - - /** - * Gets what the phone number of the new user will be. - * - * @return what the phone number of the new user will be. - */ - public String getPhone() { - return this.phone; - } - - /** - * Sets what the phone number of the new user will be. - * - * @param phone what the phone number of the new user will be. - * @return this CreateUserParams object for chaining. - */ - public CreateUserParams setPhone(String phone) { - this.phone = phone; - return this; - } - - /** - * Gets what the timezone of the new user will be. - * - * @return what the timezone of the new user will be. - */ - public String getTimezone() { - return this.timezone; - } - - /** - * Sets what the timezone of the new user will be. - * - * @param timezone what the timezone of the new user will be. - * @return this CreateUserParams object for chaining. - */ - public CreateUserParams setTimezone(String timezone) { - this.timezone = timezone; - return this; - } - - /** - * Gets the external app user id that has been set for the app user. - * - * @return the external app user id. - */ - public String getExternalAppUserId() { - return this.externalAppUserId; - } - - /** - * Sets the external app user id. - * - * @param externalAppUserId external app user id. - * @return this CreateUserParams object for chaining. - */ - public CreateUserParams setExternalAppUserId(String externalAppUserId) { - this.externalAppUserId = externalAppUserId; - return this; - } - - /** - * Gets whether this user is allowed or not to collaborate with users outside their enterprise. - * - * @return true if the user is not able to collaborate with users outside their enterpise; otherwise false. - */ - public Boolean getIsExternalCollabRestricted() { - return this.isExternalCollabRestricted; - } - - /** - * Sets whether this user is allowed or not to collaborate with users outside their enterprise. - * - * @param isExternalCollabRestricted whether the user is allowed to collaborate with users outside their enterprise. - * @return this CreateUserParams object for chaining. - */ - public CreateUserParams setIsExternalCollabRestricted(boolean isExternalCollabRestricted) { - this.isExternalCollabRestricted = isExternalCollabRestricted; - return this; - } - - /** - * Gets 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. - * - * @return map of tracking codes. - */ - public Map getTrackingCodes() { - return this.trackingCodes; - } - - /** - * Sets 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 trackingCodes map of tracking codes. - * @return this CreateUserParams object for chaining. - */ - 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; - } + 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 String address; + private String jobTitle; + private String language; + private String phone; + private String timezone; + private String externalAppUserId; + private Map trackingCodes; + + /** + * Gets whether or not the new user will be able to see other enterprise users in their contact + * list. + * + * @return true if the new user will be able to see other enterprise users in their contact list; + * otherwise false. + */ + public Boolean getCanSeeManagedUsers() { + return this.canSeeManagedUsers; + } + + /** + * Sets whether or not the new user will be able to see other enterprise users in their contact + * list. + * + * @param canSeeManagedUsers whether or not the new user will be able to see other enterprise + * users in their contact list. + * @return this CreateUserParams object for chaining. + */ + public CreateUserParams setCanSeeManagedUsers(boolean canSeeManagedUsers) { + this.canSeeManagedUsers = canSeeManagedUsers; + return this; + } + + /** + * Gets whether or not the new user will be exempt from Enterprise device limits. + * + * @return true if the new user will be exempt from Enterprise device limits; otherwise false. + */ + public Boolean getIsExemptFromDeviceLimits() { + return this.isExemptFromDeviceLimits; + } + + /** + * Sets whether or not the new user will be exempt from Enterprise device limits. + * + * @param isExemptFromDeviceLimits whether or not the new user will be exempt from Enterprise + * device limits. + * @return this CreateUserParams object for chaining. + */ + public CreateUserParams setIsExemptFromDeviceLimits(boolean isExemptFromDeviceLimits) { + this.isExemptFromDeviceLimits = isExemptFromDeviceLimits; + return this; + } + + /** + * Gets whether or not the new user will be required to use two-factor authentication. + * + * @return true if the new user will be required to use two-factor authentication; otherwise + * false. + */ + public Boolean getIsExemptFromLoginVerification() { + return this.isExemptFromLoginVerification; + } + + /** + * Sets whether or not the new user will be required to use two-factor authentication. + * + * @param isExemptFromLoginVerification whether or not the new user will be required to use + * two-factor authentication. + * @return this CreateUserParams object for chaining. + */ + public CreateUserParams setIsExemptFromLoginVerification(boolean isExemptFromLoginVerification) { + this.isExemptFromLoginVerification = isExemptFromLoginVerification; + return this; + } + + /** + * Gets whether or not the user we are creating is an app user with Box Developer Edition. + * + * @return true if the new user is an app user for Box Developer Addition; otherwise false. + */ + public Boolean getIsPlatformAccessOnly() { + return this.isPlatformAccessOnly; + } + + /** + * Sets whether or not the user we are creating is an app user with Box Developer Edition. + * + * @param isPlatformAccessOnly whether or not the user we are creating is an app user with Box + * Developer Edition. + * @return this CreateUserParams object for chaining. + */ + public CreateUserParams setIsPlatformAccessOnly(boolean isPlatformAccessOnly) { + this.isPlatformAccessOnly = isPlatformAccessOnly; + return this; + } + + /** + * Gets whether or not the new user will be able to use Box Sync. + * + * @return true if the new user will be able to use Box Sync; otherwise false. + */ + public Boolean getIsSyncEnabled() { + return this.isSyncEnabled; + } + + /** + * Sets whether or not the new user will be able to use Box Sync. + * + * @param isSyncEnabled whether or not the new user will be able to use Box Sync. + * @return this CreateUserParams object for chaining. + */ + public CreateUserParams setIsSyncEnabled(boolean isSyncEnabled) { + this.isSyncEnabled = isSyncEnabled; + return this; + } + + /** + * Gets what the new user's enterprise role will be. + * + * @return what the new user's enterprise role will be. + */ + public BoxUser.Role getRole() { + return this.role; + } + + /** + * Sets what the new user's enterprise role will be. + * + * @param role what the new user's enterprise role will be. + * @return this CreateUserParams object for chaining. + */ + public CreateUserParams setRole(BoxUser.Role role) { + this.role = role; + return this; + } + + /** + * Gets what the new user's account status will be. + * + * @return what the new user's account status will be. + */ + public BoxUser.Status getStatus() { + return this.status; + } + + /** + * Sets what the new user's account status will be. + * + * @param status what the new user's account status will be. + * @return this CreateUserParams object for chaining. + */ + public CreateUserParams setStatus(BoxUser.Status status) { + this.status = status; + return this; + } + + /** + * Gets what the new user's total available space will be in bytes. + * + * @return what the new user's total available space will be in bytes. + */ + public Long getSpaceAmount() { + return this.spaceAmount; + } + + /** + * Sets what the new user's total available space will be in bytes. + * + * @param spaceAmount what the new user's total available space will be in bytes. + * @return this CreateUserParams object for chaining. + */ + public CreateUserParams setSpaceAmount(long spaceAmount) { + this.spaceAmount = spaceAmount; + return this; + } + + /** + * Gets what the address of the new user will be. + * + * @return what the address of the new user will be. + */ + public String getAddress() { + return this.address; + } + + /** + * Sets what the address of the new user will be. + * + * @param address what the address of the new user will be. + * @return this CreateUserParams object for chaining. + */ + public CreateUserParams setAddress(String address) { + this.address = address; + return this; + } + + /** + * Gets what the job title of the new user will be. + * + * @return what the job title of the new user will be. + */ + public String getJobTitle() { + return this.jobTitle; + } + + /** + * Sets what the job title of the new user will be. + * + * @param jobTitle what the job title of the new user will be. + * @return this CreateUserParams object for chaining. + */ + public CreateUserParams setJobTitle(String jobTitle) { + this.jobTitle = jobTitle; + return this; + } + + /** + * Gets what the language of the new user will be. + * + * @return what the language of the new user will be. + */ + public String getLanguage() { + return this.language; + } + + /** + * Sets what the language of the new user will be. + * + * @param language what the language of the new user will be. + * @return this CreateUserParams object for chaining. + */ + public CreateUserParams setLanguage(String language) { + this.language = language; + return this; + } + + /** + * Gets what the phone number of the new user will be. + * + * @return what the phone number of the new user will be. + */ + public String getPhone() { + return this.phone; + } + + /** + * Sets what the phone number of the new user will be. + * + * @param phone what the phone number of the new user will be. + * @return this CreateUserParams object for chaining. + */ + public CreateUserParams setPhone(String phone) { + this.phone = phone; + return this; + } + + /** + * Gets what the timezone of the new user will be. + * + * @return what the timezone of the new user will be. + */ + public String getTimezone() { + return this.timezone; + } + + /** + * Sets what the timezone of the new user will be. + * + * @param timezone what the timezone of the new user will be. + * @return this CreateUserParams object for chaining. + */ + public CreateUserParams setTimezone(String timezone) { + this.timezone = timezone; + return this; + } + + /** + * Gets the external app user id that has been set for the app user. + * + * @return the external app user id. + */ + public String getExternalAppUserId() { + return this.externalAppUserId; + } + + /** + * Sets the external app user id. + * + * @param externalAppUserId external app user id. + * @return this CreateUserParams object for chaining. + */ + public CreateUserParams setExternalAppUserId(String externalAppUserId) { + this.externalAppUserId = externalAppUserId; + return this; + } + + /** + * Gets whether this user is allowed or not to collaborate with users outside their enterprise. + * + * @return true if the user is not able to collaborate with users outside their enterpise; + * otherwise false. + */ + public Boolean getIsExternalCollabRestricted() { + return this.isExternalCollabRestricted; + } + + /** + * Sets whether this user is allowed or not to collaborate with users outside their enterprise. + * + * @param isExternalCollabRestricted whether the user is allowed to collaborate with users outside + * their enterprise. + * @return this CreateUserParams object for chaining. + */ + public CreateUserParams setIsExternalCollabRestricted(boolean isExternalCollabRestricted) { + this.isExternalCollabRestricted = isExternalCollabRestricted; + return this; + } + + /** + * Gets 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. + * + * @return map of tracking codes. + */ + public Map getTrackingCodes() { + return this.trackingCodes; + } + + /** + * Sets 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 trackingCodes map of tracking codes. + * @return this CreateUserParams object for chaining. + */ + 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/DateRange.java b/src/main/java/com/box/sdk/DateRange.java index 158feedc7..29355cb84 100644 --- a/src/main/java/com/box/sdk/DateRange.java +++ b/src/main/java/com/box/sdk/DateRange.java @@ -2,75 +2,72 @@ import java.util.Date; -/** - * Class is used to be a range for two dates. Ususally paired with varying search filters. - */ +/** Class is used to be a range for two dates. Ususally paired with varying search filters. */ public class DateRange { - private Date from; - private Date to; + private Date from; + private Date to; - /** - * Used for specify a date range to filter to be used in search. - * - * @param from is the start date in a range. - * @param to is the end date in a range. - */ - public DateRange(Date from, Date to) { - this.from = from; - this.to = to; - } - - /** - * Returns the from date which is the start date. - * - * @return Date this is start date. - */ - public Date getFromDate() { - return this.from; - } + /** + * Used for specify a date range to filter to be used in search. + * + * @param from is the start date in a range. + * @param to is the end date in a range. + */ + public DateRange(Date from, Date to) { + this.from = from; + this.to = to; + } - /** - * Set the from date which is equivalent to the start date. - * - * @param from date which is the starting point. - */ - public void setFrom(Date from) { - this.from = from; - } + /** + * Returns the from date which is the start date. + * + * @return Date this is start date. + */ + public Date getFromDate() { + return this.from; + } - /** - * Returns the to date which is the end date. - * - * @return Date this is the end date. - */ - public Date getToDate() { - return this.to; - } + /** + * Set the from date which is equivalent to the start date. + * + * @param from date which is the starting point. + */ + public void setFrom(Date from) { + this.from = from; + } - /** - * Set the to date which is equivalent to the start date. - * - * @param to date which is the end point. - */ - public void setTo(Date to) { - this.to = to; - } + /** + * Returns the to date which is the end date. + * + * @return Date this is the end date. + */ + public Date getToDate() { + return this.to; + } - /** - * Used to build out a string a http box api friendly range string. - * - * @return String that is uses as a rest parameter. - */ - public String buildRangeString() { + /** + * Set the to date which is equivalent to the start date. + * + * @param to date which is the end point. + */ + public void setTo(Date to) { + this.to = to; + } - String fromString = BoxDateFormat.format(this.from); - String toString = BoxDateFormat.format(this.to); + /** + * Used to build out a string a http box api friendly range string. + * + * @return String that is uses as a rest parameter. + */ + public String buildRangeString() { + String fromString = BoxDateFormat.format(this.from); + String toString = BoxDateFormat.format(this.to); - String rangeString = String.format("%s,%s", fromString, toString); - if (rangeString == ",") { - rangeString = null; - } - return rangeString; + String rangeString = String.format("%s,%s", fromString, toString); + if (rangeString == ",") { + rangeString = null; } + return rangeString; + } } diff --git a/src/main/java/com/box/sdk/DeveloperEditionEntityType.java b/src/main/java/com/box/sdk/DeveloperEditionEntityType.java index f6e7489b3..bba536131 100644 --- a/src/main/java/com/box/sdk/DeveloperEditionEntityType.java +++ b/src/main/java/com/box/sdk/DeveloperEditionEntityType.java @@ -1,36 +1,28 @@ package com.box.sdk; -/** - * Enum to represent the JWT entity type for BoxDeveloperEditionAPIConnection. - */ +/** Enum to represent the JWT entity type for BoxDeveloperEditionAPIConnection. */ public enum DeveloperEditionEntityType { - /** - * Represents the entity type enterprise. - */ - ENTERPRISE("enterprise"), + /** Represents the entity type enterprise. */ + ENTERPRISE("enterprise"), - /** - * Represents the entity type user. - */ - USER("user"); + /** Represents the entity type user. */ + USER("user"); - private final String value; + private final String value; - /** - * @param value - */ - DeveloperEditionEntityType(String value) { - this.value = value; - } + /** @param value */ + DeveloperEditionEntityType(String value) { + this.value = value; + } - /** - * To get the string value for the enum type. - * - * @return The string value for the enum type - */ - @Override - public String toString() { - return this.value; - } + /** + * To get the string value for the enum type. + * + * @return The string value for the enum type + */ + @Override + public String toString() { + return this.value; + } } diff --git a/src/main/java/com/box/sdk/EmailAlias.java b/src/main/java/com/box/sdk/EmailAlias.java index c61c4b119..a26d322b1 100644 --- a/src/main/java/com/box/sdk/EmailAlias.java +++ b/src/main/java/com/box/sdk/EmailAlias.java @@ -3,74 +3,69 @@ import com.eclipsesource.json.JsonObject; import com.eclipsesource.json.JsonValue; -/** - * Represents a Box user's email alias. - */ +/** Represents a Box user's email alias. */ public class EmailAlias extends BoxJSONObject { - private String id; - private boolean isConfirmed; - private String email; + private String id; + private boolean isConfirmed; + private String email; - /** - * Constructs an empty EmailAlias. - */ - public EmailAlias() { - } + /** Constructs an empty EmailAlias. */ + public EmailAlias() {} - /** - * Constructs an EmailAlias from a JSON string. - * - * @param json the json encoded email alias. - */ - public EmailAlias(String json) { - super(json); - } + /** + * Constructs an EmailAlias from a JSON string. + * + * @param json the json encoded email alias. + */ + public EmailAlias(String json) { + super(json); + } - EmailAlias(JsonObject jsonObject) { - super(jsonObject); - } + EmailAlias(JsonObject jsonObject) { + super(jsonObject); + } - /** - * Gets the ID of this email alias. - * - * @return the ID of this email alias. - */ - public String getID() { - return this.id; - } + /** + * Gets the ID of this email alias. + * + * @return the ID of this email alias. + */ + public String getID() { + return this.id; + } - /** - * Gets whether or not the user has confirmed this email alias. - * - * @return true if the user has confirmed this email alias; otherwise false. - */ - public boolean getIsConfirmed() { - return this.isConfirmed; - } + /** + * Gets whether or not the user has confirmed this email alias. + * + * @return true if the user has confirmed this email alias; otherwise false. + */ + public boolean getIsConfirmed() { + return this.isConfirmed; + } - /** - * Gets the email address of this email alias. - * - * @return the email address of this email alias. - */ - public String getEmail() { - return this.email; - } + /** + * Gets the email address of this email alias. + * + * @return the email address of this email alias. + */ + public String getEmail() { + return this.email; + } - @Override - void parseJSONMember(JsonObject.Member member) { - JsonValue value = member.getValue(); - String memberName = member.getName(); - try { - if (memberName.equals("id")) { - this.id = value.asString(); - } else if (memberName.equals("is_confirmed")) { - this.isConfirmed = value.asBoolean(); - } else if (memberName.equals("email")) { - this.email = value.asString(); - } - } catch (Exception e) { - throw new BoxDeserializationException(memberName, value.toString(), e); - } + @Override + void parseJSONMember(JsonObject.Member member) { + JsonValue value = member.getValue(); + String memberName = member.getName(); + try { + if (memberName.equals("id")) { + this.id = value.asString(); + } else if (memberName.equals("is_confirmed")) { + this.isConfirmed = value.asBoolean(); + } else if (memberName.equals("email")) { + this.email = value.asString(); + } + } catch (Exception e) { + throw new BoxDeserializationException(memberName, value.toString(), e); } + } } diff --git a/src/main/java/com/box/sdk/EncryptionAlgorithm.java b/src/main/java/com/box/sdk/EncryptionAlgorithm.java index be66ccd52..840aba682 100644 --- a/src/main/java/com/box/sdk/EncryptionAlgorithm.java +++ b/src/main/java/com/box/sdk/EncryptionAlgorithm.java @@ -1,22 +1,14 @@ package com.box.sdk; -/** - * Enum to identify algorithm for JWT. - */ +/** Enum to identify algorithm for JWT. */ public enum EncryptionAlgorithm { - /** - * RSA with SHA 256. - */ - RSA_SHA_256, + /** RSA with SHA 256. */ + RSA_SHA_256, - /** - * RSA with SHA 384. - */ - RSA_SHA_384, + /** RSA with SHA 384. */ + RSA_SHA_384, - /** - * RSA with SHA 512. - */ - RSA_SHA_512; + /** RSA with SHA 512. */ + RSA_SHA_512; } diff --git a/src/main/java/com/box/sdk/EnterpriseEventsRequest.java b/src/main/java/com/box/sdk/EnterpriseEventsRequest.java index 521b501cf..215b144be 100644 --- a/src/main/java/com/box/sdk/EnterpriseEventsRequest.java +++ b/src/main/java/com/box/sdk/EnterpriseEventsRequest.java @@ -9,105 +9,107 @@ import java.util.Date; /** - * Class describing request to get Admin Logs. You can use it's fluent interface to create new request like so: - *
- * {@code
+ * Class describing request to get Admin Logs. You can use it's fluent interface to create new
+ * request like so:
+ *
+ * 
{@code
  * new EnterpriseEventsRequest().position("stream_position").limit(50);
- * }
- * 
+ * }
*/ public final class EnterpriseEventsRequest { - private static final String ADMIN_LOGS_STREAM_TYPE = "admin_logs"; - private Date before; - private Date after; - private String position; - private int limit = ENTERPRISE_LIMIT; - private Collection types = new ArrayList<>(); - - /** - * The lower bound on the timestamp of the events returned. - * @param date the lower bound on the timestamp of the events returned. - * @return request being created. - */ - public EnterpriseEventsRequest after(Date date) { - this.after = date; - return this; - } - - /** - * The upper bound on the timestamp of the events returned. - * @param date the upper bound on the timestamp of the events returned. - * @return request being created. - */ - public EnterpriseEventsRequest before(Date date) { - this.before = date; - return this; - } - - /** - * The starting position of the event stream. - * @param position the starting position of the event stream. - * @return request being created. - */ - public EnterpriseEventsRequest position(String position) { - this.position = position; - return this; - } - - /** - * The number of entries to be returned in the response. - * @param limit the number of entries to be returned in the response. - * @return request being created. - */ - public EnterpriseEventsRequest limit(int limit) { - this.limit = limit; - return this; - } - - /** - * List of event types to filter by. - * @param types list of event types to filter by. - * @return request being created. - */ - public EnterpriseEventsRequest types(EventType... types) { - return typeNames(Arrays.stream(types) - .map(EventType::toJSONString) - .toArray(String[]::new) - ); - } - - /** - * List of event type names to filter by. - * @param typeNames list of event type names to filter by. - * @return request being created. - */ - public EnterpriseEventsRequest typeNames(String... typeNames) { - this.types = Arrays.asList(typeNames); - return this; - } - - Date getAfter() { - return after; - } - - Date getBefore() { - return before; - } - - String getPosition() { - return position; - } - - int getLimit() { - return limit; - } - - - Collection getTypes() { - return types; - } - - String getStreamType() { - return ADMIN_LOGS_STREAM_TYPE; - } + private static final String ADMIN_LOGS_STREAM_TYPE = "admin_logs"; + private Date before; + private Date after; + private String position; + private int limit = ENTERPRISE_LIMIT; + private Collection types = new ArrayList<>(); + + /** + * The lower bound on the timestamp of the events returned. + * + * @param date the lower bound on the timestamp of the events returned. + * @return request being created. + */ + public EnterpriseEventsRequest after(Date date) { + this.after = date; + return this; + } + + /** + * The upper bound on the timestamp of the events returned. + * + * @param date the upper bound on the timestamp of the events returned. + * @return request being created. + */ + public EnterpriseEventsRequest before(Date date) { + this.before = date; + return this; + } + + /** + * The starting position of the event stream. + * + * @param position the starting position of the event stream. + * @return request being created. + */ + public EnterpriseEventsRequest position(String position) { + this.position = position; + return this; + } + + /** + * The number of entries to be returned in the response. + * + * @param limit the number of entries to be returned in the response. + * @return request being created. + */ + public EnterpriseEventsRequest limit(int limit) { + this.limit = limit; + return this; + } + + /** + * List of event types to filter by. + * + * @param types list of event types to filter by. + * @return request being created. + */ + public EnterpriseEventsRequest types(EventType... types) { + return typeNames(Arrays.stream(types).map(EventType::toJSONString).toArray(String[]::new)); + } + + /** + * List of event type names to filter by. + * + * @param typeNames list of event type names to filter by. + * @return request being created. + */ + public EnterpriseEventsRequest typeNames(String... typeNames) { + this.types = Arrays.asList(typeNames); + return this; + } + + Date getAfter() { + return after; + } + + Date getBefore() { + return before; + } + + String getPosition() { + return position; + } + + int getLimit() { + return limit; + } + + Collection getTypes() { + return types; + } + + String getStreamType() { + return ADMIN_LOGS_STREAM_TYPE; + } } diff --git a/src/main/java/com/box/sdk/EnterpriseEventsStreamRequest.java b/src/main/java/com/box/sdk/EnterpriseEventsStreamRequest.java index fce19942f..b8896537c 100644 --- a/src/main/java/com/box/sdk/EnterpriseEventsStreamRequest.java +++ b/src/main/java/com/box/sdk/EnterpriseEventsStreamRequest.java @@ -8,76 +8,75 @@ import java.util.Collection; /** - * Class describing request to get Admin Logs Streaming. You can use it's fluent interface to create new request like so: - *
- * {@code
+ * Class describing request to get Admin Logs Streaming. You can use it's fluent interface to create
+ * new request like so:
+ *
+ * 
{@code
  * new EnterpriseEventsStreamRequest().position("stream_position").limit(50);
- * }
- * 
+ * }
*/ public final class EnterpriseEventsStreamRequest { - private static final String ADMIN_LOGS_STREAM_TYPE = "admin_logs_streaming"; - private String position; - private int limit = ENTERPRISE_LIMIT; - private Collection types = new ArrayList<>(); + private static final String ADMIN_LOGS_STREAM_TYPE = "admin_logs_streaming"; + private String position; + private int limit = ENTERPRISE_LIMIT; + private Collection types = new ArrayList<>(); + /** + * The starting position of the event stream. + * + * @param position the starting position of the event stream. + * @return request being created. + */ + public EnterpriseEventsStreamRequest position(String position) { + this.position = position; + return this; + } - /** - * The starting position of the event stream. - * @param position the starting position of the event stream. - * @return request being created. - */ - public EnterpriseEventsStreamRequest position(String position) { - this.position = position; - return this; - } + /** + * The number of entries to be returned in the response. + * + * @param limit the number of entries to be returned in the response. + * @return request being created. + */ + public EnterpriseEventsStreamRequest limit(int limit) { + this.limit = limit; + return this; + } - /** - * The number of entries to be returned in the response. - * @param limit the number of entries to be returned in the response. - * @return request being created. - */ - public EnterpriseEventsStreamRequest limit(int limit) { - this.limit = limit; - return this; - } + /** + * List of event types to filter by. + * + * @param types list of event types to filter by. + * @return request being created. + */ + public EnterpriseEventsStreamRequest types(EventType... types) { + return typeNames(Arrays.stream(types).map(EventType::toJSONString).toArray(String[]::new)); + } - /** - * List of event types to filter by. - * @param types list of event types to filter by. - * @return request being created. - */ - public EnterpriseEventsStreamRequest types(EventType... types) { - return typeNames(Arrays.stream(types) - .map(EventType::toJSONString) - .toArray(String[]::new) - ); - } + /** + * List of event type names to filter by. + * + * @param typeNames list of event type names to filter by. + * @return request being created. + */ + public EnterpriseEventsStreamRequest typeNames(String... typeNames) { + this.types = Arrays.asList(typeNames); + return this; + } - /** - * List of event type names to filter by. - * @param typeNames list of event type names to filter by. - * @return request being created. - */ - public EnterpriseEventsStreamRequest typeNames(String... typeNames) { - this.types = Arrays.asList(typeNames); - return this; - } + String getPosition() { + return position; + } - String getPosition() { - return position; - } + int getLimit() { + return limit; + } - int getLimit() { - return limit; - } + Collection getTypes() { + return types; + } - - Collection getTypes() { - return types; - } - - String getStreamType() { - return ADMIN_LOGS_STREAM_TYPE; - } + String getStreamType() { + return ADMIN_LOGS_STREAM_TYPE; + } } diff --git a/src/main/java/com/box/sdk/EventListener.java b/src/main/java/com/box/sdk/EventListener.java index 2d27ed83a..a1dc1db0d 100644 --- a/src/main/java/com/box/sdk/EventListener.java +++ b/src/main/java/com/box/sdk/EventListener.java @@ -1,31 +1,29 @@ package com.box.sdk; -/** - * The listener interface for receiving events from an {@link EventStream}. - */ +/** The listener interface for receiving events from an {@link EventStream}. */ public interface EventListener { - /** - * Invoked when an event is received from the API. - * - * @param event the received event. - */ - void onEvent(BoxEvent event); + /** + * Invoked when an event is received from the API. + * + * @param event the received event. + */ + void onEvent(BoxEvent event); - /** - * Invoked when an updated stream position is received from the API. - * - * @param position of the stream. - */ - void onNextPosition(long position); + /** + * Invoked when an updated stream position is received from the API. + * + * @param position of the stream. + */ + void onNextPosition(long position); - /** - * Invoked when an error occurs while waiting for events to be received. - * - *

When an EventStream encounters an exception, it will invoke this method on each of its listeners until one - * of them returns true, indicating that the exception was handled.

- * - * @param e the exception that was thrown while waiting for events. - * @return true if the exception was handled; otherwise false. - */ - boolean onException(Throwable e); + /** + * Invoked when an error occurs while waiting for events to be received. + * + *

When an EventStream encounters an exception, it will invoke this method on each of its + * listeners until one of them returns true, indicating that the exception was handled. + * + * @param e the exception that was thrown while waiting for events. + * @return true if the exception was handled; otherwise false. + */ + boolean onException(Throwable e); } diff --git a/src/main/java/com/box/sdk/EventLog.java b/src/main/java/com/box/sdk/EventLog.java index e00fbc54c..9375c4343 100644 --- a/src/main/java/com/box/sdk/EventLog.java +++ b/src/main/java/com/box/sdk/EventLog.java @@ -15,306 +15,296 @@ /** * A log of events that were retrieved from the events endpoint. * - *

An EventLog cannot be instantiated directly. Instead, use one of the static methods to retrieve a log of events. - * Unlike the {@link EventStream} class, EventLog doesn't support retrieving events in real-time. - *

+ *

An EventLog cannot be instantiated directly. Instead, use one of the static methods to + * retrieve a log of events. Unlike the {@link EventStream} class, EventLog doesn't support + * retrieving events in real-time. */ public class EventLog implements Iterable { - static final int ENTERPRISE_LIMIT = 500; - /** - * Enterprise Event URL Template. - */ - public static final URLTemplate ENTERPRISE_EVENT_URL_TEMPLATE = new URLTemplate("events?stream_type=admin_logs&" - + "limit=" + ENTERPRISE_LIMIT); - private final int chunkSize; - private final int limit; - private final String nextStreamPosition; - private final String streamPosition; - private final Set events; + static final int ENTERPRISE_LIMIT = 500; + /** Enterprise Event URL Template. */ + public static final URLTemplate ENTERPRISE_EVENT_URL_TEMPLATE = + new URLTemplate("events?stream_type=admin_logs&" + "limit=" + ENTERPRISE_LIMIT); - private Date startDate; - private Date endDate; + private final int chunkSize; + private final int limit; + private final String nextStreamPosition; + private final String streamPosition; + private final Set events; - EventLog(BoxAPIConnection api, JsonObject json, String streamPosition, int limit) { - this.streamPosition = streamPosition; - this.limit = limit; - JsonValue nextStreamPosition = json.get("next_stream_position"); - if (nextStreamPosition.isString()) { - this.nextStreamPosition = nextStreamPosition.asString(); - } else { - this.nextStreamPosition = nextStreamPosition.toString(); - } - this.chunkSize = json.get("chunk_size").asInt(); + private Date startDate; + private Date endDate; - this.events = new LinkedHashSet<>(this.chunkSize); - JsonArray entries = json.get("entries").asArray(); - for (JsonValue entry : entries) { - this.events.add(new BoxEvent(api, entry.asObject())); - } + EventLog(BoxAPIConnection api, JsonObject json, String streamPosition, int limit) { + this.streamPosition = streamPosition; + this.limit = limit; + JsonValue nextStreamPosition = json.get("next_stream_position"); + if (nextStreamPosition.isString()) { + this.nextStreamPosition = nextStreamPosition.asString(); + } else { + this.nextStreamPosition = nextStreamPosition.toString(); } + this.chunkSize = json.get("chunk_size").asInt(); - /** - * Method reads from the `admin-logs` stream and returns {@link BoxEvent} {@link Iterator}. - * The emphasis for this stream is on completeness over latency, - * which means that Box will deliver admin events in chronological order and without duplicates, - * but with higher latency. You can specify start and end time/dates. This method - * will only work with an API connection for an enterprise admin account - * or service account with manage enterprise properties. - * You can specify a date range to limit when events occured, starting from a given position within the - * event stream, set limit or specify event types that should be filtered. - * Example: - *

-     * {@code
-     * EnterpriseEventsRequest request = new EnterpriseEventsRequest()
-     *     .after(after)        // The lower bound on the timestamp of the events returned.
-     *     .before(before)      // The upper bound on the timestamp of the events returned.
-     *     .limit(20)           // The number of entries to be returned in the response.
-     *     .position(position)  // The starting position of the event stream.
-     *     .types(EventType.LOGIN, EventType.FAILED_LOGIN); // List of event types to filter by.
-     * EventLog.getEnterpriseEvents(api, request);
-     * }
-     * 
- * - * @param api the API connection to use. - * @param enterpriseEventsRequest request to get events. - * @return a log of all the events that met the given criteria. - */ - public static EventLog getEnterpriseEvents(BoxAPIConnection api, EnterpriseEventsRequest enterpriseEventsRequest) { - EventLogRequest request = new EventLogRequest( + this.events = new LinkedHashSet<>(this.chunkSize); + JsonArray entries = json.get("entries").asArray(); + for (JsonValue entry : entries) { + this.events.add(new BoxEvent(api, entry.asObject())); + } + } + + /** + * Method reads from the `admin-logs` stream and returns {@link BoxEvent} {@link Iterator}. The + * emphasis for this stream is on completeness over latency, which means that Box will deliver + * admin events in chronological order and without duplicates, but with higher latency. You can + * specify start and end time/dates. This method will only work with an API connection for an + * enterprise admin account or service account with manage enterprise properties. You can specify + * a date range to limit when events occured, starting from a given position within the event + * stream, set limit or specify event types that should be filtered. Example: + * + *
{@code
+   * EnterpriseEventsRequest request = new EnterpriseEventsRequest()
+   *     .after(after)        // The lower bound on the timestamp of the events returned.
+   *     .before(before)      // The upper bound on the timestamp of the events returned.
+   *     .limit(20)           // The number of entries to be returned in the response.
+   *     .position(position)  // The starting position of the event stream.
+   *     .types(EventType.LOGIN, EventType.FAILED_LOGIN); // List of event types to filter by.
+   * EventLog.getEnterpriseEvents(api, request);
+   * }
+ * + * @param api the API connection to use. + * @param enterpriseEventsRequest request to get events. + * @return a log of all the events that met the given criteria. + */ + public static EventLog getEnterpriseEvents( + BoxAPIConnection api, EnterpriseEventsRequest enterpriseEventsRequest) { + EventLogRequest request = + new EventLogRequest( enterpriseEventsRequest.getBefore(), enterpriseEventsRequest.getAfter(), enterpriseEventsRequest.getPosition(), enterpriseEventsRequest.getLimit(), - enterpriseEventsRequest.getTypes() - ); - return getEnterpriseEventsForStreamType(api, enterpriseEventsRequest.getStreamType(), request); - } + enterpriseEventsRequest.getTypes()); + return getEnterpriseEventsForStreamType(api, enterpriseEventsRequest.getStreamType(), request); + } - /** - * Method reads from the `admin-logs-streaming` stream and returns {@link BoxEvent} {@link Iterator} - * The emphasis for this feed is on low latency rather than chronological accuracy, which means that Box may return - * events more than once and out of chronological order. Events are returned via the API around 12 seconds after they - * are processed by Box (the 12 seconds buffer ensures that new events are not written after your cursor position). - * Only two weeks of events are available via this feed, and you cannot set start and end time/dates. This method - * will only work with an API connection for an enterprise admin account - * or service account with manage enterprise properties. - * You can specify a starting from a given position within the event stream, - * set limit or specify event types that should be filtered. - * Example: - *
-     * {@code
-     * EnterpriseEventsStreamRequest request = new EnterpriseEventsStreamRequest()
-     *     .limit(200)          // The number of entries to be returned in the response.
-     *     .position(position)  // The starting position of the event stream.
-     *     .types(EventType.LOGIN, EventType.FAILED_LOGIN); // List of event types to filter by.
-     * EventLog.getEnterpriseEventsStream(api, request);
-     * }
-     * 
- * - * @param api the API connection to use. - * @param enterpriseEventsStreamRequest request to get events. - * @return a log of all the events that met the given criteria. - */ - public static EventLog getEnterpriseEventsStream( - BoxAPIConnection api, EnterpriseEventsStreamRequest enterpriseEventsStreamRequest - ) { - EventLogRequest request = new EventLogRequest( + /** + * Method reads from the `admin-logs-streaming` stream and returns {@link BoxEvent} {@link + * Iterator} The emphasis for this feed is on low latency rather than chronological accuracy, + * which means that Box may return events more than once and out of chronological order. Events + * are returned via the API around 12 seconds after they are processed by Box (the 12 seconds + * buffer ensures that new events are not written after your cursor position). Only two weeks of + * events are available via this feed, and you cannot set start and end time/dates. This method + * will only work with an API connection for an enterprise admin account or service account with + * manage enterprise properties. You can specify a starting from a given position within the event + * stream, set limit or specify event types that should be filtered. Example: + * + *
{@code
+   * EnterpriseEventsStreamRequest request = new EnterpriseEventsStreamRequest()
+   *     .limit(200)          // The number of entries to be returned in the response.
+   *     .position(position)  // The starting position of the event stream.
+   *     .types(EventType.LOGIN, EventType.FAILED_LOGIN); // List of event types to filter by.
+   * EventLog.getEnterpriseEventsStream(api, request);
+   * }
+ * + * @param api the API connection to use. + * @param enterpriseEventsStreamRequest request to get events. + * @return a log of all the events that met the given criteria. + */ + public static EventLog getEnterpriseEventsStream( + BoxAPIConnection api, EnterpriseEventsStreamRequest enterpriseEventsStreamRequest) { + EventLogRequest request = + new EventLogRequest( null, null, enterpriseEventsStreamRequest.getPosition(), enterpriseEventsStreamRequest.getLimit(), - enterpriseEventsStreamRequest.getTypes() - ); - return getEnterpriseEventsForStreamType(api, enterpriseEventsStreamRequest.getStreamType(), request); - } + enterpriseEventsStreamRequest.getTypes()); + return getEnterpriseEventsForStreamType( + api, enterpriseEventsStreamRequest.getStreamType(), request); + } - private static EventLog getEnterpriseEventsForStreamType( - BoxAPIConnection api, String streamType, EventLogRequest request - ) { - URL url = new URLTemplate("events?").build(api.getBaseURL()); - QueryStringBuilder queryBuilder = new QueryStringBuilder(url.getQuery()); - queryBuilder.appendParam("stream_type", streamType); - addParamsToQuery(request, queryBuilder); + private static EventLog getEnterpriseEventsForStreamType( + BoxAPIConnection api, String streamType, EventLogRequest request) { + URL url = new URLTemplate("events?").build(api.getBaseURL()); + QueryStringBuilder queryBuilder = new QueryStringBuilder(url.getQuery()); + queryBuilder.appendParam("stream_type", streamType); + addParamsToQuery(request, queryBuilder); - try { - url = queryBuilder.addToURL(url); - } catch (MalformedURLException e) { - throw new BoxAPIException("Couldn't append a query string to the provided URL."); - } + try { + url = queryBuilder.addToURL(url); + } catch (MalformedURLException e) { + throw new BoxAPIException("Couldn't append a query string to the provided URL."); + } - BoxJSONRequest apiRequest = new BoxJSONRequest(api, url, "GET"); - try (BoxJSONResponse response = apiRequest.send()) { - JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); - EventLog log = new EventLog(api, responseJSON, request.getPosition(), request.getLimit()); - log.setStartDate(request.getAfter()); - log.setEndDate(request.getBefore()); - return log; - } + BoxJSONRequest apiRequest = new BoxJSONRequest(api, url, "GET"); + try (BoxJSONResponse response = apiRequest.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + EventLog log = new EventLog(api, responseJSON, request.getPosition(), request.getLimit()); + log.setStartDate(request.getAfter()); + log.setEndDate(request.getBefore()); + return log; } + } - private static void addParamsToQuery(EventLogRequest request, QueryStringBuilder queryBuilder) { - queryBuilder.appendParam("limit", request.getLimit()); + private static void addParamsToQuery(EventLogRequest request, QueryStringBuilder queryBuilder) { + queryBuilder.appendParam("limit", request.getLimit()); - if (request.getAfter() != null) { - queryBuilder.appendParam("created_after", BoxDateFormat.format(request.getAfter())); - } - if (request.getBefore() != null) { - queryBuilder.appendParam("created_before", BoxDateFormat.format(request.getBefore())); - } - if (request.getPosition() != null) { - queryBuilder.appendParam("stream_position", request.getPosition()); - } - if (request.getTypes().size() > 0) { - String types = String.join(",", request.getTypes()); - queryBuilder.appendParam("event_type", types); - } + if (request.getAfter() != null) { + queryBuilder.appendParam("created_after", BoxDateFormat.format(request.getAfter())); } - - /** - * Returns an iterator over the events in this log. - * - * @return an iterator over the events in this log. - */ - @Override - public Iterator iterator() { - return this.events.iterator(); + if (request.getBefore() != null) { + queryBuilder.appendParam("created_before", BoxDateFormat.format(request.getBefore())); } - - /** - * Gets the date of the earliest event in this log. - * - *

The value returned by this method corresponds to the created_after URL parameter that was used - * when retrieving the events in this EventLog.

- * - * @return the date of the earliest event in this log. - */ - public Date getStartDate() { - return this.startDate; + if (request.getPosition() != null) { + queryBuilder.appendParam("stream_position", request.getPosition()); } - - void setStartDate(Date startDate) { - this.startDate = startDate; + if (request.getTypes().size() > 0) { + String types = String.join(",", request.getTypes()); + queryBuilder.appendParam("event_type", types); } + } - /** - * Gets the date of the latest event in this log. - * - *

The value returned by this method corresponds to the created_before URL parameter that was used - * when retrieving the events in this EventLog.

- * - * @return the date of the latest event in this log. - */ - public Date getEndDate() { - return this.endDate; - } + /** + * Returns an iterator over the events in this log. + * + * @return an iterator over the events in this log. + */ + @Override + public Iterator iterator() { + return this.events.iterator(); + } - void setEndDate(Date endDate) { - this.endDate = endDate; - } + /** + * Gets the date of the earliest event in this log. + * + *

The value returned by this method corresponds to the created_after URL + * parameter that was used when retrieving the events in this EventLog. + * + * @return the date of the earliest event in this log. + */ + public Date getStartDate() { + return this.startDate; + } - /** - * Gets the maximum number of events that this event log could contain given its start date, end date, and stream - * position. - * - *

The value returned by this method corresponds to the limit URL parameter that was used when - * retrieving the events in this EventLog.

- * - * @return the maximum number of events. - */ - public int getLimit() { - return this.limit; - } + void setStartDate(Date startDate) { + this.startDate = startDate; + } - /** - * Gets the starting position of the events in this log within the event stream. - * - *

The value returned by this method corresponds to the stream_position URL parameter that was used - * when retrieving the events in this EventLog.

- * - * @return the starting position within the event stream. - */ - public String getStreamPosition() { - return this.streamPosition; - } + /** + * Gets the date of the latest event in this log. + * + *

The value returned by this method corresponds to the created_before URL + * parameter that was used when retrieving the events in this EventLog. + * + * @return the date of the latest event in this log. + */ + public Date getEndDate() { + return this.endDate; + } - /** - * Gets the next position within the event stream for retrieving subsequent events. - * - *

The value returned by this method corresponds to the next_stream_position field returned by the - * API's events endpoint.

- * - * @return the next position within the event stream. - */ - public String getNextStreamPosition() { - return this.nextStreamPosition; - } + void setEndDate(Date endDate) { + this.endDate = endDate; + } - /** - * Gets the number of events in this log, including duplicate events. - * - *

The chunk size may not be representative of the number of events returned by this EventLog's iterator because - * the iterator will automatically ignore duplicate events.

- * - *

The value returned by this method corresponds to the chunk_size field returned by the API's - * events endpoint.

- * - * @return the number of events, including duplicates. - */ - public int getChunkSize() { - return this.chunkSize; - } + /** + * Gets the maximum number of events that this event log could contain given its start date, end + * date, and stream position. + * + *

The value returned by this method corresponds to the limit URL parameter that + * was used when retrieving the events in this EventLog. + * + * @return the maximum number of events. + */ + public int getLimit() { + return this.limit; + } - /** - * Gets the number of events in this list, excluding duplicate events. - * - *

The size is guaranteed to be representative of the number of events returned by this EventLog's iterator.

- * - * @return the number of events, excluding duplicates. - */ - public int getSize() { - return this.events.size(); - } + /** + * Gets the starting position of the events in this log within the event stream. + * + *

The value returned by this method corresponds to the stream_position URL + * parameter that was used when retrieving the events in this EventLog. + * + * @return the starting position within the event stream. + */ + public String getStreamPosition() { + return this.streamPosition; + } - private static final class EventLogRequest { - private final Date before; - private final Date after; - private final String position; - private final Integer limit; - private final Collection types; + /** + * Gets the next position within the event stream for retrieving subsequent events. + * + *

The value returned by this method corresponds to the next_stream_position field + * returned by the API's events endpoint. + * + * @return the next position within the event stream. + */ + public String getNextStreamPosition() { + return this.nextStreamPosition; + } - private EventLogRequest( - Date before, - Date after, - String position, - Integer limit, - Collection types - ) { - this.before = before; - this.after = after; - this.position = position; - this.limit = limit; - this.types = types; - } + /** + * Gets the number of events in this log, including duplicate events. + * + *

The chunk size may not be representative of the number of events returned by this EventLog's + * iterator because the iterator will automatically ignore duplicate events. + * + *

The value returned by this method corresponds to the chunk_size field returned + * by the API's events endpoint. + * + * @return the number of events, including duplicates. + */ + public int getChunkSize() { + return this.chunkSize; + } - private Date getBefore() { - return before; - } + /** + * Gets the number of events in this list, excluding duplicate events. + * + *

The size is guaranteed to be representative of the number of events returned by this + * EventLog's iterator. + * + * @return the number of events, excluding duplicates. + */ + public int getSize() { + return this.events.size(); + } - private Date getAfter() { - return after; - } + private static final class EventLogRequest { + private final Date before; + private final Date after; + private final String position; + private final Integer limit; + private final Collection types; - private String getPosition() { - return position; - } + private EventLogRequest( + Date before, Date after, String position, Integer limit, Collection types) { + this.before = before; + this.after = after; + this.position = position; + this.limit = limit; + this.types = types; + } + + private Date getBefore() { + return before; + } - private Integer getLimit() { - return limit; - } + private Date getAfter() { + return after; + } + + private String getPosition() { + return position; + } + + private Integer getLimit() { + return limit; + } - private Collection getTypes() { - return types; - } + private Collection getTypes() { + return types; } + } } diff --git a/src/main/java/com/box/sdk/EventStream.java b/src/main/java/com/box/sdk/EventStream.java index 075973825..9f50022ab 100644 --- a/src/main/java/com/box/sdk/EventStream.java +++ b/src/main/java/com/box/sdk/EventStream.java @@ -10,233 +10,237 @@ /** * Receives real-time events from the API and forwards them to {@link EventListener EventListeners}. * - *

This class handles long polling the Box events endpoint in order to receive real-time user events. - * When an EventStream is started, it begins long polling on a separate thread until the {@link #stop} method - * is called. - * Since the API may return duplicate events, EventStream also maintains a small cache of the most recently received - * event IDs in order to automatically deduplicate events.

- *

Note: Enterprise Events can be accessed by admin users with the EventLog.getEnterpriseEvents method

+ *

This class handles long polling the Box events endpoint in order to receive real-time user + * events. When an EventStream is started, it begins long polling on a separate thread until the + * {@link #stop} method is called. Since the API may return duplicate events, EventStream also + * maintains a small cache of the most recently received event IDs in order to automatically + * deduplicate events. + * + *

Note: Enterprise Events can be accessed by admin users with the EventLog.getEnterpriseEvents + * method */ public class EventStream { - private static final int LIMIT = 800; - /** - * Events URL. - */ - public static final URLTemplate EVENT_URL = new URLTemplate("events?limit=" + LIMIT + "&stream_position=%s"); - private static final int STREAM_POSITION_NOW = -1; - private static final int DEFAULT_POLLING_DELAY = 1000; - private final BoxAPIConnection api; - private final long startingPosition; - private final int pollingDelay; - private final Collection listeners; - private final Object listenerLock; - - private LRUCache receivedEvents; - private boolean started; - private Poller poller; - private Thread pollerThread; - - /** - * Constructs an EventStream using an API connection. - * - * @param api the API connection to use. - */ - public EventStream(BoxAPIConnection api) { - this(api, STREAM_POSITION_NOW, DEFAULT_POLLING_DELAY); + private static final int LIMIT = 800; + /** Events URL. */ + public static final URLTemplate EVENT_URL = + new URLTemplate("events?limit=" + LIMIT + "&stream_position=%s"); + + private static final int STREAM_POSITION_NOW = -1; + private static final int DEFAULT_POLLING_DELAY = 1000; + private final BoxAPIConnection api; + private final long startingPosition; + private final int pollingDelay; + private final Collection listeners; + private final Object listenerLock; + + private LRUCache receivedEvents; + private boolean started; + private Poller poller; + private Thread pollerThread; + + /** + * Constructs an EventStream using an API connection. + * + * @param api the API connection to use. + */ + public EventStream(BoxAPIConnection api) { + this(api, STREAM_POSITION_NOW, DEFAULT_POLLING_DELAY); + } + + /** + * Constructs an EventStream using an API connection and a starting initial position. + * + * @param api the API connection to use. + * @param startingPosition the starting position of the event stream. + */ + public EventStream(BoxAPIConnection api, long startingPosition) { + this(api, startingPosition, DEFAULT_POLLING_DELAY); + } + + /** + * Constructs an EventStream using an API connection and a starting initial position with custom + * polling delay. + * + * @param api the API connection to use. + * @param startingPosition the starting position of the event stream. + * @param pollingDelay the delay in milliseconds between successive calls to get more events. + */ + public EventStream(BoxAPIConnection api, long startingPosition, int pollingDelay) { + this.api = api; + this.startingPosition = startingPosition; + this.listeners = new ArrayList<>(); + this.listenerLock = new Object(); + this.pollingDelay = pollingDelay; + } + + /** + * Adds a listener that will be notified when an event is received. + * + * @param listener the listener to add. + */ + public void addListener(EventListener listener) { + synchronized (this.listenerLock) { + this.listeners.add(listener); } - - /** - * Constructs an EventStream using an API connection and a starting initial position. - * - * @param api the API connection to use. - * @param startingPosition the starting position of the event stream. - */ - public EventStream(BoxAPIConnection api, long startingPosition) { - this(api, startingPosition, DEFAULT_POLLING_DELAY); + } + + /** + * Indicates whether or not this EventStream has been started. + * + * @return true if this EventStream has been started; otherwise false. + */ + public boolean isStarted() { + return this.started; + } + + /** + * Stops this EventStream and disconnects from the API. + * + * @throws IllegalStateException if the EventStream is already stopped. + */ + public void stop() { + if (!this.started) { + throw new IllegalStateException("Cannot stop the EventStream because it isn't started."); } - /** - * Constructs an EventStream using an API connection and a starting initial position with custom polling delay. - * - * @param api the API connection to use. - * @param startingPosition the starting position of the event stream. - * @param pollingDelay the delay in milliseconds between successive calls to get more events. - */ - public EventStream(BoxAPIConnection api, long startingPosition, int pollingDelay) { - this.api = api; - this.startingPosition = startingPosition; - this.listeners = new ArrayList<>(); - this.listenerLock = new Object(); - this.pollingDelay = pollingDelay; + this.started = false; + this.pollerThread.interrupt(); + } + + /** + * Starts this EventStream and begins long polling the API. + * + * @throws IllegalStateException if the EventStream is already started. + */ + public void start() { + if (this.started) { + throw new IllegalStateException("Cannot start the EventStream because it isn't stopped."); } - /** - * Adds a listener that will be notified when an event is received. - * - * @param listener the listener to add. - */ - public void addListener(EventListener listener) { - synchronized (this.listenerLock) { - this.listeners.add(listener); - } + final long initialPosition; + + if (this.startingPosition == STREAM_POSITION_NOW) { + BoxJSONRequest request = + new BoxJSONRequest(this.api, EVENT_URL.buildAlpha(this.api.getBaseURL(), "now"), "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); + initialPosition = jsonObject.get("next_stream_position").asLong(); + } + } else { + assert this.startingPosition >= 0 : "Starting position must be non-negative"; + initialPosition = this.startingPosition; } - /** - * Indicates whether or not this EventStream has been started. - * - * @return true if this EventStream has been started; otherwise false. - */ - public boolean isStarted() { - return this.started; + this.poller = new Poller(initialPosition); + + this.pollerThread = new Thread(this.poller); + this.pollerThread.setUncaughtExceptionHandler((t, e) -> EventStream.this.notifyException(e)); + this.pollerThread.start(); + + this.started = true; + } + + /** + * Indicates whether or not an event ID is a duplicate. + * + *

This method can be overridden by a subclass in order to provide custom de-duping logic. + * + * @param eventID the event ID. + * @return true if the event is a duplicate; otherwise false. + */ + protected boolean isDuplicate(String eventID) { + if (this.receivedEvents == null) { + this.receivedEvents = new LRUCache<>(); } - /** - * Stops this EventStream and disconnects from the API. - * - * @throws IllegalStateException if the EventStream is already stopped. - */ - public void stop() { - if (!this.started) { - throw new IllegalStateException("Cannot stop the EventStream because it isn't started."); - } + return !this.receivedEvents.add(eventID); + } - this.started = false; - this.pollerThread.interrupt(); + private void notifyNextPosition(long position) { + synchronized (this.listenerLock) { + for (EventListener listener : this.listeners) { + listener.onNextPosition(position); + } } - - /** - * Starts this EventStream and begins long polling the API. - * - * @throws IllegalStateException if the EventStream is already started. - */ - public void start() { - if (this.started) { - throw new IllegalStateException("Cannot start the EventStream because it isn't stopped."); + } + + private void notifyEvent(BoxEvent event) { + synchronized (this.listenerLock) { + boolean isDuplicate = this.isDuplicate(event.getID()); + if (!isDuplicate) { + for (EventListener listener : this.listeners) { + listener.onEvent(event); } - - final long initialPosition; - - if (this.startingPosition == STREAM_POSITION_NOW) { - BoxJSONRequest request = new BoxJSONRequest(this.api, - EVENT_URL.buildAlpha(this.api.getBaseURL(), "now"), "GET" - ); - try (BoxJSONResponse response = request.send()) { - JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - initialPosition = jsonObject.get("next_stream_position").asLong(); - } - } else { - assert this.startingPosition >= 0 : "Starting position must be non-negative"; - initialPosition = this.startingPosition; - } - - this.poller = new Poller(initialPosition); - - this.pollerThread = new Thread(this.poller); - this.pollerThread.setUncaughtExceptionHandler((t, e) -> EventStream.this.notifyException(e)); - this.pollerThread.start(); - - this.started = true; + } } + } - /** - * Indicates whether or not an event ID is a duplicate. - * - *

This method can be overridden by a subclass in order to provide custom de-duping logic.

- * - * @param eventID the event ID. - * @return true if the event is a duplicate; otherwise false. - */ - protected boolean isDuplicate(String eventID) { - if (this.receivedEvents == null) { - this.receivedEvents = new LRUCache<>(); - } - - return !this.receivedEvents.add(eventID); + private void notifyException(Throwable e) { + if (e instanceof InterruptedException && !this.started) { + return; } - private void notifyNextPosition(long position) { - synchronized (this.listenerLock) { - for (EventListener listener : this.listeners) { - listener.onNextPosition(position); - } + this.stop(); + synchronized (this.listenerLock) { + for (EventListener listener : this.listeners) { + if (listener.onException(e)) { + return; } + } } + } - private void notifyEvent(BoxEvent event) { - synchronized (this.listenerLock) { - boolean isDuplicate = this.isDuplicate(event.getID()); - if (!isDuplicate) { - for (EventListener listener : this.listeners) { - listener.onEvent(event); - } - } - } - } + private class Poller implements Runnable { + private final long initialPosition; - private void notifyException(Throwable e) { - if (e instanceof InterruptedException && !this.started) { - return; - } + private RealtimeServerConnection server; - this.stop(); - synchronized (this.listenerLock) { - for (EventListener listener : this.listeners) { - if (listener.onException(e)) { - return; - } - } - } + Poller(long initialPosition) { + this.initialPosition = initialPosition; + this.server = new RealtimeServerConnection(EventStream.this.api); } - private class Poller implements Runnable { - private final long initialPosition; - - private RealtimeServerConnection server; - - Poller(long initialPosition) { - this.initialPosition = initialPosition; - this.server = new RealtimeServerConnection(EventStream.this.api); + @Override + public void run() { + long position = this.initialPosition; + while (!Thread.interrupted()) { + if (this.server.getRemainingRetries() == 0) { + this.server = new RealtimeServerConnection(EventStream.this.api); } - @Override - public void run() { - long position = this.initialPosition; - while (!Thread.interrupted()) { - if (this.server.getRemainingRetries() == 0) { - this.server = new RealtimeServerConnection(EventStream.this.api); - } - - if (this.server.waitForChange(position)) { - if (Thread.interrupted()) { - return; - } - - BoxJSONRequest request = new BoxJSONRequest(EventStream.this.api, - EVENT_URL.buildAlpha(EventStream.this.api.getBaseURL(), position), "GET" - ); - try (BoxJSONResponse response = request.send()) { - JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - JsonArray entriesArray = jsonObject.get("entries").asArray(); - for (JsonValue entry : entriesArray) { - BoxEvent event = new BoxEvent(EventStream.this.api, entry.asObject()); - EventStream.this.notifyEvent(event); - } - position = jsonObject.get("next_stream_position").asLong(); - EventStream.this.notifyNextPosition(position); - try { - // Delay re-polling to avoid making too many API calls - // Since duplicate events may appear in the stream, without any delay added - // the stream can make 3-5 requests per second and not produce any new - // events. A short delay between calls balances latency for new events - // and the risk of hitting rate limits. - Thread.sleep(EventStream.this.pollingDelay); - } catch (InterruptedException ex) { - return; - } - } - } + if (this.server.waitForChange(position)) { + if (Thread.interrupted()) { + return; + } + + BoxJSONRequest request = + new BoxJSONRequest( + EventStream.this.api, + EVENT_URL.buildAlpha(EventStream.this.api.getBaseURL(), position), + "GET"); + try (BoxJSONResponse response = request.send()) { + JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); + JsonArray entriesArray = jsonObject.get("entries").asArray(); + for (JsonValue entry : entriesArray) { + BoxEvent event = new BoxEvent(EventStream.this.api, entry.asObject()); + EventStream.this.notifyEvent(event); + } + position = jsonObject.get("next_stream_position").asLong(); + EventStream.this.notifyNextPosition(position); + try { + // Delay re-polling to avoid making too many API calls + // Since duplicate events may appear in the stream, without any delay added + // the stream can make 3-5 requests per second and not produce any new + // events. A short delay between calls balances latency for new events + // and the risk of hitting rate limits. + Thread.sleep(EventStream.this.pollingDelay); + } catch (InterruptedException ex) { + return; } + } } + } } + } } diff --git a/src/main/java/com/box/sdk/FileUploadParams.java b/src/main/java/com/box/sdk/FileUploadParams.java index 386d2bf02..9bdb5d6ce 100644 --- a/src/main/java/com/box/sdk/FileUploadParams.java +++ b/src/main/java/com/box/sdk/FileUploadParams.java @@ -3,205 +3,198 @@ import java.io.InputStream; import java.util.Date; -/** - * Contains parameters for configuring an upload to Box. - */ +/** Contains parameters for configuring an upload to Box. */ public class FileUploadParams { - private InputStream content; - private UploadFileCallback uploadFileCallback; - private String name; - private Date created; - private Date modified; - private long size; - private ProgressListener listener; - private String sha1; - private String description; - - /** - * Constructs a new FileUploadParams with default parameters. - */ - public FileUploadParams() { - } - - /** - * Gets the content that will be uploaded to Box. - * - * @return an InputStream that reads the content to be uploaded to Box. - */ - public InputStream getContent() { - return this.content; - } - - /** - * Sets the content that will be uploaded to Box. - * - * @param content an InputStream that reads from the content to be uploaded to Box. - * @return this FileUploadParams object for chaining. - */ - public FileUploadParams setContent(InputStream content) { - this.content = content; - return this; - } - - /** - * @return content writer callback. - */ - public UploadFileCallback getUploadFileCallback() { - return this.uploadFileCallback; - } - - /** - * Sets the content writer callback. - * - * @param uploadFileCallback callback called when file upload starts. - * @return this FileUploadParams object for chaining. - */ - public FileUploadParams setUploadFileCallback(UploadFileCallback uploadFileCallback) { - this.uploadFileCallback = uploadFileCallback; - return this; - } - - /** - * Gets the name that will be given to the uploaded file. - * - * @return the name that will be given to the uploaded file. - */ - public String getName() { - return this.name; - } - - /** - * Sets the name that will be given to the uploaded file. - * - * @param name the name that will be given to the uploaded file. - * @return this FileUploadParams object for chaining. - */ - public FileUploadParams setName(String name) { - this.name = name; - return this; - } - - /** - * Gets the content created date that will be given to the uploaded file. - * - * @return the content created date that will be given to the uploaded file. - */ - public Date getCreated() { - return this.created; - } - - /** - * Sets the content created date that will be given to the uploaded file. - * - * @param created the content created date that will be given to the uploaded file. - * @return this FileUploadParams object for chaining. - */ - public FileUploadParams setCreated(Date created) { - this.created = created; - return this; - } - - /** - * Gets the content modified date that will be given to the uploaded file. - * - * @return the content modified date that will be given to the uploaded file. - */ - public Date getModified() { - return this.modified; - } - - /** - * Sets the content modified date that will be given to the uploaded file. - * - * @param modified the content modified date that will be given to the uploaded file. - * @return this FileUploadParams object for chaining. - */ - public FileUploadParams setModified(Date modified) { - this.modified = modified; - return this; - } - - /** - * Gets the size of the file's content used for monitoring the upload's progress. - * If the size cannot be determined value will be -1. - * - * @return the size of the file's content. - */ - public long getSize() { - return this.size; - } - - /** - * Sets the size of the file content used for monitoring the upload's progress. - * When the content is coming from a dynamic source - other thread reading value - * set size to -1 to tell SDK that file size cannot be determined. Usefull - * when encuntering problems with writing different size of bytes than assumed. - * - * @param size the size of the file's content. - * @return this FileUploadParams object for chaining. - */ - public FileUploadParams setSize(long size) { - this.size = size; - return this; - } - - /** - * Gets the ProgressListener that will be used for monitoring the upload's progress. - * - * @return the ProgressListener that will be used for monitoring the upload's progress. - */ - public ProgressListener getProgressListener() { - return this.listener; - } - - /** - * Sets the ProgressListener that will be used for monitoring the upload's progress. - * - * @param listener the listener that will be used for monitoring the upload's progress. - * @return this FileUploadParams object for chaining. - */ - public FileUploadParams setProgressListener(ProgressListener listener) { - this.listener = listener; - return this; - } - - /** - * Gets the file's SHA-1 hash. - * - * @return the file hash. - */ - public String getSHA1() { - return this.sha1; - } - - /** - * Set the SHA-1 hash of the file to ensure it is not corrupted during the upload. - * - * @param sha1 the SHA-1 hash of the file. - * @return this FileUploadParams for chaining. - */ - public FileUploadParams setSHA1(String sha1) { - this.sha1 = sha1; - return this; - } - - /** - * Gets the file's description set for uploading. - * - * @return the file description. - */ - public String getDescription() { - return this.description; - } - - /** - * Sets the file description during the file upload. - * - * @param description the description of the file. - * @return this FileUploadParams for chaining. - */ - public FileUploadParams setDescription(String description) { - this.description = description; - return this; - } + private InputStream content; + private UploadFileCallback uploadFileCallback; + private String name; + private Date created; + private Date modified; + private long size; + private ProgressListener listener; + private String sha1; + private String description; + + /** Constructs a new FileUploadParams with default parameters. */ + public FileUploadParams() {} + + /** + * Gets the content that will be uploaded to Box. + * + * @return an InputStream that reads the content to be uploaded to Box. + */ + public InputStream getContent() { + return this.content; + } + + /** + * Sets the content that will be uploaded to Box. + * + * @param content an InputStream that reads from the content to be uploaded to Box. + * @return this FileUploadParams object for chaining. + */ + public FileUploadParams setContent(InputStream content) { + this.content = content; + return this; + } + + /** @return content writer callback. */ + public UploadFileCallback getUploadFileCallback() { + return this.uploadFileCallback; + } + + /** + * Sets the content writer callback. + * + * @param uploadFileCallback callback called when file upload starts. + * @return this FileUploadParams object for chaining. + */ + public FileUploadParams setUploadFileCallback(UploadFileCallback uploadFileCallback) { + this.uploadFileCallback = uploadFileCallback; + return this; + } + + /** + * Gets the name that will be given to the uploaded file. + * + * @return the name that will be given to the uploaded file. + */ + public String getName() { + return this.name; + } + + /** + * Sets the name that will be given to the uploaded file. + * + * @param name the name that will be given to the uploaded file. + * @return this FileUploadParams object for chaining. + */ + public FileUploadParams setName(String name) { + this.name = name; + return this; + } + + /** + * Gets the content created date that will be given to the uploaded file. + * + * @return the content created date that will be given to the uploaded file. + */ + public Date getCreated() { + return this.created; + } + + /** + * Sets the content created date that will be given to the uploaded file. + * + * @param created the content created date that will be given to the uploaded file. + * @return this FileUploadParams object for chaining. + */ + public FileUploadParams setCreated(Date created) { + this.created = created; + return this; + } + + /** + * Gets the content modified date that will be given to the uploaded file. + * + * @return the content modified date that will be given to the uploaded file. + */ + public Date getModified() { + return this.modified; + } + + /** + * Sets the content modified date that will be given to the uploaded file. + * + * @param modified the content modified date that will be given to the uploaded file. + * @return this FileUploadParams object for chaining. + */ + public FileUploadParams setModified(Date modified) { + this.modified = modified; + return this; + } + + /** + * Gets the size of the file's content used for monitoring the upload's progress. If the size + * cannot be determined value will be -1. + * + * @return the size of the file's content. + */ + public long getSize() { + return this.size; + } + + /** + * Sets the size of the file content used for monitoring the upload's progress. When the content + * is coming from a dynamic source - other thread reading value set size to -1 to tell SDK that + * file size cannot be determined. Usefull when encuntering problems with writing different size + * of bytes than assumed. + * + * @param size the size of the file's content. + * @return this FileUploadParams object for chaining. + */ + public FileUploadParams setSize(long size) { + this.size = size; + return this; + } + + /** + * Gets the ProgressListener that will be used for monitoring the upload's progress. + * + * @return the ProgressListener that will be used for monitoring the upload's progress. + */ + public ProgressListener getProgressListener() { + return this.listener; + } + + /** + * Sets the ProgressListener that will be used for monitoring the upload's progress. + * + * @param listener the listener that will be used for monitoring the upload's progress. + * @return this FileUploadParams object for chaining. + */ + public FileUploadParams setProgressListener(ProgressListener listener) { + this.listener = listener; + return this; + } + + /** + * Gets the file's SHA-1 hash. + * + * @return the file hash. + */ + public String getSHA1() { + return this.sha1; + } + + /** + * Set the SHA-1 hash of the file to ensure it is not corrupted during the upload. + * + * @param sha1 the SHA-1 hash of the file. + * @return this FileUploadParams for chaining. + */ + public FileUploadParams setSHA1(String sha1) { + this.sha1 = sha1; + return this; + } + + /** + * Gets the file's description set for uploading. + * + * @return the file description. + */ + public String getDescription() { + return this.description; + } + + /** + * Sets the file description during the file upload. + * + * @param description the description of the file. + * @return this FileUploadParams for chaining. + */ + public FileUploadParams setDescription(String description) { + this.description = description; + return this; + } } diff --git a/src/main/java/com/box/sdk/Filter.java b/src/main/java/com/box/sdk/Filter.java index 795826582..d47da1d6f 100644 --- a/src/main/java/com/box/sdk/Filter.java +++ b/src/main/java/com/box/sdk/Filter.java @@ -1,5 +1,5 @@ package com.box.sdk; interface Filter { - boolean shouldInclude(T object); + boolean shouldInclude(T object); } diff --git a/src/main/java/com/box/sdk/IAccessTokenCache.java b/src/main/java/com/box/sdk/IAccessTokenCache.java index 2d104e402..6617ec80c 100644 --- a/src/main/java/com/box/sdk/IAccessTokenCache.java +++ b/src/main/java/com/box/sdk/IAccessTokenCache.java @@ -1,26 +1,28 @@ package com.box.sdk; /** - * Implement this interface to provide a custom access token cache implementation for your environment. + * Implement this interface to provide a custom access token cache implementation for your + * environment. * - *

For production applications it is recommended to use a distributed cache like Memcached or Redis, and to - * implement this interface to store and retrieve access tokens appropriately for your environment.

+ *

For production applications it is recommended to use a distributed cache like Memcached or + * Redis, and to implement this interface to store and retrieve access tokens appropriately for your + * environment. */ public interface IAccessTokenCache { - /** - * Get the access token information from the cache. - * - * @param key key to look for. - * @return access token information. - */ - String get(String key); + /** + * Get the access token information from the cache. + * + * @param key key to look for. + * @return access token information. + */ + String get(String key); - /** - * Store the access token information in the cache. - * - * @param key key to use. - * @param value access token information to store. - */ - void put(String key, String value); + /** + * Store the access token information in the cache. + * + * @param key key to use. + * @param value access token information to store. + */ + void put(String key, String value); } diff --git a/src/main/java/com/box/sdk/IPrivateKeyDecryptor.java b/src/main/java/com/box/sdk/IPrivateKeyDecryptor.java index a8ecbab83..7aac5aa6e 100644 --- a/src/main/java/com/box/sdk/IPrivateKeyDecryptor.java +++ b/src/main/java/com/box/sdk/IPrivateKeyDecryptor.java @@ -3,18 +3,18 @@ import java.security.PrivateKey; /** - * Implement this interface to provide a custom private key decryptor. - * If you require the decryption operation to be FIPS compliant, - * ensure that your implementation exclusively utilizes FIPS certified libraries. + * Implement this interface to provide a custom private key decryptor. If you require the decryption + * operation to be FIPS compliant, ensure that your implementation exclusively utilizes FIPS + * certified libraries. */ public interface IPrivateKeyDecryptor { - /** - * Decrypts private key with provided passphrase using Bouncy Castle library - * - * @param encryptedPrivateKey Encoded private key string. - * @param passphrase Private key passphrase. - * @return java.security.PrivateKey instance representing decrypted private key. - */ - PrivateKey decryptPrivateKey(String encryptedPrivateKey, String passphrase); + /** + * Decrypts private key with provided passphrase using Bouncy Castle library + * + * @param encryptedPrivateKey Encoded private key string. + * @param passphrase Private key passphrase. + * @return java.security.PrivateKey instance representing decrypted private key. + */ + PrivateKey decryptPrivateKey(String encryptedPrivateKey, String passphrase); } diff --git a/src/main/java/com/box/sdk/InMemoryLRUAccessTokenCache.java b/src/main/java/com/box/sdk/InMemoryLRUAccessTokenCache.java index b04e9b08f..f4eb30b9f 100644 --- a/src/main/java/com/box/sdk/InMemoryLRUAccessTokenCache.java +++ b/src/main/java/com/box/sdk/InMemoryLRUAccessTokenCache.java @@ -4,50 +4,51 @@ import java.util.Map; /** - * Use this class to create an in-memory LRU (least recently used) access token cache to be - * passed to BoxDeveloperEditionAPIConnection. + * Use this class to create an in-memory LRU (least recently used) access token cache to be passed + * to BoxDeveloperEditionAPIConnection. */ public class InMemoryLRUAccessTokenCache implements IAccessTokenCache { - private final Map cache; + private final Map cache; - /** - * Creates an in-memory LRU access token cache. - * - * @param maxEntries maximum number of entries to store. - */ - public InMemoryLRUAccessTokenCache(final int maxEntries) { - this.cache = new LinkedHashMap(maxEntries, 0.75F, true) { - private static final long serialVersionUID = -187234623489L; + /** + * Creates an in-memory LRU access token cache. + * + * @param maxEntries maximum number of entries to store. + */ + public InMemoryLRUAccessTokenCache(final int maxEntries) { + this.cache = + new LinkedHashMap(maxEntries, 0.75F, true) { + private static final long serialVersionUID = -187234623489L; - @Override - protected boolean removeEldestEntry(java.util.Map.Entry eldest) { - return size() > maxEntries; - } + @Override + protected boolean removeEldestEntry(java.util.Map.Entry eldest) { + return size() > maxEntries; + } }; - } + } - /** - * Add an entry to the cache. - * - * @param key key to use. - * @param value access token information to store. - */ - public void put(String key, String value) { - synchronized (this.cache) { - this.cache.put(key, value); - } + /** + * Add an entry to the cache. + * + * @param key key to use. + * @param value access token information to store. + */ + public void put(String key, String value) { + synchronized (this.cache) { + this.cache.put(key, value); } + } - /** - * Get an entry from the cache. - * - * @param key key to look for. - * @return access token information. - */ - public String get(String key) { - synchronized (this.cache) { - return this.cache.get(key); - } + /** + * Get an entry from the cache. + * + * @param key key to look for. + * @return access token information. + */ + public String get(String key) { + synchronized (this.cache) { + return this.cache.get(key); } + } } diff --git a/src/main/java/com/box/sdk/JWTEncryptionPreferences.java b/src/main/java/com/box/sdk/JWTEncryptionPreferences.java index b8bd774fd..8769c8ccf 100644 --- a/src/main/java/com/box/sdk/JWTEncryptionPreferences.java +++ b/src/main/java/com/box/sdk/JWTEncryptionPreferences.java @@ -1,103 +1,100 @@ package com.box.sdk; -/** - * Contains the encryption preferences for JWT assertion. - */ - +/** Contains the encryption preferences for JWT assertion. */ public class JWTEncryptionPreferences { - private String publicKeyID; - private String privateKey; - private String privateKeyPassword; - private EncryptionAlgorithm encryptionAlgorithm; - private IPrivateKeyDecryptor privateKeyDecryptor = new BCPrivateKeyDecryptor(); + private String publicKeyID; + private String privateKey; + private String privateKeyPassword; + private EncryptionAlgorithm encryptionAlgorithm; + private IPrivateKeyDecryptor privateKeyDecryptor = new BCPrivateKeyDecryptor(); - /** - * Returns the ID for public key for validating the JWT signature. - * - * @return the publicKeyID. - */ - public String getPublicKeyID() { - return this.publicKeyID; - } + /** + * Returns the ID for public key for validating the JWT signature. + * + * @return the publicKeyID. + */ + public String getPublicKeyID() { + return this.publicKeyID; + } - /** - * Sets the ID for public key for validating the JWT signature. - * - * @param publicKeyID the publicKeyID to set. - */ - public void setPublicKeyID(String publicKeyID) { - this.publicKeyID = publicKeyID; - } + /** + * Sets the ID for public key for validating the JWT signature. + * + * @param publicKeyID the publicKeyID to set. + */ + public void setPublicKeyID(String publicKeyID) { + this.publicKeyID = publicKeyID; + } - /** - * Returns the private key for generating the JWT signature. - * - * @return the privateKey. - */ - public String getPrivateKey() { - return this.privateKey; - } + /** + * Returns the private key for generating the JWT signature. + * + * @return the privateKey. + */ + public String getPrivateKey() { + return this.privateKey; + } - /** - * Sets the private key for generating the JWT signature. - * - * @param privateKey the privateKey to set. - */ - public void setPrivateKey(String privateKey) { - this.privateKey = privateKey; - } + /** + * Sets the private key for generating the JWT signature. + * + * @param privateKey the privateKey to set. + */ + public void setPrivateKey(String privateKey) { + this.privateKey = privateKey; + } - /** - * Returns the password for the private key. - * - * @return the privateKeyPassword. - */ - public String getPrivateKeyPassword() { - return this.privateKeyPassword; - } + /** + * Returns the password for the private key. + * + * @return the privateKeyPassword. + */ + public String getPrivateKeyPassword() { + return this.privateKeyPassword; + } - /** - * Sets the password for the private key. - * - * @param privateKeyPassword the privateKeyPassword to set. - */ - public void setPrivateKeyPassword(String privateKeyPassword) { - this.privateKeyPassword = privateKeyPassword; - } + /** + * Sets the password for the private key. + * + * @param privateKeyPassword the privateKeyPassword to set. + */ + public void setPrivateKeyPassword(String privateKeyPassword) { + this.privateKeyPassword = privateKeyPassword; + } - /** - * Returns the type of encryption algorithm for JWT. - * - * @return the encryptionAlgorithm. - */ - public EncryptionAlgorithm getEncryptionAlgorithm() { - return this.encryptionAlgorithm; - } + /** + * Returns the type of encryption algorithm for JWT. + * + * @return the encryptionAlgorithm. + */ + public EncryptionAlgorithm getEncryptionAlgorithm() { + return this.encryptionAlgorithm; + } - /** - * Sets the type of encryption algorithm for JWT. - * - * @param encryptionAlgorithm the encryptionAlgorithm to set. - */ - public void setEncryptionAlgorithm(EncryptionAlgorithm encryptionAlgorithm) { - this.encryptionAlgorithm = encryptionAlgorithm; - } + /** + * Sets the type of encryption algorithm for JWT. + * + * @param encryptionAlgorithm the encryptionAlgorithm to set. + */ + public void setEncryptionAlgorithm(EncryptionAlgorithm encryptionAlgorithm) { + this.encryptionAlgorithm = encryptionAlgorithm; + } - /** - * Gets a decryptor used for decrypting the private key. - * - * @return the decryptor used for decrypting the private key. - */ - public IPrivateKeyDecryptor getPrivateKeyDecryptor() { - return privateKeyDecryptor; - } + /** + * Gets a decryptor used for decrypting the private key. + * + * @return the decryptor used for decrypting the private key. + */ + public IPrivateKeyDecryptor getPrivateKeyDecryptor() { + return privateKeyDecryptor; + } - /** - * Sets a custom decryptor used for decrypting the private key. - * - * @param privateKeyDecryptor the decryptor used for decrypting the private key. - */ - public void setPrivateKeyDecryptor(IPrivateKeyDecryptor privateKeyDecryptor) { - this.privateKeyDecryptor = privateKeyDecryptor; - } + /** + * Sets a custom decryptor used for decrypting the private key. + * + * @param privateKeyDecryptor the decryptor used for decrypting the private key. + */ + public void setPrivateKeyDecryptor(IPrivateKeyDecryptor privateKeyDecryptor) { + this.privateKeyDecryptor = privateKeyDecryptor; + } } diff --git a/src/main/java/com/box/sdk/JsonIterator.java b/src/main/java/com/box/sdk/JsonIterator.java index fe8249015..e4b6dd3a6 100644 --- a/src/main/java/com/box/sdk/JsonIterator.java +++ b/src/main/java/com/box/sdk/JsonIterator.java @@ -10,112 +10,112 @@ import java.util.NoSuchElementException; class JsonIterator { - private final BoxAPIConnection api; - private final URL url; - private PagingParameters pagingParameters; - private boolean hasMorePages; - private Iterator currentPage; - private JsonObject nextJsonObject; - private Filter filter; - - JsonIterator(BoxAPIConnection api, URL url, PagingParameters pagingParameters) { - this.api = api; - this.url = url; - this.pagingParameters = pagingParameters; + private final BoxAPIConnection api; + private final URL url; + private PagingParameters pagingParameters; + private boolean hasMorePages; + private Iterator currentPage; + private JsonObject nextJsonObject; + private Filter filter; + + JsonIterator(BoxAPIConnection api, URL url, PagingParameters pagingParameters) { + this.api = api; + this.url = url; + this.pagingParameters = pagingParameters; + } + + public boolean hasNext() { + if (this.nextJsonObject == null) { + this.nextJsonObject = this.loadNextJsonObject(); } - public boolean hasNext() { - if (this.nextJsonObject == null) { - this.nextJsonObject = this.loadNextJsonObject(); - } + return this.nextJsonObject != null; + } - return this.nextJsonObject != null; + public JsonObject next() { + if (this.nextJsonObject == null) { + this.nextJsonObject = this.loadNextJsonObject(); } - public JsonObject next() { - if (this.nextJsonObject == null) { - this.nextJsonObject = this.loadNextJsonObject(); - } - - if (this.nextJsonObject == null) { - throw new NoSuchElementException(); - } - - JsonObject next = this.nextJsonObject; - this.nextJsonObject = null; - return next; + if (this.nextJsonObject == null) { + throw new NoSuchElementException(); } - public void remove() { - throw new UnsupportedOperationException(); - } + JsonObject next = this.nextJsonObject; + this.nextJsonObject = null; + return next; + } - public void setFilter(Filter filter) { - this.filter = filter; - } + public void remove() { + throw new UnsupportedOperationException(); + } - private void loadNextPage() { - QueryStringBuilder builder = pagingParameters.asQueryStringBuilder(); + public void setFilter(Filter filter) { + this.filter = filter; + } - URL url; - try { - url = builder.addToURL(this.url); - } catch (MalformedURLException e) { - throw new BoxAPIException("Couldn't append a query string to the provided URL."); - } + private void loadNextPage() { + QueryStringBuilder builder = pagingParameters.asQueryStringBuilder(); - BoxJSONRequest request = new BoxJSONRequest(this.api, url, "GET"); - try (BoxJSONResponse response = request.send()) { - String json = response.getJSON(); + URL url; + try { + url = builder.addToURL(this.url); + } catch (MalformedURLException e) { + throw new BoxAPIException("Couldn't append a query string to the provided URL."); + } - JsonObject responseObject = Json.parse(json).asObject(); + BoxJSONRequest request = new BoxJSONRequest(this.api, url, "GET"); + try (BoxJSONResponse response = request.send()) { + String json = response.getJSON(); - if (pagingParameters.isMarkerBasedPaging()) { - continueAsMarkerBasedPaging(responseObject); - } else { - continueAsOffsetBasedPaging(responseObject); - } + JsonObject responseObject = Json.parse(json).asObject(); - JsonArray jsonArray = responseObject.get("entries").asArray(); - this.currentPage = jsonArray.iterator(); - } - } + if (pagingParameters.isMarkerBasedPaging()) { + continueAsMarkerBasedPaging(responseObject); + } else { + continueAsOffsetBasedPaging(responseObject); + } - private void continueAsOffsetBasedPaging(JsonObject response) { - try { - long offset = response.get("offset").asLong(); - long totalCount = response.get("total_count").asLong(); - hasMorePages = offset + pagingParameters.getLimit() < totalCount; - this.pagingParameters = pagingParameters.nextOffset(offset); - } catch (NullPointerException e) { - hasMorePages = false; - } + JsonArray jsonArray = responseObject.get("entries").asArray(); + this.currentPage = jsonArray.iterator(); } - - private void continueAsMarkerBasedPaging(JsonObject response) { - String nextMarker = response.getString("next_marker", null); - this.hasMorePages = nextMarker != null && nextMarker.length() > 0; - this.pagingParameters = pagingParameters.nextMarker(nextMarker); + } + + private void continueAsOffsetBasedPaging(JsonObject response) { + try { + long offset = response.get("offset").asLong(); + long totalCount = response.get("total_count").asLong(); + hasMorePages = offset + pagingParameters.getLimit() < totalCount; + this.pagingParameters = pagingParameters.nextOffset(offset); + } catch (NullPointerException e) { + hasMorePages = false; } + } - private JsonObject loadNextJsonObject() { - if (this.currentPage == null) { - this.loadNextPage(); - } + private void continueAsMarkerBasedPaging(JsonObject response) { + String nextMarker = response.getString("next_marker", null); + this.hasMorePages = nextMarker != null && nextMarker.length() > 0; + this.pagingParameters = pagingParameters.nextMarker(nextMarker); + } + + private JsonObject loadNextJsonObject() { + if (this.currentPage == null) { + this.loadNextPage(); + } - while (this.currentPage.hasNext() || this.hasMorePages) { - while (this.currentPage.hasNext()) { - JsonObject jsonObject = this.currentPage.next().asObject(); - if (this.filter == null || this.filter.shouldInclude(jsonObject)) { - return jsonObject; - } - } - - if (this.hasMorePages) { - this.loadNextPage(); - } + while (this.currentPage.hasNext() || this.hasMorePages) { + while (this.currentPage.hasNext()) { + JsonObject jsonObject = this.currentPage.next().asObject(); + if (this.filter == null || this.filter.shouldInclude(jsonObject)) { + return jsonObject; } + } - return null; + if (this.hasMorePages) { + this.loadNextPage(); + } } + + return null; + } } diff --git a/src/main/java/com/box/sdk/LRUCache.java b/src/main/java/com/box/sdk/LRUCache.java index 94e58749d..a80730161 100644 --- a/src/main/java/com/box/sdk/LRUCache.java +++ b/src/main/java/com/box/sdk/LRUCache.java @@ -4,24 +4,24 @@ import java.util.LinkedHashSet; class LRUCache { - static final int MAX_SIZE = 512; + static final int MAX_SIZE = 512; - private final LinkedHashSet linkedHashSet; + private final LinkedHashSet linkedHashSet; - LRUCache() { - this.linkedHashSet = new LinkedHashSet(MAX_SIZE); - } - - boolean add(E item) { - boolean newItem = !this.linkedHashSet.remove(item); - this.linkedHashSet.add(item); + LRUCache() { + this.linkedHashSet = new LinkedHashSet(MAX_SIZE); + } - if (this.linkedHashSet.size() >= MAX_SIZE) { - Iterator it = this.linkedHashSet.iterator(); - it.next(); - it.remove(); - } + boolean add(E item) { + boolean newItem = !this.linkedHashSet.remove(item); + this.linkedHashSet.add(item); - return newItem; + if (this.linkedHashSet.size() >= MAX_SIZE) { + Iterator it = this.linkedHashSet.iterator(); + it.next(); + it.remove(); } + + return newItem; + } } diff --git a/src/main/java/com/box/sdk/LargeFileUpload.java b/src/main/java/com/box/sdk/LargeFileUpload.java index fa4bc3cea..080f2889b 100644 --- a/src/main/java/com/box/sdk/LargeFileUpload.java +++ b/src/main/java/com/box/sdk/LargeFileUpload.java @@ -16,291 +16,309 @@ import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; -/** - * Utility class for uploading large files. - */ +/** Utility class for uploading large files. */ public final class LargeFileUpload { - private static final String DIGEST_ALGORITHM_SHA1 = "SHA1"; - private static final int DEFAULT_CONNECTIONS = 3; - private static final int DEFAULT_TIMEOUT = 1; - private static final TimeUnit DEFAULT_TIMEUNIT = TimeUnit.HOURS; - private static final int THREAD_POOL_WAIT_TIME_IN_MILLIS = 1000; - private final ThreadPoolExecutor executorService; - private final long timeout; - private final TimeUnit timeUnit; - - /** - * Creates a LargeFileUpload object. - * - * @param nParallelConnections number of parallel http connections to use - * @param timeOut time to wait before killing the job - * @param unit time unit for the time wait value - */ - public LargeFileUpload(int nParallelConnections, long timeOut, TimeUnit unit) { - this.executorService = (ThreadPoolExecutor) Executors.newFixedThreadPool(nParallelConnections); - this.timeout = timeOut; - this.timeUnit = unit; + private static final String DIGEST_ALGORITHM_SHA1 = "SHA1"; + private static final int DEFAULT_CONNECTIONS = 3; + private static final int DEFAULT_TIMEOUT = 1; + private static final TimeUnit DEFAULT_TIMEUNIT = TimeUnit.HOURS; + private static final int THREAD_POOL_WAIT_TIME_IN_MILLIS = 1000; + private final ThreadPoolExecutor executorService; + private final long timeout; + private final TimeUnit timeUnit; + + /** + * Creates a LargeFileUpload object. + * + * @param nParallelConnections number of parallel http connections to use + * @param timeOut time to wait before killing the job + * @param unit time unit for the time wait value + */ + public LargeFileUpload(int nParallelConnections, long timeOut, TimeUnit unit) { + this.executorService = (ThreadPoolExecutor) Executors.newFixedThreadPool(nParallelConnections); + this.timeout = timeOut; + this.timeUnit = unit; + } + + /** Creates a LargeFileUpload object with a default number of parallel conections and timeout. */ + public LargeFileUpload() { + this.executorService = + (ThreadPoolExecutor) Executors.newFixedThreadPool(LargeFileUpload.DEFAULT_CONNECTIONS); + this.timeout = LargeFileUpload.DEFAULT_TIMEOUT; + this.timeUnit = LargeFileUpload.DEFAULT_TIMEUNIT; + } + + private static byte[] getBytesFromStream(InputStream stream, int numBytes) { + + int bytesNeeded = numBytes; + int offset = 0; + byte[] bytes = new byte[numBytes]; + + while (bytesNeeded > 0) { + + int bytesRead; + try { + bytesRead = stream.read(bytes, offset, bytesNeeded); + } catch (IOException ioe) { + throw new BoxAPIException("Reading data from stream failed.", ioe); + } + + if (bytesRead == -1) { + throw new BoxAPIException("Stream ended while upload was progressing"); + } + + bytesNeeded = bytesNeeded - bytesRead; + offset = offset + bytesRead; } - /** - * Creates a LargeFileUpload object with a default number of parallel conections and timeout. - */ - public LargeFileUpload() { - this.executorService = (ThreadPoolExecutor) Executors.newFixedThreadPool(LargeFileUpload.DEFAULT_CONNECTIONS); - this.timeout = LargeFileUpload.DEFAULT_TIMEOUT; - this.timeUnit = LargeFileUpload.DEFAULT_TIMEUNIT; - } - - private static byte[] getBytesFromStream(InputStream stream, int numBytes) { + return bytes; + } - int bytesNeeded = numBytes; - int offset = 0; - byte[] bytes = new byte[numBytes]; + private BoxFileUploadSession.Info createUploadSession( + BoxAPIConnection boxApi, String folderId, URL url, String fileName, long fileSize) { - while (bytesNeeded > 0) { + BoxJSONRequest request = new BoxJSONRequest(boxApi, url, HttpMethod.POST); - int bytesRead; - try { - bytesRead = stream.read(bytes, offset, bytesNeeded); - } catch (IOException ioe) { - throw new BoxAPIException("Reading data from stream failed.", ioe); - } + // Create the JSON body of the request + JsonObject body = new JsonObject(); + body.add("folder_id", folderId); + body.add("file_name", fileName); + body.add("file_size", fileSize); + request.setBody(body.toString()); - if (bytesRead == -1) { - throw new BoxAPIException("Stream ended while upload was progressing"); - } + try (BoxJSONResponse response = request.send()) { + JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - bytesNeeded = bytesNeeded - bytesRead; - offset = offset + bytesRead; - } + String sessionId = jsonObject.get("id").asString(); + BoxFileUploadSession session = new BoxFileUploadSession(boxApi, sessionId); - return bytes; + return session.new Info(jsonObject); } - - private BoxFileUploadSession.Info createUploadSession(BoxAPIConnection boxApi, String folderId, - URL url, String fileName, long fileSize) { - - BoxJSONRequest request = new BoxJSONRequest(boxApi, url, HttpMethod.POST); - - //Create the JSON body of the request - JsonObject body = new JsonObject(); - body.add("folder_id", folderId); - body.add("file_name", fileName); - body.add("file_size", fileSize); - request.setBody(body.toString()); - - try (BoxJSONResponse response = request.send()) { - JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - - String sessionId = jsonObject.get("id").asString(); - BoxFileUploadSession session = new BoxFileUploadSession(boxApi, sessionId); - - return session.new Info(jsonObject); - } + } + + /** + * Uploads a new large file. + * + * @param boxApi the API connection to be used by the upload session. + * @param folderId the id of the folder in which the file will be uploaded. + * @param stream the input stream that feeds the content of the file. + * @param url the upload session URL. + * @param fileName the name of the file to be created. + * @param fileSize the total size of the file. + * @return the created file instance. + * @throws InterruptedException when a thread gets interupted. + * @throws IOException when reading a stream throws exception. + */ + public BoxFile.Info upload( + BoxAPIConnection boxApi, + String folderId, + InputStream stream, + URL url, + String fileName, + long fileSize) + throws InterruptedException, IOException { + // Create a upload session + BoxFileUploadSession.Info session = + this.createUploadSession(boxApi, folderId, url, fileName, fileSize); + return this.uploadHelper(session, stream, fileSize, null); + } + + /** + * Uploads a new large file and sets file attributes. + * + * @param boxApi the API connection to be used by the upload session. + * @param folderId the id of the folder in which the file will be uploaded. + * @param stream the input stream that feeds the content of the file. + * @param url the upload session URL. + * @param fileName the name of the file to be created. + * @param fileSize the total size of the file. + * @param fileAttributes file attributes to set + * @return the created file instance. + * @throws InterruptedException when a thread gets interupted. + * @throws IOException when reading a stream throws exception. + */ + public BoxFile.Info upload( + BoxAPIConnection boxApi, + String folderId, + InputStream stream, + URL url, + String fileName, + long fileSize, + Map fileAttributes) + throws InterruptedException, IOException { + // Create a upload session + BoxFileUploadSession.Info session = + this.createUploadSession(boxApi, folderId, url, fileName, fileSize); + return this.uploadHelper(session, stream, fileSize, fileAttributes); + } + + /** + * Creates a new version of a large file. + * + * @param boxApi the API connection to be used by the upload session. + * @param stream the input stream that feeds the content of the file. + * @param url the upload session URL. + * @param fileSize the total size of the file. + * @return the file instance that also contains the version information. + * @throws InterruptedException when a thread gets interupted. + * @throws IOException when reading a stream throws exception. + */ + public BoxFile.Info upload(BoxAPIConnection boxApi, InputStream stream, URL url, long fileSize) + throws InterruptedException, IOException { + // creates a upload session + BoxFileUploadSession.Info session = this.createUploadSession(boxApi, url, fileSize); + return this.uploadHelper(session, stream, fileSize, null); + } + + /** + * Creates a new version of a large file and sets file attributes. + * + * @param boxApi the API connection to be used by the upload session. + * @param stream the input stream that feeds the content of the file. + * @param url the upload session URL. + * @param fileSize the total size of the file. + * @param fileAttributes file attributes to set. + * @return the file instance that also contains the version information. + * @throws InterruptedException when a thread gets interupted. + * @throws IOException when reading a stream throws exception. + */ + public BoxFile.Info upload( + BoxAPIConnection boxApi, + InputStream stream, + URL url, + long fileSize, + Map fileAttributes) + throws InterruptedException, IOException { + // creates an upload session + BoxFileUploadSession.Info session = this.createUploadSession(boxApi, url, fileSize); + return this.uploadHelper(session, stream, fileSize, fileAttributes); + } + + private BoxFile.Info uploadHelper( + BoxFileUploadSession.Info session, + InputStream stream, + long fileSize, + Map fileAttributes) + throws InterruptedException { + // Upload parts using the upload session + MessageDigest digest; + try { + digest = MessageDigest.getInstance(DIGEST_ALGORITHM_SHA1); + } catch (NoSuchAlgorithmException ae) { + throw new BoxAPIException("Digest algorithm not found", ae); } - - /** - * Uploads a new large file. - * - * @param boxApi the API connection to be used by the upload session. - * @param folderId the id of the folder in which the file will be uploaded. - * @param stream the input stream that feeds the content of the file. - * @param url the upload session URL. - * @param fileName the name of the file to be created. - * @param fileSize the total size of the file. - * @return the created file instance. - * @throws InterruptedException when a thread gets interupted. - * @throws IOException when reading a stream throws exception. - */ - public BoxFile.Info upload(BoxAPIConnection boxApi, String folderId, InputStream stream, URL url, - String fileName, long fileSize) throws InterruptedException, IOException { - //Create a upload session - BoxFileUploadSession.Info session = this.createUploadSession(boxApi, folderId, url, fileName, fileSize); - return this.uploadHelper(session, stream, fileSize, null); + DigestInputStream dis = new DigestInputStream(stream, digest); + List parts = this.uploadParts(session, dis, fileSize); + + // Creates the file hash + byte[] digestBytes = digest.digest(); + String digestStr = Base64.encode(digestBytes); + + // Commit the upload session. If there is a failure, abort the commit. + try { + return session.getResource().commit(digestStr, parts, fileAttributes, null, null); + } catch (Exception e) { + session.getResource().abort(); + throw new BoxAPIException("Unable to commit the upload session", e); } + } - /** - * Uploads a new large file and sets file attributes. - * - * @param boxApi the API connection to be used by the upload session. - * @param folderId the id of the folder in which the file will be uploaded. - * @param stream the input stream that feeds the content of the file. - * @param url the upload session URL. - * @param fileName the name of the file to be created. - * @param fileSize the total size of the file. - * @param fileAttributes file attributes to set - * @return the created file instance. - * @throws InterruptedException when a thread gets interupted. - * @throws IOException when reading a stream throws exception. - */ - public BoxFile.Info upload(BoxAPIConnection boxApi, String folderId, InputStream stream, URL url, - String fileName, long fileSize, Map fileAttributes) - throws InterruptedException, IOException { - //Create a upload session - BoxFileUploadSession.Info session = this.createUploadSession(boxApi, folderId, url, fileName, fileSize); - return this.uploadHelper(session, stream, fileSize, fileAttributes); - } + private BoxFileUploadSession.Info createUploadSession( + BoxAPIConnection boxApi, URL url, long fileSize) { + BoxJSONRequest request = new BoxJSONRequest(boxApi, url, HttpMethod.POST); - /** - * Creates a new version of a large file. - * - * @param boxApi the API connection to be used by the upload session. - * @param stream the input stream that feeds the content of the file. - * @param url the upload session URL. - * @param fileSize the total size of the file. - * @return the file instance that also contains the version information. - * @throws InterruptedException when a thread gets interupted. - * @throws IOException when reading a stream throws exception. - */ - public BoxFile.Info upload(BoxAPIConnection boxApi, InputStream stream, URL url, long fileSize) - throws InterruptedException, IOException { - //creates a upload session - BoxFileUploadSession.Info session = this.createUploadSession(boxApi, url, fileSize); - return this.uploadHelper(session, stream, fileSize, null); - } + // Creates the body of the request + JsonObject body = new JsonObject(); + body.add("file_size", fileSize); + request.setBody(body.toString()); - /** - * Creates a new version of a large file and sets file attributes. - * - * @param boxApi the API connection to be used by the upload session. - * @param stream the input stream that feeds the content of the file. - * @param url the upload session URL. - * @param fileSize the total size of the file. - * @param fileAttributes file attributes to set. - * @return the file instance that also contains the version information. - * @throws InterruptedException when a thread gets interupted. - * @throws IOException when reading a stream throws exception. - */ - public BoxFile.Info upload(BoxAPIConnection boxApi, InputStream stream, URL url, long fileSize, - Map fileAttributes) - throws InterruptedException, IOException { - //creates an upload session - BoxFileUploadSession.Info session = this.createUploadSession(boxApi, url, fileSize); - return this.uploadHelper(session, stream, fileSize, fileAttributes); - } + try (BoxJSONResponse response = request.send()) { + JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - private BoxFile.Info uploadHelper(BoxFileUploadSession.Info session, InputStream stream, long fileSize, - Map fileAttributes) - throws InterruptedException { - //Upload parts using the upload session - MessageDigest digest; - try { - digest = MessageDigest.getInstance(DIGEST_ALGORITHM_SHA1); - } catch (NoSuchAlgorithmException ae) { - throw new BoxAPIException("Digest algorithm not found", ae); + String sessionId = jsonObject.get("id").asString(); + BoxFileUploadSession session = new BoxFileUploadSession(boxApi, sessionId); + + return session.new Info(jsonObject); + } + } + + /* + * Upload parts of the file. The part size is retrieved from the upload session. + */ + private List uploadParts( + BoxFileUploadSession.Info session, InputStream stream, long fileSize) + throws InterruptedException { + List parts = new ArrayList<>(); + + int partSize = session.getPartSize(); + long offset = 0; + long processed = 0; + int partPostion = 0; + // Set the Max Queue Size to 1.5x the number of processors + double maxQueueSizeDouble = Math.ceil(this.executorService.getMaximumPoolSize() * 1.5); + int maxQueueSize = Double.valueOf(maxQueueSizeDouble).intValue(); + while (processed < fileSize) { + // Waiting for any thread to finish before + long timeoutForWaitingInMillis = TimeUnit.MILLISECONDS.convert(this.timeout, this.timeUnit); + if (this.executorService.getCorePoolSize() <= this.executorService.getActiveCount()) { + if (timeoutForWaitingInMillis > 0) { + Thread.sleep(LargeFileUpload.THREAD_POOL_WAIT_TIME_IN_MILLIS); + timeoutForWaitingInMillis -= THREAD_POOL_WAIT_TIME_IN_MILLIS; + } else { + throw new BoxAPIException("Upload parts timedout"); } - DigestInputStream dis = new DigestInputStream(stream, digest); - List parts = this.uploadParts(session, dis, fileSize); - - //Creates the file hash - byte[] digestBytes = digest.digest(); - String digestStr = Base64.encode(digestBytes); - - //Commit the upload session. If there is a failure, abort the commit. - try { - return session.getResource().commit(digestStr, parts, fileAttributes, null, null); - } catch (Exception e) { - session.getResource().abort(); - throw new BoxAPIException("Unable to commit the upload session", e); + } + if (this.executorService.getQueue().size() < maxQueueSize) { + long diff = fileSize - processed; + // The size last part of the file can be lesser than the part size. + if (diff < (long) partSize) { + partSize = (int) diff; } + parts.add(null); + byte[] bytes = getBytesFromStream(stream, partSize); + this.executorService.execute( + new LargeFileUploadTask( + session.getResource(), bytes, offset, partSize, fileSize, parts, partPostion)); + + // Increase the offset and proceesed bytes to calculate the Content-Range header. + processed += partSize; + offset += partSize; + partPostion++; + } } - - private BoxFileUploadSession.Info createUploadSession(BoxAPIConnection boxApi, URL url, long fileSize) { - BoxJSONRequest request = new BoxJSONRequest(boxApi, url, HttpMethod.POST); - - //Creates the body of the request - JsonObject body = new JsonObject(); - body.add("file_size", fileSize); - request.setBody(body.toString()); - - try (BoxJSONResponse response = request.send()) { - JsonObject jsonObject = Json.parse(response.getJSON()).asObject(); - - String sessionId = jsonObject.get("id").asString(); - BoxFileUploadSession session = new BoxFileUploadSession(boxApi, sessionId); - - return session.new Info(jsonObject); - } + this.executorService.shutdown(); + this.executorService.awaitTermination(this.timeout, this.timeUnit); + return parts; + } + + /** + * Generates the Base64 encoded SHA-1 hash for content available in the stream. It can be used to + * calculate the hash of a file. + * + * @param stream the input stream of the file or data. + * @return the Base64 encoded hash string. + */ + public String generateDigest(InputStream stream) { + MessageDigest digest; + try { + digest = MessageDigest.getInstance(DIGEST_ALGORITHM_SHA1); + } catch (NoSuchAlgorithmException ae) { + throw new BoxAPIException("Digest algorithm not found", ae); } - /* - * Upload parts of the file. The part size is retrieved from the upload session. - */ - private List uploadParts( - BoxFileUploadSession.Info session, InputStream stream, long fileSize - ) throws InterruptedException { - List parts = new ArrayList<>(); - - int partSize = session.getPartSize(); - long offset = 0; - long processed = 0; - int partPostion = 0; - //Set the Max Queue Size to 1.5x the number of processors - double maxQueueSizeDouble = Math.ceil(this.executorService.getMaximumPoolSize() * 1.5); - int maxQueueSize = Double.valueOf(maxQueueSizeDouble).intValue(); - while (processed < fileSize) { - //Waiting for any thread to finish before - long timeoutForWaitingInMillis = TimeUnit.MILLISECONDS.convert(this.timeout, this.timeUnit); - if (this.executorService.getCorePoolSize() <= this.executorService.getActiveCount()) { - if (timeoutForWaitingInMillis > 0) { - Thread.sleep(LargeFileUpload.THREAD_POOL_WAIT_TIME_IN_MILLIS); - timeoutForWaitingInMillis -= THREAD_POOL_WAIT_TIME_IN_MILLIS; - } else { - throw new BoxAPIException("Upload parts timedout"); - } - } - if (this.executorService.getQueue().size() < maxQueueSize) { - long diff = fileSize - processed; - //The size last part of the file can be lesser than the part size. - if (diff < (long) partSize) { - partSize = (int) diff; - } - parts.add(null); - byte[] bytes = getBytesFromStream(stream, partSize); - this.executorService.execute( - new LargeFileUploadTask(session.getResource(), bytes, offset, - partSize, fileSize, parts, partPostion) - ); - - //Increase the offset and proceesed bytes to calculate the Content-Range header. - processed += partSize; - offset += partSize; - partPostion++; - } - } - this.executorService.shutdown(); - this.executorService.awaitTermination(this.timeout, this.timeUnit); - return parts; + // Calcuate the digest using the stream. + DigestInputStream dis = new DigestInputStream(stream, digest); + try { + int value = dis.read(); + while (value != -1) { + value = dis.read(); + } + } catch (IOException ioe) { + throw new BoxAPIException("Reading the stream failed.", ioe); } - /** - * Generates the Base64 encoded SHA-1 hash for content available in the stream. - * It can be used to calculate the hash of a file. - * - * @param stream the input stream of the file or data. - * @return the Base64 encoded hash string. - */ - public String generateDigest(InputStream stream) { - MessageDigest digest; - try { - digest = MessageDigest.getInstance(DIGEST_ALGORITHM_SHA1); - } catch (NoSuchAlgorithmException ae) { - throw new BoxAPIException("Digest algorithm not found", ae); - } - - //Calcuate the digest using the stream. - DigestInputStream dis = new DigestInputStream(stream, digest); - try { - int value = dis.read(); - while (value != -1) { - value = dis.read(); - } - } catch (IOException ioe) { - throw new BoxAPIException("Reading the stream failed.", ioe); - } - - //Get the calculated digest for the stream - byte[] digestBytes = digest.digest(); - return Base64.encode(digestBytes); - } + // Get the calculated digest for the stream + byte[] digestBytes = digest.digest(); + return Base64.encode(digestBytes); + } } diff --git a/src/main/java/com/box/sdk/LargeFileUploadTask.java b/src/main/java/com/box/sdk/LargeFileUploadTask.java index 988603c45..908b54aea 100644 --- a/src/main/java/com/box/sdk/LargeFileUploadTask.java +++ b/src/main/java/com/box/sdk/LargeFileUploadTask.java @@ -2,56 +2,61 @@ import java.util.List; -/** - * - */ +/** */ public class LargeFileUploadTask implements Runnable { - private final int partPostion; - private BoxFileUploadSession session; - private byte[] data; - private List parts; - private long offset; - private int partSize; - private long fileSize; + private final int partPostion; + private BoxFileUploadSession session; + private byte[] data; + private List parts; + private long offset; + private int partSize; + private long fileSize; - /** - * Runable task to create parallel http connctions for file upload session. - * - * @param session file upload session object - * @param data bytes to be uploaded - * @param offset stream offset - * @param partSize part size of the put request - * @param fileSize total file size - * @param parts list of the BoxFileUploadSessionPart objects - * @param partPostion sequence number of the part - */ - public LargeFileUploadTask(BoxFileUploadSession session, byte[] data, long offset, - int partSize, long fileSize, List parts, int partPostion) { - this.session = session; - this.data = data; - this.offset = offset; - this.partSize = partSize; - this.fileSize = fileSize; - this.parts = parts; - this.partPostion = partPostion; - } + /** + * Runable task to create parallel http connctions for file upload session. + * + * @param session file upload session object + * @param data bytes to be uploaded + * @param offset stream offset + * @param partSize part size of the put request + * @param fileSize total file size + * @param parts list of the BoxFileUploadSessionPart objects + * @param partPostion sequence number of the part + */ + public LargeFileUploadTask( + BoxFileUploadSession session, + byte[] data, + long offset, + int partSize, + long fileSize, + List parts, + int partPostion) { + this.session = session; + this.data = data; + this.offset = offset; + this.partSize = partSize; + this.fileSize = fileSize; + this.parts = parts; + this.partPostion = partPostion; + } - @Override - public void run() { - //Retries the upload part 3 times in case of failure. - for (int i = 0; i < 3; i++) { - try { - BoxFileUploadSessionPart part = - this.session.uploadPart(this.data, this.offset, this.partSize, this.fileSize); - this.parts.set(this.partPostion, part); - return; - } catch (BoxAPIException ex) { - if (i == 2) { - throw ex; - } - } + @Override + public void run() { + // Retries the upload part 3 times in case of failure. + for (int i = 0; i < 3; i++) { + try { + BoxFileUploadSessionPart part = + this.session.uploadPart(this.data, this.offset, this.partSize, this.fileSize); + this.parts.set(this.partPostion, part); + return; + } catch (BoxAPIException ex) { + if (i == 2) { + throw ex; } - throw new BoxAPIException("Upload part failed for offset: " + this.offset + " range: " + this.partSize); + } } + throw new BoxAPIException( + "Upload part failed for offset: " + this.offset + " range: " + this.partSize); + } } diff --git a/src/main/java/com/box/sdk/Metadata.java b/src/main/java/com/box/sdk/Metadata.java index ac3ee7f1f..45019ff67 100644 --- a/src/main/java/com/box/sdk/Metadata.java +++ b/src/main/java/com/box/sdk/Metadata.java @@ -11,506 +11,472 @@ /** * The Metadata class represents one type instance of Box metadata. - *

- * Learn more about Box metadata: - * https://developers.box.com/metadata-api/ + * + *

Learn more about Box metadata: https://developers.box.com/metadata-api/ */ public class Metadata { - /** - * Specifies the name of the default "properties" metadata template. - */ - public static final String DEFAULT_METADATA_TYPE = "properties"; - - /** - * Specifies the "global" metadata scope. - */ - public static final String GLOBAL_METADATA_SCOPE = "global"; - - /** - * Specifies the "enterprise" metadata scope. - */ - public static final String ENTERPRISE_METADATA_SCOPE = "enterprise"; - - /** - * Specifies the classification template key. - */ - public static final String CLASSIFICATION_TEMPLATE_KEY = "securityClassification-6VMVochwUWo"; - - /** - * Classification key path. - */ - public static final String CLASSIFICATION_KEY = "/Box__Security__Classification__Key"; - - /** - * The default limit of entries per response. - */ - public static final int DEFAULT_LIMIT = 100; - - /** - * URL template for all metadata associated with item. - */ - public static final URLTemplate GET_ALL_METADATA_URL_TEMPLATE = new URLTemplate("/metadata"); - - /** - * Values contained by the metadata object. - */ - private final JsonObject values; - - /** - * Operations to be applied to the metadata object. - */ - private JsonArray operations = new JsonArray(); - - /** - * Creates an empty metadata. - */ - public Metadata() { - this.values = new JsonObject(); - } - - /** - * Creates a new metadata. - * - * @param values the initial metadata values. - */ - public Metadata(JsonObject values) { - this.values = values; - } - - /** - * Creates a copy of another metadata. - * - * @param other the other metadata object to copy. - */ - public Metadata(Metadata other) { - this.values = new JsonObject(other.values); - } - - /** - * Creates a new metadata with the specified scope and template. - * - * @param scope the scope of the metadata. - * @param template the template of the metadata. - */ - public Metadata(String scope, String template) { - this.values = new JsonObject() - .add("$scope", scope) - .add("$template", template); - } - - /** - * Used to retrieve all metadata associated with the item. - * - * @param item item to get metadata for. - * @param fields the optional fields to retrieve. - * @return An iterable of metadata instances associated with the item. - */ - public static Iterable getAllMetadata(BoxItem item, String... fields) { - QueryStringBuilder builder = new QueryStringBuilder(); - if (fields.length > 0) { - builder.appendParam("fields", fields); - } - return new BoxResourceIterable( - item.getAPI(), - GET_ALL_METADATA_URL_TEMPLATE.buildWithQuery(item.getItemURL().toString(), builder.toString()), - DEFAULT_LIMIT) { - - @Override - protected Metadata factory(JsonObject jsonObject) { - return new Metadata(jsonObject); - } - - }; - } - - static String scopeBasedOnType(String typeName) { - String scope; - if (typeName.equals(DEFAULT_METADATA_TYPE)) { - scope = GLOBAL_METADATA_SCOPE; - } else { - scope = ENTERPRISE_METADATA_SCOPE; - } - return scope; - } - - /** - * Returns the 36 character UUID to identify the metadata object. - * - * @return the metadata ID. - */ - public String getID() { - return getStringOrNull("/$id"); - } - - /** - * Returns the metadata type. - * - * @return the metadata type. - */ - public String getTypeName() { - return getStringOrNull("/$type"); - } - - /** - * Returns the parent object ID (typically the file ID). - * - * @return the parent object ID. - */ - public String getParentID() { - return getStringOrNull("/$parent"); - } - - /** - * Returns the scope. - * Can throw {@link NullPointerException} is value if not present. - * - * @return the scope. - */ - public String getScope() { - return getStringOrNull("/$scope"); - } - - /** - * Returns the template name. - * Can throw {@link NullPointerException} is value if not present. - * - * @return the template name. - */ - public String getTemplateName() { - return getStringOrNull("/$template"); - } - - /** - * Adds a new metadata value. - * - * @param path the path that designates the key. Must be prefixed with a "/". - * @param value the value. - * @return this metadata object. - */ - public Metadata add(String path, String value) { - this.values.add(this.pathToProperty(path), value); - this.addOp("add", path, value); - return this; - } - - /** - * Adds a new metadata value. - * - * @param path the path that designates the key. Must be prefixed with a "/". - * @param value the value. - * @return this metadata object. - */ - public Metadata add(String path, double value) { - this.values.add(this.pathToProperty(path), value); - this.addOp("add", path, value); - return this; - } - - /** - * Adds a new metadata value of array type. - * - * @param path the path to the field. - * @param values the collection of values. - * @return the metadata object for chaining. - */ - public Metadata add(String path, List values) { - JsonArray arr = new JsonArray(); - for (String value : values) { - arr.add(value); - } - this.values.add(this.pathToProperty(path), arr); - this.addOp("add", path, arr); - return this; - } - - /** - * Replaces an existing metadata value. - * - * @param path the path that designates the key. Must be prefixed with a "/". - * @param value the value. - * @return this metadata object. - */ - public Metadata replace(String path, String value) { - this.values.set(this.pathToProperty(path), value); - this.addOp("replace", path, value); - return this; - } - - /** - * Replaces an existing metadata value. - * - * @param path the path that designates the key. Must be prefixed with a "/". - * @param value the value. - * @return this metadata object. - */ - public Metadata replace(String path, float value) { - this.values.set(this.pathToProperty(path), value); - this.addOp("replace", path, value); - return this; - } - - /** - * Replaces an existing metadata value. - * - * @param path the path that designates the key. Must be prefixed with a "/". - * @param value the value. - * @return this metadata object. - */ - public Metadata replace(String path, double value) { - this.values.set(this.pathToProperty(path), value); - this.addOp("replace", path, value); - return this; - } - - /** - * Replaces an existing metadata value of array type. - * - * @param path the path that designates the key. Must be prefixed with a "/". - * @param values the collection of values. - * @return the metadata object. - */ - public Metadata replace(String path, List values) { - JsonArray arr = new JsonArray(); - for (String value : values) { - arr.add(value); - } - this.values.add(this.pathToProperty(path), arr); - this.addOp("replace", path, arr); - return this; - } - - /** - * Removes an existing metadata value. - * - * @param path the path that designates the key. Must be prefixed with a "/". - * @return this metadata object. - */ - public Metadata remove(String path) { - this.values.remove(this.pathToProperty(path)); - this.addOp("remove", path, (String) null); - return this; - } - - /** - * Tests that a property has the expected value. - * - * @param path the path that designates the key. Must be prefixed with a "/". - * @param value the expected value. - * @return this metadata object. - */ - public Metadata test(String path, String value) { - this.addOp("test", path, value); - return this; - } - - /** - * Tests that a list of properties has the expected value. - * The values passed in will have to be an exact match with no extra elements. - * - * @param path the path that designates the key. Must be prefixed with a "/". - * @param values the list of expected values. - * @return this metadata object. - */ - public Metadata test(String path, List values) { - JsonArray arr = new JsonArray(); - for (String value : values) { - arr.add(value); - } - this.addOp("test", path, arr); - return this; - } - - /** - * Returns a value, regardless of type. - * - * @param path the path that designates the key. Must be prefixed with a "/". - * @return the metadata property value as an indeterminate JSON type. - */ - public JsonValue getValue(String path) { - return this.values.get(this.pathToProperty(path)); - } - - /** - * Get a value from a string or enum metadata field. - * Can throw {@link NullPointerException} is value if not present. - * - * @param path the key path in the metadata object. Must be prefixed with a "/". - * @return the metadata value as a string. - */ - public String getString(String path) { - return this.getValue(path).asString(); - } - - /** - * Get a value from a double metadata field. - * Can throw {@link NullPointerException} is value if not present. - * - * @param path the key path in the metadata object. Must be prefixed with a "/". - * @return the metadata value as a floating point number. - */ - public double getDouble(String path) { - return this.getValue(path).asDouble(); - } - - /** - * Get a value from a date metadata field. - * Can throw {@link NullPointerException} is value if not present. - * - * @param path the key path in the metadata object. Must be prefixed with a "/". - * @return the metadata value as a Date. - * @throws ParseException when the value cannot be parsed as a valid date - */ - public Date getDate(String path) throws ParseException { - return BoxDateFormat.parse(this.getValue(path).asString()); - } - - /** - * Get a value from a multiselect metadata field. - * - * @param path the key path in the metadata object. Must be prefixed with a "/". - * @return the list of values set in the field. - */ - public List getMultiSelect(String path) { - List values = new ArrayList<>(); - for (JsonValue val : this.getValue(path).asArray()) { - values.add(val.asString()); - } - - return values; - } - - /** - * Returns a list of metadata property paths. - * - * @return the list of metdata property paths. - */ - public List getPropertyPaths() { - List result = new ArrayList<>(); - - for (String property : this.values.names()) { - if (!property.startsWith("$")) { - result.add(this.propertyToPath(property)); - } - } - - return result; - } - - /** - * Returns the JSON patch string with all operations. - * - * @return the JSON patch string. - */ - public String getPatch() { - if (this.operations == null) { - return "[]"; - } - return this.operations.toString(); - } - - /** - * Returns an array of operations on metadata. - * - * @return a JSON array of operations. - */ - public JsonArray getOperations() { - return this.operations; - } - - /** - * Returns the JSON representation of this metadata. - * - * @return the JSON representation of this metadata. - */ - @Override - public String toString() { - return this.values.toString(); - } - - /** - * Converts a JSON patch path to a JSON property name. - * Currently the metadata API only supports flat maps. - * - * @param path the path that designates the key. Must be prefixed with a "/". - * @return the JSON property name. - */ - private String pathToProperty(String path) { - if (path == null || !path.startsWith("/")) { - throw new IllegalArgumentException("Path must be prefixed with a \"/\"."); - } - return path.substring(1); - } - - /** - * Converts a JSON property name to a JSON patch path. - * - * @param property the JSON property name. - * @return the path that designates the key. - */ - private String propertyToPath(String property) { - if (property == null) { - throw new IllegalArgumentException("Property must not be null."); - } - return "/" + property; - } - - /** - * Adds a patch operation. - * - * @param op the operation type. Must be add, replace, remove, or test. - * @param path the path that designates the key. Must be prefixed with a "/". - * @param value the value to be set. - */ - private void addOp(String op, String path, String value) { - if (this.operations == null) { - this.operations = new JsonArray(); - } - - this.operations.add(new JsonObject() - .add("op", op) - .add("path", path) - .add("value", value)); - } - - /** - * Adds a patch operation. - * - * @param op the operation type. Must be add, replace, remove, or test. - * @param path the path that designates the key. Must be prefixed with a "/". - * @param value the value to be set. - */ - private void addOp(String op, String path, double value) { - if (this.operations == null) { - this.operations = new JsonArray(); - } - - this.operations.add(new JsonObject() - .add("op", op) - .add("path", path) - .add("value", value)); - } - - /** - * Adds a new patch operation for array values. - * - * @param op the operation type. Must be add, replace, remove, or test. - * @param path the path that designates the key. Must be prefixed with a "/". - * @param values the array of values to be set. - */ - private void addOp(String op, String path, JsonArray values) { - - if (this.operations == null) { - this.operations = new JsonArray(); - } - - this.operations.add(new JsonObject() - .add("op", op) - .add("path", path) - .add("value", values)); - } - - private String getStringOrNull(String path) { - return Optional.ofNullable(this.getValue(path)).map(JsonValue::asString).orElse(null); - } + /** Specifies the name of the default "properties" metadata template. */ + public static final String DEFAULT_METADATA_TYPE = "properties"; + + /** Specifies the "global" metadata scope. */ + public static final String GLOBAL_METADATA_SCOPE = "global"; + + /** Specifies the "enterprise" metadata scope. */ + public static final String ENTERPRISE_METADATA_SCOPE = "enterprise"; + + /** Specifies the classification template key. */ + public static final String CLASSIFICATION_TEMPLATE_KEY = "securityClassification-6VMVochwUWo"; + + /** Classification key path. */ + public static final String CLASSIFICATION_KEY = "/Box__Security__Classification__Key"; + + /** The default limit of entries per response. */ + public static final int DEFAULT_LIMIT = 100; + + /** URL template for all metadata associated with item. */ + public static final URLTemplate GET_ALL_METADATA_URL_TEMPLATE = new URLTemplate("/metadata"); + + /** Values contained by the metadata object. */ + private final JsonObject values; + + /** Operations to be applied to the metadata object. */ + private JsonArray operations = new JsonArray(); + + /** Creates an empty metadata. */ + public Metadata() { + this.values = new JsonObject(); + } + + /** + * Creates a new metadata. + * + * @param values the initial metadata values. + */ + public Metadata(JsonObject values) { + this.values = values; + } + + /** + * Creates a copy of another metadata. + * + * @param other the other metadata object to copy. + */ + public Metadata(Metadata other) { + this.values = new JsonObject(other.values); + } + + /** + * Creates a new metadata with the specified scope and template. + * + * @param scope the scope of the metadata. + * @param template the template of the metadata. + */ + public Metadata(String scope, String template) { + this.values = new JsonObject().add("$scope", scope).add("$template", template); + } + + /** + * Used to retrieve all metadata associated with the item. + * + * @param item item to get metadata for. + * @param fields the optional fields to retrieve. + * @return An iterable of metadata instances associated with the item. + */ + public static Iterable getAllMetadata(BoxItem item, String... fields) { + QueryStringBuilder builder = new QueryStringBuilder(); + if (fields.length > 0) { + builder.appendParam("fields", fields); + } + return new BoxResourceIterable( + item.getAPI(), + GET_ALL_METADATA_URL_TEMPLATE.buildWithQuery( + item.getItemURL().toString(), builder.toString()), + DEFAULT_LIMIT) { + + @Override + protected Metadata factory(JsonObject jsonObject) { + return new Metadata(jsonObject); + } + }; + } + + static String scopeBasedOnType(String typeName) { + String scope; + if (typeName.equals(DEFAULT_METADATA_TYPE)) { + scope = GLOBAL_METADATA_SCOPE; + } else { + scope = ENTERPRISE_METADATA_SCOPE; + } + return scope; + } + + /** + * Returns the 36 character UUID to identify the metadata object. + * + * @return the metadata ID. + */ + public String getID() { + return getStringOrNull("/$id"); + } + + /** + * Returns the metadata type. + * + * @return the metadata type. + */ + public String getTypeName() { + return getStringOrNull("/$type"); + } + + /** + * Returns the parent object ID (typically the file ID). + * + * @return the parent object ID. + */ + public String getParentID() { + return getStringOrNull("/$parent"); + } + + /** + * Returns the scope. Can throw {@link NullPointerException} is value if not present. + * + * @return the scope. + */ + public String getScope() { + return getStringOrNull("/$scope"); + } + + /** + * Returns the template name. Can throw {@link NullPointerException} is value if not present. + * + * @return the template name. + */ + public String getTemplateName() { + return getStringOrNull("/$template"); + } + + /** + * Adds a new metadata value. + * + * @param path the path that designates the key. Must be prefixed with a "/". + * @param value the value. + * @return this metadata object. + */ + public Metadata add(String path, String value) { + this.values.add(this.pathToProperty(path), value); + this.addOp("add", path, value); + return this; + } + + /** + * Adds a new metadata value. + * + * @param path the path that designates the key. Must be prefixed with a "/". + * @param value the value. + * @return this metadata object. + */ + public Metadata add(String path, double value) { + this.values.add(this.pathToProperty(path), value); + this.addOp("add", path, value); + return this; + } + + /** + * Adds a new metadata value of array type. + * + * @param path the path to the field. + * @param values the collection of values. + * @return the metadata object for chaining. + */ + public Metadata add(String path, List values) { + JsonArray arr = new JsonArray(); + for (String value : values) { + arr.add(value); + } + this.values.add(this.pathToProperty(path), arr); + this.addOp("add", path, arr); + return this; + } + + /** + * Replaces an existing metadata value. + * + * @param path the path that designates the key. Must be prefixed with a "/". + * @param value the value. + * @return this metadata object. + */ + public Metadata replace(String path, String value) { + this.values.set(this.pathToProperty(path), value); + this.addOp("replace", path, value); + return this; + } + + /** + * Replaces an existing metadata value. + * + * @param path the path that designates the key. Must be prefixed with a "/". + * @param value the value. + * @return this metadata object. + */ + public Metadata replace(String path, float value) { + this.values.set(this.pathToProperty(path), value); + this.addOp("replace", path, value); + return this; + } + + /** + * Replaces an existing metadata value. + * + * @param path the path that designates the key. Must be prefixed with a "/". + * @param value the value. + * @return this metadata object. + */ + public Metadata replace(String path, double value) { + this.values.set(this.pathToProperty(path), value); + this.addOp("replace", path, value); + return this; + } + + /** + * Replaces an existing metadata value of array type. + * + * @param path the path that designates the key. Must be prefixed with a "/". + * @param values the collection of values. + * @return the metadata object. + */ + public Metadata replace(String path, List values) { + JsonArray arr = new JsonArray(); + for (String value : values) { + arr.add(value); + } + this.values.add(this.pathToProperty(path), arr); + this.addOp("replace", path, arr); + return this; + } + + /** + * Removes an existing metadata value. + * + * @param path the path that designates the key. Must be prefixed with a "/". + * @return this metadata object. + */ + public Metadata remove(String path) { + this.values.remove(this.pathToProperty(path)); + this.addOp("remove", path, (String) null); + return this; + } + + /** + * Tests that a property has the expected value. + * + * @param path the path that designates the key. Must be prefixed with a "/". + * @param value the expected value. + * @return this metadata object. + */ + public Metadata test(String path, String value) { + this.addOp("test", path, value); + return this; + } + + /** + * Tests that a list of properties has the expected value. The values passed in will have to be an + * exact match with no extra elements. + * + * @param path the path that designates the key. Must be prefixed with a "/". + * @param values the list of expected values. + * @return this metadata object. + */ + public Metadata test(String path, List values) { + JsonArray arr = new JsonArray(); + for (String value : values) { + arr.add(value); + } + this.addOp("test", path, arr); + return this; + } + + /** + * Returns a value, regardless of type. + * + * @param path the path that designates the key. Must be prefixed with a "/". + * @return the metadata property value as an indeterminate JSON type. + */ + public JsonValue getValue(String path) { + return this.values.get(this.pathToProperty(path)); + } + + /** + * Get a value from a string or enum metadata field. Can throw {@link NullPointerException} is + * value if not present. + * + * @param path the key path in the metadata object. Must be prefixed with a "/". + * @return the metadata value as a string. + */ + public String getString(String path) { + return this.getValue(path).asString(); + } + + /** + * Get a value from a double metadata field. Can throw {@link NullPointerException} is value if + * not present. + * + * @param path the key path in the metadata object. Must be prefixed with a "/". + * @return the metadata value as a floating point number. + */ + public double getDouble(String path) { + return this.getValue(path).asDouble(); + } + + /** + * Get a value from a date metadata field. Can throw {@link NullPointerException} is value if not + * present. + * + * @param path the key path in the metadata object. Must be prefixed with a "/". + * @return the metadata value as a Date. + * @throws ParseException when the value cannot be parsed as a valid date + */ + public Date getDate(String path) throws ParseException { + return BoxDateFormat.parse(this.getValue(path).asString()); + } + + /** + * Get a value from a multiselect metadata field. + * + * @param path the key path in the metadata object. Must be prefixed with a "/". + * @return the list of values set in the field. + */ + public List getMultiSelect(String path) { + List values = new ArrayList<>(); + for (JsonValue val : this.getValue(path).asArray()) { + values.add(val.asString()); + } + + return values; + } + + /** + * Returns a list of metadata property paths. + * + * @return the list of metdata property paths. + */ + public List getPropertyPaths() { + List result = new ArrayList<>(); + + for (String property : this.values.names()) { + if (!property.startsWith("$")) { + result.add(this.propertyToPath(property)); + } + } + + return result; + } + + /** + * Returns the JSON patch string with all operations. + * + * @return the JSON patch string. + */ + public String getPatch() { + if (this.operations == null) { + return "[]"; + } + return this.operations.toString(); + } + + /** + * Returns an array of operations on metadata. + * + * @return a JSON array of operations. + */ + public JsonArray getOperations() { + return this.operations; + } + + /** + * Returns the JSON representation of this metadata. + * + * @return the JSON representation of this metadata. + */ + @Override + public String toString() { + return this.values.toString(); + } + + /** + * Converts a JSON patch path to a JSON property name. Currently the metadata API only supports + * flat maps. + * + * @param path the path that designates the key. Must be prefixed with a "/". + * @return the JSON property name. + */ + private String pathToProperty(String path) { + if (path == null || !path.startsWith("/")) { + throw new IllegalArgumentException("Path must be prefixed with a \"/\"."); + } + return path.substring(1); + } + + /** + * Converts a JSON property name to a JSON patch path. + * + * @param property the JSON property name. + * @return the path that designates the key. + */ + private String propertyToPath(String property) { + if (property == null) { + throw new IllegalArgumentException("Property must not be null."); + } + return "/" + property; + } + + /** + * Adds a patch operation. + * + * @param op the operation type. Must be add, replace, remove, or test. + * @param path the path that designates the key. Must be prefixed with a "/". + * @param value the value to be set. + */ + private void addOp(String op, String path, String value) { + if (this.operations == null) { + this.operations = new JsonArray(); + } + + this.operations.add(new JsonObject().add("op", op).add("path", path).add("value", value)); + } + + /** + * Adds a patch operation. + * + * @param op the operation type. Must be add, replace, remove, or test. + * @param path the path that designates the key. Must be prefixed with a "/". + * @param value the value to be set. + */ + private void addOp(String op, String path, double value) { + if (this.operations == null) { + this.operations = new JsonArray(); + } + + this.operations.add(new JsonObject().add("op", op).add("path", path).add("value", value)); + } + + /** + * Adds a new patch operation for array values. + * + * @param op the operation type. Must be add, replace, remove, or test. + * @param path the path that designates the key. Must be prefixed with a "/". + * @param values the array of values to be set. + */ + private void addOp(String op, String path, JsonArray values) { + + if (this.operations == null) { + this.operations = new JsonArray(); + } + + this.operations.add(new JsonObject().add("op", op).add("path", path).add("value", values)); + } + + private String getStringOrNull(String path) { + return Optional.ofNullable(this.getValue(path)).map(JsonValue::asString).orElse(null); + } } diff --git a/src/main/java/com/box/sdk/MetadataFieldFilter.java b/src/main/java/com/box/sdk/MetadataFieldFilter.java index b4a5a517e..9f4a0c8f9 100644 --- a/src/main/java/com/box/sdk/MetadataFieldFilter.java +++ b/src/main/java/com/box/sdk/MetadataFieldFilter.java @@ -4,48 +4,46 @@ import com.eclipsesource.json.JsonObject; import com.eclipsesource.json.JsonValue; -/** - * Filter for matching against a metadata field. - */ +/** Filter for matching against a metadata field. */ public class MetadataFieldFilter { - private final String field; - private final JsonValue value; - - /** - * Create a filter for matching against a string metadata field. - * - * @param field the field to match against. - * @param value the value to match against. - */ - public MetadataFieldFilter(String field, String value) { - - this.field = field; - this.value = Json.value(value); - } - - /** - * Create a filter for matching against a metadata field defined in JSON. - * - * @param jsonObj the JSON object to construct the filter from. - */ - public MetadataFieldFilter(JsonObject jsonObj) { - this.field = jsonObj.get("field").asString(); - this.value = jsonObj.get("value"); - } - - /** - * Get the JSON representation of the metadata field filter. - * - * @return the JSON object representing the filter. - */ - public JsonObject getJsonObject() { - - JsonObject obj = new JsonObject(); - obj.add("field", this.field); - - obj.add("value", this.value); - - return obj; - } + private final String field; + private final JsonValue value; + + /** + * Create a filter for matching against a string metadata field. + * + * @param field the field to match against. + * @param value the value to match against. + */ + public MetadataFieldFilter(String field, String value) { + + this.field = field; + this.value = Json.value(value); + } + + /** + * Create a filter for matching against a metadata field defined in JSON. + * + * @param jsonObj the JSON object to construct the filter from. + */ + public MetadataFieldFilter(JsonObject jsonObj) { + this.field = jsonObj.get("field").asString(); + this.value = jsonObj.get("value"); + } + + /** + * Get the JSON representation of the metadata field filter. + * + * @return the JSON object representing the filter. + */ + public JsonObject getJsonObject() { + + JsonObject obj = new JsonObject(); + obj.add("field", this.field); + + obj.add("value", this.value); + + return obj; + } } diff --git a/src/main/java/com/box/sdk/MetadataQuery.java b/src/main/java/com/box/sdk/MetadataQuery.java index 4971042db..d2b621a98 100644 --- a/src/main/java/com/box/sdk/MetadataQuery.java +++ b/src/main/java/com/box/sdk/MetadataQuery.java @@ -10,289 +10,286 @@ import java.util.Arrays; import java.util.List; -/** - * Represents Metadata Query. - */ +/** Represents Metadata Query. */ public class MetadataQuery { - static final String FROM = "from"; - static final String LIMIT = "limit"; - static final String QUERY = "query"; - static final String ANCESTOR_FOLDER_ID = "ancestor_folder_id"; - static final String MARKER = "marker"; - static final String ORDER_BY = "order_by"; - static final String FIELDS = "fields"; - static final String QUERY_PARAMS = "query_params"; - private final String from; - private final int limit; - private String query; - private JsonObject queryParameters = new JsonObject(); - private String ancestorFolderId = "0"; - private List orderBy = new ArrayList<>(); - private String marker; - private List fields = new ArrayList<>(); + static final String FROM = "from"; + static final String LIMIT = "limit"; + static final String QUERY = "query"; + static final String ANCESTOR_FOLDER_ID = "ancestor_folder_id"; + static final String MARKER = "marker"; + static final String ORDER_BY = "order_by"; + static final String FIELDS = "fields"; + static final String QUERY_PARAMS = "query_params"; + private final String from; + private final int limit; + private String query; + private JsonObject queryParameters = new JsonObject(); + private String ancestorFolderId = "0"; + private List orderBy = new ArrayList<>(); + private String marker; + private List fields = new ArrayList<>(); - /** - * Creates Metadata Query - * - * @param from The template used in the query. Must be in the form scope_enterpriseID.templateKey - * @param limit Max results to return for a single request (0-100 inclusive) - */ - public MetadataQuery(String from, int limit) { - this.from = from; - this.limit = limit; - } + /** + * Creates Metadata Query + * + * @param from The template used in the query. Must be in the form scope_enterpriseID.templateKey + * @param limit Max results to return for a single request (0-100 inclusive) + */ + public MetadataQuery(String from, int limit) { + this.from = from; + this.limit = limit; + } - /** - * Creates Metadata Query - * - * @param from The template used in the query. Must be in the form scope.templateKey - */ - public MetadataQuery(String from) { - this(from, 100); - } + /** + * Creates Metadata Query + * + * @param from The template used in the query. Must be in the form scope.templateKey + */ + public MetadataQuery(String from) { + this(from, 100); + } - /** - * The logical expression of the query - * - * @param query Query string - * @return Returns current MetadataQuery object - */ - public MetadataQuery setQuery(String query) { - this.query = query; - return this; - } + /** + * The logical expression of the query + * + * @param query Query string + * @return Returns current MetadataQuery object + */ + public MetadataQuery setQuery(String query) { + this.query = query; + return this; + } - /** - * Sets the folder_id to which to restrain the query. - * If not set query starts at root level. - * - * @param ancestorFolderId The folder id - * @return Returns current MetadataQuery object - */ - public MetadataQuery setAncestorFolderId(String ancestorFolderId) { - this.ancestorFolderId = ancestorFolderId; - return this; - } + /** + * Sets the folder_id to which to restrain the query. If not set query starts at root level. + * + * @param ancestorFolderId The folder id + * @return Returns current MetadataQuery object + */ + public MetadataQuery setAncestorFolderId(String ancestorFolderId) { + this.ancestorFolderId = ancestorFolderId; + return this; + } - /** - * The marker to use for requesting the next page - * - * @param marker Marker string. - * @return Returns current MetadataQuery object - */ - public MetadataQuery setMarker(String marker) { - this.marker = marker; - return this; - } + /** + * The marker to use for requesting the next page + * + * @param marker Marker string. + * @return Returns current MetadataQuery object + */ + public MetadataQuery setMarker(String marker) { + this.marker = marker; + return this; + } - /** - * The field_key(s) to order on and the corresponding direction(s) - * - * @param fields Fields with sort order - * @return Returns current MetadataQuery object - */ - public MetadataQuery setOrderBy(OrderBy... fields) { - this.orderBy = new ArrayList<>(); - this.orderBy.addAll(Arrays.asList(fields)); - return this; - } + /** + * The field_key(s) to order on and the corresponding direction(s) + * + * @param fields Fields with sort order + * @return Returns current MetadataQuery object + */ + public MetadataQuery setOrderBy(OrderBy... fields) { + this.orderBy = new ArrayList<>(); + this.orderBy.addAll(Arrays.asList(fields)); + return this; + } - MetadataQuery setOrderBy(JsonArray orderBy) { - if (orderBy != null) { - this.orderBy = orderBy.values().stream().map(OrderBy::fromJson).collect(toList()); - } - return this; + MetadataQuery setOrderBy(JsonArray orderBy) { + if (orderBy != null) { + this.orderBy = orderBy.values().stream().map(OrderBy::fromJson).collect(toList()); } + return this; + } - /** - * The fields to retrieve. - * - * @param fields Field names - * @return Returns current MetadataQuery object - */ - public MetadataQuery setFields(String... fields) { - this.fields = new ArrayList<>(); - this.fields.addAll(Arrays.asList(fields)); - return this; - } + /** + * The fields to retrieve. + * + * @param fields Field names + * @return Returns current MetadataQuery object + */ + public MetadataQuery setFields(String... fields) { + this.fields = new ArrayList<>(); + this.fields.addAll(Arrays.asList(fields)); + return this; + } - /** - * Adds parameter to query - * - * @param name Parameter name - * @param value Parameter value - * @return Returns current MetadataQuery object - */ - public MetadataQuery addParameter(String name, String value) { - this.queryParameters.add(name, value); - return this; - } + /** + * Adds parameter to query + * + * @param name Parameter name + * @param value Parameter value + * @return Returns current MetadataQuery object + */ + public MetadataQuery addParameter(String name, String value) { + this.queryParameters.add(name, value); + return this; + } - /** - * Adds parameter to query - * - * @param name Parameter name - * @param value Parameter value - * @return Returns current MetadataQuery object - */ - public MetadataQuery addParameter(String name, int value) { - this.queryParameters.add(name, value); - return this; - } + /** + * Adds parameter to query + * + * @param name Parameter name + * @param value Parameter value + * @return Returns current MetadataQuery object + */ + public MetadataQuery addParameter(String name, int value) { + this.queryParameters.add(name, value); + return this; + } - /** - * Adds parameter to query - * - * @param name Parameter name - * @param value Parameter value - * @return Returns current MetadataQuery object - */ - public MetadataQuery addParameter(String name, boolean value) { - this.queryParameters.add(name, value); - return this; - } + /** + * Adds parameter to query + * + * @param name Parameter name + * @param value Parameter value + * @return Returns current MetadataQuery object + */ + public MetadataQuery addParameter(String name, boolean value) { + this.queryParameters.add(name, value); + return this; + } - /** - * Adds parameter to query - * - * @param name Parameter name - * @param value Parameter value - * @return Returns current MetadataQuery object - */ - public MetadataQuery addParameter(String name, float value) { - this.queryParameters.add(name, value); - return this; - } + /** + * Adds parameter to query + * + * @param name Parameter name + * @param value Parameter value + * @return Returns current MetadataQuery object + */ + public MetadataQuery addParameter(String name, float value) { + this.queryParameters.add(name, value); + return this; + } - /** - * Adds parameter to query - * - * @param name Parameter name - * @param value Parameter value - * @return Returns current MetadataQuery object - */ - public MetadataQuery addParameter(String name, long value) { - this.queryParameters.add(name, value); - return this; - } + /** + * Adds parameter to query + * + * @param name Parameter name + * @param value Parameter value + * @return Returns current MetadataQuery object + */ + public MetadataQuery addParameter(String name, long value) { + this.queryParameters.add(name, value); + return this; + } - /** - * Adds parameter to query - * - * @param name Parameter name - * @param value Parameter value - * @return Returns current MetadataQuery object - */ - public MetadataQuery addParameter(String name, double value) { - this.queryParameters.add(name, value); - return this; - } + /** + * Adds parameter to query + * + * @param name Parameter name + * @param value Parameter value + * @return Returns current MetadataQuery object + */ + public MetadataQuery addParameter(String name, double value) { + this.queryParameters.add(name, value); + return this; + } - /** - * Adds parameter to query - * - * @param name Parameter name - * @param value Parameter value - * @return Returns current MetadataQuery object - */ - public MetadataQuery addParameter(String name, JsonValue value) { - this.queryParameters.add(name, Json.parse(value.toString())); - return this; - } + /** + * Adds parameter to query + * + * @param name Parameter name + * @param value Parameter value + * @return Returns current MetadataQuery object + */ + public MetadataQuery addParameter(String name, JsonValue value) { + this.queryParameters.add(name, Json.parse(value.toString())); + return this; + } - MetadataQuery setQueryParams(JsonObject queryParameters) { - this.queryParameters = new JsonObject(queryParameters); - return this; - } + MetadataQuery setQueryParams(JsonObject queryParameters) { + this.queryParameters = new JsonObject(queryParameters); + return this; + } - JsonObject toJsonObject() { - JsonObject jsonObject = new JsonObject() - .add(FROM, from) - .add(LIMIT, limit); - if (query != null) { - jsonObject.add(QUERY, query); - } - if (ancestorFolderId != null) { - jsonObject.add(ANCESTOR_FOLDER_ID, ancestorFolderId); - } - if (marker != null) { - jsonObject.add(MARKER, marker); - } - if (!orderBy.isEmpty()) { - JsonArray orderByJson = new JsonArray(); - orderBy.stream().map(OrderBy::toJsonObject).forEach(orderByJson::add); - jsonObject.add(ORDER_BY, orderByJson); - } - if (!fields.isEmpty()) { - JsonArray fieldsJson = new JsonArray(); - fields.forEach(fieldsJson::add); - jsonObject.add(FIELDS, fieldsJson); - } - if (queryParameters.iterator().hasNext()) { - jsonObject.add(QUERY_PARAMS, new JsonObject(queryParameters)); - } - return jsonObject; + JsonObject toJsonObject() { + JsonObject jsonObject = new JsonObject().add(FROM, from).add(LIMIT, limit); + if (query != null) { + jsonObject.add(QUERY, query); } - - int getLimit() { - return limit; + if (ancestorFolderId != null) { + jsonObject.add(ANCESTOR_FOLDER_ID, ancestorFolderId); } - - String getMarker() { - return marker; + if (marker != null) { + jsonObject.add(MARKER, marker); + } + if (!orderBy.isEmpty()) { + JsonArray orderByJson = new JsonArray(); + orderBy.stream().map(OrderBy::toJsonObject).forEach(orderByJson::add); + jsonObject.add(ORDER_BY, orderByJson); + } + if (!fields.isEmpty()) { + JsonArray fieldsJson = new JsonArray(); + fields.forEach(fieldsJson::add); + jsonObject.add(FIELDS, fieldsJson); } + if (queryParameters.iterator().hasNext()) { + jsonObject.add(QUERY_PARAMS, new JsonObject(queryParameters)); + } + return jsonObject; + } - public static final class OrderBy { + int getLimit() { + return limit; + } - static final String FIELD_KEY = "field_key"; - static final String DIRECTION = "direction"; - static final String DIRECTION_ASCENDING = "asc"; - static final String DIRECTION_DESCENDING = "desc"; - private final String fieldName; - private final String direction; + String getMarker() { + return marker; + } - private OrderBy(String fieldName, String direction) { - this.fieldName = fieldName; - this.direction = direction; - } + public static final class OrderBy { - JsonObject toJsonObject() { - return new JsonObject().add(FIELD_KEY, fieldName).add(DIRECTION, direction); - } + static final String FIELD_KEY = "field_key"; + static final String DIRECTION = "direction"; + static final String DIRECTION_ASCENDING = "asc"; + static final String DIRECTION_DESCENDING = "desc"; + private final String fieldName; + private final String direction; - /** - * Creates OrderBy for ascending sort with a specified field. - * @param fieldName Name of a field - * @return OrderBy instance - */ - public static OrderBy ascending(String fieldName) { - return new OrderBy(fieldName, DIRECTION_ASCENDING); - } + private OrderBy(String fieldName, String direction) { + this.fieldName = fieldName; + this.direction = direction; + } - /** - * Creates OrderBy for descending sort with a specified field. - * @param fieldName Name of a field - * @return OrderBy instance - */ - public static OrderBy descending(String fieldName) { - return new OrderBy(fieldName, DIRECTION_DESCENDING); - } + JsonObject toJsonObject() { + return new JsonObject().add(FIELD_KEY, fieldName).add(DIRECTION, direction); + } + + /** + * Creates OrderBy for ascending sort with a specified field. + * + * @param fieldName Name of a field + * @return OrderBy instance + */ + public static OrderBy ascending(String fieldName) { + return new OrderBy(fieldName, DIRECTION_ASCENDING); + } + + /** + * Creates OrderBy for descending sort with a specified field. + * + * @param fieldName Name of a field + * @return OrderBy instance + */ + public static OrderBy descending(String fieldName) { + return new OrderBy(fieldName, DIRECTION_DESCENDING); + } - static OrderBy fromJson(JsonValue jsonValue) { - if (jsonValue.isObject()) { - JsonObject object = jsonValue.asObject(); - String fieldName = object.get(FIELD_KEY).asString(); - String direction = object.get(DIRECTION).asString().toLowerCase(java.util.Locale.ROOT); - if (!DIRECTION_ASCENDING.equals(direction) && !DIRECTION_DESCENDING.equals(direction)) { - throw new RuntimeException( - String.format("Unsupported sort direction [%s] for field [%s]", direction, fieldName) - ); - } - return object.getString(DIRECTION, "").equals(DIRECTION_ASCENDING) - ? ascending(fieldName) - : descending(fieldName); - } - throw new RuntimeException("Unsupported json " + jsonValue); + static OrderBy fromJson(JsonValue jsonValue) { + if (jsonValue.isObject()) { + JsonObject object = jsonValue.asObject(); + String fieldName = object.get(FIELD_KEY).asString(); + String direction = object.get(DIRECTION).asString().toLowerCase(java.util.Locale.ROOT); + if (!DIRECTION_ASCENDING.equals(direction) && !DIRECTION_DESCENDING.equals(direction)) { + throw new RuntimeException( + String.format( + "Unsupported sort direction [%s] for field [%s]", direction, fieldName)); } + return object.getString(DIRECTION, "").equals(DIRECTION_ASCENDING) + ? ascending(fieldName) + : descending(fieldName); + } + throw new RuntimeException("Unsupported json " + jsonValue); } + } } diff --git a/src/main/java/com/box/sdk/MetadataTemplate.java b/src/main/java/com/box/sdk/MetadataTemplate.java index f09e08b82..94583d55b 100644 --- a/src/main/java/com/box/sdk/MetadataTemplate.java +++ b/src/main/java/com/box/sdk/MetadataTemplate.java @@ -9,1448 +9,1349 @@ import java.util.List; /** - * The MetadataTemplate class represents the Box metadata template object. - * Templates allow the metadata service to provide a multitude of services, - * such as pre-defining sets of key:value pairs or schema enforcement on specific fields. + * The MetadataTemplate class represents the Box metadata template object. Templates allow the + * metadata service to provide a multitude of services, such as pre-defining sets of key:value pairs + * or schema enforcement on specific fields. * - * @see Box metadata templates + * @see Box metadata + * templates */ public class MetadataTemplate extends BoxJSONObject { - /** - * @see #getMetadataTemplate(BoxAPIConnection) - */ - public static final URLTemplate METADATA_TEMPLATE_URL_TEMPLATE - = new URLTemplate("metadata_templates/%s/%s/schema"); + /** @see #getMetadataTemplate(BoxAPIConnection) */ + public static final URLTemplate METADATA_TEMPLATE_URL_TEMPLATE = + new URLTemplate("metadata_templates/%s/%s/schema"); + + /** @see #getMetadataTemplateByID(BoxAPIConnection, String) */ + public static final URLTemplate METADATA_TEMPLATE_BY_ID_URL_TEMPLATE = + new URLTemplate("metadata_templates/%s"); + + /** @see #createMetadataTemplate(BoxAPIConnection, String, String, String, boolean, List) */ + public static final URLTemplate METADATA_TEMPLATE_SCHEMA_URL_TEMPLATE = + new URLTemplate("metadata_templates/schema"); + + /** @see #getEnterpriseMetadataTemplates(String, int, BoxAPIConnection, String...) */ + public static final URLTemplate ENTERPRISE_METADATA_URL_TEMPLATE = + new URLTemplate("metadata_templates/%s"); + + /** */ + private static final URLTemplate METADATA_QUERIES_URL_TEMPLATE = + new URLTemplate("metadata_queries/execute_read"); + + /** Default metadata type to be used in query. */ + private static final String DEFAULT_METADATA_TYPE = "properties"; + + /** Global metadata scope. Used by default if the metadata type is "properties". */ + private static final String GLOBAL_METADATA_SCOPE = "global"; + + /** Enterprise metadata scope. Used by default if the metadata type is not "properties". */ + private static final String ENTERPRISE_METADATA_SCOPE = "enterprise"; + + /** Default number of entries per page. */ + private static final int DEFAULT_ENTRIES_LIMIT = 100; + + /** @see #getID() */ + private String id; + + /** @see #getTemplateKey() */ + private String templateKey; + + /** @see #getScope() */ + private String scope; + + /** @see #getDisplayName() */ + private String displayName; + + /** @see #getIsHidden() */ + private Boolean isHidden; + + /** @see #getFields() */ + private List fields; + + /** @see #getCopyInstanceOnItemCopy() */ + private Boolean copyInstanceOnItemCopy; + + /** Constructs an empty metadata template. */ + public MetadataTemplate() { + super(); + } + + /** + * Constructs a metadata template from a JSON string. + * + * @param json the json encoded metadate template. + */ + public MetadataTemplate(String json) { + super(json); + } + + /** + * Constructs a metadate template from a JSON object. + * + * @param jsonObject the json encoded metadate template. + */ + MetadataTemplate(JsonObject jsonObject) { + super(jsonObject); + } + + /** + * Creates new metadata template. + * + * @param api the API connection to be used. + * @param scope the scope of the object. + * @param templateKey a unique identifier for the template. + * @param displayName the display name of the field. + * @param hidden whether this template is hidden in the UI. + * @param fields the ordered set of fields for the template + * @return the metadata template returned from the server. + */ + public static MetadataTemplate createMetadataTemplate( + BoxAPIConnection api, + String scope, + String templateKey, + String displayName, + boolean hidden, + List fields) { + return createMetadataTemplate(api, scope, templateKey, displayName, hidden, fields, null); + } + + /** + * Creates new metadata template. + * + * @param api the API connection to be used. + * @param scope the scope of the object. + * @param templateKey a unique identifier for the template. + * @param displayName the display name of the field. + * @param hidden whether this template is hidden in the UI. + * @param fields the ordered set of fields for the template + * @param copyInstanceOnItemCopy determines whether the copy operation should copy the metadata + * along with the item. + * @return the metadata template returned from the server. + */ + public static MetadataTemplate createMetadataTemplate( + BoxAPIConnection api, + String scope, + String templateKey, + String displayName, + Boolean hidden, + List fields, + Boolean copyInstanceOnItemCopy) { + + JsonObject jsonObject = new JsonObject(); + jsonObject.add("scope", scope); + jsonObject.add("displayName", displayName); + + if (hidden != null) { + jsonObject.add("hidden", hidden); + } - /** - * @see #getMetadataTemplateByID(BoxAPIConnection, String) - */ - public static final URLTemplate METADATA_TEMPLATE_BY_ID_URL_TEMPLATE = new URLTemplate("metadata_templates/%s"); + if (copyInstanceOnItemCopy != null) { + jsonObject.add("copyInstanceOnItemCopy", copyInstanceOnItemCopy); + } + + if (templateKey != null) { + jsonObject.add("templateKey", templateKey); + } + + JsonArray fieldsArray = new JsonArray(); + if (fields != null && !fields.isEmpty()) { + for (Field field : fields) { + JsonObject fieldObj = getFieldJsonObject(field); + + fieldsArray.add(fieldObj); + } + + jsonObject.add("fields", fieldsArray); + } + + URL url = METADATA_TEMPLATE_SCHEMA_URL_TEMPLATE.build(api.getBaseURL()); + BoxJSONRequest request = new BoxJSONRequest(api, url, "POST"); + request.setBody(jsonObject.toString()); + + try (BoxJSONResponse response = request.send()) { + JsonObject responseJSON = Json.parse(response.getJSON()).asObject(); + + return new MetadataTemplate(responseJSON); + } + } + + /** + * Gets the JsonObject representation of the given field object. + * + * @param field represents a template field + * @return the json object + */ + private static JsonObject getFieldJsonObject(Field field) { + JsonObject fieldObj = new JsonObject(); + fieldObj.add("type", field.getType()); + fieldObj.add("key", field.getKey()); + fieldObj.add("displayName", field.getDisplayName()); + + String fieldDesc = field.getDescription(); + if (fieldDesc != null) { + fieldObj.add("description", field.getDescription()); + } + + Boolean fieldIsHidden = field.getIsHidden(); + if (fieldIsHidden != null) { + fieldObj.add("hidden", field.getIsHidden()); + } + + JsonArray array = new JsonArray(); + List options = field.getOptions(); + if (options != null && !options.isEmpty()) { + for (String option : options) { + JsonObject optionObj = new JsonObject(); + optionObj.add("key", option); + + array.add(optionObj); + } + fieldObj.add("options", array); + } + + return fieldObj; + } + + /** + * Updates the schema of an existing metadata template. + * + * @param api the API connection to be used + * @param scope the scope of the object + * @param template Unique identifier of the template + * @param fieldOperations the fields that needs to be updated / added in the template + * @return the updated metadata template + */ + public static MetadataTemplate updateMetadataTemplate( + BoxAPIConnection api, String scope, String template, List fieldOperations) { + + JsonArray array = new JsonArray(); + + for (FieldOperation fieldOperation : fieldOperations) { + JsonObject jsonObject = getFieldOperationJsonObject(fieldOperation); + array.add(jsonObject); + } + + URL url = METADATA_TEMPLATE_URL_TEMPLATE.buildAlpha(api.getBaseURL(), scope, template); + BoxJSONRequest request = new BoxJSONRequest(api, url, "PUT"); + request.setBody(array.toString()); + + try (BoxJSONResponse response = request.send()) { + JsonObject responseJson = Json.parse(response.getJSON()).asObject(); + + return new MetadataTemplate(responseJson); + } + } + + /** + * Deletes the schema of an existing metadata template. + * + * @param api the API connection to be used + * @param scope the scope of the object + * @param template Unique identifier of the template + */ + public static void deleteMetadataTemplate(BoxAPIConnection api, String scope, String template) { + URL url = METADATA_TEMPLATE_URL_TEMPLATE.buildAlpha(api.getBaseURL(), scope, template); + BoxAPIRequest request = new BoxAPIRequest(api, url, "DELETE"); + request.send().close(); + } + + /** + * Executes a metadata query. + * + * @param api The API connection to be used + * @param queryBody The query + * @return An iterable of BoxItem.Info search results + */ + public static BoxResourceIterable executeMetadataQuery( + final BoxAPIConnection api, final MetadataQuery queryBody) { + + URL url = METADATA_QUERIES_URL_TEMPLATE.build(api.getBaseURL()); + return new BoxResourceIterable( + api, url, queryBody.getLimit(), queryBody.toJsonObject(), queryBody.getMarker()) { + + @Override + protected BoxItem.Info factory(JsonObject jsonObject) { + String type = jsonObject.get("type").asString(); + String id = jsonObject.get("id").asString(); + + BoxItem.Info nextItemInfo; + switch (type) { + case "folder": + BoxFolder folder = new BoxFolder(api, id); + nextItemInfo = folder.new Info(jsonObject); + break; + case "file": + BoxFile file = new BoxFile(api, id); + nextItemInfo = file.new Info(jsonObject); + break; + case "web_link": + BoxWebLink link = new BoxWebLink(api, id); + nextItemInfo = link.new Info(jsonObject); + break; + default: + assert false : "Unsupported item type: " + type; + throw new BoxAPIException("Unsupported item type: " + type); + } + + return nextItemInfo; + } + }; + } + + /** + * Gets the JsonObject representation of the Field Operation. + * + * @param fieldOperation represents the template update operation + * @return the json object + */ + private static JsonObject getFieldOperationJsonObject(FieldOperation fieldOperation) { + JsonObject jsonObject = new JsonObject(); + jsonObject.add("op", fieldOperation.getOp().toString()); + + String fieldKey = fieldOperation.getFieldKey(); + if (fieldKey != null) { + jsonObject.add("fieldKey", fieldKey); + } + + Field field = fieldOperation.getData(); + if (field != null) { + JsonObject fieldObj = new JsonObject(); + + String type = field.getType(); + if (type != null) { + fieldObj.add("type", type); + } + + String key = field.getKey(); + if (key != null) { + fieldObj.add("key", key); + } + + String displayName = field.getDisplayName(); + if (displayName != null) { + fieldObj.add("displayName", displayName); + } + + String description = field.getDescription(); + if (description != null) { + fieldObj.add("description", description); + } + + Boolean hidden = field.getIsHidden(); + if (hidden != null) { + fieldObj.add("hidden", hidden); + } + + List options = field.getOptions(); + if (options != null) { + JsonArray array = new JsonArray(); + for (String option : options) { + JsonObject optionObj = new JsonObject(); + optionObj.add("key", option); + + array.add(optionObj); + } + + fieldObj.add("options", array); + } + + Boolean copyInstanceOnItemCopy = field.getCopyInstanceOnItemCopy(); + if (copyInstanceOnItemCopy != null) { + fieldObj.add("copyInstanceOnItemCopy", copyInstanceOnItemCopy); + } + + StaticConfig staticConfig = field.getStaticConfig(); + if (staticConfig != null) { + JsonObject staticConfigObj = new JsonObject(); + JsonObject classification = staticConfig.getClassification(); + if (classification != null) { + staticConfigObj.add("classification", classification); + } + fieldObj.add("staticConfig", staticConfigObj); + } + + jsonObject.add("data", fieldObj); + } + + List fieldKeys = fieldOperation.getFieldKeys(); + if (fieldKeys != null) { + jsonObject.add("fieldKeys", getJsonArray(fieldKeys)); + } + + List enumOptionKeys = fieldOperation.getEnumOptionKeys(); + if (enumOptionKeys != null) { + jsonObject.add("enumOptionKeys", getJsonArray(enumOptionKeys)); + } + + String enumOptionKey = fieldOperation.getEnumOptionKey(); + if (enumOptionKey != null) { + jsonObject.add("enumOptionKey", enumOptionKey); + } + + String multiSelectOptionKey = fieldOperation.getMultiSelectOptionKey(); + if (multiSelectOptionKey != null) { + jsonObject.add("multiSelectOptionKey", multiSelectOptionKey); + } + + List multiSelectOptionKeys = fieldOperation.getMultiSelectOptionKeys(); + if (multiSelectOptionKeys != null) { + jsonObject.add("multiSelectOptionKeys", getJsonArray(multiSelectOptionKeys)); + } + + return jsonObject; + } + + /** + * Gets the Json Array representation of the given list of strings. + * + * @param keys List of strings + * @return the JsonArray represents the list of keys + */ + private static JsonArray getJsonArray(List keys) { + JsonArray array = new JsonArray(); + for (String key : keys) { + array.add(key); + } + + return array; + } + + /** + * Gets the metadata template of properties. + * + * @param api the API connection to be used. + * @return the metadata template returned from the server. + */ + public static MetadataTemplate getMetadataTemplate(BoxAPIConnection api) { + return getMetadataTemplate(api, DEFAULT_METADATA_TYPE); + } + + /** + * Gets the metadata template of specified template type. + * + * @param api the API connection to be used. + * @param templateName the metadata template type name. + * @return the metadata template returned from the server. + */ + public static MetadataTemplate getMetadataTemplate(BoxAPIConnection api, String templateName) { + String scope = scopeBasedOnType(templateName); + return getMetadataTemplate(api, templateName, scope); + } + + /** + * Gets the metadata template of specified template type. + * + * @param api the API connection to be used. + * @param templateName the metadata template type name. + * @param scope the metadata template scope (global or enterprise). + * @param fields the fields to retrieve. + * @return the metadata template returned from the server. + */ + public static MetadataTemplate getMetadataTemplate( + BoxAPIConnection api, String templateName, String scope, String... fields) { + QueryStringBuilder builder = new QueryStringBuilder(); + if (fields.length > 0) { + builder.appendParam("fields", fields); + } + URL url = + METADATA_TEMPLATE_URL_TEMPLATE.buildAlphaWithQuery( + api.getBaseURL(), builder.toString(), scope, templateName); + BoxJSONRequest request = new BoxJSONRequest(api, url, "GET"); + try (BoxJSONResponse response = request.send()) { + return new MetadataTemplate(response.getJSON()); + } + } + + /** + * Geta the specified metadata template by its ID. + * + * @param api the API connection to be used. + * @param templateID the ID of the template to get. + * @return the metadata template object. + */ + public static MetadataTemplate getMetadataTemplateByID(BoxAPIConnection api, String templateID) { + + URL url = METADATA_TEMPLATE_BY_ID_URL_TEMPLATE.buildAlpha(api.getBaseURL(), templateID); + BoxJSONRequest request = new BoxJSONRequest(api, url, "GET"); + try (BoxJSONResponse response = request.send()) { + return new MetadataTemplate(response.getJSON()); + } + } + + /** + * Returns all metadata templates within a user's enterprise. + * + * @param api the API connection to be used. + * @param fields the fields to retrieve. + * @return the metadata template returned from the server. + */ + public static Iterable getEnterpriseMetadataTemplates( + BoxAPIConnection api, String... fields) { + return getEnterpriseMetadataTemplates(ENTERPRISE_METADATA_SCOPE, api, fields); + } + + /** + * Returns all metadata templates within a user's scope. Currently only the enterprise scope is + * supported. + * + * @param scope the scope of the metadata templates. + * @param api the API connection to be used. + * @param fields the fields to retrieve. + * @return the metadata template returned from the server. + */ + public static Iterable getEnterpriseMetadataTemplates( + String scope, BoxAPIConnection api, String... fields) { + return getEnterpriseMetadataTemplates( + ENTERPRISE_METADATA_SCOPE, DEFAULT_ENTRIES_LIMIT, api, fields); + } + + /** + * Returns all metadata templates within a user's scope. Currently only the enterprise scope is + * supported. + * + * @param scope the scope of the metadata templates. + * @param limit maximum number of entries per response. + * @param api the API connection to be used. + * @param fields the fields to retrieve. + * @return the metadata template returned from the server. + */ + public static Iterable getEnterpriseMetadataTemplates( + String scope, int limit, BoxAPIConnection api, String... fields) { + QueryStringBuilder builder = new QueryStringBuilder(); + if (fields.length > 0) { + builder.appendParam("fields", fields); + } + return new BoxResourceIterable( + api, + ENTERPRISE_METADATA_URL_TEMPLATE.buildAlphaWithQuery( + api.getBaseURL(), builder.toString(), scope), + limit) { + + @Override + protected MetadataTemplate factory(JsonObject jsonObject) { + return new MetadataTemplate(jsonObject); + } + }; + } + + /** + * Determines the metadata scope based on type. + * + * @param typeName type of the metadata. + * @return scope of the metadata. + */ + private static String scopeBasedOnType(String typeName) { + return typeName.equals(DEFAULT_METADATA_TYPE) + ? GLOBAL_METADATA_SCOPE + : ENTERPRISE_METADATA_SCOPE; + } + + /** + * Gets the ID of the template. + * + * @return the template ID. + */ + public String getID() { + return this.id; + } + + /** + * Gets the unique template key to identify the metadata template. + * + * @return the unique template key to identify the metadata template. + */ + public String getTemplateKey() { + return this.templateKey; + } + + /** + * Gets the metadata template scope. + * + * @return the metadata template scope. + */ + public String getScope() { + return this.scope; + } + + /** + * Gets the displayed metadata template name. + * + * @return the displayed metadata template name. + */ + public String getDisplayName() { + return this.displayName; + } + + /** + * Gets is the metadata template hidden. + * + * @return is the metadata template hidden. + */ + public Boolean getIsHidden() { + return this.isHidden; + } + + /** + * Gets the iterable with all fields the metadata template contains. + * + * @return the iterable with all fields the metadata template contains. + */ + public List getFields() { + return this.fields; + } + + /** + * Gets whether the copy operation should copy the metadata along with the item. + * + * @return whether the copy operation should copy the metadata along with the item. + */ + public Boolean getCopyInstanceOnItemCopy() { + return this.copyInstanceOnItemCopy; + } + + /** {@inheritDoc} */ + @Override + void parseJSONMember(JsonObject.Member member) { + JsonValue value = member.getValue(); + String memberName = member.getName(); + switch (memberName) { + case "templateKey": + this.templateKey = value.asString(); + break; + case "scope": + this.scope = value.asString(); + break; + case "displayName": + this.displayName = value.asString(); + break; + case "hidden": + this.isHidden = value.asBoolean(); + break; + case "fields": + this.fields = new ArrayList<>(); + for (JsonValue field : value.asArray()) { + this.fields.add(new Field(field.asObject())); + } + break; + case "id": + this.id = value.asString(); + break; + case "copyInstanceOnItemCopy": + this.copyInstanceOnItemCopy = value.asBoolean(); + break; + default: + break; + } + } + + /** Possible template operations. */ + public enum Operation { + + /** Adds an enum option at the end of the enum option list for the specified field. */ + addEnumOption, + + /** Edits the enum option. */ + editEnumOption, + + /** Removes the specified enum option from the specified enum field. */ + removeEnumOption, + + /** Adds a field at the end of the field list for the template. */ + addField, + + /** Edits any number of the base properties of a field: displayName, hidden, description. */ + editField, + + /** Removes the specified field from the template. */ + removeField, + + /** Edits any number of the base properties of a template: displayName, hidden. */ + editTemplate, + + /** Reorders the enum option list to match the requested enum option list. */ + reorderEnumOptions, + + /** Reorders the field list to match the requested field list. */ + reorderFields, + + /** Adds a new option to a multiselect field. */ + addMultiSelectOption, + + /** Edits an existing option in a multiselect field. */ + editMultiSelectOption, + + /** Removes an option from a multiselect field. */ + removeMultiSelectOption, + + /** Changes the display order of options in a multiselect field. */ + reorderMultiSelectOptions + } + + /** Class contains information about the static configuration for the classification. */ + public static class StaticConfig extends BoxJSONObject { + private JsonObject classification; + + /** Constructs an empty static configuration. */ + public StaticConfig() { + super(); + } /** - * @see #createMetadataTemplate(BoxAPIConnection, String, String, String, boolean, List) + * Constructs a static configuration from a JSON string. + * + * @param json the json encoded metadate template field. */ - public static final URLTemplate METADATA_TEMPLATE_SCHEMA_URL_TEMPLATE - = new URLTemplate("metadata_templates/schema"); + public StaticConfig(String json) { + super(json); + } /** - * @see #getEnterpriseMetadataTemplates(String, int, BoxAPIConnection, String...) + * Constructs a static configuration from a JSON object. + * + * @param jsonObject the json encoded metadate template field. */ - public static final URLTemplate ENTERPRISE_METADATA_URL_TEMPLATE = new URLTemplate("metadata_templates/%s"); + StaticConfig(JsonObject jsonObject) { + super(jsonObject); + } /** + * Gets the classification of the static configuration. * + * @return the classification of the static configuration. */ - private static final URLTemplate METADATA_QUERIES_URL_TEMPLATE = new URLTemplate("metadata_queries/execute_read"); + public JsonObject getClassification() { + return this.classification; + } /** - * Default metadata type to be used in query. + * Sets the classification of the static configuration. + * + * @param classification the classification of the static configuration. */ - private static final String DEFAULT_METADATA_TYPE = "properties"; + public void setClassification(JsonObject classification) { + this.classification = classification; + } + + /** {@inheritDoc} */ + @Override + void parseJSONMember(JsonObject.Member member) { + JsonValue value = member.getValue(); + String memberName = member.getName(); + switch (memberName) { + case "classification": + this.classification = value.asObject(); + break; + default: + break; + } + } + } + + /** Class contains information about the metadata template field. */ + public static class Field extends BoxJSONObject { + + /** @see #getID() */ + private String id; + + /** @see #getType() */ + private String type; + + /** @see #getKey() */ + private String key; + + /** @see #getDisplayName() */ + private String displayName; + + /** @see #getIsHidden() */ + private Boolean isHidden; + + /** @see #getDescription() */ + private String description; + + /** @see #getOptionsObjects() */ + private List

    + *
  • Add an enum option + *
  • Edit an enum option + *
  • Remove an enum option + *
  • Add a field + *
  • Edit a field + *
  • Remove a field + *
  • Edit template + *
  • Reorder the enum option + *
  • Reorder the field list + *
+ */ + public static class FieldOperation extends BoxJSONObject { + + private Operation op; + private Field data; + private String fieldKey; + private List fieldKeys; + private List enumOptionKeys; + private String enumOptionKey; + private String multiSelectOptionKey; + private List multiSelectOptionKeys; + + /** Constructs an empty FieldOperation. */ + public FieldOperation() { + super(); } /** - * Returns all metadata templates within a user's enterprise. + * Constructs a Field operation from a JSON string. * - * @param api the API connection to be used. - * @param fields the fields to retrieve. - * @return the metadata template returned from the server. + * @param json the json encoded metadate template field. */ - public static Iterable getEnterpriseMetadataTemplates(BoxAPIConnection api, String... fields) { - return getEnterpriseMetadataTemplates(ENTERPRISE_METADATA_SCOPE, api, fields); + public FieldOperation(String json) { + super(json); } /** - * Returns all metadata templates within a user's scope. Currently only the enterprise scope is supported. + * Constructs a Field operation from a JSON object. * - * @param scope the scope of the metadata templates. - * @param api the API connection to be used. - * @param fields the fields to retrieve. - * @return the metadata template returned from the server. + * @param jsonObject the json encoded metadate template field. */ - public static Iterable getEnterpriseMetadataTemplates( - String scope, BoxAPIConnection api, String... fields - ) { - return getEnterpriseMetadataTemplates(ENTERPRISE_METADATA_SCOPE, DEFAULT_ENTRIES_LIMIT, api, fields); + FieldOperation(JsonObject jsonObject) { + super(jsonObject); } /** - * Returns all metadata templates within a user's scope. Currently only the enterprise scope is supported. + * Gets the operation. * - * @param scope the scope of the metadata templates. - * @param limit maximum number of entries per response. - * @param api the API connection to be used. - * @param fields the fields to retrieve. - * @return the metadata template returned from the server. + * @return the operation */ - public static Iterable getEnterpriseMetadataTemplates( - String scope, int limit, BoxAPIConnection api, String... fields) { - QueryStringBuilder builder = new QueryStringBuilder(); - if (fields.length > 0) { - builder.appendParam("fields", fields); - } - return new BoxResourceIterable( - api, ENTERPRISE_METADATA_URL_TEMPLATE.buildAlphaWithQuery( - api.getBaseURL(), builder.toString(), scope), limit) { - - @Override - protected MetadataTemplate factory(JsonObject jsonObject) { - return new MetadataTemplate(jsonObject); - } - }; + public Operation getOp() { + return this.op; } /** - * Determines the metadata scope based on type. + * Sets the operation. * - * @param typeName type of the metadata. - * @return scope of the metadata. + * @param op the operation */ - private static String scopeBasedOnType(String typeName) { - return typeName.equals(DEFAULT_METADATA_TYPE) ? GLOBAL_METADATA_SCOPE : ENTERPRISE_METADATA_SCOPE; + public void setOp(Operation op) { + this.op = op; } /** - * Gets the ID of the template. + * Gets the data associated with the operation. * - * @return the template ID. + * @return the field object representing the data */ - public String getID() { - return this.id; + public Field getData() { + return this.data; } /** - * Gets the unique template key to identify the metadata template. + * Sets the data. * - * @return the unique template key to identify the metadata template. + * @param data the Field object representing the data */ - public String getTemplateKey() { - return this.templateKey; + public void setData(Field data) { + this.data = data; } /** - * Gets the metadata template scope. + * Gets the field key. * - * @return the metadata template scope. + * @return the field key */ - public String getScope() { - return this.scope; + public String getFieldKey() { + return this.fieldKey; } /** - * Gets the displayed metadata template name. + * Sets the field key. * - * @return the displayed metadata template name. + * @param fieldKey the key of the field */ - public String getDisplayName() { - return this.displayName; + public void setFieldKey(String fieldKey) { + this.fieldKey = fieldKey; } /** - * Gets is the metadata template hidden. + * Gets the list of field keys. * - * @return is the metadata template hidden. + * @return the list of Strings */ - public Boolean getIsHidden() { - return this.isHidden; + public List getFieldKeys() { + return this.fieldKeys; } /** - * Gets the iterable with all fields the metadata template contains. + * Sets the list of the field keys. * - * @return the iterable with all fields the metadata template contains. + * @param fieldKeys the list of strings */ - public List getFields() { - return this.fields; + public void setFieldKeys(List fieldKeys) { + this.fieldKeys = fieldKeys; } /** - * Gets whether the copy operation should copy the metadata along with the item. + * Gets the list of keys of the Enum options. * - * @return whether the copy operation should copy the metadata along with the item. + * @return the list of Strings */ - public Boolean getCopyInstanceOnItemCopy() { - return this.copyInstanceOnItemCopy; + public List getEnumOptionKeys() { + return this.enumOptionKeys; } /** - * {@inheritDoc} + * Sets the list of the enum option keys. + * + * @param enumOptionKeys the list of Strings */ - @Override - void parseJSONMember(JsonObject.Member member) { - JsonValue value = member.getValue(); - String memberName = member.getName(); - switch (memberName) { - case "templateKey": - this.templateKey = value.asString(); - break; - case "scope": - this.scope = value.asString(); - break; - case "displayName": - this.displayName = value.asString(); - break; - case "hidden": - this.isHidden = value.asBoolean(); - break; - case "fields": - this.fields = new ArrayList<>(); - for (JsonValue field : value.asArray()) { - this.fields.add(new Field(field.asObject())); - } - break; - case "id": - this.id = value.asString(); - break; - case "copyInstanceOnItemCopy": - this.copyInstanceOnItemCopy = value.asBoolean(); - break; - default: - break; - } + public void setEnumOptionKeys(List enumOptionKeys) { + this.enumOptionKeys = enumOptionKeys; } /** - * Possible template operations. + * Gets the enum option key. + * + * @return the enum option key */ - public enum Operation { - - /** - * Adds an enum option at the end of the enum option list for the specified field. - */ - addEnumOption, - - /** - * Edits the enum option. - */ - editEnumOption, - - /** - * Removes the specified enum option from the specified enum field. - */ - removeEnumOption, - - /** - * Adds a field at the end of the field list for the template. - */ - addField, - - /** - * Edits any number of the base properties of a field: displayName, hidden, description. - */ - editField, - - /** - * Removes the specified field from the template. - */ - removeField, - - /** - * Edits any number of the base properties of a template: displayName, hidden. - */ - editTemplate, - - /** - * Reorders the enum option list to match the requested enum option list. - */ - reorderEnumOptions, - - /** - * Reorders the field list to match the requested field list. - */ - reorderFields, - - /** - * Adds a new option to a multiselect field. - */ - addMultiSelectOption, - - /** - * Edits an existing option in a multiselect field. - */ - editMultiSelectOption, - - /** - * Removes an option from a multiselect field. - */ - removeMultiSelectOption, - - /** - * Changes the display order of options in a multiselect field. - */ - reorderMultiSelectOptions + public String getEnumOptionKey() { + return this.enumOptionKey; } /** - * Class contains information about the static configuration for the classification. + * Sets the enum option key. + * + * @param enumOptionKey the enum option key */ - public static class StaticConfig extends BoxJSONObject { - private JsonObject classification; - - /** - * Constructs an empty static configuration. - */ - public StaticConfig() { - super(); - } - - /** - * Constructs a static configuration from a JSON string. - * - * @param json the json encoded metadate template field. - */ - public StaticConfig(String json) { - super(json); - } - - /** Constructs a static configuration from a JSON object. - * - * @param jsonObject the json encoded metadate template field. - */ - StaticConfig(JsonObject jsonObject) { - super(jsonObject); - } - - /** - * Gets the classification of the static configuration. - * - * @return the classification of the static configuration. - */ - public JsonObject getClassification() { - return this.classification; - } - - /** - * Sets the classification of the static configuration. - * - * @param classification the classification of the static configuration. - */ - public void setClassification(JsonObject classification) { - this.classification = classification; - } - - /** - * {@inheritDoc} - */ - @Override - void parseJSONMember(JsonObject.Member member) { - JsonValue value = member.getValue(); - String memberName = member.getName(); - switch (memberName) { - case "classification": - this.classification = value.asObject(); - break; - default: - break; - } - } + public void setEnumOptionKey(String enumOptionKey) { + this.enumOptionKey = enumOptionKey; } /** - * Class contains information about the metadata template field. + * Gets the multi-select option key. + * + * @return the key. */ - public static class Field extends BoxJSONObject { - - /** - * @see #getID() - */ - private String id; - - /** - * @see #getType() - */ - private String type; - - /** - * @see #getKey() - */ - private String key; - - /** - * @see #getDisplayName() - */ - private String displayName; - - /** - * @see #getIsHidden() - */ - private Boolean isHidden; - - /** - * @see #getDescription() - */ - private String description; - - /** - * @see #getOptionsObjects() - */ - private List