diff --git a/.codegen.json b/.codegen.json new file mode 100644 index 000000000..fdb838280 --- /dev/null +++ b/.codegen.json @@ -0,0 +1 @@ +{ "engineHash": "7b5a612", "specHash": "86fcc6c", "version": "10.16.0" } diff --git a/.github/ISSUE_TEMPLATE/bug.md b/.github/ISSUE_TEMPLATE/bug.md new file mode 100644 index 000000000..1c852d9ca --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug.md @@ -0,0 +1,53 @@ +--- +name: Bug +about: Report a bug found in the SDK +title: '' +labels: bug +assignees: mwwoda, mhagmajer, arjankowski, lukaszsocha2, bartlomiejleszczynski, congminh1254 +--- + +- [ ] I have checked that the [SDK documentation][sdk-docs] doesn't solve my issue. +- [ ] I have checked that the [API documentation][api-docs] doesn't solve my issue. +- [ ] I have searched the [Box Developer Forums][dev-forums] and my issue isn't already reported (or if it has been reported, I have attached a link to it, for reference). +- [ ] I have searched [Issues in this repo][github-repo] and my issue isn't already reported. + +### Description of the Issue + + + + + + +### Steps to Reproduce + + + + + + +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +### Expected Behavior + + + +### Error Message, Including Stack Trace + + + + +### Screenshots + + + +### Versions Used + + + +[sdk-docs]: https://github.com/box/box-java-sdk-gen/tree/main/docs +[api-docs]: https://developer.box.com/docs +[dev-forums]: https://community.box.com/t5/Platform-and-Development-Forum/bd-p/DeveloperForum +[github-repo]: https://github.com/box/box-java-sdk-gen/search?type=Issues diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 000000000..c3b59c317 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,14 @@ +blank_issues_enabled: false +contact_links: + - name: SDK documentation + url: https://github.com/box/box-java-sdk/tree/main/docs + about: Before creating an issue, I have checked that the SDK documentation doesn't solve my issue. + - name: API documentation + url: https://developer.box.com/docs + about: Before creating an issue, I have checked that the API documentation doesn't solve my issue. + - name: Box Developer Forums + url: https://community.box.com/box-platform-5 + about: Before creating an issue, I have searched the Box Developer Forums and my issue isn't already reported there. + - name: Issues in this repo + url: https://github.com/box/box-java-sdk/search?type=Issues + about: Before creating an issue, I have searched Issues in this repo and my issue isn't already reported. diff --git a/.github/ISSUE_TEMPLATE/enhancement.md b/.github/ISSUE_TEMPLATE/enhancement.md new file mode 100644 index 000000000..ea91c6e44 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/enhancement.md @@ -0,0 +1,23 @@ +--- +name: Enhancement +about: Suggest a new feature or change +title: '' +labels: enhancement +assignees: mwwoda, mhagmajer, arjankowski, lukaszsocha2, bartlomiejleszczynski, congminh1254 +--- + +### Is your feature request related to a problem? Please describe. + + + +### Describe the solution you'd like + + + +### Describe alternatives you've considered + + + +### Additional context + + diff --git a/.github/ISSUE_TEMPLATE/question.md b/.github/ISSUE_TEMPLATE/question.md new file mode 100644 index 000000000..e8d6a28a2 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/question.md @@ -0,0 +1,53 @@ +--- +name: Question +about: Request for Assistance +title: '' +labels: question +assignees: mwwoda, mhagmajer, arjankowski, lukaszsocha2, bartlomiejleszczynski, congminh1254 +--- + +- [ ] I have checked that the [SDK documentation][sdk-docs] doesn't solve my issue. +- [ ] I have checked that the [API documentation][api-docs] doesn't solve my issue. +- [ ] I have searched the [Box Developer Forums][dev-forums] and my issue isn't already reported (or if it has been reported, I have attached a link to it, for reference). +- [ ] I have searched [Issues in this repo][github-repo] and my issue isn't already reported. + +### Description of the Issue + + + + + + +### Steps to Reproduce + + + + + + +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +### Expected Behavior + + + +### Error Message, Including Stack Trace + + + + +### Screenshots + + + +### Versions Used + + + +[sdk-docs]: https://github.com/box/box-java-sdk-gen/tree/main/docs +[api-docs]: https://developer.box.com/docs +[dev-forums]: https://community.box.com/t5/Platform-and-Development-Forum/bd-p/DeveloperForum +[github-repo]: https://github.com/box/box-java-sdk-gen/search?type=Issues diff --git a/.github/stale.yml b/.github/stale.yml new file mode 100644 index 000000000..70cf69f6b --- /dev/null +++ b/.github/stale.yml @@ -0,0 +1,22 @@ +# Number of days of inactivity before an issue becomes stale +daysUntilStale: 30 + +# Number of days of inactivity before a stale issue is closed +daysUntilClose: 7 + +# Issues or Pull Requests with these labels will never be considered stale. Set to `[]` to disable +exemptLabels: + - enhancement + - dontstale + - needs-triage + +# Label to use when marking an issue as stale +staleLabel: stale + +# Comment to post when marking an issue as stale. Set to `false` to disable +markComment: > + This issue has been automatically marked as stale because it has not been updated in the last 30 days. It will be closed if no further activity occurs within the next 7 days. Feel free to reach out or mention Box SDK team member for further help and resources if they are needed. + +# Comment to post when closing a stale issue. Set to `false` to disable +closeComment: > + This issue has been automatically closed due to maximum period of being stale. Thank you for your contribution to Box SDK and feel free to open another PR/issue at any time. diff --git a/.github/workflows/autoupdate-pr.yml b/.github/workflows/autoupdate-pr.yml new file mode 100644 index 000000000..085213119 --- /dev/null +++ b/.github/workflows/autoupdate-pr.yml @@ -0,0 +1,42 @@ +name: Autoupdate PR +on: + push: + branches: + - main + - sdk-gen + +permissions: {} + +jobs: + update_pull_requests: + runs-on: ubuntu-latest + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + token: ${{ secrets.DISPATCH_ACCESS_TOKEN }} + + - name: Set up Git + run: | + git config --global user.name 'box-sdk-build' + git config --global user.email 'box-sdk-build@box.com' + + - name: Fetch all branches and tags + run: git fetch --prune --unshallow + + - name: Auto update pull requests + run: | + PR_LIST=$(curl -s -H "Authorization: Bearer ${{ secrets.DISPATCH_ACCESS_TOKEN }}" "https://api.github.com/repos/$GITHUB_REPOSITORY/pulls?state=open&base=${{ github.ref_name }}" | jq -r '.[] | .head.ref') + for pr_branch in $PR_LIST; do + git checkout "$pr_branch" + if git merge origin/${{ github.ref_name }}; then + git push + else + # Conflict occurred, resolve by keeping our changes + git checkout --ours . + git add . + git commit -m "Auto resolve conflict by keeping our changes" + git push + fi + done diff --git a/.github/workflows/build-and-test-daily.yml b/.github/workflows/build-and-test-daily.yml new file mode 100644 index 000000000..30d2be5ca --- /dev/null +++ b/.github/workflows/build-and-test-daily.yml @@ -0,0 +1,72 @@ +name: Build and Test daily +on: + schedule: + - cron: '20 1 * * 1-5' + +permissions: + contents: read + +jobs: + build-and-test: + runs-on: ubuntu-latest + strategy: + max-parallel: 1 + matrix: + distribution: ['zulu', 'temurin'] + java: ['8', '17'] + name: Java ${{ matrix.java }} (${{ matrix.distribution }}) + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + ref: main + - name: Setup Java + uses: actions/setup-java@v4 + with: + distribution: ${{ matrix.distribution }} + java-version: ${{ matrix.java }} + cache: 'gradle' + - name: All Tests + env: + JWT_CONFIG_BASE_64: ${{ secrets.JWT_CONFIG_BASE_64 }} + ADMIN_USER_ID: ${{ secrets.ADMIN_USER_ID }} + CLIENT_ID: ${{ secrets.CLIENT_ID }} + CLIENT_SECRET: ${{ secrets.CLIENT_SECRET }} + USER_ID: ${{ secrets.USER_ID }} + ENTERPRISE_ID: ${{ secrets.ENTERPRISE_ID }} + BOX_FILE_REQUEST_ID: ${{ secrets.BOX_FILE_REQUEST_ID }} + BOX_EXTERNAL_USER_EMAIL: ${{ secrets.BOX_EXTERNAL_USER_EMAIL }} + BOX_EXTERNAL_USER_ID: ${{ secrets.BOX_EXTERNAL_USER_ID }} + APP_ITEM_ASSOCIATION_FILE_ID: ${{ secrets.APP_ITEM_ASSOCIATION_FILE_ID }} + APP_ITEM_ASSOCIATION_FOLDER_ID: ${{ secrets.APP_ITEM_ASSOCIATION_FOLDER_ID }} + WORKFLOW_FOLDER_ID: ${{ secrets.WORKFLOW_FOLDER_ID }} + APP_ITEM_SHARED_LINK: ${{ secrets.APP_ITEM_SHARED_LINK }} + SLACK_AUTOMATION_USER_ID: ${{ secrets.SLACK_AUTOMATION_USER_ID }} + SLACK_ORG_ID: ${{ secrets.SLACK_ORG_ID }} + SLACK_PARTNER_ITEM_ID: ${{ secrets.SLACK_PARTNER_ITEM_ID }} + AUTOMATE_WORKFLOW_FOLDER_ID: ${{ secrets.AUTOMATE_WORKFLOW_FOLDER_ID }} + run: ./gradlew check --stacktrace + - name: Coverage + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: ./gradlew jacocoTestReport coverallsJacoco + notify: + name: Send Slack Notification + runs-on: ubuntu-latest + needs: [build-and-test] + if: always() + steps: + - name: Send Slack Notification + env: + SLACK_WEBHOOK_TEST_NOTIFICATION_URL: ${{ secrets.SLACK_WEBHOOK_TEST_NOTIFICATION_URL }} + BUILD_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + if [ "${{ needs.build-and-test.result }}" != "success" ]; then + STATUS="Failure ❌" + else + STATUS="Success ✅" + fi + + curl -X POST -H "Content-Type: application/json" \ + --data "{\"text\":\"<${BUILD_URL}|Daily Tests Job> in *${GITHUB_REPOSITORY}* finished with status: ${STATUS}\"}" \ + "$SLACK_WEBHOOK_TEST_NOTIFICATION_URL" diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 000000000..84a244e1c --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,60 @@ +name: build +on: + pull_request: + branches: + - main + +permissions: + contents: read + +jobs: + build-and-test: + runs-on: ubuntu-latest + strategy: + max-parallel: 1 + matrix: + distribution: ['zulu', 'temurin'] + java: ['8', '17'] + name: Java ${{ matrix.java }} (${{ matrix.distribution }}) + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Setup Java + uses: actions/setup-java@v4 + with: + distribution: ${{ matrix.distribution }} + java-version: ${{ matrix.java }} + cache: 'gradle' + - name: All Tests + if: ${{ startsWith(github.head_ref, 'codegen-release') && github.actor != 'dependabot[bot]' }} + env: + JWT_CONFIG_BASE_64: ${{ secrets.JWT_CONFIG_BASE_64 }} + ADMIN_USER_ID: ${{ secrets.ADMIN_USER_ID }} + CLIENT_ID: ${{ secrets.CLIENT_ID }} + CLIENT_SECRET: ${{ secrets.CLIENT_SECRET }} + USER_ID: ${{ secrets.USER_ID }} + ENTERPRISE_ID: ${{ secrets.ENTERPRISE_ID }} + BOX_FILE_REQUEST_ID: ${{ secrets.BOX_FILE_REQUEST_ID }} + BOX_EXTERNAL_USER_EMAIL: ${{ secrets.BOX_EXTERNAL_USER_EMAIL }} + BOX_EXTERNAL_USER_ID: ${{ secrets.BOX_EXTERNAL_USER_ID }} + APP_ITEM_ASSOCIATION_FILE_ID: ${{ secrets.APP_ITEM_ASSOCIATION_FILE_ID }} + APP_ITEM_ASSOCIATION_FOLDER_ID: ${{ secrets.APP_ITEM_ASSOCIATION_FOLDER_ID }} + WORKFLOW_FOLDER_ID: ${{ secrets.WORKFLOW_FOLDER_ID }} + APP_ITEM_SHARED_LINK: ${{ secrets.APP_ITEM_SHARED_LINK }} + SLACK_AUTOMATION_USER_ID: ${{ secrets.SLACK_AUTOMATION_USER_ID }} + SLACK_ORG_ID: ${{ secrets.SLACK_ORG_ID }} + SLACK_PARTNER_ITEM_ID: ${{ secrets.SLACK_PARTNER_ITEM_ID }} + AUTOMATE_WORKFLOW_FOLDER_ID: ${{ secrets.AUTOMATE_WORKFLOW_FOLDER_ID }} + run: ./gradlew check --stacktrace + - name: Smoke Tests + if: ${{ !startsWith(github.head_ref, 'codegen-release') && github.actor != 'dependabot[bot]' }} + env: + JWT_CONFIG_BASE_64: ${{ secrets.JWT_CONFIG_BASE_64 }} + CLIENT_ID: ${{ secrets.CLIENT_ID }} + CLIENT_SECRET: ${{ secrets.CLIENT_SECRET }} + USER_ID: ${{ secrets.USER_ID }} + ENTERPRISE_ID: ${{ secrets.ENTERPRISE_ID }} + run: ./gradlew test --tests com.box.sdkgen.auth.AuthITest --tests com.box.sdkgen.files.FilesITest --tests com.box.sdkgen.downloads.DownloadsITest --tests com.box.sdkgen.uploads.UploadsITest --stacktrace + - name: Build (Dependabot only, no tests) + if: github.actor == 'dependabot[bot]' + run: ./gradlew assemble --stacktrace diff --git a/.github/workflows/notify-changelog.yml b/.github/workflows/notify-changelog.yml new file mode 100644 index 000000000..464fd56b7 --- /dev/null +++ b/.github/workflows/notify-changelog.yml @@ -0,0 +1,29 @@ +# A GitHub action that notifies the developer +# changelog repository of any new releases. + +name: Notify changelog + +on: + # Only trigger for a full release, + # ignoring pre-releases and drafts + release: + types: + - released + +permissions: {} + +jobs: + notify: + # This job can run on the latest Ubuntu + # and it should not take more than 3 minutes + runs-on: ubuntu-latest + timeout-minutes: 3 + + steps: + - name: Notify changelog of new release + uses: peter-evans/repository-dispatch@v1 + with: + token: ${{ secrets.DISPATCH_ACCESS_TOKEN }} + repository: box/box-developer-changelog + event-type: new-release-note + client-payload: '{"ref": "${{ github.ref }}", "repository": "${{github.repository}}", "labels": "sdks,java", "repo_display_name": "Box Java SDK"}' diff --git a/.github/workflows/semantic-pr.yml b/.github/workflows/semantic-pr.yml new file mode 100644 index 000000000..1bf079c95 --- /dev/null +++ b/.github/workflows/semantic-pr.yml @@ -0,0 +1,22 @@ +name: Semantic PR + +on: + pull_request_target: + types: + - opened + - edited + - synchronize + branches: + - main + +permissions: + contents: read + +jobs: + main: + name: Validate semantic PR title + runs-on: ubuntu-latest + steps: + - uses: amannn/action-semantic-pull-request@v4 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/spell-check-lint.yml b/.github/workflows/spell-check-lint.yml new file mode 100644 index 000000000..1adbdeb74 --- /dev/null +++ b/.github/workflows/spell-check-lint.yml @@ -0,0 +1,27 @@ +name: spell-check-lint +on: + pull_request_target: + types: [opened, synchronize, edited] + branches: + - main + +permissions: + contents: read + +jobs: + spellcheck-request-title: + runs-on: ubuntu-latest + steps: + - name: Checkout current repository + uses: actions/checkout@v4 + - name: Checkout spellchecker + uses: actions/checkout@v4 + with: + ref: refs/heads/main + repository: box/box-sdk-spellchecker + token: ${{ secrets.DISPATCH_ACCESS_TOKEN }} + path: spellchecker + - name: Execute spellchecker + uses: ./spellchecker + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.gitignore b/.gitignore index 21d476036..0df7a29b8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,16 @@ .gradle/ build/ .DS_Store -src/test/config/config.properties /target/ +.settings/ +.idea/ +*.iml +# Eclipse Related +.project +.classpath +.checkstyle +bin/ +out/ +*.secret +#Sdkman +.sdkmanrc diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index dff5f3a5d..000000000 --- a/.travis.yml +++ /dev/null @@ -1 +0,0 @@ -language: java diff --git a/.versionrc b/.versionrc new file mode 100644 index 000000000..ca2ea3076 --- /dev/null +++ b/.versionrc @@ -0,0 +1,34 @@ +{ + "types": [ + { + "type": "feat", + "section": "New Features and Enhancements", + "hidden": false + }, + { + "type": "fix", + "section": "Bug Fixes", + "hidden": false + }, + { + "type": "chore", + "hidden": true + }, + { + "type": "docs", + "hidden": true + }, + { + "type": "style", + "hidden": true + }, + { + "type": "refactor", + "hidden": true + }, + { + "type": "test", + "hidden": true + } + ] +} diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 000000000..9834014ac --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,1123 @@ +# Changelog + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + +## [10.16.0](https://github.com/box/box-java-sdk/compare/v10.15.2...v10.16.0) (2026-08-05) + + +### New Features and Enhancements + +* add `is_collaborated_content_available_when_owner_inactive` property (box/box-openapi[#613](https://github.com/box/box-java-sdk/issues/613)) ([#1946](https://github.com/box/box-java-sdk/issues/1946)) ([3a67096](https://github.com/box/box-java-sdk/commit/3a67096b0ab31836ef597daf0f2d8a25ef94013d)) +* Added two missing event types (box/box-openapi[#611](https://github.com/box/box-java-sdk/issues/611)) ([#1940](https://github.com/box/box-java-sdk/issues/1940)) ([a37b296](https://github.com/box/box-java-sdk/commit/a37b2964ab71ab789c359680e6f09ad19a310cf9)) +* Support query APIs (box/box-openapi[#610](https://github.com/box/box-java-sdk/issues/610)) ([#1938](https://github.com/box/box-java-sdk/issues/1938)) ([bf8aaaa](https://github.com/box/box-java-sdk/commit/bf8aaaab213b85d704a2735e6ef65a91f5225386)) + +### [10.15.2](https://github.com/box/box-java-sdk/compare/v10.15.1...v10.15.2) (2026-07-15) + + +### Bug Fixes + +* Fix broken readme link (box/box-codegen[#974](https://github.com/box/box-java-sdk/issues/974)) ([#1929](https://github.com/box/box-java-sdk/issues/1929)) ([f216711](https://github.com/box/box-java-sdk/commit/f2167116cc3a84782b89984abbbd9d75fc7cfc91)) + +### [10.15.1](https://github.com/box/box-java-sdk/compare/v10.15.0...v10.15.1) (2026-07-10) + + +### Bug Fixes + +* Bump `Bouncy Castle` to fix CVE in Java (box/box-codegen[#972](https://github.com/box/box-java-sdk/issues/972)) ([#1918](https://github.com/box/box-java-sdk/issues/1918)) ([4441f03](https://github.com/box/box-java-sdk/commit/4441f037afaf148b300466a23818108a364457ab)) + +## [10.15.0](https://github.com/box/box-java-sdk/compare/v10.14.0...v10.15.0) (2026-07-09) + + +### New Features and Enhancements + +* Add new fields to Hubs(box/box-openapi[#606](https://github.com/box/box-java-sdk/issues/606)) ([#1901](https://github.com/box/box-java-sdk/issues/1901)) ([f590481](https://github.com/box/box-java-sdk/commit/f590481020c9d8670dd1f3a96583b1b7c909c303)) +* Setup common default timeout (box/box-codegen[#965](https://github.com/box/box-java-sdk/issues/965)) ([#1905](https://github.com/box/box-java-sdk/issues/1905)) ([a87b8d1](https://github.com/box/box-java-sdk/commit/a87b8d1e10e0f03f61e56b1a3328714bb78efd17)) + +## [10.14.0](https://github.com/box/box-java-sdk/compare/v10.13.0...v10.14.0) (2026-06-11) + + +### New Features and Enhancements + +* Add new event types (box/box-openapi[#1703](https://github.com/box/box-java-sdk/issues/1703)) (box/box-openapi[#605](https://github.com/box/box-java-sdk/issues/605)) ([#1889](https://github.com/box/box-java-sdk/issues/1889)) ([1747b14](https://github.com/box/box-java-sdk/commit/1747b14eac8ae1b4a96e1da2602d9e6894d6b4ee)) +* Add new parameters to ai extract structured method (box/box-openapi[#604](https://github.com/box/box-java-sdk/issues/604)) ([#1888](https://github.com/box/box-java-sdk/issues/1888)) ([09c342f](https://github.com/box/box-java-sdk/commit/09c342f5979f0bdb1a93c822273638aa0e60dbdf)) +* Expose `errorCode` in sign request schemas (box/box-openapi[#601](https://github.com/box/box-java-sdk/issues/601)) ([#1887](https://github.com/box/box-java-sdk/issues/1887)) ([70dc787](https://github.com/box/box-java-sdk/commit/70dc787c16f096070428af8e2caa02be3ba6fcc0)) + +## [10.13.0](https://github.com/box/box-java-sdk/compare/v10.12.0...v10.13.0) (2026-06-03) + + +### New Features and Enhancements + +* Convert Note Public API (box/box-openapi[#599](https://github.com/box/box-java-sdk/issues/599)) ([#1855](https://github.com/box/box-java-sdk/issues/1855)) ([e396190](https://github.com/box/box-java-sdk/commit/e396190406633a2071dacbbe0b67c4a92b03c7e0)) + +## [10.12.0](https://github.com/box/box-java-sdk/compare/v10.11.0...v10.12.0) (2026-05-20) + + +### New Features and Enhancements + +* add failure related fields to `DocGenJob` (box/box-openapi[#598](https://github.com/box/box-java-sdk/issues/598)) ([#1849](https://github.com/box/box-java-sdk/issues/1849)) ([8d72727](https://github.com/box/box-java-sdk/commit/8d72727367cb0b1643db9488d0659264ad7aa45e)) +* Add new event types (box/box-openapi[#597](https://github.com/box/box-java-sdk/issues/597)) ([#1840](https://github.com/box/box-java-sdk/issues/1840)) ([aa439b4](https://github.com/box/box-java-sdk/commit/aa439b475e26f761f7f3aca8e6b5eec55d472838)) +* Sanitize request body in `BoxAPIError` (box/box-codegen[#948](https://github.com/box/box-java-sdk/issues/948)) ([#1844](https://github.com/box/box-java-sdk/issues/1844)) ([39b6fcc](https://github.com/box/box-java-sdk/commit/39b6fccb3067364d9f4eaa3a0f9627eabd526b13)) + +## [10.11.0](https://github.com/box/box-java-sdk/compare/v10.10.0...v10.11.0) (2026-05-06) + + +### ⚠ BREAKING CHANGES + +* Mark `id` field of `AIAgentReference` required (box/box-openapi[#1629](https://github.com/box/box-java-sdk/issues/1629)) (box/box-openapi[#595](https://github.com/box/box-java-sdk/issues/595)) ([#1827](https://github.com/box/box-java-sdk/issues/1827)) ([1c59b46](https://github.com/box/box-java-sdk/commit/1c59b46e90ef5d33ff85eff45125cefe00e5e950)) + +### Bug Fixes + +* Fix metadata template schema (box/box-openapi[#596](https://github.com/box/box-java-sdk/issues/596)) ([#1828](https://github.com/box/box-java-sdk/issues/1828)) ([193718a](https://github.com/box/box-java-sdk/commit/193718a5eb07e0816f7fc23daad3ebbe5cba993b)) +* Mark `id` field of `AIAgentReference` required (box/box-openapi[#1629](https://github.com/box/box-java-sdk/issues/1629)) (box/box-openapi[#595](https://github.com/box/box-java-sdk/issues/595)) ([#1827](https://github.com/box/box-java-sdk/issues/1827)) ([1c59b46](https://github.com/box/box-java-sdk/commit/1c59b46e90ef5d33ff85eff45125cefe00e5e950)) + +## [10.10.0](https://github.com/box/box-java-sdk/compare/v10.9.0...v10.10.0) (2026-04-30) + + +### Bug Fixes + +* Fix java `oneOf` serialization (box/box-codegen[#942](https://github.com/box/box-java-sdk/issues/942)) ([#1806](https://github.com/box/box-java-sdk/issues/1806)) ([dcd5df6](https://github.com/box/box-java-sdk/commit/dcd5df60f3545983209e58c50ab1648a6d5fb167)) + + +### New Features and Enhancements + +* Automate Public API (box/box-openapi[#594](https://github.com/box/box-java-sdk/issues/594)) ([#1820](https://github.com/box/box-java-sdk/issues/1820)) ([41e859a](https://github.com/box/box-java-sdk/commit/41e859acf78844b0a2e28d3d14ca721b88e2a108)) + +## [10.9.0](https://github.com/box/box-java-sdk/compare/v10.8.0...v10.9.0) (2026-04-22) + + +### New Features and Enhancements + +* Add `max_extension_length` field to Retention Policies (box/box-openapi[#593](https://github.com/box/box-java-sdk/issues/593)) ([#1799](https://github.com/box/box-java-sdk/issues/1799)) ([fc91872](https://github.com/box/box-java-sdk/commit/fc91872b19e16d919fd641e1a6b461639ebbdc54)) + +## [10.8.0](https://github.com/box/box-java-sdk/compare/v10.7.0...v10.8.0) (2026-04-16) + + +### New Features and Enhancements + +* **boxsdkgen:** Update `retentionLength` field to accept both string and integer (box/box-codegen#932) (#1776) + +### Bug Fixes + +* **boxsdkgen:** Update `retentionLength` field to accept both string and integer (box/box-codegen[#932](https://github.com/box/box-java-sdk/issues/932)) ([#1776](https://github.com/box/box-java-sdk/issues/1776)) ([31f4b04](https://github.com/box/box-java-sdk/commit/31f4b043116fb6ffde0834593fb876a636678346)) +* Fix error propagation in Java (box/box-codegen[#936](https://github.com/box/box-java-sdk/issues/936)) ([#1780](https://github.com/box/box-java-sdk/issues/1780)) ([257fdb2](https://github.com/box/box-java-sdk/commit/257fdb2b6b15ffe6b0d9b48613d5fcea481c42bd)) +* Fix serialization of `OffsetDateTime` (box/box-codegen[#935](https://github.com/box/box-java-sdk/issues/935)) ([#1778](https://github.com/box/box-java-sdk/issues/1778)) ([d9ff755](https://github.com/box/box-java-sdk/commit/d9ff7553fb958811b3344c7b98828a57a8134531)) + +## [10.7.0](https://github.com/box/box-java-sdk/compare/v10.6.0...v10.7.0) (2026-04-01) + + +### ⚠ BREAKING CHANGES + +* Correct search content type 'tags' to match API (box/box-openapi#591) (#1766) +* Align `LegalHoldPolicyAssignedItem` with API (box/box-openapi#1554) (box/box-openapi#590) (#1762) + +### Bug Fixes + +* Align `LegalHoldPolicyAssignedItem` with API (box/box-openapi[#1554](https://github.com/box/box-java-sdk/issues/1554)) (box/box-openapi[#590](https://github.com/box/box-java-sdk/issues/590)) ([#1762](https://github.com/box/box-java-sdk/issues/1762)) ([8f82b46](https://github.com/box/box-java-sdk/commit/8f82b46afe978342fb93af6ad31006342a1f5b5a)) +* Correct search content type 'tags' to match API (box/box-openapi[#591](https://github.com/box/box-java-sdk/issues/591)) ([#1766](https://github.com/box/box-java-sdk/issues/1766)) ([52b408e](https://github.com/box/box-java-sdk/commit/52b408ec649dd7d36d3ecc6f2506f34afde644bd)) + + +### New Features and Enhancements + +* Add `reference` to `AI` and `parent_id` to `HubsItems` (box/box-openapi[#588](https://github.com/box/box-java-sdk/issues/588)) ([#1741](https://github.com/box/box-java-sdk/issues/1741)) ([fccccb7](https://github.com/box/box-java-sdk/commit/fccccb766d961e9badd1cde274595e07ba88b7a2)) +* Support Hub Document API (box/box-codegen[#930](https://github.com/box/box-java-sdk/issues/930)) ([#1767](https://github.com/box/box-java-sdk/issues/1767)) ([8b2ef9f](https://github.com/box/box-java-sdk/commit/8b2ef9f003b76f88ea0481a0539efad38ae63a3b)) + +## [10.6.0](https://github.com/box/box-java-sdk/compare/v10.5.0...v10.6.0) (2026-03-18) + + +### New Features and Enhancements + +* add `canPublicSharedLinkBeCreated` to `Hubs` (box/box-codegen[#928](https://github.com/box/box-java-sdk/issues/928)) ([#1737](https://github.com/box/box-java-sdk/issues/1737)) ([50c2bc9](https://github.com/box/box-java-sdk/commit/50c2bc9dcaaac2445876d2d305c5547e434105b1)) +* Add configurable timeouts for SDKs (box/box-codegen[#924](https://github.com/box/box-java-sdk/issues/924)) ([#1730](https://github.com/box/box-java-sdk/issues/1730)) ([1fa2c9a](https://github.com/box/box-java-sdk/commit/1fa2c9ad954ed01ec387b7a1d1018c62d5de3867)) + +## [10.5.0](https://github.com/box/box-java-sdk/compare/v10.4.0...v10.5.0) (2026-02-11) + + +### Bug Fixes + +* Correct enum value for legal hold policy changes (box/box-openapi[#581](https://github.com/box/box-java-sdk/issues/581)) ([#1695](https://github.com/box/box-java-sdk/issues/1695)) ([f9e3d5e](https://github.com/box/box-java-sdk/commit/f9e3d5ee3c54d074d5b5aef1c5c01599c0b8c9e9)) +* Move assigning default values from builder constructor to `build()` method (box/box-codegen[#922](https://github.com/box/box-java-sdk/issues/922)) ([#1716](https://github.com/box/box-java-sdk/issues/1716)) ([0a9dbe3](https://github.com/box/box-java-sdk/commit/0a9dbe3bebb618a0a33c53cd1e9a90582c0504e2)) + + +### New Features and Enhancements + +* add confidence scores for structured extract (box/box-openapi[#582](https://github.com/box/box-java-sdk/issues/582)) ([#1697](https://github.com/box/box-java-sdk/issues/1697)) ([112b954](https://github.com/box/box-java-sdk/commit/112b9545d0ef1839d007bf215356b31e658daad8)) +* add signer language, cancel sign request reason (box/box-openapi[#584](https://github.com/box/box-java-sdk/issues/584)) ([#1721](https://github.com/box/box-java-sdk/issues/1721)) ([3c94cfc](https://github.com/box/box-java-sdk/commit/3c94cfc69d6be2db40b72bf2902ee095824e0796)) +* Add watermarking permissions and sources information (box/box-openapi[#579](https://github.com/box/box-java-sdk/issues/579)) ([#1688](https://github.com/box/box-java-sdk/issues/1688)) ([215c0f3](https://github.com/box/box-java-sdk/commit/215c0f3cce4042332373eec66b1695ed958f1f3b)) + +## [10.4.0](https://github.com/box/box-java-sdk/compare/v10.3.0...v10.4.0) (2025-12-19) + + +### Bug Fixes + +* add taxonomy to Metadata Field (read) definition (box/box-openapi[#572](https://github.com/box/box-java-sdk/issues/572)) ([#1644](https://github.com/box/box-java-sdk/issues/1644)) ([61235da](https://github.com/box/box-java-sdk/commit/61235da7d51a64845d344a8286821e59b217a848)) +* fix `RetryAfter` function when there's no `Retry-After` header (box/box-codegen[#903](https://github.com/box/box-java-sdk/issues/903)) ([#1622](https://github.com/box/box-java-sdk/issues/1622)) ([f135e2b](https://github.com/box/box-java-sdk/commit/f135e2b62d4b2d2d266ab40b3b366c8c7968d2db)) + + +### New Features and Enhancements + +* add Metadata Taxonomies api (box/box-openapi[#569](https://github.com/box/box-java-sdk/issues/569)) ([#1630](https://github.com/box/box-java-sdk/issues/1630)) ([d1e8924](https://github.com/box/box-java-sdk/commit/d1e8924ad123e5fcbf014be50fbbf52ea45d546b)) +* text input validation for Box Sign (box/box-openapi[#568](https://github.com/box/box-java-sdk/issues/568)) ([#1624](https://github.com/box/box-java-sdk/issues/1624)) ([8c5b5c1](https://github.com/box/box-java-sdk/commit/8c5b5c17285c1c0d4a644eb8187dac92f1f96f28)) +* Treat `nullable` fields as Optional (box/box-codegen[#906](https://github.com/box/box-java-sdk/issues/906)) ([#1634](https://github.com/box/box-java-sdk/issues/1634)) ([cacc729](https://github.com/box/box-java-sdk/commit/cacc729dc246c914eb1a6d8281f4261c96711dc1)) + +## [10.3.0](https://github.com/box/box-java-sdk/compare/v10.2.0...v10.3.0) (2025-12-10) + + +### New Features and Enhancements + +* Remove `confidence_score` and `include_confidence_score` from AI extract (box/box-openapi[#567](https://github.com/box/box-java-sdk/issues/567)) ([#1615](https://github.com/box/box-java-sdk/issues/1615)) ([0a069cd](https://github.com/box/box-java-sdk/commit/0a069cdecc4837d8bdb6f1e91401d88c58af5a92)) +* Support new sign request metadata (box/box-openapi[#565](https://github.com/box/box-java-sdk/issues/565)) ([#1599](https://github.com/box/box-java-sdk/issues/1599)) ([b3c46bb](https://github.com/box/box-java-sdk/commit/b3c46bbf2f2f7b9b25befcd6442a4e5c9a92e790)) + +## [10.2.0](https://github.com/box/box-java-sdk/compare/v10.1.0...v10.2.0) (2025-11-19) + + +### Bug Fixes + +* Fix parsing `OffsetDateTime` from String (box/box-codegen[#887](https://github.com/box/box-java-sdk/issues/887)) ([#1582](https://github.com/box/box-java-sdk/issues/1582)) ([d1288c4](https://github.com/box/box-java-sdk/commit/d1288c4804b032d5211d664c396e212a08a5775b)) + + +### New Features and Enhancements + +* Support GET enterprise configuration API (box/box-openapi[#559](https://github.com/box/box-java-sdk/issues/559)) ([#1519](https://github.com/box/box-java-sdk/issues/1519)) ([88dd8d2](https://github.com/box/box-java-sdk/commit/88dd8d2867d85ca8fc3b48d2aee61060ef328821)) +* Disable OkHttp auto retries on connection failure (box/box-codegen[#874](https://github.com/box/box-java-sdk/issues/874)) ([#1541](https://github.com/box/box-java-sdk/issues/1541)) ([c2bd137](https://github.com/box/box-java-sdk/commit/c2bd137e469b9e67a14a33bb073107ff5db44175)) +* Support Archive API (box/box-openapi[#563](https://github.com/box/box-java-sdk/issues/563)) ([#1553](https://github.com/box/box-java-sdk/issues/1553)) ([609e8bb](https://github.com/box/box-java-sdk/commit/609e8bb5eb7143281543dcfaada23f2649acae9d)) + +## [10.1.0](https://github.com/box/box-java-sdk/compare/v10.0.0...v10.1.0) (2025-10-06) + + +### Bug Fixes + +* Allow flexible key-value data in `AiExtractResponse.answer` and `Event.additionalDetails` (box/box-openapi[#556](https://github.com/box/box-java-sdk/issues/556)) ([#1470](https://github.com/box/box-java-sdk/issues/1470)) ([e215a5f](https://github.com/box/box-java-sdk/commit/e215a5f2502e694421a05d8da550d2b305c09460)) +* Make `role` parameter of update collaboration optional (box/box-openapi[#557](https://github.com/box/box-java-sdk/issues/557)) ([#1479](https://github.com/box/box-java-sdk/issues/1479)) ([6896386](https://github.com/box/box-java-sdk/commit/6896386c6086996399066b09b5afc998a5a95ca4)) + + +### New Features and Enhancements + +* Add `Javadoc` comments (box/box-codegen[#839](https://github.com/box/box-java-sdk/issues/839)) ([#1465](https://github.com/box/box-java-sdk/issues/1465)) ([c72407d](https://github.com/box/box-java-sdk/commit/c72407dc77cc67f3a178d607a2b1bd4e90e832a8)) + +## [10.0.0](https://github.com/box/box-java-sdk/compare/v4.16.3...v10.0.0) (2025-09-17) + +Introducing **`Box SDK v10`**, a major release designed to elevate your developer experience and streamline integration with Box Content Cloud. Currently available as a separate [`sdk-gen`](https://github.com/box/box-java-sdk/tree/sdk-gen) branch, `v10` will ultimately become the main branch. + +### Breaking Changes + +- This SDK version is auto-generated and introduces a new interface for all methods. Extensive documentation is available [here](https://github.com/box/box-java-sdk/tree/sdk-gen/docs). + +### What's New in `v10` + +- **Full API Support** — Complete coverage of the Box API ecosystem, giving you access to all the latest features and functionalities to build feature-rich applications. + +- **Rapid API Updates** — Our new auto-generation approach enables Box API additions within days, ensuring you can leverage the most up-to-date features without delay. + +- **Embedded Documentation** — All objects and parameters are documented directly in the SDK source code, keeping essential information in one place. + +- **Enhanced Convenience Methods** — New methods for authentication, chunk uploads, automatic retries, retry strategy, and more. + +### Important Notes + +This version includes the Box Next Generation SDK artifact, previously developed in parallel to core Box SDKs. To facilitate migration and provide access to the newest features, we'll soon release an additional major version combining both artifacts. Migration to `v10` includes breaking changes, please review the [migration guide](https://github.com/box/box-java-sdk/blob/sdk-gen/migration-guides/from-v4-to-v10.md) for details. For more information, see the [SDK versioning strategy document](https://developer.box.com/guides/tooling/sdks/sdk-versioning). Follow developer changelog for future updates. + +--- + +### What’s New Compared to [Java SDK Gen](https://github.com/box/box-java-sdk-gen) `v0.8.1` + +#### ⚠ BREAKING CHANGES + +* Change names of unions (box/box-codegen[#787](https://github.com/box/box-java-sdk/issues/787)) ([#1359](https://github.com/box/box-java-sdk/issues/1359)) ([114e778](https://github.com/box/box-java-sdk/commit/114e7785031e19fb58933f231e656a991b5effb7)) +* Remove unused models from schemas (box/box-openapi[#547](https://github.com/box/box-java-sdk/issues/547)) ([#1354](https://github.com/box/box-java-sdk/issues/1354)) ([e031308](https://github.com/box/box-java-sdk/commit/e031308f102137351238bf3823372150d3927442)), closes [box/box-openapi#542](https://github.com/box/box-openapi/issues/542) [box/box-openapi#544](https://github.com/box/box-openapi/issues/544) [box/box-codegen#781](https://github.com/box/box-codegen/issues/781) [box/box-openapi#545](https://github.com/box/box-openapi/issues/545) [box/box-codegen#782](https://github.com/box/box-codegen/issues/782) +* Replace `Date` with `OffsetDateTime` (box/box-codegen[#826](https://github.com/box/box-java-sdk/issues/826)) ([#1419](https://github.com/box/box-java-sdk/issues/1419)) ([ed04407](https://github.com/box/box-java-sdk/commit/ed04407e8effa8811bc85023783097f8a95e5223)) + +#### New Features and Enhancements + +* Add proxy support (box/box-codegen[#830](https://github.com/box/box-java-sdk/issues/830)) ([#1424](https://github.com/box/box-java-sdk/issues/1424)) ([cc53247](https://github.com/box/box-java-sdk/commit/cc532475cdaf5ec3fd710149b41a6e7b04dcd32f)) + +For more details check [migration guide](https://github.com/box/box-java-sdk/blob/sdk-gen/migration-guides/from-box-java-sdk-gen-v0-to-box-java-sdk-v10.md) from `box-java-sdk-gen` `v0` to `box-java-sdk` `v10`. + +### [4.16.3](https://github.com/box/box-java-sdk/compare/v4.16.2...v4.16.3) (2025-07-23) + + +### Bug Fixes: + +* Fix compare message webhook message signature ([#1315](https://github.com/box/box-java-sdk/issues/1315)) ([e2d407d](https://github.com/box/box-java-sdk/commit/e2d407ded3370ffee6eb074044fd562629a904be)) +* Fix File Request Copy method to return valid data ([#1320](https://github.com/box/box-java-sdk/issues/1320)) ([8392a43](https://github.com/box/box-java-sdk/commit/8392a437c1a738bebb4e7d0f84d6bf833c76bdf3)) + +### [4.16.2](https://github.com/box/box-java-sdk/compare/v4.16.1...v4.16.2) (2025-06-02) + + +### Bug Fixes: + +* Fix parsing `downloadFileCount` property for `BoxZipDownloadStatus` ([50c2249](https://github.com/box/box-java-sdk/commit/50c2249ff5e0f0d1fdc99c9ff8786e9c134e58eb)) + +### [4.16.1](https://github.com/box/box-java-sdk/compare/v4.16.0...v4.16.1) (2025-04-29) + + +### Bug Fixes: + +* use `Locale.ROOT` to prevent issues with non-US locales ([#1306](https://github.com/box/box-java-sdk/issues/1306)) ([f083092](https://github.com/box/box-java-sdk/commit/f083092d5fdac37c93493945ab0c05ecdcdbc838)) + +## [4.16.0](https://github.com/box/box-java-sdk/compare/v4.15.3...v4.16.0) (2025-04-15) + + +### New Features and Enhancements: + +* Bump version of `zstd-jni` ([#1302](https://github.com/box/box-java-sdk/issues/1302)) ([9ebf8b5](https://github.com/box/box-java-sdk/commit/9ebf8b5d16c0ab8f4aa19849fdaa86935d38b294)) + +### [4.15.3](https://github.com/box/box-java-sdk/compare/v4.15.2...v4.15.3) (2025-03-12) + + +### Bug Fixes: + +* trim `content-length` header value ([#1297](https://github.com/box/box-java-sdk/issues/1297)) ([fa11d14](https://github.com/box/box-java-sdk/commit/fa11d141edf511eabc5f2398e55dc411d0cdcd31)) + +### [4.15.2](https://github.com/box/box-java-sdk/compare/v4.15.1...v4.15.2) (2025-02-26) + + +### Bug Fixes: + +* Improve logging for API Request and API Response ([#1295](https://github.com/box/box-java-sdk/issues/1295)) ([6eb1f57](https://github.com/box/box-java-sdk/commit/6eb1f57a584571b46daa14d045a36bca382493fa)) + +### [4.15.1](https://github.com/box/box-java-sdk/compare/v4.15.0...v4.15.1) (2025-02-24) + + +### Bug Fixes: + +* Fix parsing content length header ([#1292](https://github.com/box/box-java-sdk/issues/1292)) ([3bcf788](https://github.com/box/box-java-sdk/commit/3bcf788dd9849305aa2cc85b8e5f88b35803ecb2)) + +## [4.15.0](https://github.com/box/box-java-sdk/compare/v4.14.0...v4.15.0) (2025-02-19) + + +### New Features and Enhancements: + +* Add `canNonOwnersViewCollaborators` flag to `Folder` ([#1288](https://github.com/box/box-java-sdk/issues/1288)) ([9119adc](https://github.com/box/box-java-sdk/commit/9119adceae35e892e73ed61ed30cf82ad912960d)) +* Support `zstd` encoding for downloads ([#1287](https://github.com/box/box-java-sdk/issues/1287)) ([0e3c4c0](https://github.com/box/box-java-sdk/commit/0e3c4c07e65ef1887cd5c393e3daf98aeb50ee47)) + +### Bug Fixes: + +* Fix AI dialogue history ([#1289](https://github.com/box/box-java-sdk/issues/1289)) ([29b6519](https://github.com/box/box-java-sdk/commit/29b651987a5cbeead4b129cab20970f983cb6889)) + +## [4.14.0](https://github.com/box/box-java-sdk/compare/v4.13.1...v4.14.0) (2025-01-22) + + +### New Features and Enhancements: + +* Support downloading file from shared link ([#1282](https://github.com/box/box-java-sdk/issues/1282)) ([9b7f28b](https://github.com/box/box-java-sdk/commit/9b7f28b0288977513b0db3ed4f800647545e1f2c)) + +### Bug Fixes: + +* Remove sensitive data when `BoxAPIException` logs request ([#1284](https://github.com/box/box-java-sdk/issues/1284)) ([f1e226f](https://github.com/box/box-java-sdk/commit/f1e226f710c301202acff067ef34687ddbb57b7b)) +* Support creating ongoing Legal Hold policy with start date ([#1281](https://github.com/box/box-java-sdk/issues/1281)) ([d9564e2](https://github.com/box/box-java-sdk/commit/d9564e2e86ea110af933ca3dd0f728111d7140ae)) + +### [4.13.1](https://github.com/box/box-java-sdk/compare/v4.13.0...v4.13.1) (2024-11-29) + + +### Bug Fixes: + +* Correctly calculate `Content-Length` when reading from a stream ([#1277](https://github.com/box/box-java-sdk/issues/1277)) ([b1d5371](https://github.com/box/box-java-sdk/commit/b1d5371491abe1729a95eb9dc39d375135c8681d)) + +## [4.13.0](https://github.com/box/box-java-sdk/compare/v4.12.0...v4.13.0) (2024-11-21) + + +### New Features and Enhancements: + +* Enforce exact byte reading from `Content-Length` header for `BoxFile` representation ([#1274](https://github.com/box/box-java-sdk/issues/1274)) ([0b45cdb](https://github.com/box/box-java-sdk/commit/0b45cdb74c21996d1dfea505d25430a1fa9ee730)) +* Expose `getVersionByID` method on `BoxFile` ([#1268](https://github.com/box/box-java-sdk/issues/1268)) ([6ea70f7](https://github.com/box/box-java-sdk/commit/6ea70f79ad39dd9a427ee574b5536d0ab1e3a9a4)) +* make `tryRestoreUsingAccessTokenCache` in Box API connection public ([#1272](https://github.com/box/box-java-sdk/issues/1272)) ([50f5a61](https://github.com/box/box-java-sdk/commit/50f5a61184bd1a17a17e811536166f9f8e081a13)) + +### Bug Fixes: + +* Fix `accessToken` locking mechanism ([#1270](https://github.com/box/box-java-sdk/issues/1270)) ([5eb4c93](https://github.com/box/box-java-sdk/commit/5eb4c93bd3653b28dc7def747779d008369f486a)) + +## [4.12.0](https://github.com/box/box-java-sdk/compare/v4.11.1...v4.12.0) (2024-10-17) + + +### New Features and Enhancements: + +* Support AI Agent ([#1265](https://github.com/box/box-java-sdk/issues/1265)) ([3cb2c7c](https://github.com/box/box-java-sdk/commit/3cb2c7c275761a24be9403a6a2b41d0725ba8d9b)) +* Support AI extract and AI extract structured ([#1266](https://github.com/box/box-java-sdk/issues/1266)) ([7ba90b9](https://github.com/box/box-java-sdk/commit/7ba90b96070a32b3e2ac60e5c55bd04d0a5973c0)) + +### [4.11.1](https://github.com/box/box-java-sdk/compare/v4.11.0...v4.11.1) (2024-07-16) + + +### Bug Fixes: + +* Fix order of file upload multipart request ([#1261](https://github.com/box/box-java-sdk/issues/1261)) ([7200ac7](https://github.com/box/box-java-sdk/commit/7200ac77888b3639f2c294486be278e316efcfb0)) + +## [4.11.0](https://github.com/box/box-java-sdk/compare/v4.10.0...v4.11.0) (2024-07-15) + + +### New Features and Enhancements: + +* Allow overriding creation of OkHttp Call ([#1257](https://github.com/box/box-java-sdk/issues/1257)) ([bd6fde6](https://github.com/box/box-java-sdk/commit/bd6fde6689bebe6cb5889c91214db68e08a4ec8b)) + +### Bug Fixes: + +* Add missing fields when update classification template ([#1255](https://github.com/box/box-java-sdk/issues/1255)) ([f17f817](https://github.com/box/box-java-sdk/commit/f17f817bde5a412358bf3de8e489ed080715ec4b)) +* Fix deserializing permissions for `BoxFile` and `BoxFolder` ([#1256](https://github.com/box/box-java-sdk/issues/1256)) ([f088448](https://github.com/box/box-java-sdk/commit/f08844889800a01f7c78941036f6228502fca8b0)) + +## [4.10.0](https://github.com/box/box-java-sdk/compare/v4.9.1...v4.10.0) (2024-06-06) + + +### New Features and Enhancements: + +* Overload the `getRepresentationContent` method with a `maxRetries` parameter ([#1251](https://github.com/box/box-java-sdk/issues/1251)) ([d26bd4f](https://github.com/box/box-java-sdk/commit/d26bd4f5a141150a372159bc3867abbbbdda1406)) +* Support `login_required`, `password`, `suppress_nofitications`, `verification_phone_number` and `additional_info` fields in sign request ([#1250](https://github.com/box/box-java-sdk/issues/1250)) ([3ee55b3](https://github.com/box/box-java-sdk/commit/3ee55b3613c5f5fa92cdd4a17c0cb3e2cc86a9a4)) + +### [4.9.1](https://github.com/box/box-java-sdk/compare/v4.9.0...v4.9.1) (2024-05-20) + + +### Bug Fixes: + +* Bumped `org.bouncycastle:bcprov-jdk18on:1.78.1` and `org.bouncycastle:bcpkix-jdk18on:1.78.1` ([#1246](https://github.com/box/box-java-sdk/issues/1246)) ([0557bed](https://github.com/box/box-java-sdk/commit/0557bed2b65d1be717b64a612d74fca73ba21096)) + +## [4.9.0](https://github.com/box/box-java-sdk/compare/v4.8.0...v4.9.0) (2024-05-06) + + +### New Features and Enhancements: + +* Support AI API ([#1243](https://github.com/box/box-java-sdk/issues/1243)) ([4e64f27](https://github.com/box/box-java-sdk/commit/4e64f27874fabf36f7fbf385ca4a60683f4a7670)) +* Support pagination of file versions ([#1240](https://github.com/box/box-java-sdk/issues/1240)) ([7e7af3f](https://github.com/box/box-java-sdk/commit/7e7af3f6e40a44522a7649817547846e3f633fc8)) + +### Bug Fixes: + +* Support create empty shared link ([#1241](https://github.com/box/box-java-sdk/issues/1241)) ([0c86487](https://github.com/box/box-java-sdk/commit/0c86487848e5004a713873baffa2d9dcc63b1502)) +* Update exception message for get representation content ([#1239](https://github.com/box/box-java-sdk/issues/1239)) ([a608f9a](https://github.com/box/box-java-sdk/commit/a608f9a4350b723e9f07eaf00af45243737a17c9)) + +## [4.8.0](https://github.com/box/box-java-sdk/compare/v4.7.0...v4.8.0) (2024-02-27) + + +### New Features and Enhancements: + +* allow modifying `BoxAPIRequest` URL ([#1236](https://github.com/box/box-java-sdk/issues/1236)) ([eaea019](https://github.com/box/box-java-sdk/commit/eaea0193ab7e72b73746ea85806e62468825bbce)) +* Bumped `org.bouncycastle:bcprov-jdk18on:1.77` and `org.bouncycastle:bcpkix-jdk18on:1.77` ([#1237](https://github.com/box/box-java-sdk/issues/1237)) ([6c7fe7b](https://github.com/box/box-java-sdk/commit/6c7fe7b74dbfb34e729fcecf8a29a1d3a1ba596f)), closes [#1235](https://github.com/box/box-java-sdk/issues/1235) + +### Bug Fixes: + +* fix download for empty files ([#1231](https://github.com/box/box-java-sdk/issues/1231)) ([0e2230b](https://github.com/box/box-java-sdk/commit/0e2230b0be36f6bfb35f1d6b9dd4ba58e4d125ec)) +* stop using `SharedLinkAPIConnection` in `getSharedItem()` ([#1234](https://github.com/box/box-java-sdk/issues/1234)) ([9f9af8e](https://github.com/box/box-java-sdk/commit/9f9af8e22b4a38dc9a31a611ff1b962966bbd6b5)) + +## [4.7.0](https://github.com/box/box-java-sdk/compare/v4.6.1...v4.7.0) (2024-01-16) + + +### New Features and Enhancements: + +* Add `signer_group_id` for signer in sign request ([#1220](https://github.com/box/box-java-sdk/issues/1220)) ([f560db8](https://github.com/box/box-java-sdk/commit/f560db8d5587406099066803789d16374ec7dbb9)) +* Introduce `IPrivateKeyDecryptor` to allow using custom cryptography provider ([#1226](https://github.com/box/box-java-sdk/issues/1226)) ([727e6d7](https://github.com/box/box-java-sdk/commit/727e6d71ee375a48b4241a26a093becfe0965898)) + +### Bug Fixes: + +* Remove delete classification ([#1222](https://github.com/box/box-java-sdk/issues/1222)) ([9814038](https://github.com/box/box-java-sdk/commit/981403896b4cd16a42c9feeecf30e75e1e8fa072)) + +### [4.6.1](https://github.com/box/box-java-sdk/compare/v4.6.0...v4.6.1) (2023-11-02) + + +### Dependency Upgrades: + +* Bumped `org.bitbucket.b_c:jose4j:0.9.3` ([#1212](https://github.com/box/box-java-sdk/issues/1212)) ([f522a56](https://github.com/box/box-java-sdk/commit/f522a5660f3522b11a0516774ba0cca69db3ec31)) + +## [4.6.0](https://github.com/box/box-java-sdk/compare/v4.5.0...v4.6.0) (2023-09-28) + + +### New Features and Enhancements: + +* Support search deleted filters ([#1207](https://github.com/box/box-java-sdk/issues/1207)) ([5e0e9ed](https://github.com/box/box-java-sdk/commit/5e0e9ed9aea2818da6fba0d562b56987c4948aaa)) + +### Bug Fixes: + +* Added protected accessors for trust manager and hostname verifier. ([#1206](https://github.com/box/box-java-sdk/issues/1206)) ([0c79d17](https://github.com/box/box-java-sdk/commit/0c79d1754bffeb3f0487e10d55d716ba1cbed1aa)) +* fix not closing response body ([#1208](https://github.com/box/box-java-sdk/issues/1208)) ([ab5e170](https://github.com/box/box-java-sdk/commit/ab5e1702934607b258802b33f3663af3e9c56027)) + +## [4.5.0](https://github.com/box/box-java-sdk/compare/v4.4.0...v4.5.0) (2023-09-13) + + +### New Features and Enhancements: + +* Add `iframeable_embed_url` field to `BoxSignRequestSigner` class ([#1202](https://github.com/box/box-java-sdk/issues/1202)) ([2e931d8](https://github.com/box/box-java-sdk/commit/2e931d8c36694a665d1c6315d3bf2d226929b713)) + +### Bug Fixes: + +* `SharedLinkAPIConnection` uses request interceptor ([#1203](https://github.com/box/box-java-sdk/issues/1203)) ([b2b6a1d](https://github.com/box/box-java-sdk/commit/b2b6a1dba316ba50a1e011250c320fca156c6708)), closes [#1200](https://github.com/box/box-java-sdk/issues/1200) +* Update sign template missing enum ([#1201](https://github.com/box/box-java-sdk/issues/1201)) ([fcb6657](https://github.com/box/box-java-sdk/commit/fcb6657bb2375e32c3fb0f861e7ecaeb84503f2c)) + +## [4.4.0](https://github.com/box/box-java-sdk/compare/v4.3.0...v4.4.0) (2023-08-29) + + +### New Features and Enhancements: + +* Support sign template and new sign status ([#1197](https://github.com/box/box-java-sdk/issues/1197)) ([e37c0dc](https://github.com/box/box-java-sdk/commit/e37c0dce86a422de5e8e6ed26fd93f1324f4b3e3)) + +## [4.3.0](https://github.com/box/box-java-sdk/compare/v4.2.1...v4.3.0) (2023-08-11) + + +### New Features and Enhancements: + +* Support access only collaboration ([#1193](https://github.com/box/box-java-sdk/issues/1193)) ([664c01f](https://github.com/box/box-java-sdk/commit/664c01f80ca0647645c60920eb0ef1f9353a619f)) + +### [4.2.1](https://github.com/box/box-java-sdk/compare/v4.2.0...v4.2.1) (2023-08-03) + + +### Bug Fixes: + +* Fixed upload when data are coming from a dynamic source ([#1189](https://github.com/box/box-java-sdk/issues/1189)) ([77b39f2](https://github.com/box/box-java-sdk/commit/77b39f2645d53bdab0ade23b637c211ea070fcf5)), closes [#1183](https://github.com/box/box-java-sdk/issues/1183) [#1190](https://github.com/box/box-java-sdk/issues/1190) + +## [4.2.0](https://github.com/box/box-java-sdk/compare/v4.1.2...v4.2.0) (2023-06-21) + + +### New Features and Enhancements: + +* Getting collaborators allows to specify fields ([#1178](https://github.com/box/box-java-sdk/issues/1178)) ([1694d75](https://github.com/box/box-java-sdk/commit/1694d75fff0fbddb938426ef03ba24f360a344aa)) + +### [4.1.2](https://github.com/box/box-java-sdk/compare/v4.1.1...v4.1.2) (2023-06-14) + + +### Bug Fixes: + +* Class cast exception when uploading large file ([#1174](https://github.com/box/box-java-sdk/issues/1174)) ([e7d28bd](https://github.com/box/box-java-sdk/commit/e7d28bddb706c8b4fd1328f0eebc50db19a8c656)), closes [#1173](https://github.com/box/box-java-sdk/issues/1173) +* Make `SharedLinkAPIConnection` constructors public ([#1172](https://github.com/box/box-java-sdk/issues/1172)) ([4d1616d](https://github.com/box/box-java-sdk/commit/4d1616ddd2c39d1cb0d03af998d2c47efe607853)) +* Remove invalid Group membership role ([#1171](https://github.com/box/box-java-sdk/issues/1171)) ([a5915f9](https://github.com/box/box-java-sdk/commit/a5915f94114a8269287831280a57949ed203e4e8)) + +### [4.1.1](https://github.com/box/box-java-sdk/compare/v4.1.0...v4.1.1) (2023-05-16) + + +### Bug Fixes: + +* Allow users to disable adding authentication header. ([#1167](https://github.com/box/box-java-sdk/issues/1167)) ([3433e5a](https://github.com/box/box-java-sdk/commit/3433e5a405ceb9bc32791642518b1fd65c4b4032)) +* Logging headers when retrying request ([#1164](https://github.com/box/box-java-sdk/issues/1164)) ([e0c3d8e](https://github.com/box/box-java-sdk/commit/e0c3d8e730962ba5c97105ce506ee931a3bba362)) + +## [4.1.0](https://github.com/box/box-java-sdk/compare/v4.0.1...v4.1.0) (2023-04-24) + + +### New Features and Enhancements: + +* Add missing `fields` parameter to create and update `BoxUser` methods ([#1155](https://github.com/box/box-java-sdk/issues/1155)) ([be3820d](https://github.com/box/box-java-sdk/commit/be3820dc4df15e99dfc13602d4f7269841bd15b3)), closes [#1154](https://github.com/box/box-java-sdk/issues/1154) + +### Bug Fixes: + +* Allow registering custom logger handlers ([#1156](https://github.com/box/box-java-sdk/issues/1156)) ([7373d5c](https://github.com/box/box-java-sdk/commit/7373d5cc2bf49bc198cbca70d056e43f0dffdb3a)) +* Fallback to default value of `maxRetryAttempts` when restoring `BoxAPIConnection` ([#1161](https://github.com/box/box-java-sdk/issues/1161)) ([2a10e5d](https://github.com/box/box-java-sdk/commit/2a10e5d07497611e077a9207fe98c1d8146cfd22)), closes [#1160](https://github.com/box/box-java-sdk/issues/1160) + +### [4.0.1](https://github.com/box/box-java-sdk/compare/v4.0.0...v4.0.1) (2023-03-06) + + +### Bug Fixes: + +* `OAUTH_SUFFIX` gets appended twice to `baseAuthorizationURL` ([#1148](https://github.com/box/box-java-sdk/issues/1148)) ([3164770](https://github.com/box/box-java-sdk/commit/3164770498e5115a43318640735317a896950f54)), closes [#1147](https://github.com/box/box-java-sdk/issues/1147) +* Wrong progress reported to `ProgressListener` by `AbstractBoxMultipartRequest` ([#1151](https://github.com/box/box-java-sdk/issues/1151)) ([947ded3](https://github.com/box/box-java-sdk/commit/947ded394490fc840b8191bc7ad69ae0ea5f5c7d)), closes [#1149](https://github.com/box/box-java-sdk/issues/1149) + +## [4.0.0](https://github.com/box/box-java-sdk/compare/v3.8.2...v4.0.0) (2023-01-17) + + +The most important change this release includes is the replacement of the HTTP library from a native one to +[OkHttp](https://square.github.io/okhttp/) which allows SDK to +- Support the HTTP2 version of the HTTP protocol. +- Support proxies that do not use only basic authentication method. For details on creating custom proxy authenticators and an example of + [NTLM proxy authentication](https://github.com/box/box-java-sdk/blob/kb/ok-http/doc/configuration.md#custom-proxy-authenticator). + +### Breaking Changes +* `BatchAPIRequest` – is no longer supported by the SDK +* `BoxAPIConnection#DEFAULT_MAX_ATTEMPTS` is replaced with `BoxAPIConnection#DEFAULT_MAX_RETRIES` +* `BoxRedirectResponse` – was removed and will not be replaced +* `BoxEvent.Type` is replaced with `EventType` +* Removing deprecated methods from `BoxFile`, `BoxFileVersionRetention`, `BoxFolder`, `BoxGroup`, `BoxGroupMembership`,`BoxItem`, `BoxRetentionPolicy`, `BoxTask`, `BoxUser`, `BoxWebLink`, `EventLog`, `Metadata` and `MetadataTemplate`. + +Migration details can be found [here](doc/upgrades/3.x.x%20to%204.x.x.md). + +### New Features and Enhancements: + +* Using `OkHttp` in Java SDK ([#1083](https://github.com/box/box-java-sdk/issues/1083)) ([2656698](https://github.com/box/box-java-sdk/commit/265669897100dd8f1757fc2c5f25665da42c2889)) + +### [3.8.2](https://github.com/box/box-java-sdk/compare/v3.8.1...v3.8.2) (2023-01-04) + + +### Bug Fixes: + +* Fixed restoring state without refresh token. ([#1139](https://github.com/box/box-java-sdk/issues/1139)) ([3544709](https://github.com/box/box-java-sdk/commit/3544709480eb03e5bd50f5dc99be7409569304c4)) + +### [3.8.1](https://github.com/box/box-java-sdk/compare/v3.8.0...v3.8.1) (2022-12-19) + + +### Bug Fixes: + +* Restoring state from previous `SDK` version works. ([#1134](https://github.com/box/box-java-sdk/issues/1134)) ([b6d97dd](https://github.com/box/box-java-sdk/commit/b6d97dd5b0cc91eb2e4c922ff217e0878e0f63ec)) + +## [3.8.0](https://github.com/box/box-java-sdk/compare/v3.7.1...v3.8.0) (2022-11-15) + + +### New Features and Enhancements: + +* Added Box Sign webhooks ([#1109](https://github.com/box/box-java-sdk/issues/1109)) ([99051a5](https://github.com/box/box-java-sdk/commit/99051a575f120a8c0939359c1f4875b16b98b7f0)) + +### Bug Fixes: + +* `NullPointerException` when using `BoxSignRequestPrefillTag` ([#1121](https://github.com/box/box-java-sdk/issues/1121)) ([73fd5b6](https://github.com/box/box-java-sdk/commit/73fd5b6e6e40f7e79b385edf46b8eee5ff612ace)), closes [#1120](https://github.com/box/box-java-sdk/issues/1120) +* Regenerate JWT ID and retry auth request when JTI claim is rejected ([#1110](https://github.com/box/box-java-sdk/issues/1110)) ([420da0f](https://github.com/box/box-java-sdk/commit/420da0f2c80bfe8cfbaba4fa8dec4826c4cb6337)) + +### Dependency Upgrades: + +* Bumped org.bitbucket.b_c:jose4j:0.9.0 ([#1111](https://github.com/box/box-java-sdk/issues/1111)) ([349694d](https://github.com/box/box-java-sdk/commit/349694ddcfeb701a9ecdfd5ae555d49bea4d1030)) + +### [3.7.1](https://github.com/box/box-java-sdk/compare/v3.7.0...v3.7.1) (2022-09-29) + + +### Bug Fixes: + +* Better logging when JSON cannot be parsed ([#1106](https://github.com/box/box-java-sdk/issues/1106)) ([5e66ef8](https://github.com/box/box-java-sdk/commit/5e66ef8cc983a6cff34995efc75e9effd3195d48)) + +## [3.7.0](https://github.com/box/box-java-sdk/compare/v3.6.0...v3.7.0) (2022-09-20) + + +### New Features and Enhancements: + +* Add `is_accessible_via_shared_link` field to File and Folder ([#1103](https://github.com/box/box-java-sdk/issues/1103)) ([45e9906](https://github.com/box/box-java-sdk/commit/45e9906efca6a7f2d4d738914dc804de12d3646e)) + +### Bug Fixes: + +* `BoxCollaboration.getItem()` returns `BoxItem.Info` not `BoxFolder.Info` ([#1102](https://github.com/box/box-java-sdk/issues/1102)) ([135850d](https://github.com/box/box-java-sdk/commit/135850d97164ee5f6d74708d74c531f7fa8bee26)), closes [#1101](https://github.com/box/box-java-sdk/issues/1101) [#1100](https://github.com/box/box-java-sdk/issues/1100). `BoxCollaboration.getItem()` used to return `BoxFolder.Info`. However, if collaboration was added on a file it would still return `BoxFolder.Info` which will end with throwing `BoxAPIException` when doing any API call. If you are getting collaboration item it is best to store it as `BoxItem.Info` or check its type and store it as `BoxFile.Info` or `BoxFolder.Info`. +* Add missing constructor to `BoxNotificationEmail` class ([#1098](https://github.com/box/box-java-sdk/issues/1098)) ([2534f34](https://github.com/box/box-java-sdk/commit/2534f34133f9554abd1e80fc1555659a2c52b23f)) + +## [3.6.0](https://github.com/box/box-java-sdk/compare/v3.5.0...v3.6.0) (2022-09-07) + + +### New Features and Enhancements: + +* Add support for modifiable retention policies & enable deleting retention policy assignment ([#1093](https://github.com/box/box-java-sdk/issues/1093)) ([30e2fcb](https://github.com/box/box-java-sdk/commit/30e2fcb74c12867fd3859c3490539557b47ab006)) + +### Bug Fixes: + +* Stop sending not specified optional fields when creating a user ([#1095](https://github.com/box/box-java-sdk/issues/1095)) ([b7d894d](https://github.com/box/box-java-sdk/commit/b7d894d3f134137f3a5925f09accfd4334837f81)) + +## [3.5.0](https://github.com/box/box-java-sdk/compare/v3.4.0...v3.5.0) (2022-08-26) + + +### New Features and Enhancements: + +* Add `content-type` sign request and response ([#1087](https://github.com/box/box-java-sdk/issues/1087)) ([49411aa](https://github.com/box/box-java-sdk/commit/49411aaeea6d3ff8de10e3fbc3c60bba1bc54748)) +* Add `notification_email` to `BoxUser` ([#1088](https://github.com/box/box-java-sdk/issues/1088)) ([5477223](https://github.com/box/box-java-sdk/commit/547722347a920ba11e5fff7a8df5201720af815a)) +* Add `redirect_url` and `declined_redirect_url` to sign request response ([#1089](https://github.com/box/box-java-sdk/issues/1089)) ([3921fe1](https://github.com/box/box-java-sdk/commit/3921fe1a4a6249146a8dd2f22e15801846bc073b)) + +### Bug Fixes: + +* Fixed canceling sign request fails because of empty body ([#1085](https://github.com/box/box-java-sdk/issues/1085)) ([32b8e79](https://github.com/box/box-java-sdk/commit/32b8e79ebc8995ab933c32d28c3e2f17d9627a70)) + +## [3.4.0](https://github.com/box/box-java-sdk/compare/v3.3.0...v3.4.0) (2022-08-10) + + +### New Features and Enhancements: + +* Added pagination for getting items in trash with new `BoxTrash#items` API ([#1072](https://github.com/box/box-java-sdk/issues/1072)) ([9cd411d](https://github.com/box/box-java-sdk/commit/9cd411d20af1bc76ae815905396d72008af62539)) + +### Bug Fixes: + +* buffered body write and fixed SDK logging ([#1079](https://github.com/box/box-java-sdk/issues/1079)) ([bc35ef3](https://github.com/box/box-java-sdk/commit/bc35ef3279e68a3d794de454f506ba41d14c3b16)) + +## [3.3.0](https://github.com/box/box-java-sdk/compare/v3.2.1...v3.3.0) (2022-07-01) + + +### New Features and Enhancements: + +* Added support of Editable Shared Links ([#1064](https://github.com/box/box-java-sdk/issues/1064)) ([9b7d60c](https://github.com/box/box-java-sdk/commit/9b7d60c41fbd481465bf3f2a5877746f10849712)) + +### Bug Fixes: + +* Fix closed stream exception in `canUpload` method ([#1067](https://github.com/box/box-java-sdk/issues/1067)) ([543f91c](https://github.com/box/box-java-sdk/commit/543f91c46dfcc9de7e61ce11cd93d472916533ac)) + +### [3.2.1](https://github.com/box/box-java-sdk/compare/v3.2.0...v3.2.1) (2022-06-10) + + +### Bug Fixes: + +* Fix getting proper URL to authenticate with OAuth ([#1059](https://github.com/box/box-java-sdk/issues/1059)) ([42876b4](https://github.com/box/box-java-sdk/commit/42876b45ccdb7fa6f357186cecaba051abf1c269)), closes [#1057](https://github.com/box/box-java-sdk/issues/1057) + +## [3.2.0](https://github.com/box/box-java-sdk/compare/v3.1.2...v3.2.0) (2022-05-23) + + +### New Features and Enhancements: + +* Revamped setting base URLs ([#1042](https://github.com/box/box-java-sdk/issues/1042)) ([129baf7](https://github.com/box/box-java-sdk/commit/129baf704ced127788bb0f62ef9f4fb6a50fdc63)) +* support for Avatar V2 API ([#1044](https://github.com/box/box-java-sdk/issues/1044)) ([18651d7](https://github.com/box/box-java-sdk/commit/18651d7a5b419796e3733c7582ae471d7af7ed5c)) + +### [3.1.2](https://github.com/box/box-java-sdk/compare/v3.1.1...v3.1.2) (2022-03-22) + + +### Bug Fixes: + +* Allow using `As-User` header with CCG Authentication ([#1031](https://github.com/box/box-java-sdk/issues/1031)) ([b0c2389](https://github.com/box/box-java-sdk/commit/b0c238913cc1dbcecfd546a5eae68277c3c76d42)) +* Fix retry logic when `Retry-After` header is present ([#1033](https://github.com/box/box-java-sdk/issues/1033)) ([05224c4](https://github.com/box/box-java-sdk/commit/05224c433d2a101a01959644674153df9542b711)) + +### [3.1.1](https://github.com/box/box-java-sdk/compare/v3.1.0...v3.1.1) (2022-02-28) + + +### Bug Fixes: + +* retry `jwt` auth when error code is in error field ([#1020](https://github.com/box/box-java-sdk/issues/1020)) ([8c9d11d](https://github.com/box/box-java-sdk/commit/8c9d11d1b3556552751c9f4ac99a0f7180af97f3)), closes [#1019](https://github.com/box/box-java-sdk/issues/1019) + +## [3.1.0](https://github.com/box/box-java-sdk/compare/v3.0.0...v3.1.0) (2022-02-17) + + +### New Features and Enhancements: + +* Added support for Client Credentials Grant authentication method ([#1002](https://github.com/box/box-java-sdk/issues/1002)) ([9cfcaff](https://github.com/box/box-java-sdk/commit/9cfcaff243dbf0541409f91f9f863a207345dc47)) +* API to extend disposition date on a file ([#1001](https://github.com/box/box-java-sdk/issues/1001)) ([f3f6b60](https://github.com/box/box-java-sdk/commit/f3f6b6043eec362c5a8ad9a01d6588538ca34e71)) +* Deprecating `indexName` when executing metadata query ([#1000](https://github.com/box/box-java-sdk/issues/1000)) ([c20dbbf](https://github.com/box/box-java-sdk/commit/c20dbbf6a927e31cfdd7ffa71069c0897f7a0536)) + +### Dependency Upgrades: + +* Upgrade Gradle to 7.3.3 ([#985](https://github.com/box/box-java-sdk/issues/985)) ([e4acbb1](https://github.com/box/box-java-sdk/commit/e4acbb1f0c10ccdeeee139e2566b344052680010)) + +## [3.0.0](https://github.com/box/box-java-sdk/compare/v2.58.0...v3.0.0) (2022-01-17) + + +### ⚠ BREAKING CHANGES + +* Changed `BoxFileVersion` class and removed `fileVersion` field (#978) +* Removed deprecated API `BoxCollaborationWhitelist` replaced with `BoxCollaborationAllowlist`, `BoxCollaborationWhitelistExemptTarget` replaced with `BoxCollaborationAllowlistExemptTarget` (#969) +* Dropping Java 7 support (#962) +* Downgrading `bouncycastle` libraries to 1.57 (#942) + +### New Features and Enhancements: + +* Add `typeName` to `BoxEvent` that contains name of the event, even if it is not mapped to `BoxEvent.EventType` ([#979](https://github.com/box/box-java-sdk/issues/979)) ([b30f61f](https://github.com/box/box-java-sdk/commit/b30f61f8cc9c02a1fc4cd5eb35469749e1a16558)), closes [#968](https://github.com/box/box-java-sdk/issues/968) +* Add new optional `description` parameter to the `retention_policies` endpoint and `start_date_field` to the `retention_policy_assignments endpoint`. ([#967](https://github.com/box/box-java-sdk/issues/967)) ([0aa4ff4](https://github.com/box/box-java-sdk/commit/0aa4ff48a1e035efc9ac6aaa42f18f4c92955b7b)) +* Adding `BoxFile#getVersions(String... fields)` to allow users to specify what information they want to extract. Fixes [#946](https://github.com/box/box-java-sdk/issues/946). ([#947](https://github.com/box/box-java-sdk/issues/947)) ([a2eb638](https://github.com/box/box-java-sdk/commit/a2eb63896606a6c00ccee6bd9745f4c51f8d89a2)) +* Missing `eventTypes` from `BoxAPI` Documents. Fixes [#974](https://github.com/box/box-java-sdk/issues/974) ([#975](https://github.com/box/box-java-sdk/issues/975)) ([2c69360](https://github.com/box/box-java-sdk/commit/2c69360e80b1bdd6213933cf2f4da195d52c92d4)) +* Removed deprecated API `BoxCollaborationWhitelist` replaced with `BoxCollaborationAllowlist`, `BoxCollaborationWhitelistExemptTarget` replaced with `BoxCollaborationAllowlistExemptTarget` ([#969](https://github.com/box/box-java-sdk/issues/969)) ([2fd4d6f](https://github.com/box/box-java-sdk/commit/2fd4d6f884410c8884c4c038687bfc8f32837b55)) + +### Bug Fixes: + +* Changed `BoxFileVersion` class and removed `fileVersion` field ([#978](https://github.com/box/box-java-sdk/issues/978)) ([8c39451](https://github.com/box/box-java-sdk/commit/8c3945167581400043a070c2f6906ef05d3d7b85)) +* Changed SDK loggers name to `"com.box.sdk"`, fixes [#638](https://github.com/box/box-java-sdk/issues/638) ([#950](https://github.com/box/box-java-sdk/issues/950)) ([443c230](https://github.com/box/box-java-sdk/commit/443c23085e55bbcaa1524c5b9e1bf852a1e2a1ce)) +* Date parsing error when `BoxSignRequestPrefillTag` created with date value. ([#970](https://github.com/box/box-java-sdk/issues/970)) ([cc2c8da](https://github.com/box/box-java-sdk/commit/cc2c8da9ea7d066ae2c247c2de5ac8b8bbba9b99)) +* Fix sending limit param in `EventLog` ([#977](https://github.com/box/box-java-sdk/issues/977)) ([96bdccc](https://github.com/box/box-java-sdk/commit/96bdccc9ca40ed43a6028a2b0d055d9d9a8de525)) +* Fixed `NullPointerException` when empty metadata used on BoxFile or `BoxFolder` ([#918](https://github.com/box/box-java-sdk/issues/918)) ([#945](https://github.com/box/box-java-sdk/issues/945)) ([68bc3c5](https://github.com/box/box-java-sdk/commit/68bc3c578d760b7239f6d704fed9bb5a834bf52a)) +* Fixes issue ([#951](https://github.com/box/box-java-sdk/issues/951)) error when deserialising sign request ([#952](https://github.com/box/box-java-sdk/issues/952)) ([070bdc5](https://github.com/box/box-java-sdk/commit/070bdc56074a1533c41f9085943d09502c79a7f4)) + +### Dependency Upgrades: + +* Dropping Java 7 support ([#962](https://github.com/box/box-java-sdk/issues/962)) ([953ad78](https://github.com/box/box-java-sdk/commit/953ad78ac84833082439d0def1dcc63dc11ac04a)) +* Downgrading `bouncycastle` libraries to 1.57 ([#942](https://github.com/box/box-java-sdk/issues/942)) ([26aaed5](https://github.com/box/box-java-sdk/commit/26aaed51fd914eaf2061da735f11830524e4cfe4)) + + +## [2.58.0] (2021-11-23) + +### ⚠ BREAKING CHANGES + +### New Features and Enhancements: + - SDK support for new GET /events stream_type: admin_logs_streaming ([#938](https://github.com/box/box-java-sdk/pull/938)) + - Adding BoxDeveloperEditionAPIConnection#getUserConnection to indicate that we can use this connection for managed users or app users ([#940](https://github.com/box/box-java-sdk/pull/940)) + +### Bug Fixes: + - Fix for deprecated enums still being used ([#931](https://github.com/box/box-java-sdk/issues/931)) + +## [2.57.0] (2021-10-18) + +### ⚠ BREAKING CHANGES + +### New Features and Enhancements: +- Add support for marker-based paging in BoxFolder.getChildren ([#927](https://github.com/box/box-java-sdk/pull/927)) +- Upgraded minimal-json to v0.9.5 +- Upgraded jose4j to v0.7.9 +- Adding Gradle wrapper in version 4.0.1 ([#928](https://github.com/box/box-java-sdk/pull/928)) + +### Bug Fixes: +- Fix for infinite recursion ([#924](https://github.com/box/box-java-sdk/pull/924)) +- Fix unable to set Vanity URL on `BoxSharedLink` for BoxFile and BoxFolder ([#925](https://github.com/box/box-java-sdk/issues/925)) + +## [2.56.0] (2021-08-31) + +### New Features and Enhancements: +- Replace `submaster` GroupMembershipRole with `coadmin`. Replace `MASTER_INVITE_ACCEPT` and `MASTER_INVITE_REJECT` with `ADMIN_INVITE_ACCEPT` and `ADMIN_INVITE_REJECT`. ([#907](https://github.com/box/box-java-sdk/pull/907)) +- Add `tracking_codes` to create User API call ([#910](https://github.com/box/box-java-sdk/pull/910)) + +### Bug Fixes: +- Fix `url` for `BoxFileRequest.Info` object ([#906](https://github.com/box/box-java-sdk/pull/906)) +- Attempt to fix thread locking issue on refresh of access token ([#912](https://github.com/box/box-java-sdk/pull/912)) + +## [2.55.1] (2021-07-30) + +### Bug Fixes: +- Restore methods for Execute Metadata Query, which were removed in ([#890](https://github.com/box/box-java-sdk/pull/890)), and mark them as deprecated ([#905](https://github.com/box/box-java-sdk/pull/905)) + +## [2.55.0] (2021-07-26) + +NOTE: Due to the benign nature of the "breaking change" below, we decided NOT to increment the major version for this release. There should be no customer impact due to this change. + +### ⚠ BREAKING CHANGES +- Update execute metadata query to match API response ([#890](https://github.com/box/box-java-sdk/pull/890)) + - NOTE: This change removes a method without deprecating it. It was not possible to use the method correctly at all, because the underlying service no longer supported it. + +### New Features and Enhancements: +- Remove or deprecate insensitive language ([#889])(https://github.com/box/box-java-sdk/pull/889) +- Add support for `is_external_collab_restricted` parameter for User ([#896](https://github.com/box/box-java-sdk/pull/896)) +- Add configurable permissions support for `GroupMembership` ([#897](https://github.com/box/box-java-sdk/pull/897)) +- Add `SHIELD_JUSTIFICATION_APPROVAL` event type ([#898](https://github.com/box/box-java-sdk/pull/898)) +- Add ability to get files under retention for assignment and file versions under retention for assignment ([#899](https://github.com/box/box-java-sdk/pull/899)) +- Add `TASK_UPDATE`, `FILE_VERSION_RESTORE` and `ADVANCED_FOLDER_SETTINGS_UPDATE` event types ([#902](https://github.com/box/box-java-sdk/pull/902)) +- Add SignAPI support ([#904](https://github.com/box/box-java-sdk/pull/904)) + +### Bug Fixes: +- Add setters for `BoxLegalHoldPolicy` ([#885](https://github.com/box/box-java-sdk/pull/885)) +- Add setters for `BoxTaskAssignment` ([#886](https://github.com/box/box-java-sdk/pull/886)) +- Add setters for Group Membership and Web Links ([#887](https://github.com/box/box-java-sdk/pull/887)) +- Add setters for Webhooks ([#888](https://github.com/box/box-java-sdk/pull/888)) +- Deprecate `BoxFile.getThumbnail` in favor of `BoxFile.getRepresentationContent` ([#891](https://github.com/box/box-java-sdk/pull/891)) + +## [2.54.0] (2021-04-01) + +### New Features and Enhancements: + +- Add file request support ([#869](https://github.com/box/box-java-sdk/pull/869)) + +### Bug Fixes: + +- Fix `BoxWeblink` deserialization ([#881](https://github.com/box/box-java-sdk/pull/881)) + +## [2.53.0] (2021-01-08) + +### New Features and Enhancements: + +- Add offset and limit parameters to `BoxFolder.getChildren` ([#861](https://github.com/box/box-java-sdk/pull/861)) + +## [2.52.0] (2020-11-24) + +### New Features and Enhancements: + +- Add folder lock functionality ([#856](https://github.com/box/box-java-sdk/pull/856)) +- Add support for search param to get shared link items ([#855](https://github.com/box/box-java-sdk/pull/855)) + +### Bug Fixes: + +- Fix bug with updating tracking codes ([#857](https://github.com/box/box-java-sdk/pull/857)) + +## [2.51.1] (2020-11-12) + +### Bug Fixes: + +- Fix for cross-enterprise collaborator calls to updateMetadata on files + +## [2.51.0] (2020-10-29) + +### New Features and Enhancements: + +- Add support for `copyInstanceOnItemCopy` field for metadata templates ([#850](https://github.com/box/box-java-sdk/pull/850)) +- Add support for more fields in `BoxCollaborator.Info` ([#843](https://github.com/box/box-java-sdk/pull/843)) + +### Bug Fixes: + +- Update `getAllGroupsByName()` to use documented parameter ([#851](https://github.com/box/box-java-sdk/pull/851)) + +## [2.50.1] (2020-08-20) +- Fix bug that occurred when downscoping a token for a Box folder ([#832](https://github.com/box/box-java-sdk/pull/832)) + +## [2.50.0] (2020-07-21) +- API request creation errors are now retried with the same automatic retry logic as 429 and 5XX response errors ([#828](https://github.com/box/box-java-sdk/pull/828)) + +## [2.49.0] (2020-07-17) +- Fix bug with setting the unshared at date for a shared link ([#819](https://github.com/box/box-java-sdk/pull/819)) +- Add zip functionality ([#825](https://github.com/box/box-java-sdk/pull/825)) +- Add `fields` parameter for metadata query ([#826](https://github.com/box/box-java-sdk/pull/826)) + +## [2.48.0] (2020-06-23) +- Add ability to get groups by name with fields option ([#789](https://github.com/box/box-java-sdk/pull/789)) +- Add shared link downscoping ([#785](https://github.com/box/box-java-sdk/pull/785)) +- Deprecate the use of float for Metadata values, in preference of the underlying value (double) ([#811](https://github.com/box/box-java-sdk/pull/811)) +- Add iterator support for group collaborations ([#813](https://github.com/box/box-java-sdk/pull/813)) +- Add ability to set the filename when uploading a new version of a file ([#810](https://github.com/box/box-java-sdk/pull/810)) +- Add support for the classification field for Files and Folders ([#809](https://github.com/box/box-java-sdk/pull/809)) +- Add support for setting Tracking Codes ([#766](https://github.com/box/box-java-sdk/pull/766)) +- Fix issue for `getIsExternallyOwned()` for Files and Folders ([#808](https://github.com/box/box-java-sdk/pull/808)) + +## [2.47.0] (2020-04-23) +- Add support for the uploader display name field for Files and File Versions ([#791](https://github.com/box/box-java-sdk/pull/791)) +- Fix path parameter sanitization ([#797](https://github.com/box/box-java-sdk/pull/797)) + +## [2.46.0] (2020-04-09) +- Fix retry logic ([#787](https://github.com/box/box-java-sdk/pull/787)) + - Retry for 400 `invalid_grant` error in authentication requests (Clock Skew) + - Honor Retry-After header, if present, by waiting for the time specified in the header before retrying + - The concept of setting / getting "Maximum API Requests" has been deprecated in favor of "Maximum API Retries" to more clearly show the number of times a request will be retried after an error response is received. +- Add ability to set expiration date for a collaboration ([#788](https://github.com/box/box-java-sdk/pull/788)) +- Add path parameter sanitization ([#790](https://github.com/box/box-java-sdk/pull/790)) + +## [2.45.0] (2020-04-02) +- Add preflight check before chunked uploads ([#782](https://github.com/box/box-java-sdk/pull/782)) +- Check that part was successfully uploaded for large file uploads before retrying for 500 errors ([#781](https://github.com/box/box-java-sdk/pull/781)) +- Fix bug with premature disconnect when renaming files and weblinks ([#779](https://github.com/box/box-java-sdk/pull/779)) +- Add metadata to each item returned by a metadata query ([#778](https://github.com/box/box-java-sdk/pull/778)) + +## [2.44.1] (2020-02-13) +- Fix formatting bug for Java Logger +- Improve date / time parsing for responses + +## [2.44.0] (2020-01-21) +- Fix Authentication Request Retries + +## [2.43.0] (2019-12-20) +- Throw exceptions for setMetadata on Files and Folders for non-409 errors + +## [2.42.0] (2019-12-17) +- Added Metadata Query support +- Added marker based pagination for get users methods + +## [2.41.0] (2019-10-24) +- Added enum action option for completed in Box Task class. + +## [2.40.0] (2019-10-24) +- General doc changes. + +## [2.39.0] (2019-10-17) +- Deprecated Batch API functionality. +- Added support for [Task completion_rule](https://github.com/box/box-java-sdk/blob/main/src/main/java/com/box/sdk/BoxFile.java#L249) + +## [2.38.0] (2019-09-19) +- Added missing fields for File Version: trashed_by, restored_at, purged_at, purged_by. +- Added support for [chunked uploads with file attributes](https://github.com/box/box-java-sdk/blob/main/doc/files.md#upload-a-large-file-in-chunks-including-attributes). + +## [2.37.0] (2019-08-22) +- Added support for replace in multi-select metadata for [files](https://github.com/box/box-java-sdk/blob/main/doc/files.md#update-metadata) and + for [folders](https://github.com/box/box-java-sdk/blob/main/doc/folders.md#update-metadata) +- Improved getting started with JWT authentication docs that can be found [here](https://github.com/box/box-java-sdk/blob/main/doc/authentication.md#server-authentication-with-jwt) + +## [2.36.0] (2019-08-01) +- Added support for [removing shared link](https://github.com/box/box-java-sdk/blob/main/src/main/java/com/box/sdk/BoxItem.java#L413) and fixed an issue with setting null for shared link field on BoxItem. +- Added support for additional fields for Box files, folders, and web links. + +## [2.35.0] (2019-07-18) +- Added support for retrieving [is_external_only field](https://github.com/box/box-java-sdk/blob/main/src/main/java/com/box/sdk/BoxFile.java#L1668) for Box Files and Folders. + +## [2.34.0] (2019-06-06) +- Added support for retrieving a [string type action for tasks](https://github.com/box/box-java-sdk/blob/main/src/main/java/com/box/sdk/BoxTask.java#L281). + Please use getActionType() going forward instead of the deprecated getAction(). + +## [2.33.0] (2019-05-23) + +- Added support for [setting can_owners_invite field](https://github.com/box/box-java-sdk/blob/1ed10d7a457e44b863ec1c9b1d0d1408fb55e1e5/src/main/java/com/box/sdk/BoxFolder.java#L1272) Thank you @Band-Aid for you pull request! Greatly Appreciated. +- Fixed a bug where chunked upload was not populating the correct part size for upload part. + +## [2.32.0] (2019-04-25) +- Added support [setting metadata](https://github.com/box/box-java-sdk/blob/main/doc/folders.md#set-metadata). + +## [2.31.0] (2019-04-11) + +- Added support for [sorting folder items](https://github.com/box/box-java-sdk/blob/main/doc/folders.md#get-a-folders-items) retrieved from a folder by ascending or descending order. + +## [2.30.1] (2019-04-08) + +- Fixed a bug where the SDK could throw when parsing JSON containing dates using the Zulu timezone format + +## [2.30.0] (2019-04-04) +- Added `action_by` field to enterprise events stream. + +## [2.29.0] (2019-04-01) +- Added support for [sorting results returned from Box Search](https://github.com/box/box-java-sdk/blob/main/doc/search.md#search-1) +- Added ability to [attach a file description upon file upload](https://github.com/box/box-java-sdk/blob/main/doc/files.md#upload-a-file) + +## [2.28.1] (2019-03-07) +- Fixed a bug where BoxMetadataCascadePolicy.forceApply() would not return correctly. + +## [2.28.0] (2019-02-21) +- Added ability for user to [retrieve an avatar](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getAvatar--)) for a specified user. + +## [2.27.0] (2019-01-31) +- Added support for Metadata Classification for [File](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#setClassification-java.lang.String...-) and [Folder](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#setClassification-java.lang.String...-) + +## [2.26.0] (2019-01-17) +- Added [invite_email](https://github.com/box/box-java-sdk/blob/main/src/main/java/com/box/sdk/BoxCollaboration.java#L277) field to collaboration object. +- Added [is_collaboration_restricted_to_enterprise](https://github.com/box/box-java-sdk/blob/main/src/main/java/com/box/sdk/BoxFolder.java#L1104) field to folder object. +- Added [status](https://github.com/box/box-java-sdk/blob/main/src/main/java/com/box/sdk/BoxTaskAssignment.java#L196) field to task assignment object. +- Added ability to retrieve fields for [`BoxFile#getTasks()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getTasks-java.lang.String...-) +- Fixed bug where offset based paging would not return correctly. + +## [2.25.1] (2019-01-03) +- Upgraded dependencies: jose4j to v0.5.5, and bouncycastle to v1.60 + +## [2.25.0] (2018-12-13) +- Added functionality to allow [content streaming to Box through outputstream](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#uploadFile-com.box.UploadFileCallback-java.lang.String-). Thank you @gajarajkalburgi for the pr! + +## [2.24.0] (2018-11-16) +- Added `getOptionsObjects()` on `MetadataTemplate.Field` which returns both key and type. +- Added functionality for [`BoxItem#getType()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxItem.html#getType--) for BoxItem. +- Added functionality for [`BoxAPIConnection#BoxGlobalSettings()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html#setConnectTimeout-java.lang.String-) +and [`BoxAPIConnection#BoxGlobalSettings()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html#getConnectTimeout--) as well as getting and reading the timeout for the connection. +- Added functionality for [`BoxGlobalSettings#getMaxRequestAttempts()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGlobalSettings.html#getMaxRequestAttempts--) +and [`BoxGlobalSettings#setMaxRquestAttempts()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGlobalSettings.html#setMaxRequestAttempts-java.lang.Integer-) +- Fixed a bug where [`BoxLegalHoldPolicy#create()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#create-com.box.BoxAPIConnection-java.lang.String-) was not setting the correct legal hold policy duration. + +## [2.23.2] (2018-09-27) +- Fixed a bug where the specified headers for batch requests were not being sent. + +## [2.23.1] (2018-09-13) +- Fixed a bug where too many TCP connections were being opened. Thank you @pmatte1 for implementing this fix! + +## [2.23.0] (2018-08-23) +- Added support for [Metadata Cascade Policy](https://github.com/box/box-java-sdk/blob/main/doc/folders.md#create-cascade-policy-on-folder) + +## [2.22.0] (2018-08-09) +- Deprecated the [moveFolderToUser()](https://github.com/box/box-java-sdk/blob/main/src/main/java/com/box/sdk/BoxUser.java#L455) for Box Users. We encourage users to +use [transferContent](https://github.com/box/box-java-sdk/blob/main/src/main/java/com/box/sdk/BoxUser.java#L482) going forward because idiomatically it is more correct. + +## [2.21.0] (2018-07-05) +- Added functionality to allow users to [set passwords on shared links](https://github.com/box/box-java-sdk/pull/623) for Box files, folders, and web links. +- Fixed wrong redirect for two links in the `Getting Started` and `Quick Test` section of the README. + +## [2.20.2] (2018-06-28) +- Fixed a bug where customers had issues with large file uploads because they fail to parse the Retry-After header from the +commit response. Reason being headers storage/lookup was case sensitive. + +## [2.20.1] (2018-06-04) +- Added better exception handling for JSON parse in response exception. +- Fixed a bug where uploadNewVersion() was returning an empty object. + +## [2.20.0] (2018-05-24) +- Fixed a bug where multiple As-User headers could be set. +- Added support to [test update](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/Metadata.html#test-java.lang.String-java.util.List-) for multiselect field on metadata + +## [2.19.0] (2018-05-10) +- Added support for enterprise admins with Box Zones purchased to have support for [Box Storage Policies and Box Storage Policy Assignments](./doc/storage_policy) +- Added support to allow users to work with [multiselect metadata](./doc/files.md#get-metadata) +- Added `getLogin()` method for the "login" field on the "accessible by" for BoxCollaboration.Info class. + + +## [2.18.0] (2018-04-30) +- Fixed a bug where the the private key password should be passed into `setPrivateKetPassword()` instead of the private key. A big thank you to [breach10ck](https://github.com/breach10ck) +for their pull request! +- Added an additional check to ensure that the [request properties on the request object is not null in the `toString()` method](https://github.com/box/box-java-sdk/pull/595) +- Added support to [fetch the content of the generated representation](./doc/files.md#get-representation-content) after it has been generated +- Improved error messages for API response errors to allow for better debugging. + +## [2.17.0] (2018-04-10) +- Added support for assigning [Retention Policies to Metadata Templates](./doc/retention_policies.md#create-retention-policy-assignment) + +## [2.16.1] (2018-03-29) + +- Added `CONTENT_ACCESS` to event type enum + +## [2.16.0] (2018-03-22) +- Added support for [user tracking codes](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.Info.html#getTrackingCodes--) on the user object. +- Fixed a bug where JWT authentication would fail due to improper date parsing. +- Added support for setting custom headers on API connection. This allow for setting [As-User support](./doc/overview.md#as-user) +and [suppressing notifications](./doc/overview.md/suppressing-notifications) support. +- Changed default JWT expiration window to reduce chances of error. + +## [2.15.0] (2018-03-12) +- Added support for retrieving a [metadata template by ID](./doc/metadata_template.md#get-by-id) +- Added support for allowing the user to [retrieve specific Collaboration fields on a Collaboration object](./doc/collaborations.md#get-a-collaborations-information) + +## [2.14.1] (2018-03-01) + +- Reduced the number of API calls that the `EventStream` makes to fetch new events, which should +help users who are running into rate limit issues. +- Force support for TLSv1.1 or higher when available to improve the security of connections to the Box API +- Add randomized jitter to the exponential backoff algorithm used by the SDK to improve the success rate +of retried requests. + +## [2.14.0] (2018-02-15) + +- Added support for getting and setting the `can_view_path` field on a collaboration object. +- Added support for getting and setting the `tags` field on files and folders. + +## [2.13.0] (2018-02-07) + +- Fixed an issue where all types of metadata values were being coerced to Strings. This change deprecates +`Metadata#get()` in favor of type-specific methods like `Metadata#getFloat()` or a generic `Metadata#getValue()`, +which returns a `JsonValue` object that represents any JSON type. See the [file metadata](./doc/files.md#get-metadata) +or [folder metadata](./doc/folders.md#get-metadata) documentation for more information. + +## [2.12.0] (2018-02-01) + +- Fixed ability to notify users or groups regarding [file collaboration](https://github.com/box/box-java-sdk/blob/main/doc/files.md#share-a-file) or [folder collaboration](https://github.com/box/box-java-sdk/blob/main/doc/folders.md#share-a-folder) +- Added [OAuth2 token creation event types](https://github.com/box/box-java-sdk/blob/main/src/main/java/com/box/sdk/BoxEvent.java#L747) +- Added support for [inviting a user to another Box Enterprise](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxInvite.html) +- Fixed an [OutOfMemory error in large file upload by capping the maximum number of parts that are uploaded concurrently](https://github.com/box/box-java-sdk/pull/543) + + +## [2.11.0] (2018-01-25) + +- [uploadLargeFile now returns a BoxFile object](https://github.com/box/box-java-sdk/pull/524) +- [Fixed chunked upload for Box Files greater than 2GB](https://github.com/box/box-java-sdk/pull/531) +- [Perform modified retry on JWT auth for when the local clock and the Box Server clock are not aligned as well as if the JWT ID has already been consumed](https://github.com/box/box-java-sdk/pull/523) +- BoxFolder.search has been deprecated in favor of [BoxSearch.searchRange](https://github.com/box/box-java-sdk/blob/86b82f2be3c57e3b89ae150b5f237d410e2d4900/doc/search.md) + +## [2.10.0] (2018-01-11) + +- [Add optional is_confirmed paramater for adding user email alias](https://github.com/box/box-java-sdk/pull/499) +- Added support for [Metadata Template Delete](./doc/metadata_template#delete-a-metadata-template) + +## [2.9.0] (2018-01-04) + +- Added option to pass file [SHA-1 hash for upload integrity](https://github.com/box/box-java-sdk/blob/main/doc/files.md#upload-a-file) +- Added support for [Terms of Service](./doc/terms_of_service) endpoint +- Fixed missing [webhook triggers](https://github.com/box/box-java-sdk/pull/497) +- Fixed missing [event types for events enum](https://github.com/box/box-java-sdk/pull/500) +- Added [modified_at timestamp to BoxComment.Info](https://github.com/box/box-java-sdk/pull/499) +- Added support for [Collaboration Whitelists](./doc/collaboration_whitelists) endpoint + +## [2.8.2] (2017-10-05) + +- Added additional check for `PrivateKeyInfo` in `BoxDeveloperEditionApiConnection` + +## [2.8.1] (2017-10-05) + +- Added ability to [set connect and read timeout globally](https://github.com/box/box-java-sdk/pull/459) + +## [2.8.0] (2017-09-07) + +- Added method for getting file representations +- Changes to Representation object + +## [2.7.0] (2017-08-30) + +- Added support for [Representations](https://github.com/box/box-java-sdk/blob/main/src/main/java/com/box/sdk/BoxFile.java#L445) endpoint + +## [2.6.0] (2017-08-28) + +- Added support for [Batch](https://github.com/box/box-java-sdk/blob/575861fad0b3e67d432b5d5955d1e760b3f6444e/README.md#batchrequestexample) +- Added support for [Unified Metadata](./doc/folders#get-metadata-using-unified-metadata-api) + +## [2.5.0] (2017-07-28) + +- Added support for [Recent Items](https://github.com/box/box-java-sdk/blob/main/src/main/java/com/box/sdk/BoxRecents.java#L1) endpoint +- Added support [Get All Groups By Name](https://github.com/box/box-java-sdk/blob/a1833950c18139fd9cbb4d8ee61d310c7bbedadf/src/main/java/com/box/sdk/BoxGroup.java#L143) endpoint +- Added support for [Token Exchange](https://github.com/box/box-java-sdk/blob/main/src/main/java/com/box/sdk/BoxAPIConnection.java#L634) + +## [2.4.0] (2017-05-02) + +- Support for multiput upload. New methods in BoxFolder and BoxFile support multiput upload for better performance and reliability for large files. +- Single file collaborations. The BoxFile class now supports sharing individual files. +- Automatic configuration for JWT auth. The Box Developer console now lets you download a JSON file of your JWT app configuration settings. You can import this file into the Java SDK to easily configure your app. + +## [2.3.0] (2017-01-12) + +New API Endpoints: + +[Legal Holds](https://github.com/box/box-java-sdk/blob/main/doc/legal_holds.md) +[Retention Policies](https://github.com/box/box-java-sdk/blob/main/doc/retention_policies.md) +[Create Metadata Template](https://github.com/box/box-java-sdk/blob/main/doc/metadata_template.md#create-metadata-template) +[Get All Metadata on File](https://github.com/box/box-java-sdk/blob/main/doc/files.md#get-all-metadata-on-file) +[Get All Metadata on Folder](https://github.com/box/box-java-sdk/blob/main/doc/folders.md#get-all-metadata-on-folder) +[Get Enterprise Metadata Templates](https://github.com/box/box-java-sdk/blob/main/doc/metadata_template.md#get-enterprise-metadata-templates) +[Update Group](https://github.com/box/box-java-sdk/blob/main/doc/groups.md#update-a-group) +[Watermarking](https://github.com/box/box-java-sdk/blob/main/doc/watermarking.md) +[Webhooks V2](https://github.com/box/box-java-sdk/blob/main/doc/webhooks.md) +[WebLinks](https://github.com/box/box-java-sdk/blob/main/doc/weblinks.md) +[Collections](https://github.com/box/box-java-sdk/blob/main/doc/collections.md) +[BoxGroupMembership with for Paging](https://github.com/box/box-java-sdk/blob/main/doc/groups.md) +[Enterprise Device Pins](https://github.com/box/box-java-sdk/blob/86b82f2be3c57e3b89ae150b5f237d410e2d4900/doc/devices.md) + +New Features: + +Transactional Authentication. Support for Box's new Transactional Auth APIs. +Upload file versions with SHA1. A file's SHA1 can be passed in to BoxFile.uploadVersion(...) when uploading new versions. +Get effective_access for shared links. The effective_access field is accessible through BoxSharedLink. getEffectiveAccess(). +Added additional Event Types. The TASK_ASSIGNMENT_COMPLETE, TASK_ASSIGNMENT_UPDATE, TASK_CREATE, COMMENT_DELETE types are now included in the BoxEvent class. + +## [2.1.0] (2016-02-22) + +This release includes improvements to token caching for App Users and support for additional API endpoints. + +New Features: + + - App Users token caching. A token cache can now be specified in BoxDeveloperEditionAPIConnection. This allows for improved performance when using App Users authentication. + - Support for retrieving download URLs. The BoxFile.getDownloadURL() method allows for retrieving a direct download URL to a file. + - File thumbnails. The BoxFile.getThumbnail() method allows for downloading the [Thumbnail](https://github.com/box/box-java-sdk/blob/main/doc/files.md#get-thumbnail) for a file. + +Bug Fixes: + + - Getting info for a file could crash when there's no preview. Previously, an exception would be thrown if BoxFile.getInfo (BoxFile.ALL_FIELDS) was called and the file didn't have a preview available. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index fc1d7822f..e12872653 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,108 +1,20 @@ -Contributing -============ +# Contributing All contributions are welcome to this project. -Contributor License Agreement ------------------------------ +## Contributor License Agreement -Before a contribution can be merged into this project, please fill out the -Contributor License Agreement (CLA) located at: +Before a contribution can be merged into this project, please fill out the Contributor License Agreement (CLA) located at: http://opensource.box.com/cla -To learn more about CLAs and why they are important to open source projects, -please see the [Wikipedia entry][1]. +To learn more about CLAs and why they are important to open source projects, please see the [Wikipedia entry](http://en.wikipedia.org/wiki/Contributor_License_Agreement). -How to contribute ------------------ +## Code of Conduct -* **File an issue** - if you found a bug, want to request an enhancement, or - want to implement something (bug fix or feature). -* **Send a pull request** - if you want to contribute code. Please be sure to - file an issue first. +This project adheres to the [Box Open Code of Conduct](http://opensource.box.com/code-of-conduct/). By participating, you are expected to uphold this code. -Pull request best practices ---------------------------- +## How to contribute -Following these steps will help ensure that your pull request gets reviewed and -accepted as quickly as possible. - -### Step 1: File an issue - -Before writing any code, please file an issue stating the problem you want to -solve or the feature you want to implement. This allows us to give you feedback -before you spend any time writing code. There may be a known limitation that -can't be addressed, or a bug that has already been fixed in a different way. The -issue allows us to communicate and figure out if it's worth your time to write a -bunch of code for the project. - -### Step 2: Fork this repository in GitHub - -This will create your own copy of our repository. - -### Step 3: Add the upstream source - -The upstream source is the project under the Box organization on GitHub. To add -an upstream source for this project, type: - -``` -git remote add upstream git@github.com:box/box-java-sdk.git -``` - -This will come in useful later. - -### Step 4: Create a feature branch - -Create a branch with a descriptive name, such as `add-search`. - -### Step 5: Push your feature branch to your fork - -As you develop code, continue to push code to your remote feature branch. Please -make sure to include the issue number you're addressing in the body of your -commit message and adhere to [standard git commit message guidelines][2]. For -example: - -``` -Add search - -Introduced a new BoxSearch class that uses the /search API endpoint. - -Closes #123. -``` - -This helps us out by allowing us to track which issue your commit relates to. - -Keep a separate feature branch for each issue you want to address. - -### Step 6: Rebase - -Before sending a pull request, rebase against upstream, such as: - -``` -git fetch upstream -git rebase upstream/master -``` - -This will add your changes on top of what's already in upstream, minimizing -merge issues. - -### Step 7: Build and test your changes - -Make sure that the code builds and passes all unit tests by running: - -```bash -$ gradle clean build -``` - -### Step 8: Send the pull request - -Send the pull request from your feature branch to us. Be sure to include a -description in your commit message (not the pull request description) that lets -us know what work you did. - -Keep in mind that we like to see one issue addressed per pull request, as this -helps keep our git history clean and we can more easily track down issues. - -[1]: http://en.wikipedia.org/wiki/Contributor_License_Agreement -[2]: http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html +- **File an issue** - if you found a bug, want to request an enhancement, or want to implement something (bug fix or feature). +- **Send a pull request** - this project is generated using [Box Codegen](https://github.com/box/box-codegen) based on[Box OpenAPI 3.0 Specification](https://github.com/box/box-openapi), so if you want found something you want to change in the generated code, you'll need to modify the codegen project and submit a pull request there. diff --git a/README.md b/README.md index 29523a2b0..123549c76 100644 --- a/README.md +++ b/README.md @@ -1,113 +1,307 @@ +

+ “box-dev-logo” +

+ +# Box Java SDK v10 + [![Project Status](http://opensource.box.com/badges/active.svg)](http://opensource.box.com/badges) +![build](https://github.com/box/box-java-sdk/actions/workflows/build.yml/badge.svg?branch=main) +![Maven Central Version](https://img.shields.io/maven-central/v/com.box/box-java-sdk) +![Platform](https://img.shields.io/badge/java-%3E%3D8-blue) +[![Coverage](https://coveralls.io/repos/github/box/box-java-sdk/badge.svg?branch=main)](https://coveralls.io/github/box/box-java-sdk-gen?branch=main) + + + + +- [Introduction](#introduction) +- [Supported versions](#supported-versions) + - [Version v5](#version-v5) + - [Version v10](#version-v10) + - [Which Version Should I Use?](#which-version-should-i-use) +- [Installing](#installing) +- [Getting Started](#getting-started) +- [Authentication](#authentication) +- [Documentation](#documentation) +- [Migration guides](#migration-guides) +- [Versioning](#versioning) + - [Version schedule](#version-schedule) +- [Contributing](#contributing) +- [3rd Party Libraries & Licenses](#3rd-party-libraries--licenses) +- [FIPS 140-2 Compliance](#fips-140-2-compliance) +- [Questions, Bugs, and Feature Requests?](#questions-bugs-and-feature-requests) +- [Copyright and License](#copyright-and-license) + + + +# Introduction + +We are excited to introduce the v10 major release of the Box Java SDK, +designed to elevate the developer experience and streamline your integration with the Box Content Cloud. + +With this SDK version, we provide the `com.box.sdkgen` package, which gives you access to: + +1. Full API Support: The new generation of Box SDKs empowers developers with complete coverage of the Box API ecosystem. You can now access all the latest features and functionalities offered by Box, allowing you to build even more sophisticated and feature-rich applications. +2. Rapid API Updates: Say goodbye to waiting for new Box APIs to be incorporated into the SDK. With our new auto-generation development approach, we can now add new Box APIs to the SDK at a much faster pace (in a matter of days). This means you can leverage the most up-to-date features in your applications without delay. +3. Embedded Documentation: We understand that easy access to information is crucial for developers. With our new approach, we have included comprehensive documentation for all objects and parameters directly in the source code of the SDK. This means you no longer need to look up this information on the developer portal, saving you time and streamlining your development process. +4. Enhanced Convenience Methods: Our commitment to enhancing your development experience continues with the introduction of convenience methods. These methods cover various aspects such as chunk uploads, classification, and much more. +5. Seamless Start: The new SDKs integrate essential functionalities like authentication, automatic retries with exponential backoff, exception handling, request cancellation, and type checking, enabling you to focus solely on your application's business logic. + +Embrace the new generation of Box SDKs and unlock the full potential of the Box Content Cloud. + +# Supported versions + +To enhance developer experience, we have introduced the new generated codebase through the `com.box.sdkgen` package. +The `com.box.sdkgen` package is available in two major supported versions: v5 and v10. + +## Version v5 + +In v5 of the Box Java SDK, we are introducing a version that consolidates both the manually written package (`com.box.sdk`) +and the new generated package (`com.box.sdkgen`). This allows developers to use both packages simultaneously within a single project. + +The codebase for v5 of the Box Java SDK is currently available on the [combined-sdk](https://github.com/box/box-java-sdk/tree/combined-sdk) branch. +Migration guide which would help with migration from `com.box.sdk` to `com.box.sdkgen` can be found [here](./migration-guides/from-com-box-sdk-to-com-box-sdkgen.md). -Box Java SDK -============ +Version v5 is intended for: -**This SDK is currently in beta and is subject to change.** +- Existing developers of the Box Java SDK v4 who want to access new API features while keeping their current codebase largely unchanged. +- Existing developers who are in the process of migrating to `com.box.sdkgen`, but do not want to move all their code to the new package immediately. + +## Version v10 + +Starting with v10, the SDK is built entirely on the generated `com.box.sdkgen` package, which fully and exclusively replaces the old `com.box.sdk` package. +The codebase for v10 of the Box Java SDK is currently available on the [main](https://github.com/box/box-java-sdk/tree/main) branch. + +Version v10 is intended for: + +- New users of the Box Java SDK. +- Developers already working with the generated Box Java SDK previously available under the [Box Java SDK Gen repository](https://github.com/box/box-java-sdk-gen). + +## Which Version Should I Use? + +| Scenario | Recommended Version | Example gradle dependency | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------- | ----------------------------- | +| Creating a new application | Use [v10](https://github.com/box/box-java-sdk/tree/main) | `com.box:box-java-sdk:10.0.0` | +| App using [box-java-sdk-gen](https://central.sonatype.com/artifact/com.box/box-java-sdk-gen) artifact | Migrate to [v10](https://github.com/box/box-java-sdk/tree/main) | `com.box:box-java-sdk:10.0.0` | +| App using both [box-java-sdk-gen](https://central.sonatype.com/artifact/com.box/box-java-sdk-gen) and [box-java-sdk](https://central.sonatype.com/artifact/com.box/box-java-sdk) artifacts | Upgrade to [v5](https://github.com/box/box-java-sdk/tree/combined-sdk) | `com.box:box-java-sdk:5.0.0` | +| App using v4 of [box-java-sdk](https://central.sonatype.com/artifact/com.box/box-java-sdk) artifact | Upgrade to [v5](https://github.com/box/box-java-sdk/tree/combined-sdk) | `com.box:box-java-sdk:5.0.0` | + +For full guidance on SDK versioning, see the [Box SDK Versioning Guide](https://developer.box.com/guides/tooling/sdks/sdk-versioning/). + +# Installing + +The SDK is available on [Maven Central Repository](https://mvnrepository.com/artifact/com.box/box-java-sdk). To include the SDK in your project, add the following dependency to your `pom.xml` file: + +```xml + + com.box + box-java-sdk + VERSION + +``` + +To include the SDK in your project using Gradle, add the following dependency to your `build.gradle` file: + +```gradle +implementation 'com.box:box-java-sdk:VERSION' +``` -This is the beta for the next major version of the Box Java SDK. The [previous -version](https://github.com/box/box-java-sdk-v2) will be deprecated after this -new version is released. +Where `VERSION` is the version of the SDK you want to use. The next generation of the SDK starts with version `10.0.0`. +You can find the latest version in the [Maven Central Repository](https://mvnrepository.com/artifact/com.box/box-java-sdk). -Quickstart ----------- +# Getting Started -The SDK can be obtained by adding it as a [maven dependency] -(http://opensource.box.com/box-java-sdk/), cloning the source into your project, -or by downloading one of the precompiled JARs from the [releases page on GitHub] -(https://gitenterprise.inside-box.net/Box/box-java-sdk/releases). +To get started with the SDK, get a Developer Token from the Configuration page of your app in the [Box Developer +Console](https://app.box.com/developers/console). You can use this token to make test calls for your own Box account. -If you use the JAR, you'll also need to include [minimal-json v0.9.1] -(https://github.com/ralfstx/minimal-json) - which is the SDK's only dependency. -You can get minimal-json from maven with `com.eclipsesource.minimal-json:minimal-json:0.9.1`. +The SDK provides an `BoxDeveloperTokenAuth` class, which allows you to authenticate using your Developer Token. +Use instance of `BoxDeveloperTokenAuth` to initialize `BoxClient` object. +Using `BoxClient` object you can access managers, which allow you to perform some operations on your Box account. -Here is a simple example of how to authenticate with the API using a developer -token and then print the ID and name of each item in your root folder. +The example below demonstrates how to authenticate with Developer Token and print names of all items inside a root folder. ```java -BoxAPIConnection api = new BoxAPIConnection("developer-token"); -BoxFolder rootFolder = BoxFolder.getRootFolder(api); -for (BoxItem.Info itemInfo : rootFolder) { - System.out.format("[%d] %s\n", itemInfo.getID(), itemInfo.getName()); -} +BoxDeveloperTokenAuth auth = new BoxDeveloperTokenAuth("DEVELOPER_TOKEN"); +BoxClient client = new BoxClient(auth); +client.folders.getFolderItems("0").getEntries().forEach(item -> { + System.out.println(item.toString()); +}); ``` -For more details on how to get started, check out the [overview -guide](doc/overview.md). It has a short explanation of how the SDK works and how -you can get started using it. +# Authentication + +Box Java SDK v10 supports multiple authentication methods including Developer Token, OAuth 2.0, +Client Credentials Grant, and JSON Web Token (JWT). + +You can find detailed instructions and example code for each authentication method in +[Authentication](./docs/authentication.md) document. + +# Documentation + +Browse the [docs](docs/README.md) or see [API Reference](https://developer.box.com/reference/) for more information. + +# Migration guides + +Migration guides which help you to migrate to supported major SDK versions can be found [here](./migration-guides). + +# Versioning + +We use a modified version of [Semantic Versioning](https://semver.org/) for all changes. See [version strategy](VERSIONS.md) for details which is effective from 30 July 2022. + +A current release is on the leading edge of our SDK development, and is intended for customers who are in active development and want the latest and greatest features. +Instead of stating a release date for a new feature, we set a fixed minor or patch release cadence of maximum 2-3 months (while we may release more often). +At the same time, there is no schedule for major or breaking release. Instead, we will communicate one quarter in advance the upcoming breaking change to allow customers to plan for the upgrade. + +We always recommend that all users run the latest available minor release for whatever major version is in use. +We highly recommend upgrading to the latest SDK major release at the earliest convenient time and before the EOL date. + +## Version schedule + +| Version | Supported Environments | State | First Release | EOL/Terminated | +| ------- | ---------------------- | --------- | ------------- | ---------------------- | +| 10 | Java 8 and up | Supported | 17 Sep 2025 | TBD | +| 5 | Java 8 and up | Supported | 23 Oct 2025 | 2027 or v6 is released | +| 4 | Java 8 and up | EOL | 17 Jan 2023 | 23 Oct 2025 | +| 3 | Java 8 and up | EOL | 17 Jan 2022 | 17 Jan 2023 | +| 2 | | EOL | 07 Jan 2016 | 17 Jan 2022 | +| 1 | | EOL | 15 Apr 2015 | 07 Jan 2016 | + +# Contributing -### Sample Project +See [CONTRIBUTING.md](./CONTRIBUTING.md). -A sample project can be found in `src/example`. This project will output your -name and a list of the files and folders in your root directory. +# 3rd Party Libraries & Licenses -To run the project, first provide a developer token in -`src/example/java/com/box/sdk/example/Main.java`. You can obtain a developer -token from your application's [developer -console](https://cloud.app.box.com/developers/services). +The Java SDK uses third-party libraries that are required for usage. Their licenses are listed below: + +1. [jackson-annotations v2.21](https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations/2.21) + Maven: `com.fasterxml.jackson.core:jackson-annotations:2.21` + Licence: [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0) +2. [jackson-core v2.21.4](https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core/2.21.4) + Maven: `com.fasterxml.jackson.core:jackson-core:2.21.4` + Licence: [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0) +3. [jackson-databind v2.21.4](https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind/2.21.4) + Maven: `com.fasterxml.jackson.core:jackson-databind:2.21.4` + Licence: [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0) +4. [okhttp v4.12.0](https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp/4.12.0) + Maven: `com.squareup.okhttp3:okhttp:4.12.0` + Licence: [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0) +5. [okio v3.5.0](https://mvnrepository.com/artifact/com.squareup.okio/okio/3.5.0) + Maven: `com.squareup.okio:okio:3.5.0` + Licence: [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0) +6. [jose4j v0.9.6](https://mvnrepository.com/artifact/org.bitbucket.b_c/jose4j/0.9.6) + Maven: `org.bitbucket.b_c:jose4j:0.9.6` + Licence: [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0) +7. [bcprov-jdk18on v1.84](https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk18on/1.84) + Maven: `org.bouncycastle:bcprov-jdk18on:1.84` + Licence: [MIT](https://opensource.org/licenses/MIT) +8. [bcpkix-jdk18on v1.84](https://mvnrepository.com/artifact/org.bouncycastle/bcpkix-jdk18on/1.84) + Maven: `org.bouncycastle:bcpkix-jdk18on:1.84` + Licence: [MIT](https://opensource.org/licenses/MIT) + +The following libraries are required for running tests: + +1. [junit-jupiter-api v5.10.0](https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api/5.10.0) + Maven: `org.junit.jupiter:junit-jupiter-api:5.10.0` + Licence: [EPL 2.0](https://www.eclipse.org/legal/epl-2.0/) +2. [junit-jupiter-engine v5.10.0](https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-engine/5.10.0) + Maven: `org.junit.jupiter:junit-jupiter-engine:5.10.0` + Licence: [EPL 2.0](https://www.eclipse.org/legal/epl-2.0/) + +# FIPS 140-2 Compliance + +To generate a Json Web Signature used for retrieving tokens in the JWT authentication method, the Box Java SDK decrypts an encrypted private key. +For this purpose, Box Java SDK uses libraries (`org.bouncycastle:bcpkix-jdk18on:1.84` and `org.bouncycastle:bcprov-jdk18on:1.84`) +that are NOT compatible with FIPS 140-2 validated cryptographic library (`org.bouncycastle:bc-fips`). + +There are two ways of ensuring that decryption operation is FIPS-compiant. + +1. You can provide a custom implementation of the `IPrivateKeyDecryptor` interface, + which performs the decryption operation using FIPS-certified library of your choice. + The interface requires the implementation of just one method: ```java -public final class Main { - private static final String DEVELOPER_TOKEN = ""; +PrivateKey decryptPrivateKey(String encryptedPrivateKey, String passphrase); +``` - // ... -} +After implementing the custom decryptor, you need to set your custom decryptor class: + +```java +JWTConfig newConfig = JWTConfig.fromConfigFile(JWT_CONFIG_PATH, customDecryptor); +BoxJWTAuth auth = new BoxJWTAuth(jwtConfig); +BoxClient client = new BoxClient(auth); ``` -Then just invoke `gradle runExample` to run the example! +2. Alternative method is to override the Bouncy Castle libraries to the v.1.57 version, + which are compatible with the FIPS 140-2 validated cryptographic library (`org.bouncycastle:bc-fips`). -Building --------- +NOTE: This solution is not recommended as Bouncy Castle v.1.57 has some moderate vulnerabilities reported against those versions, including: -The SDK uses Gradle for its build system. Running `gradle build` from the root -of the repository will compile, lint, and test the SDK. +- [CVE-2020-26939](https://github.com/advisories/GHSA-72m5-fvvv-55m6) - Observable Differences in Behavior to Error Inputs in Bouncy Castle +- [CVE-2020-15522](https://github.com/advisories/GHSA-6xx3-rg99-gc3p) - Timing based private key exposure in Bouncy Castle -```bash -$ gradle build -``` +Furthermore,using Bouncy Castle v.1.57 may lead to [Bouncycastle BadPaddingException for JWT auth](#bouncycastle-badPaddingException-for-jWT-auth). -The SDK also includes integration tests which make real API calls, and therefore -are run separately from unit tests. Integration tests should be run against a -test account since they create and delete data. To run the integration tests, -remove the `.template` extension from -`src/test/config/config.properties.template` and fill in your test account's -information. Then run: +Gradle example -```bash -$ gradle integrationTest +```groovy +implementation('com.box:box-java-sdk:x.y.z') { + exclude group: 'org.bouncycastle', module: 'bcprov-jdk18on' + exclude group: 'org.bouncycastle', module: 'bcpkix-jdk18on' +} +runtimeOnly('org.bouncycastle:bcprov-jdk15on:1.57') +runtimeOnly('org.bouncycastle:bcpkix-jdk15on:1.57') ``` -Documentation -------------- +Maven example: -You can find guides and tutorials in the `doc` directory. +```xml + + + com.box + box-java-sdk + x.y.z + compile + + + org.bouncycastle + bcprov-jdk18on + + + org.bouncycastle + bcpkix-jdk18on + + + + + org.bouncycastle + bcprov-jdk15on + 1.57 + runtime + + + org.bouncycastle + bcpkix-jdk15on + 1.57 + runtime + + +``` -* [Javadocs](http://box.github.io/box-java-sdk/javadoc/com/box/sdk/package-summary.html) -* [Overview](doc/overview.md) -* [Authentication](doc/authentication.md) -* [Files](doc/files.md) -* [Folders](doc/folders.md) -* [Comments](doc/comments.md) -* [Collaborations](doc/collaborations.md) -* [Events](doc/events.md) -* [Search](doc/search.md) -* [Users](doc/users.md) -* [Groups](doc/groups.md) -* [Tasks](doc/tasks.md) +# Questions, Bugs, and Feature Requests? -Javadocs are generated when `gradle javadoc` is run and can be found in -`build/doc/javadoc`. +Need to contact us directly? [Browse the issues tickets](https://github.com/box/box-java-sdk/issues)! Or, if that +doesn't work, [file a new one](https://github.com/box/box-java-sdk/issues/new), and we will get +back to you. If you have general questions about the Box API, you can post to the [Box Developer Forum](https://community.box.com/box-platform-5). -Copyright and License ---------------------- +# Copyright and License -Copyright 2014 Box, Inc. All rights reserved. +Copyright 2025 Box, Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 +http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, diff --git a/VERSIONS.md b/VERSIONS.md new file mode 100644 index 000000000..45c972031 --- /dev/null +++ b/VERSIONS.md @@ -0,0 +1,24 @@ +# Version Lifecycle + +We use a modified version of [Semantic Versioning](https://semver.org/) for all changes. It is strongly encouraged that you pin at least the major version and potentially the minor version to avoid pulling in breaking changes. Increasing the major version of an SDK indicates that this SDK underwent significant and substantial changes to support new idioms and patterns in the language. Major versions are introduced when public interfaces (e.g. classes, methods, types, etc.), behaviours, or semantics have changed. + +Semantic Versions take the form of `MAJOR.MINOR.PATCH`. + +When bugs are fixed in the library in a backwards-compatible way, the PATCH level will be incremented by one. PATCH changes should not break your code and are generally safe for upgrade. + +When a new feature set comes online or a small breaking change is introduced, the MINOR version will be incremented by one and the PATCH version resets to zero. MINOR changes may require some amount of manual code change for upgrade. These backwards-incompatible changes will mostly be limited to a small number of function signature changes. + +The MAJOR version is used to indicate the family of technology represented by the library. Breaking changes that require extensive reworking of code will cause the MAJOR version to be incremented by one, and the MINOR and PATCH versions will be reset to zero. Since frequent major updates can be very disruptive, we will only introduce this type of breaking change when absolutely necessary. + +New MAJOR versions will be communicated in advance via: + +- An email announcement is sent to affected accounts, announcing our plans to end support for the specific SDK version. The email will outline the path to end-of-support, specify the campaign timelines, and provide upgrade guidance. +- Box SDK documentation, such as API reference documentation, user guides, SDK product marketing pages, and GitHub readme(s) are updated to indicate the campaign timeline and provide guidance on upgrading affected applications. +- Deprecation warnings are added to the SDKs, outlining the path to end-of-support and linking to the SDK documentation. + +Deprecations are introduced in minor releases. We will not introduce new deprecations in patch releases. These deprecations will preserve the existing behaviour while emitting a warning that provide guidance on: + +- How to achieve similar behaviour if an alternative is available +- The version in which the deprecation will be enforced. + +Deprecations will only be enforced in major releases. For example, if a behaviour is deprecated in version 1.2.0, it will continue to work, with a warning, for all releases in the 1.x series. The behaviour will change and the deprecation will be removed in the next major release (2.x.x). diff --git a/build.gradle b/build.gradle index 5b3de2594..576248aee 100644 --- a/build.gradle +++ b/build.gradle @@ -1,153 +1,154 @@ -apply plugin: 'checkstyle' -apply plugin: 'jacoco' -apply plugin: 'java' -apply plugin: 'maven' -apply plugin: 'signing' - -sourceCompatibility = 1.6 - -group = 'com.box' -archivesBaseName = 'box-java-sdk' -version = '0.7.0' - +plugins { + id "java" + id "com.diffplug.spotless" version "${spotlessVersion}" + id "maven-publish" + id "signing" + id "org.jreleaser" version "1.18.0" + id "com.github.nbaztec.coveralls-jacoco" version "${coverallsJacocoVersion}" + id "jacoco" + id "org.gradle.test-retry" version "${testRetryVersion}" +} +group = "com.box" +archivesBaseName = "box-java-sdk" +version = "10.16.0" +java { + sourceCompatibility = JavaVersion.toVersion(libraryJavaVersion) + targetCompatibility = JavaVersion.toVersion(libraryJavaVersion) + withSourcesJar() + withJavadocJar() +} repositories { - mavenCentral() + mavenCentral() } - dependencies { - compile 'com.eclipsesource.minimal-json:minimal-json:0.9.1' - testCompile 'junit:junit:4.11' - testCompile 'org.hamcrest:hamcrest-library:1.3' - testCompile 'com.github.tomakehurst:wiremock:1.52' - testCompile 'org.mockito:mockito-core:1.9.5' - testCompile 'org.slf4j:slf4j-api:1.7.7' - testCompile 'org.slf4j:slf4j-nop:1.7.7' + implementation "com.fasterxml.jackson.core:jackson-annotations:${jacksonAnnotationVersion}" + implementation "com.fasterxml.jackson.core:jackson-core:${jacksonCoreVersion}" + implementation "com.fasterxml.jackson.core:jackson-databind:${jacksonDatabindVersion}" + implementation "com.squareup.okhttp3:okhttp:${okhttpVersion}" + implementation "com.squareup.okio:okio:${okioVersion}" + implementation "org.bitbucket.b_c:jose4j:${jose4jVersion}" + implementation "org.bouncycastle:bcprov-jdk18on:${bouncyCastleBcprovJdk18onVersion}" + implementation "org.bouncycastle:bcpkix-jdk18on:${bouncyCastleBcpkixJdk18onVersion}" + testImplementation "org.junit.jupiter:junit-jupiter-api:${junitApiVersion}" + testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:${junitEngineVersion}" } +spotless { + java { + googleJavaFormat "${googleJavaFormatVersion}" + target "src/**/*.java" + } -javadoc { - options.windowTitle 'Box Java SDK' - options.noQualifiers 'all' - options.stylesheetFile file('doc/css/javadoc.css') - options.noTree true - options.noIndex true - options.noHelp true - options.noDeprecatedList true - options.noNavBar true - options.docEncoding 'utf-8' - options.charSet 'utf-8' - options.linkSource true - options.links 'https://docs.oracle.com/javase/8/docs/api/' } +test { + useJUnitPlatform() + retry { + maxRetries = 2 + failOnPassedAfterRetry = false + } + + testLogging { + events = ['passed', 'failed', 'skipped'] + showStandardStreams = true + } + + jacoco { + destinationFile = file("$buildDir/jacoco/test.exec") + } + + filter { + // Socket timeout + excludeTestsMatching 'com.box.sdkgen.transfer.TransferITest.testTransferUserContent' + } -sourceSets { - example { - java { - compileClasspath += main.output - runtimeClasspath += main.runtimeClasspath - } - } } +publishing { + publications { + boxJavaSdk(MavenPublication) { + from components.java + pom { + artifactId = project.getArchivesBaseName() + name = "Box Java SDK" + description = "Official Box Java SDK." + url = "https://opensource.box.com/box-java-sdk/" + packaging = "jar" + licenses { + license { + name = "The Apache License, Version 2.0" + url = "https://www.apache.org/licenses/LICENSE-2.0.txt" + } -task runExample(type: JavaExec, dependsOn: 'exampleClasses') { - classpath = sourceSets.example.runtimeClasspath - main = 'com.box.sdk.example.Main' -} + } -task javadocJar(type: Jar) { - classifier = 'javadoc' - from javadoc -} + developers { + developer { + id = "box" + name = "box" + email = "sdks@box.com" + } -task sourcesJar(type: Jar) { - classifier = 'sources' - from sourceSets.main.allSource -} + } -task integrationTest(type: Test) { - description 'Runs the integration tests.' - group 'Verification' + scm { + connection = "scm:git:https://github.com/box/box-java-sdk.git" + developerConnection = "scm:git:https://github.com/box/box-java-sdk.git" + url = "https://github.com/box/box-java-sdk" + } - useJUnit { - includeCategories 'com.box.sdk.IntegrationTest' - } -} + } -jacocoTestReport.dependsOn(integrationTest); + } -tasks.withType(JavaCompile) { - options.compilerArgs << '-Xlint:all' -} + } -tasks.withType(Test) { - testLogging { - exceptionFormat = 'full' + repositories { + maven { + url = layout.buildDirectory.dir('staging-deploy') } - jacoco { - append = true - destinationFile = file("$buildDir/jacoco/test.exec") - } + } - outputs.upToDateWhen { false } } - -artifacts { - archives sourcesJar, javadocJar +signing { + required { !version.endsWith("SNAPSHOT") && gradle.taskGraph.hasTask("publish") } + // we are switching to gpg-agent and not using Java-based implementation because of + // org.bouncycastle:bc-fips:1.0.2.1 libray preset in our Docker machines which is + // not compatible with Gradle implementation + useGpgCmd() + sign publishing.publications.boxJavaSdk } +def centralUsername = project.findProperty("centralUsername") +def centralPassword = project.findProperty("centralPassword") +jreleaser { + signing { + active = "NEVER" + } + + deploy { + maven { + mavenCentral { + sonatype { + active = "ALWAYS" + url = "https://central.sonatype.com/api/v1/publisher" + sign = false + stagingRepository('build/staging-deploy') + username = centralUsername + password = centralPassword + } + + } -test { - useJUnit { - excludeCategories 'com.box.sdk.IntegrationTest' } -} -signing { - required { !version.endsWith('SNAPSHOT') && gradle.taskGraph.hasTask('uploadArchives') } - sign configurations.archives + } + } +jacoco { + reportsDirectory = file("$buildDir/reports/jacoco") +} +jacocoTestReport { + reports { + xml.required = true + html.required = true + } -uploadArchives { - repositories { - mavenDeployer { - beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } - - if (project.hasProperty('ossrhUsername') && project.hasProperty('ossrhPassword')) { - repository(url: 'https://oss.sonatype.org/service/local/staging/deploy/maven2/') { - authentication(userName: ossrhUsername, password: ossrhPassword) - } - - snapshotRepository(url: 'https://oss.sonatype.org/content/repositories/snapshots/') { - authentication(userName: ossrhUsername, password: ossrhPassword) - } - } - - pom.project { - name 'Box Java SDK' - packaging 'jar' - description 'The Box SDK for Java.' - url 'http://opensource.box.com/box-java-sdk/' - - scm { - connection 'scm:git:https://github.com/box/box-java-sdk.git' - developerConnection 'scm:git:https://github.com/box/box-java-sdk.git' - url 'https://github.com/box/box-java-sdk' - } - - licenses { - license { - name 'The Apache License, Version 2.0' - url 'http://www.apache.org/licenses/LICENSE-2.0.txt' - } - } - - developers { - developer { - id 'gcurtis' - name 'Greg Curtis' - email 'gcurtis@box.com' - } - } - } - } - } } diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml deleted file mode 100755 index ecbcec2f3..000000000 --- a/config/checkstyle/checkstyle.xml +++ /dev/null @@ -1,197 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/config/checkstyle/suppressions.xml b/config/checkstyle/suppressions.xml deleted file mode 100644 index 3913785c9..000000000 --- a/config/checkstyle/suppressions.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - diff --git a/doc/authentication.md b/doc/authentication.md deleted file mode 100644 index e0bcbe168..000000000 --- a/doc/authentication.md +++ /dev/null @@ -1,71 +0,0 @@ -Authentication -============== - -The Box API uses OAuth2 for authentication, which can be difficult to implement. -The SDK makes it easier by providing classes that handle obtaining tokens and -automatically refreshing them. - -Ways to Authenticate --------------------- - -### Developer Tokens - -The fastest way to get started using the API is with developer tokens. 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](https://cloud.app.box.com/developers/services). - -The following example creates an API connection with a developer token: - -```java -BoxAPIConnection api = new BoxAPIConnection("YOUR-DEVELOPER-TOKEN"); -``` - -### Normal Authentication - -Using an auth code is the most common way of authenticating with the Box API. -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. - -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. - -```java -BoxAPIConnection api = new BoxAPIConnection("YOUR-CLIENT-ID", - "YOUR-CLIENT-SECRET", "YOUR-AUTH-CODE"); -``` - -### Manual Authentication - -In certain advanced scenarios, you may want to obtain an access and refresh -token yourself through manual calls to the API. In this case, you can create an -API connection with the tokens directly. - -```java -BoxAPIConnection api = new BoxAPIConnection("YOUR-CLIENT-ID", - "YOUR-CLIENT-SECRET", "YOUR-ACCESS-TOKEN", "YOUR-REFRESH-TOKEN"); -``` - -Auto-Refresh ------------- - -By default, a `BoxAPIConnection` will automatically refresh the access token if -it has expired. To disable auto-refresh, set the connection's auto-refresh -setting to false with [`setAutoRefresh(false)`][auto-refresh]. Keep in mind that -you will have to manually refresh the access token yourself. - -```java -// This connection won't auto-refresh. -BoxAPIConnection api = new BoxAPIConnection("YOUR-CLIENT-ID", - "YOUR-CLIENT-SECRET", "YOUR-ACCESS-TOKEN", "YOUR-REFRESH-TOKEN"); -api.setAutoRefresh(false); - -// If the access token expires, you will have to manually refresh it. -api.refresh(); -``` - -[auto-refresh]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html#setAutoRefresh(boolean) diff --git a/doc/collaborations.md b/doc/collaborations.md deleted file mode 100644 index c1e526ef9..000000000 --- a/doc/collaborations.md +++ /dev/null @@ -1,106 +0,0 @@ -Collaborations -============== - -Collaborations are used to share folders between users or groups. They also -define what permissions a user has for a folder. - -* [Add a Collaboration](#add-a-collaboration) -* [Edit a Collaboration](#edit-a-collaboration) -* [Remove a Collaboration](#remove-a-collaboration) -* [Get a Collaboration's Information](#get-a-collaborations-information) -* [Get the Collaborations on a Folder](#get-the-collaborations-on-a-folder) -* [Get Pending Collaborations](#get-pending-collaborations) - -Add a Collaboration -------------------- - -A collaboration can be added for an existing user or group with -[`collaborate(BoxCollaborator, BoxCollaboration.Role)`][collaborate1]. The -`role` parameter determines what permissions the collaborator will have on the -folder. - -```java -BoxCollaborator user = new BoxUser(api, "user-id") -BoxFolder folder = new BoxFile(api, "folder-id"); -folder.collaborate(user, BoxCollaboration.Role.EDITOR); -``` - -You can also add a collaboration by providing an email address with -[`collaborate(String, BoxCollaboration.Role)`][collaborate2]. If the receipient -doesn't have a Box account, they will be asked create one. - -```java -BoxFolder folder = new BoxFile(api, "id"); -folder.collaborate("gcurtis@box.com", BoxCollaboration.Role.EDITOR); -``` - -[collaborate1]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#collaborate(com.box.sdk.BoxCollaborator,%20com.box.sdk.BoxCollaboration.Role) -[collaborate2]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#collaborate(java.lang.String,%20com.box.sdk.BoxCollaboration.Role) - -Edit a Collaboration --------------------- - -A collaboration can be edited by creating a new -[`BoxCollaboration.Info`][box-collaboration-info] object or updating an existing -one, and then calling [`updateInfo(BoxCollaboration.Info)`][update-info] - -```java -BoxCollaboration collaboration = new BoxCollaboration(api, "id"); -BoxCollaboration.Info info = collaboration.new Info(); -info.setStatus(BoxCollaboration.Status.ACCEPTED); -collaboration.updateInfo(info); -``` - -[box-collaboration-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaboration.Info.html -[update-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaboration.html#updateInfo(com.box.sdk.BoxCollaboration.Info) - -Remove a Collaboration ----------------------- - -A collaboration can be removed by calling [`delete()`][delete]. - -```java -BoxCollaboration collaboration = new BoxCollaboration(api, "id"); -collaboration.delete(); -``` - -[delete]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaboration.html#delete() - -Get a Collaboration's Information ---------------------------------- - -Calling [`getInfo()`][get-info] on a collaboration returns a snapshot of the -collaboration's info. - -```java -BoxCollaboration collaboration = new BoxCollaboration(api, "id"); -BoxCollaboration.Info info = collaboration.getInfo(); -``` - -[get-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaboration.html#getInfo() - -Get the Collaborations on a Folder ----------------------------------- - -You can get all of the collaborations on a folder by calling -[`getCollaborations()`][get-collaborations] on the folder. - -```java -BoxFolder folder = new BoxFile(api, "id"); -Collection collaborations = folder.getCollaborations(); -``` - -[get-collaborations]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getCollaborations() - -Get Pending Collaborations --------------------------- - -A collection of all the user's pending collaborations can be retrieved with -[`getPendingCollaborations(BoxAPIConnection)`][get-pending-collaborations]. - -```java -Collection pendingCollaborations = - BoxCollaboration.getPendingCollaborations(api); -``` - -[get-pending-collaborations]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaboration.html#getPendingCollaborations(com.box.sdk.BoxAPIConnection) diff --git a/doc/comments.md b/doc/comments.md deleted file mode 100644 index 9b1b4fe10..000000000 --- a/doc/comments.md +++ /dev/null @@ -1,99 +0,0 @@ -Comments -======== - -Comment objects represent a user-created comment on a file. They can be added -directly to a file or they can be a reply to another comment. - -* [Get a Comment's Information](#get-a-comments-information) -* [Get the Comments on a File](#get-the-comments-on-a-file) -* [Add a Comment to a File](#add-a-comment-to-a-file) -* [Reply to a Comment](#reply-to-a-comment) -* [Change a Comment's Message](#change-a-comments-message) -* [Delete a Comment](#delete-a-comment) - -Get a Comment's Information ---------------------------- - -Calling [`getInfo()`][get-info] on a comment returns a snapshot of the comment's -info. - -```java -BoxComment comment = new BoxComment(api, "id"); -BoxComment.Info info = comment.getInfo(); -``` - -[get-info]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxComment.html#getInfo() - -Get the Comments on a File --------------------------- - -You can get all of the comments on a file by calling the -[`getComments()`][get-comments] method. - -```java -BoxFile file = new BoxFile(api, "id"); -List comments = file.getComments(); -``` - -[get-comments]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getComments() - -Add a Comment to a File ------------------------ - -A comment can be added to a file with the [`addComment(String)`][add-comment] -method. - -```java -BoxFile file = new BoxFile(api, "id"); -file.addComment("This file is pretty cool."); -``` - -The comment's message can also 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. [See the documentation] -(https://developers.box.com/docs/#comments-comment-object) on the -`tagged_message` field for more information on @mentions. - -```java -BoxFile file = new BoxFile(api, "id"); -file.addComment("Message mentioning @[1234:user@box.com]."); -``` - -[add-comment]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#addComment(java.lang.String) - -Reply to a Comment ------------------- - -You can reply to a comment with the [`reply(String)`][reply] method. - -```java -BoxComment comment = new BoxComment(api, "id"); -comment.reply("A reply to another comment."); -``` - -[reply]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxComment.html#reply(java.lang.String) - -Change a Comment's Message --------------------------- - -The message of a comment can be changed with the -[`changeMessage(String)`][change-message] method. - -```java -BoxComment comment = new BoxComment(api, "id"); -comment.changeMessage("An edited message."); -``` - -[change-message]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxComment.html#changeMessage(java.lang.String) - -Delete a Comment ----------------- - -A comment can be deleted with the [`delete()`][delete] method. - -```java -BoxComment comment = new BoxComment(api, "id"); -comment.delete(); -``` - -[delete]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxComment.html#delete() diff --git a/doc/css/javadoc.css b/doc/css/javadoc.css deleted file mode 100644 index ad7887e4d..000000000 --- a/doc/css/javadoc.css +++ /dev/null @@ -1,488 +0,0 @@ -body { - color: #333; - font-family: 'Helvetica Neue', Calibri, sans-serif; - margin: 0; -} -hr { - display: none; -} -caption { - display: none; -} -a:link, -a:visited { - text-decoration: none; - color: rgb(26, 116, 186); -} -a:hover, -a:focus { - text-decoration: none; - color: rgb(22, 100, 160); -} -a:active { - text-decoration: none; - color: #4c6b87; -} -a[name] { - color: #353833; -} -a[name]:hover { - text-decoration: none; - color: #353833; -} -pre { - font-family: Menlo, Consolas, monospace; - font-size: 1em; -} -code { - font-family: Menlo, Consolas, monospace; - font-size: 1em; -} -h1 { - font-size: 2em; -} -h2 { - font-size: 1.7em; -} -h3 { - font-size: 1.5em; -} -h4 { - font-size: 1.2em; -} -h5 { - font-size: 1.1em; -} -h6 { - font-size: 1.1em; -} -ul { - list-style-type: disc; -} -table tr td dt code { - vertical-align: top; -} -sup { - font-size: .6em; -} -h3 a:link, -h3 a:visited { - text-decoration: none; - color: rgb(153, 153, 153); -} -h3 a:hover, -h3 a:focus { - text-decoration: none; - color: rgb(169, 169, 169); -} -tbody:first-of-type tr:nth-child(odd) { - background: #f3f3f3 -} -tbody:nth-of-type(2) tr:nth-child(even) { - background: #f3f3f3 -} -tbody:first-of-type tr:first-child { - font-size: 1.2em -} -.constantValuesContainer h2 { - margin: 0 0 0 .5882em; -} -.details { - margin: 1em; -} -.clear { - clear: both; - height: 0px; - overflow: hidden; -} -.aboutLanguage { - float: right; - padding: 0px 21px; - font-size: .8em; - z-index: 200; - margin-top: -7px; -} -.legalCopy { - margin-left: .5em; -} -.bar a, -.bar a:link, -.bar a:visited, -.bar a:active { - color: #FFFFFF; - text-decoration: none; -} -.bar a:hover, -.bar a:focus { - color: #bb7a2a; -} -.tab { - background-color: #0066FF; - background-image: url(resources/titlebar.gif); - background-position: left top; - background-repeat: no-repeat; - color: #ffffff; - padding: 8px; - width: 5em; - font-weight: bold; -} -.bar { - display: none; -} -ul.navList, -ul.subNavList { - float: left; - margin: 0 25px 0 0; - padding: 0; -} -ul.navList li { - list-style: none; - float: left; - padding: 3px 6px; -} -ul.subNavList li { - list-style: none; - float: left; - font-size: 90%; -} -.topNav a:link, -.topNav a:active, -.topNav a:visited, -.bottomNav a:link, -.bottomNav a:active, -.bottomNav a:visited { - color: rgb(153, 153, 153); - text-decoration: none; -} -.topNav a:hover, -.bottomNav a:hover { - text-decoration: none; - color: #fff; -} -.navBarCell1Rev { - font-weight: bold; -} -.header, -.footer { - clear: both; - margin: 1em; -} -.indexHeader { - margin: 10px; - position: relative; -} -.indexHeader h1 { - font-size: 1.3em; -} -.subTitle { - display: none; -} -.header ul { - margin: 0 0 25px 0; - padding: 0; -} -.footer ul { - margin: 20px 0 5px 0; -} -.header ul li, -.footer ul li { - list-style: none; - font-size: 1.2em; -} -.header .docSummary ~ p { - display: none; -} -ul.blockList ul.blockList ul.blockList li.blockList h3 { - background-color: rgb(64, 64, 64); - color: #fff; - font-size: 1.2em; - padding: .5em 1em .5em 1em; -} -ul.blockList ul.blockList li.blockList h3 { - display: none; -} -ul.blockList li.blockList h2 { - padding: 0px 0 20px 0; -} -div.summary ul.blockList li.blockList ul.blockList li.blockList ul.blockList code { - display: block; - margin: 1em; -} -div.summary ul.blockList li.blockList ul.blockList li.blockList ul.blockList li.blockList h3 { - display: block; -} -.contentContainer, -.sourceContainer, -.classUseContainer, -.serializedFormContainer, -.constantValuesContainer { - clear: both; - position: relative; -} -.indexContainer { - margin: 10px; - position: relative; - font-size: 1.0em; -} -.indexContainer h2 { - font-size: 1.1em; - padding: 0 0 3px 0; -} -.indexContainer ul { - margin: 0; - padding: 0; -} -.indexContainer ul li { - list-style: none; -} -.contentContainer .description dl dt, -.contentContainer .details dl dt, -.serializedFormContainer dl dt { - font-size: 1.1em; - font-weight: bold; - margin: 10px 0 0 0; - color: #4E4E4E; -} -.contentContainer .description dl dd, -.contentContainer .details dl dd, -.serializedFormContainer dl dd { - margin: 10px 0 10px 20px; -} -.serializedFormContainer dl.nameValue dt { - margin-left: 1px; - font-size: 1.1em; - display: inline; - font-weight: bold; -} -.serializedFormContainer dl.nameValue dd { - margin: 0 0 0 1px; - font-size: 1.1em; - display: inline; -} -ul.horizontal li { - display: inline; - font-size: 0.9em; -} -ul.inheritance { - margin-left: 1em; - padding: 0; -} -ul.inheritance li { - display: inline; - list-style: none; -} -ul.inheritance li ul.inheritance { - margin-left: 15px; - padding-left: 15px; - padding-top: 1px; -} -ul.blockList, -ul.blockListLast { - margin: 1em 0 1em 0; - padding: 0; -} -ul.blockList h4, -ul.blockListLast h4 { - background-color: rgb(64, 64, 64); - color: #fff; - margin: 0 -.8333em 0 -.8333em; - padding: .5em 1em .5em 1em; -} -ul.blockList li.blockList, -ul.blockListLast li.blockList { - list-style: none; - margin-bottom: 25px; -} -ul.blockList ul.blockList ul.blockList ul.blockList li.blockList { - margin-left: 0; - padding-left: 0; - padding-bottom: 15px; - border: none; - border-bottom: 1px solid #9eadc0; -} -ul.blockList ul.blockList ul.blockList ul.blockList li.blockListLast { - list-style: none; - border-bottom: none; - padding-bottom: 0; -} -table tr td dl, -table tr td dl dt, -table tr td dl dd { - margin-top: 0; - margin-bottom: 1px; -} -.contentContainer table, -.classUseContainer table, -.constantValuesContainer table { - width: 100%; -} -.contentContainer ul li table, -.classUseContainer ul li table, -.constantValuesContainer ul li table { - width: 100%; -} -.contentContainer .description table, -.contentContainer .details table { - border-bottom: none; -} -.contentContainer ul li table th.colOne, -.contentContainer ul li table th.colFirst, -.contentContainer ul li table th.colLast, -.classUseContainer ul li table th, -.constantValuesContainer ul li table th, -.contentContainer ul li table td.colOne, -.contentContainer ul li table td.colFirst, -.contentContainer ul li table td.colLast, -.classUseContainer ul li table td, -.constantValuesContainer ul li table td { - vertical-align: top; -} -a[name="package_description"] ~ * { - display: none; -} -.overviewSummary caption, -.packageSummary caption, -.contentContainer ul.blockList li.blockList caption, -.summary caption, -.classUseContainer caption, -.constantValuesContainer caption { - position: relative; - text-align: left; - background-repeat: no-repeat; - color: #FFFFFF; - font-weight: bold; - clear: none; - overflow: hidden; - padding: 0px; - margin: 0px; -} -caption a:link, -caption a:hover, -caption a:active, -caption a:visited { - color: #FFFFFF; -} -.overviewSummary caption span, -.packageSummary caption span, -.contentContainer ul.blockList li.blockList caption span, -.summary caption span, -.classUseContainer caption span, -.constantValuesContainer caption span { - white-space: nowrap; - padding-top: 8px; - padding-left: 8px; - display: block; - float: left; - background-image: url(resources/titlebar.gif); - height: 18px; -} -.overviewSummary .tabEnd, -.packageSummary .tabEnd, -.contentContainer ul.blockList li.blockList .tabEnd, -.summary .tabEnd, -.classUseContainer .tabEnd, -.constantValuesContainer .tabEnd { - width: 10px; - background-image: url(resources/titlebar_end.gif); - background-repeat: no-repeat; - background-position: top right; - position: relative; - float: left; -} -ul.blockList ul.blockList li.blockList table { - width: 100%; -} -.tableSubHeadingColor { - background-color: #EEEEFF; -} -.rowColor { - background-color: #ffffff; -} -.overviewSummary td, -.packageSummary td, -.contentContainer ul.blockList li.blockList td, -.summary td, -.classUseContainer td, -.constantValuesContainer td { - text-align: left; - padding: .5em 1em .5em 1em; -} -th.colFirst, -th.colLast, -th.colOne, -.constantValuesContainer th { - background: rgb(64, 64, 64); - color: #fff; - text-align: left; - padding: .5em 1em .5em 1em; -} -td.colOne a:link, -td.colOne a:active, -td.colOne a:visited, -td.colOne a:hover, -td.colFirst a:link, -td.colFirst a:active, -td.colFirst a:visited, -td.colFirst a:hover, -td.colLast a:link, -td.colLast a:active, -td.colLast a:visited, -td.colLast a:hover, -.constantValuesContainer td a:link, -.constantValuesContainer td a:active, -.constantValuesContainer td a:visited, -.constantValuesContainer td a:hover { - font-weight: bold; -} -td.colFirst, -th.colFirst { - white-space: nowrap; -} -table.overviewSummary { - padding: 0px; - margin-left: 0px; -} -table.overviewSummary td.colFirst, -table.overviewSummary th.colFirst, -table.overviewSummary td.colOne, -table.overviewSummary th.colOne { - width: 25%; - vertical-align: middle; -} -table.packageSummary td.colFirst, -table.overviewSummary th.colFirst { - width: 25%; - vertical-align: middle; -} -div.description { - margin: 1em; -} -.description pre { - margin-top: 0; -} -.description .block { - margin: 2em 0 2em 0; -} -.deprecatedContent { - margin: 0; - padding: 10px 0; -} -.docSummary { - padding: 0; -} -.sourceLineNo { - color: green; - padding: 0 30px 0 0; -} -h1.hidden { - visibility: hidden; - overflow: hidden; - font-size: .9em; -} -.block { - display: block; - margin: 3px 0 0 0; -} -.strong { - font-weight: bold; -} diff --git a/doc/events.md b/doc/events.md deleted file mode 100644 index ceeb4976a..000000000 --- a/doc/events.md +++ /dev/null @@ -1,28 +0,0 @@ -Events -====== - -The Box API provides an events endpoint that utilizes long-polling to send events in real-time. The SDK provides an `EventStream` class that automatically handles long-polling and deduplicating events. - -Listening to the EventStream ----------------------------- - -When the `EventStream` is started, it will begin long-polling on a separate thread. Events received from the API are then forwarded to any listeners. - -```java -BoxAPIConnection api = new BoxAPIConnection("YOUR-DEVELOPER-TOKEN"); -EventStream stream = new EventStream(api); -stream.addListener(new EventListener() { - public void onEvent(BoxEvent event) { - // Handle the event. - } -}); -stream.start(); -``` - -Keep in mind that events are received on a separate thread, so things like UI operations may need to be explicitly delegated back to the UI thread. - -When you're done listening for events, be sure to call `stream.stop()` to stop long-polling. - -### Deduplicating Events - -Since the Box API [may send duplicate events](https://developers.box.com/docs/#events), the `EventStream` will remember the last 512 received events and automatically ignore them. diff --git a/doc/files.md b/doc/files.md deleted file mode 100644 index c9a434f91..000000000 --- a/doc/files.md +++ /dev/null @@ -1,230 +0,0 @@ -Files -===== - -File objects represent individual files in Box. They can be used to download a -file's contents, upload new versions, and perform other common file operations -(move, copy, delete, etc.). - -* [Get a File's Information](#get-a-files-information) -* [Update a File's Information](#update-a-files-information) -* [Download a File](#download-a-file) -* [Upload a File](#upload-a-file) -* [Copy a File](#copy-a-file) -* [Delete a File](#delete-a-file) -* [Get Previous Versions of a File](#get-previous-versions-of-a-file) -* [Upload a New Version of a File](#upload-a-new-version-of-a-file) -* [Download a Previous Version of a File](#download-a-previous-version-of-a-file) -* [Promote a Previous Version of a File](#promote-a-previous-version-of-a-file) -* [Delete a Previous Version of a File](#delete-a-previous-version-of-a-file) - -Get a File's Information ------------------------- - -Calling [`getInfo()`][get-info] on a file returns a snapshot of the file's info. - -```java -BoxFile file = new BoxFile(api, "id"); -BoxFile.Info info = file.getInfo(); -``` - -Requesting information for only the fields you need with [`getInfo(String...)`] -[get-info2] can improve performance and reduce the size of the network request. - -```java -BoxFile file = new BoxFile(api, "id"); -// Only get information about a few specific fields. -BoxFile.Info info = file.getInfo("size", "owned_by"); -``` - -[get-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getInfo() -[get-info2]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getInfo(java.lang.String...) - -Update a File's Information ---------------------------- - -Updating a file's information is done by creating a new [`BoxFile.Info`] -[box-file-info] object or updating an existing one, and then calling -[`updateInfo(BoxFile.Info)`][update-info]. - -```java -BoxFile file = new BoxFile(api, "id"); -BoxFile.Info info = file.new Info(); -info.setName("New Name"); -file.updateInfo(info); -``` - -[box-file-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.Info.html -[update-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#updateInfo(com.box.sdk.BoxFile.Info) - -Download a File ---------------- - -A file can be downloaded by calling [`download(OutputStream)`][download] and -providing an `OutputStream` where the file's contents will be written. - -```java -BoxFile file = new BoxFile(api, "id"); -BoxFile.Info info = file.getInfo(); - -FileOutputStream stream = new FileOutputStream(info.getName()); -file.download(stream); -stream.close(); -``` - -Download progress can be tracked by providing a `ProgressListener` to -[`download(OutputStream, ProgressListener)`][download2]. The `ProgressListener` -will then receive progress updates as the download completes. - -```java -BoxFile file = new BoxFile(api, "id"); -BoxFile.Info info = file.getInfo(); - -FileOutputStream stream = new FileOutputStream(info.getName()); -// Provide a ProgressListener to monitor the progress of the download. -file.download(stream, new ProgressListener() { - public void onProgressChanged(long numBytes, long totalBytes) { - double percentComplete = numBytes / totalBytes; - } -}); -stream.close(); -``` - -[download]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#download(java.io.OutputStream) -[download2]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#download(java.io.OutputStream,%20com.box.sdk.ProgressListener) - -Upload a File -------------- - -Files are uploaded to a folder by calling the -[`uploadFile(InputStream, String)`][upload] method. - -```java -BoxFolder rootFolder = BoxFolder.getRootFolder(api); -FileInputStream stream = new FileInputStream("My File.txt"); -rootFolder.uploadFile(stream, "My File.txt"); -stream.close(); -``` - -Upload progress can be tracked by providing the size of the file and a -`ProgressListener` to -[`uploadFile(InputStream, String, long, ProgressListener)`][upload2]. The -`ProgressListener` will then receive progress updates as the upload completes. - -```java -BoxFolder rootFolder = BoxFolder.getRootFolder(api); -FileInputStream stream = new FileInputStream("My File.txt"); -rootFolder.uploadFile(stream, "My File.txt", 1024, new ProgressListener() { - public void onProgressChanged(long numBytes, long totalBytes) { - double percentComplete = numBytes / totalBytes; - } -}); -stream.close(); -``` - -[upload]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#uploadFile(java.io.InputStream,%20java.lang.String) -[upload2]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#uploadFile(java.io.InputStream,%20java.lang.String,%20long,%20com.box.sdk.ProgressListener) - -Copy a File ------------ - -A file can be copied to a new folder and optionally be renamed with the -[`copy(BoxFolder)`][copy] and [`copy(BoxFolder, String)`][copy2] methods. - -```java -BoxFolder rootFolder = BoxFolder.getRootFolder(api); -BoxFile file = new BoxFile(api, "id"); -BoxFile.Info copiedFileInfo = file.copy(rootFolder, "New Name"); -``` - -[copy]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#copy(com.box.sdk.BoxFolder) -[copy2]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#copy(com.box.sdk.BoxFolder,%20java.lang.String) - -Delete a File -------------- - -Calling the [`delete()`][delete] method will move the file to the user's trash. - -```java -BoxFile file = new BoxFile(api, "id"); -file.delete(); -``` - -[delete]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#delete() - -Get Previous Versions of a File -------------------------------- - -For users with premium accounts, versions of a file can be retrieved with the -[`getVersions()`][get-versions] method. - -```java -BoxFile file = new BoxFile(api, "id"); -List versions = file.getVersions(); -for (BoxFileVersion version : versions) { - System.out.format("SHA1 of \"%s\": %s\n", item.getName(), version.getSha1()); -} -``` - -[get-versions]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getVersions() - -Upload a New Version of a File ------------------------------- - -New versions of a file can be uploaded with the -[`uploadVersion(InputStream)`][upload-version] method. - -```java -BoxFile file = new BoxFile(api, "id"); -FileInputStream stream = new FileInputStream("My File.txt"); -file.uploadVersion(stream); -``` - -[upload-version]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#uploadVersion(java.io.InputStream) - -Download a Previous Version of a File -------------------------------------- - -For users with premium accounts, previous versions of a file can be downloaded -by calling [`download(OutputStream)`][download-version]. - -```java -BoxFile file = new BoxFile(api, "id"); -List versions = file.getVersions(); -BoxFileVersion firstVersion = versions.get(0); - -FileOutputStream stream = new FileOutputStream(firstVersion.getName()); -firstVersion.download(stream); -stream.close(); -``` - -[download-version]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileVersion.html#download(java.io.OutputStream) - -Promote a Previous Version of a File ------------------------------------- - -A previous version of a file can be promoted with the [`promote()`][promote] -method to become the current version of the file. - -```java -BoxFile file = new BoxFile(api, "id"); -List versions = file.getVersions(); -BoxFileVersion firstVersion = versions.get(0); -firstVersion.promote(); -``` - -[promote]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileVersion.html#promote() - -Delete a Previous Version of a File ------------------------------------ - -A version of a file can be deleted and moved to the trash by calling -[`delete()`][delete-version]. - -```java -BoxFile file = new BoxFile(api, "id"); -List versions = file.getVersions(); -BoxFileVersion firstVersion = versions.get(0); -firstVersion.delete(); -``` - -[delete-version]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileVersion.html#delete() diff --git a/doc/folders.md b/doc/folders.md deleted file mode 100644 index 23593b706..000000000 --- a/doc/folders.md +++ /dev/null @@ -1,265 +0,0 @@ -Folders -======= - -Folder objects represent a folder from a user's account. They 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.). - -* [Get the User's Root Folder](#get-the-users-root-folder) -* [Get a Folder's Items](#get-a-folders-items) -* [Get a Folder's Information](#get-a-folders-information) -* [Update a Folder's Information](#update-a-folders-information) -* [Create a Folder](#create-a-folder) -* [Copy a Folder](#copy-a-folder) -* [Move a Folder](#move-a-folder) -* [Rename a Folder](#rename-a-folder) -* [Delete a Folder](#delete-a-folder) -* [Created a Shared Link for a Folder](#created-a-shared-link-for-a-folder) -* [Share a Folder](#share-a-folder) -* [Get All Collaborations for a Folder](#get-all-collaborations-for-a-folder) - -Get the User's Root Folder --------------------------- - -The user's root folder can be accessed with the static -[`getRootFolder(BoxAPIConnection)`][get-root-folder] method. - -```java -BoxFolder rootFolder = BoxFolder.getRootFolder(api); -``` - -[get-root-folder]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getRootFolder(com.box.sdk.BoxAPIConnection) - -Get a Folder's Items --------------------- - -Every `BoxFolder` implements [`Iterable`][iterator] which allows you to -iterate over the folder's contents. The iterator automatically handles paging -and will make additional network calls to load more data from Box when -necessary. - -```java -BoxFolder folder = new BoxFolder(api, "id"); -for (BoxItem.Info itemInfo : folder) { - if (itemInfo instanceof BoxFile.Info) { - BoxFile.Info fileInfo = (BoxFile.Info) itemInfo; - // Do something with the file. - } else if (itemInfo instanceof BoxFolder) { - BoxFolder.Info folderInfo = (BoxFolder.Info) itemInfo; - // Do something with the folder. - } -} -``` - -`BoxFolder` purposely doesn't provide a way of getting a collection of -`BoxItems`. Getting the entire contents of a folder is usually unnecessary and -can be extremely inefficient for folders with a large number of items. If you -really require a collection instead of an iterable, you can create the -collection manually. - -```java -Collection folderItems = new ArrayList(); -BoxFolder folder = new BoxFolder(api, "id"); -for (BoxItem.Info itemInfo : folder) { - folderItems.add(itemInfo.getResource()); -} -``` - -[iterator]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#iterator() - -Get a Folder's Information --------------------------- - -Calling [`getInfo()`][get-info] on a folder returns a snapshot of the folder's -info. - -```java -BoxFolder folder = new BoxFolder(api, "id"); -BoxFolder.Info info = folder.getInfo(); -``` - -Requesting information for only the fields you need can improve performance and -reduce the size of the network request. The [`getInfo(String...)`][get-info2] -method lets you specify which fields are retrieved. - -```java -BoxFolder folder = new BoxFolder(api, "id"); -// Only get information about a few specific fields. -BoxFolder.Info info = folder.getInfo("size", "owned_by"); -``` - -[get-info]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getInfo() -[get-info2]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getInfo(java.lang.String...) - -Update a Folder's Information ------------------------------ - -Updating a folder's information is done by creating a new `BoxFolder.Info` -object or updating an existing one, and then calling -[`updateInfo(BoxFolder.Info)`][update-info]. - -```java -BoxFolder folder = new BoxFolder(api, "id"); -BoxFolder.Info info = folder.new Info(); -info.setName("New Name"); -folder.updateInfo(info); -``` - -[update-info]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#updateInfo(com.box.sdk.BoxFolder.Info) - -Create a Folder ---------------- - -Create a child folder by calling [`createFolder(String)`][create-folder] on the -parent folder. - -```java -BoxFolder parentFolder = new BoxFolder(api, "id"); -BoxFolder.Info childFolderInfo = parentFolder.createFolder("Child Folder Name"); -``` - -[create-folder]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#createFolder(java.lang.String) - -Copy a Folder -------------- - -Call the [`copy(BoxFolder)`][copy] method to copy a folder to another folder. - -```java -BoxFolder folder = new BoxFolder(api, "id1"); -BoxFolder destination = new BoxFolder(api, "id2"); -folder.copy(destination); -``` - -You can also use the [`copy(BoxFolder, String)`][copy2] method to rename the -folder while copying it. This allows you to make a copy of the folder in the -same parent folder, but with a different name. - -```java -BoxFolder folder = new BoxFolder(api, "id1"); -BoxFolder.Info parentFolderInfo = folder.getInfo().getParent(); -BoxFolder parentFolder = parentFolderInfo.getResource(); -folder.copy(parentFolder, "New Name"); -``` - -[copy]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#copy(com.box.sdk.BoxFolder) -[copy2]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#copy(com.box.sdk.BoxFolder,%20java.lang.String) - -Move a Folder -------------- - -Call the [`move(BoxFolder)`][move] method with the destination you want the folder moved -to. - -```java -BoxFolder folder = new BoxFolder(api, "id1"); -BoxFolder destination = new BoxFolder(api, "id2"); -folder.move(destination); -``` - -[move]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#move(com.box.sdk.BoxFolder) - -Rename a Folder ---------------- - -Call the [`rename(String)`][rename] method with a new name for the folder. - -```java -BoxFolder folder = new BoxFolder(api, "id"); -folder.rename("New Name"); -``` - -A folder can also be renamed by updating the folder's information. This is -useful if you want to perform more than one change to the folder in a single API -request. - -```java -BoxFolder folder = new BoxFolder(api, "id"); -BoxFolder.Info info = folder.new Info(); -info.setName("New Name"); -folder.updateInfo(info); -``` - -[rename]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#rename(java.lang.String) - -Delete a Folder ---------------- - -A folder can be deleted with the [`delete(boolean)`][delete] method. Passing -true to this method indicates that the folder and its contents should be -recursively deleted. - -```java -BoxFolder folder = new BoxFolder(api, "id"); -folder.delete(true); -``` - -[delete]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#delete(boolean) - -Created a Shared Link for a Folder ----------------------------------- - -You can get a shared link for a folder by calling the -[`createSharedLink(BoxSharedLink.Access, Date, BoxSharedLink.Permissions)`] -[create-shared-link] method. - -```java -BoxFolder folder = new BoxFolder(api, "id"); -SharedLink link = folder.createSharedLink(BoxSharedLink.Access.OPEN, null, - permissions); -``` - -A shared link can also be created by updating the folder's information. This is -useful if you want to perform more than one change to the folder in a single API -request. - -```java -BoxSharedLink sharedLink = new BoxSharedLink(); -sharedLink.setAccess(BoxSharedLink.Access.OPEN); - -BoxFolder folder = new BoxFolder(api, "id"); -BoxFolder.Info info = folder.new Info(); -info.setSharedLink(sharedLink); -folder.updateInfo(info); -``` - -[create-shared-link]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#createSharedLink(com.box.sdk.BoxSharedLink.Access,%20java.util.Date,%20com.box.sdk.BoxSharedLink.Permissions) - -Share a Folder --------------- - -You can invite another person to collaborate on a folder with the -[`collaborate(String, BoxCollaboration.Role)`][collaborate] method. - -```java -BoxFolder folder = new BoxFolder(api, "id"); -BoxCollaboration.Info collabInfo = folder.collaborate("gcurtis@box.com", - BoxCollaboration.Role.EDITOR); -``` - -If you already know the user's ID, you can invite them directly without needing -to know their email address with the -[`collaborate(BoxCollaborator, BoxCollaboration.Role)`][collaborate2] method. - -```java -BoxUser collaborator = new User(api, "user-id"); -BoxFolder folder = new BoxFolder(api, "folder-id"); -BoxCollaboration.Info collabInfo = folder.collaborate(collaborator, - BoxCollaboration.Role.EDITOR); -``` - -[collaborate]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#collaborate(java.lang.String,%20com.box.sdk.BoxCollaboration.Role) -[collaborate2]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#collaborate(com.box.sdk.BoxCollaborator,%20com.box.sdk.BoxCollaboration.Role) - -Get All Collaborations for a Folder ------------------------------------ - -The [`getCollaborations()`][get-collaborations] method will return a collection -of `BoxCollaboration.Info` objects for a folder. - -```java -BoxFolder folder = new BoxFolder(api, "id"); -Collection collaborations = folder.getCollaborations(); -``` - -[get-collaborations]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getCollaborations() diff --git a/doc/groups.md b/doc/groups.md deleted file mode 100644 index 6b6617a40..000000000 --- a/doc/groups.md +++ /dev/null @@ -1,47 +0,0 @@ -Groups -====== - -Groups are sets of users that can be used in collaborations. - -* [Get All Groups](#get-all-groups) -* [Create a Group](#create-a-group) -* [Delete a Group](#delete-a-group) - -Get All Groups --------------- - -Calling the static [`getAllGroups(BoxAPIConnection)`][get-all-groups] will -return an iterable that will page through all of the user's groups. - -```java -Iterable groups = BoxGroup.getAllGroups(BoxAPIConnection api); -for (BoxGroup.Info groupInfo : groups) { - // Do something with the group. -} -``` - -[get-all-groups]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroup.html#getAllGroups(com.box.sdk.BoxAPIConnection) - -Create a Group --------------- - -The static [`createGroup(BoxAPIConnection, String)`][create-group] method will -let you create a new group with a specified name. - -```java -BoxGroup.Info groupInfo = BoxGroup.createGroup(api, "My Group"); -``` - -[create-group]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroup.html#createGroup(com.box.sdk.BoxAPIConnection,%20java.lang.String) - -Delete a Group --------------- - -A group can be deleted by calling the [`delete()`][delete] method. - -```java -BoxGroup group = new BoxGroup(api, "id"); -group.delete(); -``` - -[delete]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroup.html#delete() diff --git a/doc/overview.md b/doc/overview.md deleted file mode 100644 index 73993bf7e..000000000 --- a/doc/overview.md +++ /dev/null @@ -1,111 +0,0 @@ -SDK Overview -============ - -This guide covers the basics behind the various components of the Box Java SDK. -It's also recommended that you take a look at [the -documentation](https://developers.box.com/docs/) for the Box API. - -* [Authentication](#authentication) -* [Resource Types](#resource-types) -* [Requests and Responses](#requests-and-responses) -* [Error Handling](#error-handling) - -Authentication --------------- - -The first step in using the SDK is always authenticating and connecting to the -API. The SDK does this through the `BoxAPIConnection` class. This class -represents an authenticated connection to a specific version of the Box API. It -is responsible for things such as: - -* Storing authentication information. -* Automatically refreshing tokens. -* Configuring rate-limiting, number of retry attempts and other connection - settings. - -You can also create more than one `BoxAPIConnection`. For example, you can have -a connection for each user if your application supports multiple user accounts. - -See the [Authentication guide](authentication.md) for details on how to create -and use `BoxAPIConnection`. - -Resource Types --------------- - -Resources types are the classes you'll use the most. Things like `BoxFile`, -`BoxFolder`, `BoxUser`, etc. are all resource types. A resource always has an ID -and an associated API connection. Instantiating and using a resource type is -simple: - -```java -// Print the name of the folder with ID "1234". -BoxFolder folder = new BoxFolder(api, "1234") -BoxFolder.Info info = folder.getInfo(); -System.out.println(info.getName()); -``` - -A resource type will always have the same API connection as the type that -instantiated it. For example, `creator` will have the same API connection that -`folder` does. - -```java -BoxFolder folder = new BoxFolder(api, "1234") -BoxFolder.Info info = folder.getInfo(); - -// This BoxUser has the same BoxAPIConnection as "folder". -BoxUser creator = info.getCreatedBy(); -``` - -Requests and Responses ----------------------- - -All communication with Box's API is done through `BoxAPIRequest` and -`BoxAPIResponse` (or their subclasses). These classes handle all the dirty work -of setting appropriate headers, handling errors, and sending/receiving data. - -You generally won't need to use these classes directly, as the resource types -are easier and cover most use-cases. However, these classes are extremely -flexible and can be used if you need to make custom API calls. - -Here's an example using `BoxAPIRequest` and `BoxJSONResponse` that gets a list -of items with some custom fields: - -```java -BoxAPIConnection api = new BoxAPIConnection("token"); -URL url = new URL("https://api.box.com/2.0/folders/0/items?fields=name,created_at") -BoxAPIRequest request = new BoxAPIRequest(api, url, "GET"); -BoxJSONResponse response = (BoxJSONResponse) request.send(); -String json = response.getJSON(); -``` - -Error Handling --------------- - -Unless otherwise noted, the classes and methods in the SDK can throw an -unchecked [`BoxAPIException`][api-exception] (unchecked meaning that the -compiler won't force you to handle it) if an error occurs. This includes network -errors or error statuses returned by the API. - -You should be aware of this when using the SDK so that your code can catch any -errors that might happen when communicating with Box. - -If the error was due to a general networking error (for example, if the network -connection was lost), the `BoxAPIException` will contain the underlying -`IOException` as its cause. - -If the error was due to an API error, the `BoxAPIException` will contain the -response code and body returned by the API. - -```java -BoxAPIConnection api = new BoxAPIConnection("token"); - -try { - BoxFolder rootFolder = BoxFolder.getRootFolder(api); -} catch (BoxAPIException e) { - // Log the response code and the error message returned by the API. - System.err.format("The API returned the error code: %d\n\n%s", - e.getResponseCode(), e.getResponse()); -} -``` - -[api-exception]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIException.html diff --git a/doc/search.md b/doc/search.md deleted file mode 100644 index f87ea0bcf..000000000 --- a/doc/search.md +++ /dev/null @@ -1,27 +0,0 @@ -Search -====== - -* [Search a Folder and Its Children](#search-a-folder-and-its-children) -* [Advanced Search](#advanced-search) - -Basic Search ------------- - -Calling [`search(String)`][search] on a folder will recursively search the -folder and its children. To search the user's entire account, simply search -their root folder. - -```java -BoxFolder rootFolder = BoxFolder.getRootFolder(api); -Iterable results = rootFolder.search("my query"); -for (BoxItem.Info result : results) { - // Do something with the search result. -} -``` - -[search]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#search(java.lang.String) - -Advanced Search ---------------- - -Advanced is not yet implemented, but is coming soon. diff --git a/doc/tasks.md b/doc/tasks.md deleted file mode 100644 index 70d000396..000000000 --- a/doc/tasks.md +++ /dev/null @@ -1,4 +0,0 @@ -Tasks -===== - -Docs coming soon. diff --git a/doc/upgrading.md b/doc/upgrading.md deleted file mode 100644 index 9a3a0d45f..000000000 --- a/doc/upgrading.md +++ /dev/null @@ -1,116 +0,0 @@ -Upgrading to v4 -=============== - -v4 of the Box Java SDK introduces a lot of new design changes. Since this is a -major version bump, there will be breaking changes that will require you to -update your application. - -What's New ----------- - -### Features - -* __Automatic rate-limiting and error retry.__ API requests will automatically - be retried with exponential back off if a 500+ (server error) or 429 (too many - requests) response code is returned. -* __OAuth redesign.__ OAuth should now be easier to use, allowing you to - authenticate with an access token, auth code, or developer token. -* __New EventStream class.__ This class makes it easier to listen for API events - by allowing you to specify listeners that will be notified when an event - occurs. -* __New classes for making custom API requests.__ The BoxAPIRequest and - BoxAPIResponse classes make it easy to send custom requests to the API while - still having OAuth, rate-limiting back off, error handling and response - parsing automatically handled. - -### General Improvements - -* __Simpler and more intuitive design.__ We aimed to make the overall design of - the SDK more intuitive and easier to learn. -* __More documentation and examples.__ The Javadocs have been completely - overhauled and there are new guides explaining how to accomplish common tasks - with the SDK. -* __SDK size has been dramatically decreased.__ Many of the SDK's dependencies - have been removed and its overall size has been reduced - making it more - suitable for mobile apps. -* __Easier integration.__ With a single build process, it's easier and simpler - to get the SDK building with other applications. It also follows the standard - directory layout, making it easier to import into various IDEs or build - systems. - -Authentication --------------- - -Authentication has been simplified by allowing you to provide tokens or auth -codes directly. All authentication is now done by creating a `BoxAPIConnection` -in order to establish an authenticated connection with the API. - -Connect to the API using a developer token: - -```java -BoxAPIConnection api = new BoxAPIConnection("YOUR-DEVELOPER-TOKEN"); -``` - -Connect to the API using access and refresh tokens: - -```java -BoxAPIConnection api = new BoxAPIConnection("CLIENT-ID", "CLIENT-SECRET", - "ACCESS-TOKEN", "REFRESH-TOKEN"); -``` - -Connect to the API using an auth code: - -```java -BoxAPIConnection api = new BoxAPIConnection("CLIENT-ID", "CLIENT-SECRET", - "AUTH-CODE"); -``` - -More information on authentication can be found [here](authentication.md). - -New Resource Types ------------------- - -Previously, interaction with the API was done through managers and request -objects. For example: - -```java -BoxClient client = new BoxClient(...); -IBoxFilesManager filesManager = boxClient.getFilesManager(); - -BoxDefaultRequestObject requestObj = new BoxDefaultRequestObject(); -requestObj.getRequestExtras().addField(BoxFile.FIELD_SHA1); -requestObj.getRequestExtras().addField(BoxFile.FIELD_DESCRIPTION); - -BoxFile file = filesManager.getFile(fileId, requestObj); -``` - -These objects have been removed and interacting with the API has been -simplified. Resources can now be manipulated directly without needing to use -managers or build custom requests. - -```java -BoxAPIConnection api = new BoxAPIConnection(...); -BoxFile file = new BoxFile(api, fileID); -BoxFile.Info fileInfo = file.getInfo("sha1", "description"); -``` - -More information on resource types can be found [here](resource-types.md). - -Custom Requests ---------------- - -The SDK now provides request and response objects that allow you to easily make -custom requests to the Box API. These objects will handle authentication, -automatic retry, rate-limiting and errors out-of-the-box, giving you the -flexibility to make your own API requests without having to worry about handling -these things yourself. - -```java -BoxAPIConnection api = new BoxAPIConnection(...); -URL url = new URL("https://api.box.com/2.0/folders/0/items?fields=name,created_at") -BoxAPIRequest request = new BoxAPIRequest(api, url, "GET"); -BoxJSONResponse response = (BoxJSONResponse) request.send(); -String json = response.getJSON(); -``` - -More information on resource types can be found [here](overview.md). diff --git a/doc/users.md b/doc/users.md deleted file mode 100644 index b02d9c7e5..000000000 --- a/doc/users.md +++ /dev/null @@ -1,21 +0,0 @@ -Users -===== - -Users represent an individual's account on Box. - -* [Get the Current User's Information](#get-the-current-users-information) - -Get the Current User's Information ----------------------------------- - -To get the current user, call the static [`getCurrentUser(BoxAPIConnection)`] -[get-current-user] method. Then use [`getInfo()`][get-info] to get information -about the user. - -```java -BoxUser user = BoxUser.getCurrentUser(api); -BoxUser.Info info = user.getInfo(); -``` - -[get-current-user]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getCurrentUser(com.box.sdk.BoxAPIConnection) -[get-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getInfo() diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 000000000..c41719199 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,101 @@ +# Documentation + +## Configuration + +This section covers the documentation required to get up and running with the SDK, including configuration, authentication, and client initialization for making API calls. + +* [Configuration](configuration.md) +* [Authentication](authentication.md) +* [Client](client.md) + +## Box API Usage + +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) +* [Automateworkflows](automateworkflows.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) +* [Enterpriseconfigurations](enterpriseconfigurations.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) +* [Hubdocument](hubdocument.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) +* [Metadatataxonomies](metadatataxonomies.md) +* [Metadatatemplates](metadatatemplates.md) +* [Notes](notes.md) +* [Query](query.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/ai.md b/docs/ai.md new file mode 100644 index 000000000..d324a5962 --- /dev/null +++ b/docs/ai.md @@ -0,0 +1,173 @@ +# 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. + +You can ask a question about a single file, several files, or the entire contents of a Box Hub. To search across and ask questions about everything in a Box Hub, send a single item with `type` set to `hubs` and the Hub's ID as the `id`. Box AI answers the question using the indexed content of all files in that Hub. + +Asking questions about a Box Hub requires Box AI for Hubs to be enabled in the Admin Console before the Hub is created, so that its content is indexed. + +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 does the Sun rise?", Arrays.asList(new AiItemAsk.Builder(fileToAsk.getId(), AiItemAskTypeField.FILE).content("The Sun rises in the east").build())).aiAgent(aiAskAgentBasicTextConfig).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("Paraphrase the documents", Arrays.asList(new AiTextGenItemsField.Builder(fileToAsk.getId()).type(AiTextGenItemsTypeField.FILE).content("The Earth goes around the Sun. The 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())).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(aiExtractAgentBasicTextConfig).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. + +To define the extraction structure, provide either a metadata template or a list of fields. 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](https://developer.box.com/guides/metadata/templates/create). + +This endpoint also supports [Enhanced Extract Agent](https://developer.box.com/guides/box-ai/ai-tutorials/extract-metadata-structured#enhanced-extract-agent). + +For information about supported file formats and languages, see the [Extract metadata from file (structured)](https://developer.box.com/guides/box-ai/ai-tutorials/extract-metadata-structured) API guide. + +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(), new AiExtractStructuredFieldsField.Builder("address").description("Person address").displayName("Address").prompt("Extract the full mailing address.").type("struct").fields(Arrays.asList(new AiExtractSubField.Builder("street").displayName("Street").type("string").build(), new AiExtractSubField.Builder("city").displayName("City").type("string").build(), new AiExtractSubField.Builder("state").displayName("State").type("string").build(), new AiExtractSubField.Builder("zip").displayName("Zip").type("string").build(), new AiExtractSubField.Builder("country").displayName("Country").type("string").build())).build(), new AiExtractStructuredFieldsField.Builder("work_history").description("Person work history").displayName("Work history").prompt("Extract each job as a row.").type("table").fields(Arrays.asList(new AiExtractSubField.Builder("job_title").displayName("Job title").type("string").build(), new AiExtractSubField.Builder("company").displayName("Company").type("string").build(), new AiExtractSubField.Builder("start_year").displayName("Start year").type("string").build(), new AiExtractSubField.Builder("end_year").displayName("End year").type("string").build())).build())).aiAgent(aiExtractStructuredAgentBasicTextConfig).includeConfidenceScore(true).includeReference(true).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/aistudio.md b/docs/aistudio.md new file mode 100644 index 000000000..2313462ff --- /dev/null +++ b/docs/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/appitemassociations.md b/docs/appitemassociations.md new file mode 100644 index 000000000..cc8a99bc2 --- /dev/null +++ b/docs/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/archives.md b/docs/archives.md new file mode 100644 index 000000000..38be510cd --- /dev/null +++ b/docs/archives.md @@ -0,0 +1,138 @@ +# ArchivesManager + + +- [List archives](#list-archives) +- [Create archive](#create-archive) +- [Delete archive](#delete-archive) +- [Update archive](#update-archive) + +## List archives + +Retrieves archives for an enterprise. + +To learn more about the archive APIs, see the [Archive API Guide](https://developer.box.com/guides/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](https://developer.box.com/guides/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.Builder(archiveName).description(archiveDescription).build()) +``` + +### 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](https://developer.box.com/guides/archives). + + +This endpoint is currently unavailable. Please contact support for assistance. + + +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. + + +## Update archive + +Updates an archive. + +To learn more about the archive APIs, see the [Archive API Guide](https://developer.box.com/guides/archives). + +This operation is performed by calling function `updateArchiveByIdV2025R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2025.0/put-archives-id/). + + +``` +client.getArchives().updateArchiveByIdV2025R0(archive.getId(), new UpdateArchiveByIdV2025R0RequestBody.Builder().name(newArchiveName).description(newArchiveDescription).build()) +``` + +### Arguments + +- archiveId `String` + - The ID of the archive. Example: "982312" +- requestBody `UpdateArchiveByIdV2025R0RequestBody` + - Request body of updateArchiveByIdV2025R0 method +- headers `UpdateArchiveByIdV2025R0Headers` + - Headers of updateArchiveByIdV2025R0 method + + +### Returns + +This function returns a value of type `ArchiveV2025R0`. + +Returns the updated archive object. + + diff --git a/docs/authentication.md b/docs/authentication.md new file mode 100644 index 000000000..b76335410 --- /dev/null +++ b/docs/authentication.md @@ -0,0 +1,366 @@ +# 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 +OAuthConfig oauthConfig = new OAuthConfig("CLIENT_ID", "CLIENT_SECRET"); +BoxOAuth oauth = new BoxOAuth(oauthConfig); +String authorizationUrl = oauth.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/authorization.md b/docs/authorization.md new file mode 100644 index 000000000..5356772c0 --- /dev/null +++ b/docs/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](https://developer.box.com/reference/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/automateworkflows.md b/docs/automateworkflows.md new file mode 100644 index 000000000..a42abed96 --- /dev/null +++ b/docs/automateworkflows.md @@ -0,0 +1,67 @@ +# AutomateWorkflowsManager + + +- [List Automate workflows defined as callable actions](#list-automate-workflows-defined-as-callable-actions) +- [Start Automate workflow](#start-automate-workflow) + +## List Automate workflows defined as callable actions + +Returns workflow actions from Automate for a folder, using the +`WORKFLOW` action category. + +This operation is performed by calling function `getAutomateWorkflowsV2026R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2026.0/get-automate-workflows/). + + +``` +adminClient.getAutomateWorkflows().getAutomateWorkflowsV2026R0(new GetAutomateWorkflowsV2026R0QueryParams(workflowFolderId)) +``` + +### Arguments + +- queryParams `GetAutomateWorkflowsV2026R0QueryParams` + - Query parameters of getAutomateWorkflowsV2026R0 method +- headers `GetAutomateWorkflowsV2026R0Headers` + - Headers of getAutomateWorkflowsV2026R0 method + + +### Returns + +This function returns a value of type `AutomateWorkflowsV2026R0`. + +Returns workflow actions that can be manually started. + + +## Start Automate workflow + +Starts an Automate workflow manually by using a workflow action ID and file IDs. + +This operation is performed by calling function `createAutomateWorkflowStartV2026R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2026.0/post-automate-workflows-id-start/). + + +``` +adminClient.getAutomateWorkflows().createAutomateWorkflowStartV2026R0(workflowAction.getWorkflow().getId(), new AutomateWorkflowStartRequestV2026R0(workflowAction.getId(), Arrays.asList(workflowFileId))) +``` + +### Arguments + +- workflowId `String` + - The ID of the workflow. Example: "12345" +- requestBody `AutomateWorkflowStartRequestV2026R0` + - Request body of createAutomateWorkflowStartV2026R0 method +- headers `CreateAutomateWorkflowStartV2026R0Headers` + - Headers of createAutomateWorkflowStartV2026R0 method + + +### Returns + +This function returns a value of type `void`. + +Starts the workflow. + + diff --git a/docs/avatars.md b/docs/avatars.md new file mode 100644 index 000000000..902fffd58 --- /dev/null +++ b/docs/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/chunkeduploads.md b/docs/chunkeduploads.md new file mode 100644 index 000000000..715868fb4 --- /dev/null +++ b/docs/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`](https://developer.box.com/reference/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`](https://developer.box.com/reference/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`](https://developer.box.com/reference/post-files-upload-sessions) +and [`Get upload session`](https://developer.box.com/reference/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`](https://developer.box.com/reference/post-files-upload-sessions) +and [`Get upload session`](https://developer.box.com/reference/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`](https://developer.box.com/reference/post-files-upload-sessions) +and [`Get upload session`](https://developer.box.com/reference/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`](https://developer.box.com/reference/post-files-upload-sessions) +and [`Get upload session`](https://developer.box.com/reference/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`](https://developer.box.com/reference/post-files-upload-sessions) +and [`Get upload session`](https://developer.box.com/reference/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`](https://developer.box.com/reference/post-files-upload-sessions) +and [`Get upload session`](https://developer.box.com/reference/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`](https://developer.box.com/reference/post-files-upload-sessions) +and [`Get upload session`](https://developer.box.com/reference/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`](https://developer.box.com/reference/post-files-upload-sessions) +and [`Get upload session`](https://developer.box.com/reference/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/classifications.md b/docs/classifications.md new file mode 100644 index 000000000..6f3139fbe --- /dev/null +++ b/docs/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/client.md b/docs/client.md new file mode 100644 index 000000000..c78e51b7e --- /dev/null +++ b/docs/client.md @@ -0,0 +1,210 @@ +# 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 Timeouts for API calls](#use-timeouts-for-api-calls) +- [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 Timeouts for API calls + +In order to configure timeout for API calls, calling the `client.withTimeouts(config)` method creates a new client with timeout settings, leaving the original client unmodified. + +All timeout values are in milliseconds. + +```java +TimeoutConfig timeoutConfig = new TimeoutConfig.Builder() + .connectionTimeoutMs(5000L) + .readTimeoutMs(30000L) + .requestTimeoutMs(60000L) + .build(); +BoxClient newClient = client.withTimeouts(timeoutConfig); +``` + +# 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/collaborationallowlistentries.md b/docs/collaborationallowlistentries.md new file mode 100644 index 000000000..20aa3c70b --- /dev/null +++ b/docs/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/collaborationallowlistexempttargets.md b/docs/collaborationallowlistexempttargets.md new file mode 100644 index 000000000..a96a3790c --- /dev/null +++ b/docs/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/collections.md b/docs/collections.md new file mode 100644 index 000000000..dabe7ba5d --- /dev/null +++ b/docs/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/comments.md b/docs/comments.md new file mode 100644 index 000000000..4572fa92d --- /dev/null +++ b/docs/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](#parameter-fields) query parameter to explicitly request +any specific fields. + + diff --git a/docs/configuration.md b/docs/configuration.md new file mode 100644 index 000000000..a07fc503f --- /dev/null +++ b/docs/configuration.md @@ -0,0 +1,215 @@ +# Configuration + + + + +- [Retry Strategy](#retry-strategy) + - [Overview](#overview) + - [Default Configuration](#default-configuration) + - [Retry Decision Flow](#retry-decision-flow) + - [Exponential Backoff Algorithm](#exponential-backoff-algorithm) + - [Example Delays (with default settings)](#example-delays-with-default-settings) + - [Retry-After Header](#retry-after-header) + - [Network Exception Handling](#network-exception-handling) + - [Customizing Retry Parameters](#customizing-retry-parameters) + - [Custom Retry Strategy](#custom-retry-strategy) +- [Timeouts](#timeouts) + + + +## Retry Strategy + +### Overview + +The SDK ships with a built-in retry strategy (`BoxRetryStrategy`) that implements the `RetryStrategy` interface. The `BoxNetworkClient`, which serves as the default network client, uses this strategy to automatically retry failed API requests with exponential backoff. + +The retry strategy exposes two methods: + +- **`shouldRetry`** — Determines whether a failed request should be retried based on the HTTP status code, response headers, attempt count, and authentication state. +- **`retryAfter`** — Computes the delay (in seconds) before the next retry attempt, using either the server-provided `Retry-After` header or an exponential backoff formula. + +### Default Configuration + +| Parameter | Default | Description | +| -------------------------- | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `maxAttempts` | `5` | Maximum number of retry attempts for HTTP error responses (status 4xx/5xx). | +| `retryBaseInterval` | `1` (second) | Base interval used in the exponential backoff calculation. | +| `retryRandomizationFactor` | `0.5` | Jitter factor applied to the backoff delay. The actual delay is multiplied by a random value between `1 - factor` and `1 + factor`. | +| `maxRetriesOnException` | `2` | Maximum number of retries for network-level exceptions (connection failures, timeouts). These are tracked by a separate counter from HTTP error retries. | + +### Retry Decision Flow + +The following diagram shows how `BoxRetryStrategy.shouldRetry` decides whether to retry a request: + +``` + shouldRetry(fetchOptions, fetchResponse, attemptNumber) + | + v + +-----------------------+ + | status == 0 | Yes + | (network exception)? |----------> attemptNumber <= maxRetriesOnException? + +-----------------------+ | | + | No Yes No + v | | + +-----------------------+ [RETRY] [NO RETRY] + | attemptNumber >= | + | maxAttempts? | + +-----------------------+ + | | + Yes No + | | + [NO RETRY] v + +-----------------------+ + | status == 202 AND | Yes + | Retry-After header? |----------> [RETRY] + +-----------------------+ + | No + v + +-----------------------+ + | status >= 500 | Yes + | (server error)? |----------> [RETRY] + +-----------------------+ + | No + v + +-----------------------+ + | status == 429 | Yes + | (rate limited)? |----------> [RETRY] + +-----------------------+ + | No + v + +-----------------------+ + | status == 401 AND | Yes + | auth available? |----------> Refresh token, then [RETRY] + +-----------------------+ + | No + v + [NO RETRY] +``` + +### Exponential Backoff Algorithm + +When the response does not include a `Retry-After` header, the retry delay is computed using exponential backoff with randomized jitter: + +``` +delay = 2^attemptNumber * retryBaseInterval * random(1 - factor, 1 + factor) +``` + +Where: + +- `attemptNumber` is the current attempt (1-based) +- `retryBaseInterval` defaults to `1` second +- `factor` is `retryRandomizationFactor` (default `0.5`) +- `random(min, max)` returns a uniformly distributed value in `[min, max]` + +#### Example Delays (with default settings) + +| Attempt | Base Delay | Min Delay (factor=0.5) | Max Delay (factor=0.5) | +| ------- | ---------- | ---------------------- | ---------------------- | +| 1 | 2s | 1.0s | 3.0s | +| 2 | 4s | 2.0s | 6.0s | +| 3 | 8s | 4.0s | 12.0s | +| 4 | 16s | 8.0s | 24.0s | + +### Retry-After Header + +When the server includes a `Retry-After` header in the response, the SDK uses the header value directly as the delay in seconds instead of computing an exponential backoff delay. This applies to any retryable response that includes the header, including: + +- `202 Accepted` with `Retry-After` (long-running operations) +- `429 Too Many Requests` with `Retry-After` +- `5xx` server errors with `Retry-After` + +The header value is parsed as a floating-point number representing seconds. + +### Network Exception Handling + +Network-level failures (connection refused, DNS resolution errors, timeouts, TLS errors) are represented internally as responses with status `0`. These exceptions are tracked by a **separate counter** (`maxRetriesOnException`, default `2`) from the regular HTTP error retry counter (`maxAttempts`). + +This means: + +- Network exception retries are tracked independently from HTTP error retries, each with their own counter and backoff progression. +- A request can fail up to `maxRetriesOnException` times due to network exceptions, but each exception retry also increments the overall attempt counter, so the total number of retries across both exception and HTTP error types is bounded by `maxAttempts`. + +### Customizing Retry Parameters + +You can customize all retry parameters by initializing `BoxRetryStrategy` with the desired values and passing it to `NetworkSession`: + +```java +BoxDeveloperTokenAuth auth = new BoxDeveloperTokenAuth("DEVELOPER_TOKEN"); +NetworkSession session = new NetworkSession.Builder() + .retryStrategy( + new BoxRetryStrategy.Builder() + .maxAttempts(3) + .retryBaseInterval(2) + .retryRandomizationFactor(0.3) + .maxRetriesOnException(1) + .build() + ) + .build(); +BoxClient client = new BoxClient.Builder(auth) + .networkSession(session) + .build(); +``` + +### Custom Retry Strategy + +You can implement your own retry strategy by implementing the `RetryStrategy` interface and overriding the `shouldRetry` and `retryAfter` methods: + +```java +BoxDeveloperTokenAuth auth = new BoxDeveloperTokenAuth("DEVELOPER_TOKEN"); +RetryStrategy customRetryStrategy = new RetryStrategy() { + @Override + public boolean shouldRetry(FetchOptions fetchOptions, FetchResponse fetchResponse, int attemptNumber) { + return fetchResponse.getStatus() >= 500 && attemptNumber < 3; + } + + @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(); +``` + +## Timeouts + +You can configure network timeouts with `TimeoutConfig` on `NetworkSession`. +The SDK supports three timeout values, all in milliseconds: + +| Parameter | Description | +| --------------------- | -------------------------------------------------------------------------------------------------------- | +| `connectionTimeoutMs` | Maximum time to wait for the TCP connection to be established. Maps to OkHttp `connectTimeout`. | +| `readTimeoutMs` | Maximum idle time between data packets while reading the response. Maps to OkHttp `readTimeout`. | +| `requestTimeoutMs` | Maximum total time for the entire HTTP request (connect + send + receive). Maps to OkHttp `callTimeout`. | + +```java +BoxDeveloperTokenAuth auth = new BoxDeveloperTokenAuth("DEVELOPER_TOKEN"); +TimeoutConfig timeoutConfig = new TimeoutConfig.Builder() + .connectionTimeoutMs(5000L) + .readTimeoutMs(30000L) + .requestTimeoutMs(60000L) + .build(); + +NetworkSession session = new NetworkSession() + .withTimeoutConfig(timeoutConfig); + +BoxClient client = new BoxClient.Builder(auth) + .networkSession(session) + .build(); +``` + +How timeout handling works: + +- `connectionTimeoutMs` controls how long the client waits to establish a connection. +- `readTimeoutMs` controls how long the client waits for data while reading the response. +- `requestTimeoutMs` controls the maximum total time for the entire request lifecycle, including connection, sending the request body, and reading the response. +- If timeout config is not provided, the SDK uses default timeouts: `connectionTimeoutMs: 10000` (10 seconds), `readTimeoutMs: 60000` (60 seconds), and `requestTimeoutMs: 21600000` (6 hours). +- Each timeout is optional. If a value is not provided, the client keeps its existing timeout for that setting. +- To disable a timeout, set its value to `0L`. +- Timeout failures are handled as request exceptions, then retry behavior is controlled by the configured retry strategy. +- If retries are exhausted after timeout failures, the SDK throws `BoxSDKError` with the underlying timeout exception as the cause. +- Timeout applies to a single HTTP request attempt to the Box API (not the total time across all retries). diff --git a/docs/devicepinners.md b/docs/devicepinners.md new file mode 100644 index 000000000..06078a729 --- /dev/null +++ b/docs/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/docgen.md b/docs/docgen.md new file mode 100644 index 000000000..b92087491 --- /dev/null +++ b/docs/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(uploadedFileDocx.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/docgentemplate.md b/docs/docgentemplate.md new file mode 100644 index 000000000..c427b2af6 --- /dev/null +++ b/docs/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/downloads.md b/docs/downloads.md new file mode 100644 index 000000000..36c3c56ab --- /dev/null +++ b/docs/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](https://developer.box.com/guides/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](https://developer.box.com/guides/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/emailaliases.md b/docs/emailaliases.md new file mode 100644 index 000000000..2046bf577 --- /dev/null +++ b/docs/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/enterpriseconfigurations.md b/docs/enterpriseconfigurations.md new file mode 100644 index 000000000..5ee3c5740 --- /dev/null +++ b/docs/enterpriseconfigurations.md @@ -0,0 +1,36 @@ +# EnterpriseConfigurationsManager + + +- [Get enterprise configuration](#get-enterprise-configuration) + +## Get enterprise configuration + +Retrieves the configuration for an enterprise. + +This operation is performed by calling function `getEnterpriseConfigurationByIdV2025R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2025.0/get-enterprise-configurations-id/). + + +``` +adminClient.getEnterpriseConfigurations().getEnterpriseConfigurationByIdV2025R0(enterpriseId, new GetEnterpriseConfigurationByIdV2025R0QueryParams(Arrays.asList("user_settings", "content_and_sharing", "security", "shield"))) +``` + +### Arguments + +- enterpriseId `String` + - The ID of the enterprise. Example: "3442311" +- queryParams `GetEnterpriseConfigurationByIdV2025R0QueryParams` + - Query parameters of getEnterpriseConfigurationByIdV2025R0 method +- headers `GetEnterpriseConfigurationByIdV2025R0Headers` + - Headers of getEnterpriseConfigurationByIdV2025R0 method + + +### Returns + +This function returns a value of type `EnterpriseConfigurationV2025R0`. + +Returns the enterprise configuration. + + diff --git a/docs/events.md b/docs/events.md new file mode 100644 index 000000000..c826a9814 --- /dev/null +++ b/docs/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](https://developer.box.com/reference/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](https://developer.box.com/reference/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/eventstream.md b/docs/eventstream.md new file mode 100644 index 000000000..a91eef21f --- /dev/null +++ b/docs/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/externalusers.md b/docs/externalusers.md new file mode 100644 index 000000000..295e94197 --- /dev/null +++ b/docs/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/fileclassifications.md b/docs/fileclassifications.md new file mode 100644 index 000000000..dd386ad46 --- /dev/null +++ b/docs/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/filemetadata.md b/docs/filemetadata.md new file mode 100644 index 000000000..2ccd505b5 --- /dev/null +++ b/docs/filemetadata.md @@ -0,0 +1,198 @@ +# 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" +- queryParams `GetFileMetadataQueryParams` + - Query parameters of getFileMetadata method +- 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" +- queryParams `GetFileMetadataByIdQueryParams` + - Query parameters of getFileMetadataById method +- 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/filerequests.md b/docs/filerequests.md new file mode 100644 index 000000000..169912eb5 --- /dev/null +++ b/docs/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/files.md b/docs/files.md new file mode 100644 index 000000000..38d3faa2f --- /dev/null +++ b/docs/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](#parameter-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](#parameter-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](#parameter-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/fileversionlegalholds.md b/docs/fileversionlegalholds.md new file mode 100644 index 000000000..eecfa32cb --- /dev/null +++ b/docs/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/fileversionretentions.md b/docs/fileversionretentions.md new file mode 100644 index 000000000..a8bc10052 --- /dev/null +++ b/docs/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](https://developer.box.com/reference/get-retention-policy-assignments-id-files-under-retention) or [file versions under retention](https://developer.box.com/reference/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](https://developer.box.com/reference/get-retention-policy-assignments-id-files-under-retention) or [file versions under retention](https://developer.box.com/reference/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/fileversions.md b/docs/fileversions.md new file mode 100644 index 000000000..9bbdd3a01 --- /dev/null +++ b/docs/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](#parameter-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/filewatermarks.md b/docs/filewatermarks.md new file mode 100644 index 000000000..fd94bbd8b --- /dev/null +++ b/docs/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/folderclassifications.md b/docs/folderclassifications.md new file mode 100644 index 000000000..5a887a3fb --- /dev/null +++ b/docs/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/folderlocks.md b/docs/folderlocks.md new file mode 100644 index 000000000..6c050d597 --- /dev/null +++ b/docs/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/foldermetadata.md b/docs/foldermetadata.md new file mode 100644 index 000000000..02bb0146e --- /dev/null +++ b/docs/foldermetadata.md @@ -0,0 +1,201 @@ +# 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" +- queryParams `GetFolderMetadataQueryParams` + - Query parameters of getFolderMetadata method +- 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/folders.md b/docs/folders.md new file mode 100644 index 000000000..2bfee2c40 --- /dev/null +++ b/docs/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](https://developer.box.com/reference/resources/folder--full#param-item-collection). + +To fetch more items within the folder, use the +[Get items in a folder](https://developer.box.com/reference/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](https://developer.box.com/reference/get-folders-id-items)) endpoint. + +Not all available fields are returned by default. Use the +[fields](#parameter-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](#parameter-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](https://developer.box.com/reference/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](#parameter-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](#parameter-fields) query parameter to explicitly request +any specific fields. + + diff --git a/docs/folderwatermarks.md b/docs/folderwatermarks.md new file mode 100644 index 000000000..323f45ef8 --- /dev/null +++ b/docs/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/groups.md b/docs/groups.md new file mode 100644 index 000000000..5e66b2d5f --- /dev/null +++ b/docs/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/hubcollaborations.md b/docs/hubcollaborations.md new file mode 100644 index 000000000..609b5e572 --- /dev/null +++ b/docs/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/hubdocument.md b/docs/hubdocument.md new file mode 100644 index 000000000..d4d45eb3a --- /dev/null +++ b/docs/hubdocument.md @@ -0,0 +1,69 @@ +# HubDocumentManager + + +- [List Hub Document Pages](#list-hub-document-pages) +- [List Hub Document blocks for page](#list-hub-document-blocks-for-page) + +## List Hub Document Pages + +Retrieves a list of Hub Document Pages for the specified hub. +Includes both root-level pages and sub pages. + +This operation is performed by calling function `getHubDocumentPagesV2025R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2025.0/get-hub-document-pages/). + + +``` +client.getHubDocument().getHubDocumentPagesV2025R0(new GetHubDocumentPagesV2025R0QueryParams(hubId)) +``` + +### Arguments + +- queryParams `GetHubDocumentPagesV2025R0QueryParams` + - Query parameters of getHubDocumentPagesV2025R0 method +- headers `GetHubDocumentPagesV2025R0Headers` + - Headers of getHubDocumentPagesV2025R0 method + + +### Returns + +This function returns a value of type `HubDocumentPagesV2025R0`. + +Returns a Hub Document Pages response whose `entries` array contains root-level pages and sub pages. Includes pagination when more results are available. + + +## List Hub Document blocks for page + +Retrieves a sorted list of all Hub Document Blocks on a specified page in the hub document, excluding items. +Blocks are hierarchically organized by their `parent_id`. +Blocks are sorted in order based on user specification in the user interface. +The response will only include content blocks that belong to the specified page. This will not include sub pages or sub page content blocks. + +This operation is performed by calling function `getHubDocumentBlocksV2025R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2025.0/get-hub-document-blocks/). + + +``` +client.getHubDocument().getHubDocumentBlocksV2025R0(new GetHubDocumentBlocksV2025R0QueryParams(hubId, pageId)) +``` + +### Arguments + +- queryParams `GetHubDocumentBlocksV2025R0QueryParams` + - Query parameters of getHubDocumentBlocksV2025R0 method +- headers `GetHubDocumentBlocksV2025R0Headers` + - Headers of getHubDocumentBlocksV2025R0 method + + +### Returns + +This function returns a value of type `HubDocumentBlocksV2025R0`. + +Returns a Hub Document Blocks response whose `entries` array contains all content blocks of the specified page, except for items. +To retrieve items, use the `GET /hub_items` endpoint. + + diff --git a/docs/hubitems.md b/docs/hubitems.md new file mode 100644 index 000000000..b826422e4 --- /dev/null +++ b/docs/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/hubs.md b/docs/hubs.md new file mode 100644 index 000000000..45f7182e6 --- /dev/null +++ b/docs/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/integrationmappings.md b/docs/integrationmappings.md new file mode 100644 index 000000000..d05be5194 --- /dev/null +++ b/docs/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/invites.md b/docs/invites.md new file mode 100644 index 000000000..e1a89b263 --- /dev/null +++ b/docs/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/legalholdpolicies.md b/docs/legalholdpolicies.md new file mode 100644 index 000000000..dff0d51ef --- /dev/null +++ b/docs/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/legalholdpolicyassignments.md b/docs/legalholdpolicyassignments.md new file mode 100644 index 000000000..592003406 --- /dev/null +++ b/docs/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 an item type of: file, file version, folder, user, ownership, or interactions. + +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/listcollaborations.md b/docs/listcollaborations.md new file mode 100644 index 000000000..a3d691d3d --- /dev/null +++ b/docs/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/memberships.md b/docs/memberships.md new file mode 100644 index 000000000..39fd5df40 --- /dev/null +++ b/docs/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/metadatacascadepolicies.md b/docs/metadatacascadepolicies.md new file mode 100644 index 000000000..5542a8820 --- /dev/null +++ b/docs/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/metadatataxonomies.md b/docs/metadatataxonomies.md new file mode 100644 index 000000000..e9e23b048 --- /dev/null +++ b/docs/metadatataxonomies.md @@ -0,0 +1,519 @@ +# MetadataTaxonomiesManager + + +- [Create metadata taxonomy](#create-metadata-taxonomy) +- [Get metadata taxonomies for namespace](#get-metadata-taxonomies-for-namespace) +- [Get metadata taxonomy by taxonomy key](#get-metadata-taxonomy-by-taxonomy-key) +- [Update metadata taxonomy](#update-metadata-taxonomy) +- [Remove metadata taxonomy](#remove-metadata-taxonomy) +- [Create metadata taxonomy levels](#create-metadata-taxonomy-levels) +- [Update metadata taxonomy level](#update-metadata-taxonomy-level) +- [Add metadata taxonomy level](#add-metadata-taxonomy-level) +- [Delete metadata taxonomy level](#delete-metadata-taxonomy-level) +- [List metadata taxonomy nodes](#list-metadata-taxonomy-nodes) +- [Create metadata taxonomy node](#create-metadata-taxonomy-node) +- [Get metadata taxonomy node by ID](#get-metadata-taxonomy-node-by-id) +- [Update metadata taxonomy node](#update-metadata-taxonomy-node) +- [Remove metadata taxonomy node](#remove-metadata-taxonomy-node) +- [List metadata template's options for taxonomy field](#list-metadata-templates-options-for-taxonomy-field) + +## Create metadata taxonomy + +Creates a new metadata taxonomy that can be used in +metadata templates. + +This operation is performed by calling function `createMetadataTaxonomy`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-metadata-taxonomies/). + + +``` +client.getMetadataTaxonomies().createMetadataTaxonomy(new CreateMetadataTaxonomyRequestBody.Builder(displayName, namespace).key(taxonomyKey).build()) +``` + +### Arguments + +- requestBody `CreateMetadataTaxonomyRequestBody` + - Request body of createMetadataTaxonomy method +- headers `CreateMetadataTaxonomyHeaders` + - Headers of createMetadataTaxonomy method + + +### Returns + +This function returns a value of type `MetadataTaxonomy`. + +The schema representing the metadata taxonomy created. + + +## Get metadata taxonomies for namespace + +Used to retrieve all metadata taxonomies in a namespace. + +This operation is performed by calling function `getMetadataTaxonomies`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-metadata-taxonomies-id/). + + +``` +client.getMetadataTaxonomies().getMetadataTaxonomies(namespace) +``` + +### Arguments + +- namespace `String` + - The namespace of the metadata taxonomy. Example: "enterprise_123456" +- queryParams `GetMetadataTaxonomiesQueryParams` + - Query parameters of getMetadataTaxonomies method +- headers `GetMetadataTaxonomiesHeaders` + - Headers of getMetadataTaxonomies method + + +### Returns + +This function returns a value of type `MetadataTaxonomies`. + +Returns all of the metadata taxonomies within a namespace +and their corresponding schema. + + +## Get metadata taxonomy by taxonomy key + +Used to retrieve a metadata taxonomy by taxonomy key. + +This operation is performed by calling function `getMetadataTaxonomyByKey`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-metadata-taxonomies-id-id/). + + +``` +client.getMetadataTaxonomies().getMetadataTaxonomyByKey(namespace, taxonomyKey) +``` + +### Arguments + +- namespace `String` + - The namespace of the metadata taxonomy. Example: "enterprise_123456" +- taxonomyKey `String` + - The key of the metadata taxonomy. Example: "geography" +- headers `GetMetadataTaxonomyByKeyHeaders` + - Headers of getMetadataTaxonomyByKey method + + +### Returns + +This function returns a value of type `MetadataTaxonomy`. + +Returns the metadata taxonomy identified by the taxonomy key. + + +## Update metadata taxonomy + +Updates an existing metadata taxonomy. + +This operation is performed by calling function `updateMetadataTaxonomy`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/patch-metadata-taxonomies-id-id/). + + +``` +client.getMetadataTaxonomies().updateMetadataTaxonomy(namespace, taxonomyKey, new UpdateMetadataTaxonomyRequestBody(updatedDisplayName)) +``` + +### Arguments + +- namespace `String` + - The namespace of the metadata taxonomy. Example: "enterprise_123456" +- taxonomyKey `String` + - The key of the metadata taxonomy. Example: "geography" +- requestBody `UpdateMetadataTaxonomyRequestBody` + - Request body of updateMetadataTaxonomy method +- headers `UpdateMetadataTaxonomyHeaders` + - Headers of updateMetadataTaxonomy method + + +### Returns + +This function returns a value of type `MetadataTaxonomy`. + +The schema representing the updated metadata taxonomy. + + +## Remove metadata taxonomy + +Delete a metadata taxonomy. +This deletion is permanent and cannot be reverted. + +This operation is performed by calling function `deleteMetadataTaxonomy`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-metadata-taxonomies-id-id/). + + +``` +client.getMetadataTaxonomies().deleteMetadataTaxonomy(namespace, taxonomyKey) +``` + +### Arguments + +- namespace `String` + - The namespace of the metadata taxonomy. Example: "enterprise_123456" +- taxonomyKey `String` + - The key of the metadata taxonomy. Example: "geography" +- headers `DeleteMetadataTaxonomyHeaders` + - Headers of deleteMetadataTaxonomy method + + +### Returns + +This function returns a value of type `void`. + +Returns an empty response when the metadata taxonomy is successfully deleted. + + +## Create metadata taxonomy levels + +Creates new metadata taxonomy levels. + +This operation is performed by calling function `createMetadataTaxonomyLevel`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-metadata-taxonomies-id-id-levels/). + + +``` +client.getMetadataTaxonomies().createMetadataTaxonomyLevel(namespace, taxonomyKey, Arrays.asList(new MetadataTaxonomyLevel.Builder().displayName("Continent").description("Continent Level").build(), new MetadataTaxonomyLevel.Builder().displayName("Country").description("Country Level").build())) +``` + +### Arguments + +- namespace `String` + - The namespace of the metadata taxonomy. Example: "enterprise_123456" +- taxonomyKey `String` + - The key of the metadata taxonomy. Example: "geography" +- requestBody `List` + - Request body of createMetadataTaxonomyLevel method +- headers `CreateMetadataTaxonomyLevelHeaders` + - Headers of createMetadataTaxonomyLevel method + + +### Returns + +This function returns a value of type `MetadataTaxonomyLevels`. + +Returns an array of all taxonomy levels. + + +## Update metadata taxonomy level + +Updates an existing metadata taxonomy level. + +This operation is performed by calling function `updateMetadataTaxonomyLevelById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/patch-metadata-taxonomies-id-id-levels-id/). + + +``` +client.getMetadataTaxonomies().updateMetadataTaxonomyLevelById(namespace, taxonomyKey, 1L, new UpdateMetadataTaxonomyLevelByIdRequestBody.Builder("Continent UPDATED").description("Continent Level UPDATED").build()) +``` + +### Arguments + +- namespace `String` + - The namespace of the metadata taxonomy. Example: "enterprise_123456" +- taxonomyKey `String` + - The key of the metadata taxonomy. Example: "geography" +- levelIndex `long` + - The index of the metadata taxonomy level. Example: 1 +- requestBody `UpdateMetadataTaxonomyLevelByIdRequestBody` + - Request body of updateMetadataTaxonomyLevelById method +- headers `UpdateMetadataTaxonomyLevelByIdHeaders` + - Headers of updateMetadataTaxonomyLevelById method + + +### Returns + +This function returns a value of type `MetadataTaxonomyLevel`. + +The updated taxonomy level. + + +## Add metadata taxonomy level + +Creates a new metadata taxonomy level and appends it to the existing levels. +If there are no levels defined yet, this will create the first level. + +This operation is performed by calling function `addMetadataTaxonomyLevel`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-metadata-taxonomies-id-id-levels:append/). + + +``` +client.getMetadataTaxonomies().addMetadataTaxonomyLevel(namespace, taxonomyKey, new AddMetadataTaxonomyLevelRequestBody.Builder("Region").description("Region Description").build()) +``` + +### Arguments + +- namespace `String` + - The namespace of the metadata taxonomy. Example: "enterprise_123456" +- taxonomyKey `String` + - The key of the metadata taxonomy. Example: "geography" +- requestBody `AddMetadataTaxonomyLevelRequestBody` + - Request body of addMetadataTaxonomyLevel method +- headers `AddMetadataTaxonomyLevelHeaders` + - Headers of addMetadataTaxonomyLevel method + + +### Returns + +This function returns a value of type `MetadataTaxonomyLevels`. + +Returns an array of all taxonomy levels. + + +## Delete metadata taxonomy level + +Deletes the last level of the metadata taxonomy. + +This operation is performed by calling function `deleteMetadataTaxonomyLevel`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-metadata-taxonomies-id-id-levels:trim/). + + +``` +client.getMetadataTaxonomies().deleteMetadataTaxonomyLevel(namespace, taxonomyKey) +``` + +### Arguments + +- namespace `String` + - The namespace of the metadata taxonomy. Example: "enterprise_123456" +- taxonomyKey `String` + - The key of the metadata taxonomy. Example: "geography" +- headers `DeleteMetadataTaxonomyLevelHeaders` + - Headers of deleteMetadataTaxonomyLevel method + + +### Returns + +This function returns a value of type `MetadataTaxonomyLevels`. + +Returns an array of all taxonomy levels. + + +## List metadata taxonomy nodes + +Used to retrieve metadata taxonomy nodes based on the parameters specified. +Results are sorted in lexicographic order unless a `query` parameter is passed. +With a `query` parameter specified, results are sorted in order of relevance. + +This operation is performed by calling function `getMetadataTaxonomyNodes`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-metadata-taxonomies-id-id-nodes/). + + +``` +client.getMetadataTaxonomies().getMetadataTaxonomyNodes(namespace, taxonomyKey) +``` + +### Arguments + +- namespace `String` + - The namespace of the metadata taxonomy. Example: "enterprise_123456" +- taxonomyKey `String` + - The key of the metadata taxonomy. Example: "geography" +- queryParams `GetMetadataTaxonomyNodesQueryParams` + - Query parameters of getMetadataTaxonomyNodes method +- headers `GetMetadataTaxonomyNodesHeaders` + - Headers of getMetadataTaxonomyNodes method + + +### Returns + +This function returns a value of type `MetadataTaxonomyNodes`. + +Returns a list of the taxonomy nodes that match the specified parameters. + + +## Create metadata taxonomy node + +Creates a new metadata taxonomy node. + +This operation is performed by calling function `createMetadataTaxonomyNode`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/post-metadata-taxonomies-id-id-nodes/). + + +``` +client.getMetadataTaxonomies().createMetadataTaxonomyNode(namespace, taxonomyKey, new CreateMetadataTaxonomyNodeRequestBody("Europe", 1)) +``` + +### Arguments + +- namespace `String` + - The namespace of the metadata taxonomy. Example: "enterprise_123456" +- taxonomyKey `String` + - The key of the metadata taxonomy. Example: "geography" +- requestBody `CreateMetadataTaxonomyNodeRequestBody` + - Request body of createMetadataTaxonomyNode method +- headers `CreateMetadataTaxonomyNodeHeaders` + - Headers of createMetadataTaxonomyNode method + + +### Returns + +This function returns a value of type `MetadataTaxonomyNode`. + +The schema representing the taxonomy node created. + + +## Get metadata taxonomy node by ID + +Retrieves a metadata taxonomy node by its identifier. + +This operation is performed by calling function `getMetadataTaxonomyNodeById`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-metadata-taxonomies-id-id-nodes-id/). + + +``` +client.getMetadataTaxonomies().getMetadataTaxonomyNodeById(namespace, taxonomyKey, countryNode.getId()) +``` + +### Arguments + +- namespace `String` + - The namespace of the metadata taxonomy. Example: "enterprise_123456" +- taxonomyKey `String` + - The key of the metadata taxonomy. Example: "geography" +- nodeId `String` + - The identifier of the metadata taxonomy node. Example: "14d3d433-c77f-49c5-b146-9dea370f6e32" +- headers `GetMetadataTaxonomyNodeByIdHeaders` + - Headers of getMetadataTaxonomyNodeById method + + +### Returns + +This function returns a value of type `MetadataTaxonomyNode`. + +Returns the metadata taxonomy node that matches the identifier. + + +## Update metadata taxonomy node + +Updates an existing metadata taxonomy node. + +This operation is performed by calling function `updateMetadataTaxonomyNode`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/patch-metadata-taxonomies-id-id-nodes-id/). + + +``` +client.getMetadataTaxonomies().updateMetadataTaxonomyNode(namespace, taxonomyKey, countryNode.getId(), new UpdateMetadataTaxonomyNodeRequestBody.Builder().displayName("Poland UPDATED").build()) +``` + +### Arguments + +- namespace `String` + - The namespace of the metadata taxonomy. Example: "enterprise_123456" +- taxonomyKey `String` + - The key of the metadata taxonomy. Example: "geography" +- nodeId `String` + - The identifier of the metadata taxonomy node. Example: "14d3d433-c77f-49c5-b146-9dea370f6e32" +- requestBody `UpdateMetadataTaxonomyNodeRequestBody` + - Request body of updateMetadataTaxonomyNode method +- headers `UpdateMetadataTaxonomyNodeHeaders` + - Headers of updateMetadataTaxonomyNode method + + +### Returns + +This function returns a value of type `MetadataTaxonomyNode`. + +The schema representing the updated taxonomy node. + + +## Remove metadata taxonomy node + +Delete a metadata taxonomy node. +This deletion is permanent and cannot be reverted. +Only metadata taxonomy nodes without any children can be deleted. + +This operation is performed by calling function `deleteMetadataTaxonomyNode`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/delete-metadata-taxonomies-id-id-nodes-id/). + + +``` +client.getMetadataTaxonomies().deleteMetadataTaxonomyNode(namespace, taxonomyKey, countryNode.getId()) +``` + +### Arguments + +- namespace `String` + - The namespace of the metadata taxonomy. Example: "enterprise_123456" +- taxonomyKey `String` + - The key of the metadata taxonomy. Example: "geography" +- nodeId `String` + - The identifier of the metadata taxonomy node. Example: "14d3d433-c77f-49c5-b146-9dea370f6e32" +- headers `DeleteMetadataTaxonomyNodeHeaders` + - Headers of deleteMetadataTaxonomyNode method + + +### Returns + +This function returns a value of type `void`. + +Returns an empty response when the metadata taxonomy node is successfully deleted. + + +## List metadata template's options for taxonomy field + +Used to retrieve metadata taxonomy nodes which are available for the taxonomy field based +on its configuration and the parameters specified. +Results are sorted in lexicographic order unless a `query` parameter is passed. +With a `query` parameter specified, results are sorted in order of relevance. + +This operation is performed by calling function `getMetadataTemplateFieldOptions`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/get-metadata-templates-id-id-fields-id-options/). + + +``` +client.getMetadataTaxonomies().getMetadataTemplateFieldOptions(namespace, metadataTemplateKey, fieldKey) +``` + +### Arguments + +- namespace `String` + - The namespace of the metadata taxonomy. Example: "enterprise_123456" +- templateKey `String` + - The name of the metadata template. Example: "properties" +- fieldKey `String` + - The key of the metadata taxonomy field in the template. Example: "geography" +- queryParams `GetMetadataTemplateFieldOptionsQueryParams` + - Query parameters of getMetadataTemplateFieldOptions method +- headers `GetMetadataTemplateFieldOptionsHeaders` + - Headers of getMetadataTemplateFieldOptions method + + +### Returns + +This function returns a value of type `MetadataTaxonomyNodes`. + +Returns a list of the taxonomy nodes that match the specified parameters. + + diff --git a/docs/metadatatemplates.md b/docs/metadatatemplates.md new file mode 100644 index 000000000..e56609056 --- /dev/null +++ b/docs/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/notes.md b/docs/notes.md new file mode 100644 index 000000000..ab1f42981 --- /dev/null +++ b/docs/notes.md @@ -0,0 +1,34 @@ +# NotesManager + + +- [Convert content to Box Note](#convert-content-to-box-note) + +## Convert content to Box Note + +Creates a Box Note (`.boxnote` file) from supported source content. See the `content_format` field for supported formats. + +This operation is performed by calling function `createNoteConvertV2026R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2026.0/post-notes-convert/). + + +``` +client.getNotes().createNoteConvertV2026R0(new NotesConvertRequestBodyV2026R0.Builder(markdownContent, new FolderReferenceV2026R0("0"), noteName).contentFormat(NotesConvertRequestBodyV2026R0ContentFormatField.MARKDOWN).build()) +``` + +### Arguments + +- requestBody `NotesConvertRequestBodyV2026R0` + - Request body of createNoteConvertV2026R0 method +- headers `CreateNoteConvertV2026R0Headers` + - Headers of createNoteConvertV2026R0 method + + +### Returns + +This function returns a value of type `NotesConvertResponseV2026R0`. + +The note was created successfully. + + diff --git a/docs/query.md b/docs/query.md new file mode 100644 index 000000000..f5f73a3f4 --- /dev/null +++ b/docs/query.md @@ -0,0 +1,69 @@ +# QueryManager + + +- [Query for Box items](#query-for-box-items) +- [Create insights for Box items](#create-insights-for-box-items) + +## Query for Box items + +Runs a query to discover Box items using a logical predicate that can filter +across item fields and metadata templates. Results can be sorted, paginated, +and shaped to include additional item or metadata fields. + +This operation is performed by calling function `createQueryV2026R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2026.0/post-query/). + + +``` +client.getQuery().createQueryV2026R0(new QueryRequestBodyV2026R0.Builder(new QueryRequestBodyV2026R0QueryField.Builder(predicate).params(mapOf(entryOf("name", "John"), entryOf("age", 50))).ancestors(Arrays.asList(new QueryAncestorReferenceV2026R0("0", "folder"))).build()).limit(10).fields(Arrays.asList("box:item:name", searchFrom)).build()) +``` + +### Arguments + +- requestBody `QueryRequestBodyV2026R0` + - Request body of createQueryV2026R0 method +- headers `CreateQueryV2026R0Headers` + - Headers of createQueryV2026R0 method + + +### Returns + +This function returns a value of type `QueryResultsV2026R0`. + +Returns a paginated list of items matching the query. + + +## Create insights for Box items + +Computes aggregated metrics over Box items matching a query predicate. +Filters are applied first, followed by optional grouping, after which the +requested metrics (such as `sum`, `avg`, `min`, `max`, and `count`) are +computed for each resulting group or over the entire filtered dataset. + +This operation is performed by calling function `createQueryInsightV2026R0`. + +See the endpoint docs at +[API Reference](https://developer.box.com/reference/v2026.0/post-query-insights/). + + +``` +client.getQuery().createQueryInsightV2026R0(new QueryInsightsRequestBodyV2026R0(new QueryInsightsRequestBodyV2026R0QueryField.Builder(predicate).params(mapOf(entryOf("minAmount", 0))).ancestors(Arrays.asList(new QueryAncestorReferenceV2026R0("0", "folder"))).groupBy(Arrays.asList(new QueryInsightsGroupByV2026R0.Builder(String.join("", mdPrefix, ".category")).bucketLimit(5).build())).build(), metrics)) +``` + +### Arguments + +- requestBody `QueryInsightsRequestBodyV2026R0` + - Request body of createQueryInsightV2026R0 method +- headers `CreateQueryInsightV2026R0Headers` + - Headers of createQueryInsightV2026R0 method + + +### Returns + +This function returns a value of type `QueryInsightsV2026R0`. + +Returns the computed insight entries. + + diff --git a/docs/recentitems.md b/docs/recentitems.md new file mode 100644 index 000000000..bb76f26a4 --- /dev/null +++ b/docs/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/retentionpolicies.md b/docs/retentionpolicies.md new file mode 100644 index 000000000..e82f25545 --- /dev/null +++ b/docs/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/retentionpolicyassignments.md b/docs/retentionpolicyassignments.md new file mode 100644 index 000000000..3ebfe1e50 --- /dev/null +++ b/docs/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/search.md b/docs/search.md new file mode 100644 index 000000000..be7116fff --- /dev/null +++ b/docs/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/sessiontermination.md b/docs/sessiontermination.md new file mode 100644 index 000000000..72f701acf --- /dev/null +++ b/docs/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/sharedlinksappitems.md b/docs/sharedlinksappitems.md new file mode 100644 index 000000000..434a25ad7 --- /dev/null +++ b/docs/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/sharedlinksfiles.md b/docs/sharedlinksfiles.md new file mode 100644 index 000000000..2503d0c77 --- /dev/null +++ b/docs/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/sharedlinksfolders.md b/docs/sharedlinksfolders.md new file mode 100644 index 000000000..7119c05ec --- /dev/null +++ b/docs/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/sharedlinksweblinks.md b/docs/sharedlinksweblinks.md new file mode 100644 index 000000000..e192a73fb --- /dev/null +++ b/docs/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/shieldinformationbarrierreports.md b/docs/shieldinformationbarrierreports.md new file mode 100644 index 000000000..542409705 --- /dev/null +++ b/docs/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/shieldinformationbarriers.md b/docs/shieldinformationbarriers.md new file mode 100644 index 000000000..fe561fbb7 --- /dev/null +++ b/docs/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/shieldinformationbarriersegmentmembers.md b/docs/shieldinformationbarriersegmentmembers.md new file mode 100644 index 000000000..5ff9dd6c9 --- /dev/null +++ b/docs/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/shieldinformationbarriersegmentrestrictions.md b/docs/shieldinformationbarriersegmentrestrictions.md new file mode 100644 index 000000000..ab9fbb2bc --- /dev/null +++ b/docs/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/shieldinformationbarriersegments.md b/docs/shieldinformationbarriersegments.md new file mode 100644 index 000000000..99af74127 --- /dev/null +++ b/docs/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/shieldlists.md b/docs/shieldlists.md new file mode 100644 index 000000000..0be407ce9 --- /dev/null +++ b/docs/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/signrequests.md b/docs/signrequests.md new file mode 100644 index 000000000..d6dfcf408 --- /dev/null +++ b/docs/signrequests.md @@ -0,0 +1,156 @@ +# 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" +- requestBody `SignRequestCancelRequest` + - Request body of cancelSignRequest method +- 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/signtemplates.md b/docs/signtemplates.md new file mode 100644 index 000000000..7c4c1e878 --- /dev/null +++ b/docs/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/skills.md b/docs/skills.md new file mode 100644 index 000000000..8fb35a51d --- /dev/null +++ b/docs/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/storagepolicies.md b/docs/storagepolicies.md new file mode 100644 index 000000000..552cdd5ed --- /dev/null +++ b/docs/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/storagepolicyassignments.md b/docs/storagepolicyassignments.md new file mode 100644 index 000000000..a28a8a554 --- /dev/null +++ b/docs/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/taskassignments.md b/docs/taskassignments.md new file mode 100644 index 000000000..bd90913c9 --- /dev/null +++ b/docs/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/tasks.md b/docs/tasks.md new file mode 100644 index 000000000..2f11bf40b --- /dev/null +++ b/docs/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/termsofservices.md b/docs/termsofservices.md new file mode 100644 index 000000000..700ef5a6c --- /dev/null +++ b/docs/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/termsofserviceuserstatuses.md b/docs/termsofserviceuserstatuses.md new file mode 100644 index 000000000..3a2fa17df --- /dev/null +++ b/docs/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/transfer.md b/docs/transfer.md new file mode 100644 index 000000000..38fae1a6a --- /dev/null +++ b/docs/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/trashedfiles.md b/docs/trashedfiles.md new file mode 100644 index 000000000..46482f699 --- /dev/null +++ b/docs/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`](https://developer.box.com/reference/get-folders-id-trash) API. + +To list all items that have been moved to the trash, please +use the [`GET /folders/trash/items`](https://developer.box.com/reference/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/trashedfolders.md b/docs/trashedfolders.md new file mode 100644 index 000000000..c993858fc --- /dev/null +++ b/docs/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`](https://developer.box.com/reference/get-folders-id-trash) API. + +To list all items that have been moved to the trash, please +use the [`GET /folders/trash/items`](https://developer.box.com/reference/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/trasheditems.md b/docs/trasheditems.md new file mode 100644 index 000000000..d48d50648 --- /dev/null +++ b/docs/trasheditems.md @@ -0,0 +1,44 @@ +# 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. + +The number of entries returned may be less than `total_count`. For example, if a user deletes items from a shared folder and is later removed as a collaborator, those deleted items will no longer appear in this endpoint’s results, even though they are still included in `total_count`. + +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/trashedweblinks.md b/docs/trashedweblinks.md new file mode 100644 index 000000000..6a3e4b919 --- /dev/null +++ b/docs/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/uploads.md b/docs/uploads.md new file mode 100644 index 000000000..a3eb4721f --- /dev/null +++ b/docs/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/usercollaborations.md b/docs/usercollaborations.md new file mode 100644 index 000000000..b3bdaa50c --- /dev/null +++ b/docs/usercollaborations.md @@ -0,0 +1,146 @@ +# 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. In case of accepting collaboration invite, role is not required. + +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.Builder().role(UpdateCollaborationByIdRequestBodyRoleField.VIEWER).build()) +``` + +### 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, field `name` is redacted when: +- a collaboration was created using `user_id`, +- 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/users.md b/docs/users.md new file mode 100644 index 000000000..3eb493ae0 --- /dev/null +++ b/docs/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](#parameter-fields) query parameter to explicitly request +any specific fields using the [fields](#parameter-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 operation fails if the user +still owns any content. +To proceed, move their owned content first, or use the `force` parameter 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/webhooks.md b/docs/webhooks.md new file mode 100644 index 000000000..06989090a --- /dev/null +++ b/docs/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/weblinks.md b/docs/weblinks.md new file mode 100644 index 000000000..14e0cefdb --- /dev/null +++ b/docs/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/workflows.md b/docs/workflows.md new file mode 100644 index 000000000..f3ca3b98b --- /dev/null +++ b/docs/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/zipdownloads.md b/docs/zipdownloads.md new file mode 100644 index 000000000..085ba3384 --- /dev/null +++ b/docs/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](https://developer.box.com/reference/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](https://developer.box.com/reference/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/gradle.properties b/gradle.properties new file mode 100644 index 000000000..384f02a41 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,15 @@ +libraryJavaVersion=1.8 +spotlessVersion=6.2.0 +jacksonAnnotationVersion=2.21 +jacksonCoreVersion=2.21.4 +jacksonDatabindVersion=2.21.4 +okhttpVersion=4.12.0 +okioVersion=3.5.0 +jose4jVersion=0.9.6 +bouncyCastleBcprovJdk18onVersion=1.84 +bouncyCastleBcpkixJdk18onVersion=1.84 +junitApiVersion=5.10.0 +junitEngineVersion=5.10.0 +googleJavaFormatVersion=1.7 +coverallsJacocoVersion=1.2.14 +testRetryVersion=1.5.6 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..a4b76b953 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..0aaefbcaf --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 000000000..f5feea6d6 --- /dev/null +++ b/gradlew @@ -0,0 +1,252 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 000000000..9b42019c7 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/migration-guides/from-box-java-sdk-gen-v0-to-box-java-sdk.md b/migration-guides/from-box-java-sdk-gen-v0-to-box-java-sdk.md new file mode 100644 index 000000000..33d6b8bc0 --- /dev/null +++ b/migration-guides/from-box-java-sdk-gen-v0-to-box-java-sdk.md @@ -0,0 +1,248 @@ +# Migration guide from beta release (v0.X.Y) of the `box-java-sdk-gen` to the `box-java-sdk` + +Note: This guide applies only to migrations targeting Box Java SDK v5.X.Y or v10.X.Y. +It does not apply to other major versions (e.g., v6.X, v11.X). + + + + +- [Introduction](#introduction) +- [Installation](#installation) + - [How to migrate](#how-to-migrate) + - [Maven](#maven) + - [Gradle](#gradle) +- [Union classes name changes](#union-classes-name-changes) + - [How to migrate](#how-to-migrate-1) +- [Removed unused models from schemas namespace](#removed-unused-models-from-schemas-namespace) + - [How to migrate](#how-to-migrate-2) +- [Usage](#usage) + - [Using the Box Java SDK v10](#using-the-box-java-sdk-v10) + - [Using the Box Java SDK v5](#using-the-box-java-sdk-v5) + + + +## Introduction + +From the `box-java-sdk-gen` you can migrate either to v5 or v10 of the Box Java SDK. +Your choice should depend on whether you want to continue using the manually maintained SDK (Box Java SDK v4) alongside the generated one or not. + +The v5 version of the Box Java SDK consolidates both the legacy SDK package `com.box.sdk` and the generated one `com.box.sdkgen`. + +- If previously you were using both artifacts `box-java-sdk` v4 and `box-java-sdk-gen` v0, migrate to v5 version of the Box Java SDK which consolidates `com.box.sdk` and `com.box.sdkgen` packages. +- If you were only using the generated artifact `box-java-sdk-gen`, migrate to v10 version of the Box Java SDK which contains only the generated `com.box.sdkgen` package. + +| Scenario | Your current usage | Recommended target | Packages included in target | Why this choice | Notes | +| -------------------------------------------- | ---------------------------------------------------------- | ------------------ | ----------------------------------------------------- | ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | +| Using both manual and generated SDK together | `com.box.sdk` v4 + `com.box.sdkgen` v0 in the same project | v5.X.Y | `com.box.sdk` (manual) + `com.box.sdkgen` (generated) | Keep existing v4 code while adopting new features from the generated SDK | Run both modules side by side; use type aliases to avoid name conflicts if necessary | +| Using only the generated SDK | `com.box.sdkgen` v0 only | v10.X.Y | `com.box.sdkgen` (generated) only | Clean upgrade path with no legacy module; simpler dependency surface | Best when you don’t need the manual `com.box.sdk` package | + +## Installation + +In order to start using v5 or v10 version of the Box Java SDK, you need to change the dependency in your project. +The artifact name has changed from `com.box:box-java-sdk-gen` to `com.box:box-java-sdk`. +You also need to set the version to `5.X.Y` if you are migrating to v5 or `10.X.Y` if you are migrating to v10. +You can find the latest version on [Maven Central](https://search.maven.org/artifact/com.box/box-java-sdk). + +### How to migrate + +#### Maven + +To start using v5 or v10 version of Box Java SDK in your Maven project replace the dependency in your `pom.xml` file. + +**Old (`box-java-sdk-gen-v0`)** + +```xml + + com.box + box-java-sdk-gen + 0.8.0 + +``` + +**New (`box-java-sdk-v10`)** + +```xml + + com.box + box-java-sdk + 10.0.0 + +``` + +**New (`box-java-sdk-v5`)** + +```xml + + com.box + box-java-sdk + 5.0.0 + +``` + +#### Gradle + +To start using v5 or v10 version of Box Java SDK in your Gradle project replace the dependency in your `build.gradle` file. + +**Old (`box-java-sdk-gen-v0`)** + +```groovy +implementation 'com.box:box-java-sdk-gen:0.8.0' +``` + +**New (`box-java-sdk-v10`)** + +```groovy +implementation 'com.box:box-java-sdk:10.0.0' +``` + +**New (`box-java-sdk-v5`)** + +```groovy +implementation 'com.box:box-java-sdk:5.0.0' +``` + +## Union classes name changes + +In the beta version of the `box-java-sdk-gen` our `OneOf` class names (representing unions from the OpenAPI specification) +were fully auto-generated based on the included variants. This often resulted in overly long names that were difficult +to work with in tools like Git. For example: `MetadataFieldFilterDateRangeOrMetadataFieldFilterFloatRangeOrArrayOfStringOrNumberOrString`. +Additionally, every time the new variant was added to the `OneOf`, the class name itself changed. +Starting in v10, the names of `OneOf` classes are defined directly in the specification. This ensures that they are meaningful, short, and stable over time. + +### How to migrate + +If your code references any of the renamed classes, replace the old name with the new one. +If you were not explicitly using the type names, no changes are needed, since only the class names changed and their behavior remains the same. + +List of changed `OneOf` classes and types associated with them: + +| Old name | New name | +| ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------ | +| AiAgentAskOrAiAgentExtractOrAiAgentExtractStructuredOrAiAgentTextGen | AiAgent | +| AiAgentAskOrAiAgentReference | AiAskAgent | +| AiAgentExtractOrAiAgentReference | AiExtractAgent | +| AiAgentExtractStructuredOrAiAgentReference | AiExtractStructuredAgent | +| AiAgentReferenceOrAiAgentTextGen | AiTextGenAgent | +| AppItemEventSourceOrEventSourceOrFileOrFolderOrGenericSourceOrUser | EventSourceResource | +| FileBaseOrFolderBaseOrWebLinkBase | AppItemAssociatedItem | +| FileFullOrFolderFull | MetadataQueryResultItem | +| FileFullOrFolderFullOrWebLink | SearchResultWithSharedLinkItem/RecentItemResource/SearchResultItem | +| FileFullOrFolderMiniOrWebLink | Item | +| FileMiniOrFolderMini | Resource | +| FileOrFolderOrWebLink | LegalHoldPolicyAssignedItem/CollaborationItem | +| FileOrFolderScope | ResourceScope | +| FileOrFolderScopeScopeField | ResourceScopeScopeField | +| FileReferenceOrFolderReferenceOrWeblinkReferenceV2025R0 | HubItemReferenceV2025R0 | +| GroupMiniOrUserCollaborations | CollaborationAccessGrantee | +| IntegrationMappingPartnerItemSlackUnion | IntegrationMappingPartnerItemSlack | +| IntegrationMappingPartnerItemTeamsUnion | IntegrationMappingPartnerItemTeams | +| KeywordSkillCardOrStatusSkillCardOrTimelineSkillCardOrTranscriptSkillCard | SkillCard | +| MetadataFieldFilterDateRangeOrMetadataFieldFilterFloatRangeOrArrayOfStringOrNumberOrString | MetadataFilterValue | +| SearchResultsOrSearchResultsWithSharedLinks | SearchResultsResponse | + +Some classes were split into multiple ones depending on context. + +Manager functions affected by these changes: + +| Function | Old return type | New return type | +| -------------------------------------- | -------------------------------------------------------------------- | --------------------- | +| AiManager.getAiAgentDefaultConfig(...) | AiAgentAskOrAiAgentExtractOrAiAgentExtractStructuredOrAiAgentTextGen | AiAgent | +| SearchManager.searchForContent(...) | SearchResultsOrSearchResultsWithSharedLinks | SearchResultsResponse | + +## Removed unused models from schemas namespace + +Several unused types (classes and enums) have been removed from the schemas because they were not used by any SDK functions or by the Box API. + +### How to migrate + +Here is the full list of removed types: + +| Removed classes/enums | +| ------------------------------------------ | +| FileOrFolder | +| HubActionV2025R0 | +| MetadataQueryIndex | +| MetadataQueryIndexFieldsField | +| MetadataQueryIndexFieldsSortDirectionField | +| MetadataQueryIndexStatusField | +| RetentionPolicyAssignmentBase | +| RetentionPolicyAssignmentBaseTypeField | +| SkillInvocation | +| SkillInvocationEnterpriseField | +| SkillInvocationEnterpriseTypeField | +| SkillInvocationSkillField | +| SkillInvocationSkillTypeField | +| SkillInvocationStatusField | +| SkillInvocationStatusStateField | +| SkillInvocationTokenField | +| SkillInvocationTokenReadField | +| SkillInvocationTokenReadTokenTypeField | +| SkillInvocationTokenWriteField | +| SkillInvocationTokenWriteTokenTypeField | +| SkillInvocationTypeField | +| WebhookInvocation | +| WebhookInvocationTriggerField | +| WebhookInvocationTypeField | +| WorkflowFull | + +If your code references any of these types, remove those references. + +## Usage + +### Using the Box Java SDK v10 + +After migration from `box-java-sdk-gen` to the `box-java-sdk` v10, you can still use the `com.box.sdkgen` package in the same way as before. +To access the client for interacting with the Box API, simply import `BoxClient` and any other necessary classes from the `com.box.sdkgen` package. + +```java +import com.box.sdkgen.client.BoxClient; +import com.box.sdkgen.box.developertokenauth.BoxDeveloperTokenAuth; + +BoxDeveloperTokenAuth auth = new BoxDeveloperTokenAuth("DEVELOPER_TOKEN"); +BoxClient client = new BoxClient(auth); +client.folders.getFolderItems("0").getEntries().forEach(item -> { + System.out.println(item.toString()); + }); +``` + +### Using the Box Java SDK v5 + +After migration to Box Java SDK v5, you can use both the manual Box Java SDK package `com.box.sdk` and the generated one `com.box.sdkgen`. +You just need to import the required classes from the appropriate package depending on which SDK you intend to use. +If both packages contain classes with the same name, you can use fully qualified names to resolve any naming conflicts. + +```java +import com.box.sdk.BoxConfig; +import com.box.sdk.BoxDeveloperEditionAPIConnection; + +import com.box.sdk.BoxFolder; +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.folders.UpdateFolderByIdRequestBody; +import com.box.sdkgen.schemas.folder.Folder; + +import java.io.FileReader; +import java.io.Reader; + +public class Main { + public static void main(String[] args) throws Exception { + + Reader reader = new FileReader("src/example/config/config.json"); + BoxConfig boxConfig = BoxConfig.readFrom(reader); + BoxDeveloperEditionAPIConnection api = BoxDeveloperEditionAPIConnection.getAppEnterpriseConnection(boxConfig); + + JWTConfig config = JWTConfig.fromConfigFile("src/example/config/config.json"); + BoxJWTAuth auth = new BoxJWTAuth(config); + BoxClient client = new BoxClient(auth); + + BoxFolder rootFolder = new BoxFolder(api, "0"); + BoxFolder.Info subfolder = rootFolder.createFolder("My Subfolder"); + Folder updatedFolder = client.getFolders().updateFolderById( + subfolder.getID(), + new UpdateFolderByIdRequestBody.Builder().name("My Updated Subfolder").build() + ); + System.out.println("Created folder with ID " + subfolder.getID() + " has been updated to " + updatedFolder.getName()); + } +} +``` diff --git a/migration-guides/from-com-box-sdk-to-com-box-sdkgen.md b/migration-guides/from-com-box-sdk-to-com-box-sdkgen.md new file mode 100644 index 000000000..54e72aa20 --- /dev/null +++ b/migration-guides/from-com-box-sdk-to-com-box-sdkgen.md @@ -0,0 +1,685 @@ +# Migration guide: migrate from `com.box.sdk` to `com.box.sdkgen` package + + + + +- [Introduction](#introduction) + - [Who is this for?](#who-is-this-for) +- [Key differences](#key-differences) + - [Manager approach](#manager-approach) + - [Immutable design](#immutable-design) + - [Consistent method signature](#consistent-method-signature) +- [Authentication](#authentication) + - [Developer Token](#developer-token) + - [JWT Auth](#jwt-auth) + - [Using JWT configuration file](#using-jwt-configuration-file) + - [Providing JWT configuration manually](#providing-jwt-configuration-manually) + - [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) + - [Get Authorization URL](#get-authorization-url) + - [Authenticate](#authenticate) + - [Store token and retrieve token callbacks](#store-token-and-retrieve-token-callbacks) + - [Downscope token](#downscope-token) + - [Revoke token](#revoke-token) +- [Configuration](#configuration) + - [As-User header](#as-user-header) + - [Custom Base URLs](#custom-base-urls) +- [Convenience methods](#convenience-methods) + - [Webhook validation](#webhook-validation) + - [Chunked upload of big files](#chunked-upload-of-big-files) + + + +## Introduction + +Version availability: + +- v4: ships only `com.box.sdk` package +- v5: ships both `com.box.sdk` and `com.box.sdkgen` packages (side-by-side) +- v10+: ships only `com.box.sdkgen` module + +This document focuses on helping you migrate code from the manually maintained `com.box.sdk` package to the generated `com.box.sdkgen` package. +Many APIs were redesigned for consistency and modern Java patterns, so this guide calls out how to adopt the new shapes safely and incrementally. + +Supported migration paths: + +- v4 → v5: adopt `com.box.sdkgen` gradually while keeping existing `com.box.sdk` usage +- v4 → v10+: migrate directly to `com.box.sdkgen` package only +- v5 (within the same version): move usage from `com.box.sdk` to `com.box.sdkgen` gradually + +For comprehensive API docs with sample code for all methods, see the repository documentation in the root `docs` directory: [`docs/`](../docs/). + +We recommend using `com.box.sdkgen` as the preferred SDK going forward. This SDK is automatically generated from the +Box OpenAPI specification, ensuring consistency, reliability, and full API coverage. + +Key Benefits: + +- Comprehensive Coverage: Supports all Box API endpoints with consistent and predictable method signatures. +- Rapid Feature Availability: Automatically includes new features as soon as they are released in the Box API. +- Explicit Data Models: Includes clear, well-defined models for all API resources to improve readability and maintainability. +- Immutable Design: Built for immutability, making code behavior more predictable and easier to reason about. +- Rich Documentation: Offers detailed usage examples for every API method to help developers get started quickly. + +### Who is this for? + +- Developers with existing code using `com.box.sdk` who want to start using `com.box.sdkgen` APIs. +- Developers using v5 of Box Java SDK that want to transition usage from `com.box.sdk` to `com.box.sdkgen` within the same app. + +## Key differences + +### Manager approach + +The main difference between the manual `com.box.sdk` package and the nextgen generated one, +is the way how API methods are aggregated into objects. + +**Old (`com.box.sdk`)** + +Firstly, in the `com.box.sdk` to be able to perform any action on an API object, e.g. `User`, you first had to create its class. +To do it is required to call: + +```java +BoxUser user = new BoxUser(api, "12345"); +``` + +to create a class representing an already existing User with id '12345', or create a new one with a call: + +```java +BoxUser.Info createdUserInfo = BoxUser.createAppUser(api, "A User"); +BoxUser user = new BoxUser(api, createdUserInfo.getID()); +``` + +Then, you could perform any action on created class, which will affect the user, e.g. + +```java +BoxUser.Info info = user.new Info(); +info.setName(name); +user.updateInfo(info); +``` + +**New (`com.box.sdkgen`)** + +In the `com.box.sdkgen` package, the API methods are grouped into dedicated manager classes, e.g. `User` object +has dedicated `UserManager` class. Each manager class instance is available in `BoxClient` object. +The fields storing references to the managers are named in the plural form of the resource that the +manager handles - `client.users` for `UsersManager`. If you want to perform any operation +connected with a `User` you need to call a respective method of `UserManager`. +For example, to get info about existing user you need to call: + +```java +UserFull user = client.users.getUsersById("12345"); +``` + +or to create a new user: + +```java +CreateUserRequestBody requestBody = + new CreateUserRequestBody.Builder("John Doe").build(); +UserFull user = client.users.createUser(requestBody); +``` + +The `UserFull` object returned by both of these methods is a data class - it does not contain any methods to call. +To perform any action on `User` object, you need to still use a `UserManager` method for that. +Usually these methods have a first argument, which accepts id of the object you want to access, +e.g. to update a user name, call method: + +```java +UpdateUserByIdRequestBody requestBody = + new UpdateUserByIdRequestBody.Builder().name("Mary").build(); +UserFull updatedUser = client.users.updateUserById(user.getId(), requestBody); +``` + +### Immutable design + +The `com.box.sdkgen` is designed to be mostly immutable. This means that methods, +which used to modify the existing object in `com.box.sdk` now return a new instance of the class with the modified state. +This design pattern is used to avoid side effects and make the code more predictable and easier to reason about. +Methods, which returns a new modified instance of an object, will always have a prefix `with` in their names, e.g. + +**New (`com.box.sdkgen`)** + +```java +BoxClient client = new BoxClient(auth); +BoxClient asUserClient = client.withAsUserHeader("USER_ID"); +``` + +### Consistent method signature + +To facilitate easier work with the new SDK, we have changed the API method signatures to be consistent and unified. + +**Old (`com.box.sdk`)** + +In the manual version, API methods had numerous parameters, which were not grouped into any objects and were passed as separate arguments, e.g. the method for creating a sign request looked like this: + +```java +public static BoxSignRequest.Info createSignRequest(BoxAPIConnection api, List sourceFiles, + List signers, String parentFolderId, + BoxSignRequestCreateParams optionalParams) +``` + +**New (`com.box.sdkgen`)** + +In `com.box.sdkgen`, we have adopted an approach of aggregating parameters into types based on their nature (path, body, query, headers). +This can be seen in the example corresponding to the above: + +```java +public SignRequest createSignRequest( + SignRequestCreateRequest requestBody, CreateSignRequestHeaders headers) +``` + +According to the convention, if an API endpoint requires a parameter placed in the URL path, +it will appear at the beginning of our method, such as `fileId` in this case. +When a request allows for a body, as in `POST` or `PUT`, the method includes a parameter named `requestBody`. +Following that, the method signature may include the `queryParams` parameter, followed by `headers`. +The types of parameters `requestBody`, `queryParams`, and `headers` are specific to each endpoint and, in their definition, +encompass all fields allowed by the API. +It's worth noting here that when all fields of a particular type are optional, the entire parameter becomes optional as well. +This allows us to pass only the parameters we actually want to provide when calling a given method, +without the risk of not providing a sufficient number of parameters. + +## Authentication + +The `com.box.sdkgen` package offers the same authentication methods as the `com.box.sdk` one. +Let's see the differences of their usage: + +### Developer Token + +**Old (`com.box.sdk`)** + +```java +BoxAPIConnection api = new BoxAPIConnection("YOUR-DEVELOPER-TOKEN"); +``` + +The `com.box.sdkgen` package provides a convenient `BoxDeveloperTokenAuth`, which allows authenticating +using developer token without necessity to provide a Client ID and Client Secret + +**New (`com.box.sdkgen`)** + +```java +BoxDeveloperTokenAuth auth = new BoxDeveloperTokenAuth("YOUR-DEVELOPER-TOKEN"); +BoxClient client = new BoxClient(auth); +``` + +### JWT Auth + +#### Using JWT configuration file + +**Old (`com.box.sdk`)** + +The static method, which reads the JWT configuration file has been changed: + +```java +Reader reader = new FileReader("src/example/config/config.json"); +BoxConfig boxConfig = BoxConfig.readFrom(reader); +IAccessTokenCache tokenCache = new InMemoryLRUAccessTokenCache(100); +BoxDeveloperEditionAPIConnection api = BoxDeveloperEditionAPIConnection.getAppEnterpriseConnection(boxConfig, tokenCache); +``` + +**New (`com.box.sdkgen`)** + +```java +TokenStorage tokenStorage = new InMemoryTokenStorage(); // or any other implementation of TokenStorage +JWTConfig config = JWTConfig.fromConfigFile("src/example/config/config.json", tokenStorage); +BoxJWTAuth auth = new BoxJWTAuth(config); +BoxClient client = new BoxClient(auth); +``` + +#### Providing JWT configuration manually + +Some params in `JWTConfig` constructor have slightly different names than one in old `JWTAuth` class. + +**Old (`com.box.sdk`)** + +```java +JWTEncryptionPreferences jwtPreferences = new JWTEncryptionPreferences(); +jwtPreferences.setPublicKeyID("PUBLIC-KEY-ID"); +jwtPreferences.setPrivateKeyPassword("PRIVATE-KEY-PASSWORD"); +jwtPreferences.setPrivateKey("PRIVATE-KEY"); +jwtPreferences.setEncryptionAlgorithm(EncryptionAlgorithm.RSA_SHA_256); + +IAccessTokenCache accessTokenCache = new InMemoryLRUAccessTokenCache(100); +BoxDeveloperEditionAPIConnection api = BoxDeveloperEditionAPIConnection + .getUserConnection("USER-ID", "CLIENT-ID","CLIENT-SECRET", jwtPreferences, accessTokenCache); + +BoxUser.Info userInfo = BoxUser.getCurrentUser(api).getInfo(); +``` + +**New (`com.box.sdkgen`)** + +```java +TokenStorage tokenStorage = new InMemoryTokenStorage(); +JWTConfig config = new JWTConfig.Builder("YOUR_CLIENT_ID", "YOUR_CLIENT_SECRET", "JWT_KEY_ID", "PRIVATE_KEY", "PRIVATE_KEY_PASSWORD") + .enterpriseId("123456") + .tokenStorage(tokenStorage) + .build(); +BoxJWTAuth auth = new BoxJWTAuth(config); +BoxClient client = new BoxClient(auth); +``` + +#### Authenticate user + +In `com.box.sdk` package method for user authentication was named `BoxDeveloperEditionAPIConnection getUserConnection(String userId, BoxConfig boxConfig, IAccessTokenCache accessTokenCache)` +and was accepting user id. The method was returning a new instance of `BoxDeveloperEditionAPIConnection` class, which was exchanging the existing token with the one with the user access. + +**Old (`com.box.sdk`)** + +```java +BoxDeveloperEditionAPIConnection api = BoxDeveloperEditionAPIConnection.getUserConnection("USER_ID", boxConfig, tokenCache); +``` + +**New (`com.box.sdkgen`)** + +In `com.box.sdkgen`, to authenticate as user you need to call +`public BoxJWTAuth withUserSubject(String userId, TokenStorage tokenStorage)` method with id of the user +to authenticate. The method returns a new instance of `BoxJWTAuth` class, which will perform authentication call +in scope of the user on the first API call. The `tokenStorage` parameter is optional and allows to provide a custom +token storage for the new instance of `BoxJWTAuth` class. The new auth instance can be used to create a new user client +instance. + +```java +BoxJWTAuth userAuth = auth.withUserSubject("USER_ID"); +BoxClient userClient = new BoxClient(userAuth); +``` + +### Client Credentials Grant + +#### Obtaining Service Account token + +To authenticate as enterprise, the only difference between `com.box.sdk` and `com.box.sdkgen` packages is using the `CCGConfig` as a middle step. + +**Old (`com.box.sdk`)** + +```java +BoxCCGAPIConnection api = BoxCCGAPIConnection.applicationServiceAccountConnection( + "client_id", + "client_secret", + "enterprise_id" +); +``` + +**New (`com.box.sdkgen`)** + +```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 + +To authenticate as user, the only difference between the versions is using the `CCGConfig` as a middle step. + +**Old (`com.box.sdk`)** + +```java +BoxCCGAPIConnection api = BoxCCGAPIConnection.userConnection( + "client_id", + "client_secret", + "user_id" +); +``` + +**New (`com.box.sdkgen`)** + +```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 + +In `com.box.sdk` package, if you want to switch between the Service Account and User, you need to create another API connection. + +In `com.box.sdkgen`, to keep the immutability design, the methods switching authenticated subject were replaced with methods +returning a new instance of `BoxCCGAuth` class. The new instance will fetch a new token on the next API call. +The new auth instance can be used to create a new client instance. You can also specify `tokenStorage` parameter +to provide a custom token storage for the new instance. +The old instance of `BoxCCGAuth` class will remain unchanged and will still use the old token. + +**New (`com.box.sdkgen`)** + +```java +BoxCCGAuth userAuth = auth.withUserSubject("USER_ID"); +BoxClient userClient = new BoxClient(userAuth); +``` + +```java +BoxCCGAuth entAuth = auth.withEnterpriseSubject("ENTERPRISE_ID"); +BoxClient entClient = new BoxClient(entAuth); +``` + +### OAuth 2.0 Auth + +#### Get Authorization URL + +To get authorization url in the `com.box.sdkgen` package, you need to first create the `BoxOAuth` class using +`OAuthConfig` class. Then to get authorization url, call `public String getAuthorizeUrl(GetAuthorizeUrlOptions options)`. +Note that this method accepts the instance of `GetAuthorizeUrlOptions` class, which allows specifying extra options to API call. + +**Old (`com.box.sdk`)** + +In `com.box.sdk`, we did not have any method to get the authorization URL. Instead, we had to manually create the URL. + +```java +String authorizationUrl = "https://account.box.com/api/oauth2/authorize?client_id=[CLIENT_ID]&response_type=code"; +``` + +**New (`com.box.sdkgen`)** + +```java +BoxOAuth auth = new BoxOAuth(new OAuthConfig.Builder("CLIENT_ID", "CLIENT_SECRET").build()); +String authorizationUrl = auth.getAuthorizeUrl(); +``` + +#### Authenticate + +The method for authenticating using the authorization code has been changed. With the `com.box.sdk` package of the SDK, +you had to provide the authorization code to the `BoxAPIConnection` class constructor. In the `com.box.sdkgen` package, +you need to call the `public AccessToken getTokensAuthorizationCodeGrant(String authorizationCode)` method of the `BoxOAuth` class. +The method now returns an AccessToken object with `accessToken` and `refreshToken` fields, +while the old one was creating a new instance of `BoxAPIConnection` class. + +**Old (`com.box.sdk`)** + +```java +BoxAPIConnection client = new BoxAPIConnection( + "[CLIENT_ID]", + "[CLIENT_SECRET]", + "[CODE]" +); +``` + +**New (`com.box.sdkgen`)** + +```java +auth.getTokensAuthorizationCodeGrant("AUTHORIZATION_CODE"); +BoxClient client = new BoxClient(auth); +``` + +### Store token and retrieve token callbacks + +In the `com.box.sdkgen` package you can define your own class delegated for storing and retrieving a token. It has to inherit from +`TokenStorage` and implement all of its abstract methods. Next step would be to pass an instance of this class to the +AuthConfig constructor. + +**New (`com.box.sdkgen`)** + +```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); +``` + +or reuse one of the provided implementations: `InMemoryTokenStorage`: + +```java +TokenStorage tokenStorage = new InMemoryTokenStorage(); +OAuthConfig config = new OAuthConfig.Builder("CLIENT_ID", "CLIENT_SECRET") + .tokenStorage(tokenStorage) + .build(); +BoxOAuth auth = new BoxOAuth(config); +``` + +### Downscope token + +The process of downscoping token in the new version is similar to the old one. The main difference is that in the new version +you need to call `downscopeToken` method of the `BoxOAuth` class instead of `getLowerScopedToken` method of the `BoxAPIConnection` class. + +**Old (`com.box.sdk`)** + +```java +BoxAPIConnection api = new BoxAPIConnection("YOUR-ACCESS-TOKEN"); + +String resource = "https://api.box.com/2.0/files/RESOURCE-ID"; +List scopes = new ArrayList(); +scopes.add("item_preview"); +scopes.add("item_content_upload"); + +ScopedToken token = api.getLowerScopedToken(scopes, resource); +``` + +**New (`com.box.sdkgen`)** + +```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); +``` + +### Revoke token + +To revoke current client's tokens in the `com.box.sdkgen` package, you need to call `revokeToken` method of the auth class instead of +`revoke` method. + +**Old (`com.box.sdk`)** + +```java +BoxAPIConnection api = new BoxAPIConnection("YOUR-ACCESS-TOKEN"); +api.revokeToken(); +``` + +**New (`com.box.sdkgen`)** + +```java +client.auth.revokeToken() +``` + +## Configuration + +### 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. The following examples assume that the client has +been instantiated with an access token with appropriate privileges to make As-User calls. + +In `com.box.sdk` package you could call client `asUser(String userID)` method to create a new client to impersonate the provided user. + +**Old (`com.box.sdk`)** + +```java +BoxAPIConnection api = new BoxAPIConnection("YOUR-ACCESS-TOKEN"); +api.asUser("USER-ID"); +``` + +**New (`com.box.sdkgen`)** + +In the new version, the method was renamed to `withAsUserHeader` in the `BoxClient` class, +and returns a new instance of `BoxClient` class with the As-User header appended to all API calls made by the client. +The method accepts only user id as a parameter. + +```java +BoxClient userClient = client.withAsUserHeader("USER-ID"); +``` + +Additionally `BoxClient` offers a `withExtraHeaders(Map extraHeaders)` +method, which allows you to 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 clientWithExtraHeaders = client.withExtraHeaders(new HashMap<>() {{ + put("X-My-Header", "124"); +}}); + +``` + +### Custom Base URLs + +**Old (`com.box.sdk`)** + +In `com.box.sdk` you could specify the custom base URLs, which will be used for API calls made by setting +the new values of static variables of the `API` class. + +```java +BoxAPIConnection api = new BoxAPIConnection("YOUR-DEVELOPER-TOKEN"); +api.setBaseAppUrl("https://example.app.com"); +api.setBaseURL("https://example.com"); +api.setUploadURL("https://upload.example.com"); +api.setTokenURL("https://example.com/token"); +``` + +**New (`com.box.sdkgen`)** + +In `com.box.sdkgen` this functionality has been implemented as part of the `BoxClient` class. +By calling the `client.withCustomBaseUrls()` method, you can specify the custom base URLs that will be used for API +calls made by client. Following the immutability pattern, this call 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); +``` + +## Convenience methods + +### Webhook validation + +Webhook validation is used to validate a webhook message by verifying the signature and the delivery timestamp. + +**Old (`com.box.sdk`)** + +In `com.box.sdk`, when you receive a webhook message from Box, to validate that it actually came from Box +you need to call `BoxWebHookSignatureVerifier#verify(String sigVersion, String sigAlgorithm, String primarySignature, String secondarySignature, String payload, String deliveryTimestamp)` method. +It would return a `boolean` value indicating whether the message was valid. + +```java +// Webhook message contents are shown for demonstration purposes +// Normally these would come from your HTTP handler + +// Webhook message HTTP body +String messagePayload = "{" ++ "\"type\":\"webhook_event"," ++ "\"webhook\":{" ++ "\"id\":\"1234567890\"" ++ "}," ++ "\"trigger\":\"FILE.UPLOADED\"," ++ "\"source\":{" ++ "\"id\":\"1234567890\"," ++ "\"type\":\"file\"," ++ "\"name\":\"Test.txt\"" ++ "}}"; + +// Webhook message HTTP headers +Map messageHeaders = new HashMap(); +headers.put("BOX-DELIVERY-ID", "f96bb54b-ee16-4fc5-aa65-8c2d9e5b546f"); +headers.put("BOX-DELIVERY-TIMESTAMP", "2020-01-01T00:00:00-07:00"); +headers.put("BOX-SIGNATURE-ALGORITHM", "HmacSHA256"); +headers.put("BOX-SIGNATURE-PRIMARY", "6TfeAW3A1PASkgboxxA5yqHNKOwFyMWuEXny/FPD5hI="); +headers.put("BOX-SIGNATURE-SECONDARY", "v+1CD1Jdo3muIcbpv5lxxgPglOqMfsNHPV899xWYydo="); +headers.put("BOX-SIGNATURE-VERSION", "1"); + +// Your application's webhook keys, obtained from the Box Developer Console +String primaryKey = "4py2I9eSFb0ezXH5iPeQRcFK1LRLCdip"; +String secondaryKey = "Aq5EEEjAu4ssbz8n9UMu7EerI0LKj2TL"; + +BoxWebHookSignatureVerifier verifier = new BoxWebHookSignatureVerifier(primaryKey, secondaryKey); +boolean isValidMessage = verifier.verify( + headers.get("BOX-SIGNATURE-VERSION"), + headers.get("BOX-SIGNATURE-ALGORITHM"), + headers.get("BOX-SIGNATURE-PRIMARY"), + headers.get("BOX-SIGNATURE-SECONDARY"), + messagePayload, + headers.get("BOX-DELIVERY-TIMESTAMP") +); +``` + +**New (`com.box.sdkgen`)** + +In the `com.box.sdkgen` package of ths SDK, the `WebhooksManager.validateMessage()` method requires the `messagePayload` to be of type `string`, +map of headers to be of type `Map`, and the primary and secondary keys to be of type `String`. + +```java +// Webhook message HTTP body +String messagePayload = "{" + + "\"type\":\"webhook_event"," + + "\"webhook\":{" + + "\"id\":\"1234567890\"" + + "}," + + "\"trigger\":\"FILE.UPLOADED\"," + + "\"source\":{" + + "\"id\":\"1234567890\"," + + "\"type\":\"file\"," + + "\"name\":\"Test.txt\"" + + "}}"; + +// Webhook message HTTP headers +Map messageHeaders = new HashMap(); +headers.put("BOX-DELIVERY-ID", "f96bb54b-ee16-4fc5-aa65-8c2d9e5b546f"); +headers.put("BOX-DELIVERY-TIMESTAMP", "2020-01-01T00:00:00-07:00"); +headers.put("BOX-SIGNATURE-ALGORITHM", "HmacSHA256"); +headers.put("BOX-SIGNATURE-PRIMARY", "6TfeAW3A1PASkgboxxA5yqHNKOwFyMWuEXny/FPD5hI="); +headers.put("BOX-SIGNATURE-SECONDARY", "v+1CD1Jdo3muIcbpv5lxxgPglOqMfsNHPV899xWYydo="); +headers.put("BOX-SIGNATURE-VERSION", "1"); + +// Your application's webhook keys, obtained from the Box Developer Console +String primaryKey = "4py2I9eSFb0ezXH5iPeQRcFK1LRLCdip"; +String secondaryKey = "Aq5EEEjAu4ssbz8n9UMu7EerI0LKj2TL"; + +boolean isValidMessage = WebhooksManager.validateMessage( + messagePayload, messageHeaders, primaryKey, secondaryKey); +) +``` + +### Chunked upload of big files + +For large files or in cases where the network connection is less reliable, you may want to upload the file in parts. +This allows a single part to fail without aborting the entire upload, and failed parts are being retried automatically. + +**Old (`com.box.sdk`)** + +In `com.box.sdk`, you could use the `uploadLargeFile` method of the `BoxFolder` class to upload a large file. +This method accepted a `FileInputStream` as the input stream and the file size as a parameter. The method also required + +```java +File myFile = new File("My Large_File.txt"); +FileInputStream stream = new FileInputStream(myFile); + +BoxFolder rootFolder = BoxFolder.getRootFolder(api); +BoxFile.Info fileInfo = rootFolder.uploadLargeFile(inputStream, "My_Large_File.txt", myFile.length()); +``` + +**New (`com.box.sdkgen`)** + +In `com.box.sdkgen`, the equivalent method is `chunked_uploads.uploadBigFile()`. It accepts a file-like object +as the `file` parameter, and the `fileName` and `fileSize` parameters are now passed as arguments. +The `parentFolderId` parameter is also required to specify the folder where the file will be uploaded. + +```java +InputStream file = new FileInputStream(myFile); +String fileName = "My_Large_File.txt"; +long fileSize = 1234556L; +String parentFolderId = "123456789"; + +File uploadedFile = client.getChunkedUploads().uploadBigFile(file, fileName, fileSize, parentFolderId); +``` diff --git a/migration-guides/from-v3-to-v4.md b/migration-guides/from-v3-to-v4.md new file mode 100644 index 000000000..5bcf2f164 --- /dev/null +++ b/migration-guides/from-v3-to-v4.md @@ -0,0 +1,243 @@ +# Migration guide for versions 3.x.x -> 4.x.x + + + + +- [Configuration changes](#configuration-changes) + - [BoxDeveloperEditionAPIConnection](#boxdevelopereditionapiconnection) + - [MaxRequestAttempts](#maxrequestattempts) +- [Removed deprecated methods and classes](#removed-deprecated-methods-and-classes) +- [Replaced methods and classes](#replaced-methods-and-classes) + - [Shared links](#shared-links) + - [Retention Policies](#retention-policies) + - [Enterprise Events](#enterprise-events) + - [Search](#search) + - [BoxGroup](#boxgroup) + - [MetadataTemplate](#metadatatemplate) + - [Others](#others) + + + +The most important change this release includes is the replacement of the HTTP library from a native one to +OkHttp which allows SDK to: + +- Support the HTTP2 version of the HTTP protocol. +- Support proxies that do not use only basic authentication method. For details on creating custom proxy authenticators and an example of + NTLM proxy authentication, see [here](https://github.com/box/box-java-sdk/blob/kb/ok-http/doc/configuration.md#custom-proxy-authenticator). + +# Configuration changes + +## BoxDeveloperEditionAPIConnection + +Replaced `com.box.sdk.BoxDeveloperEditionAPIConnection#getAppUserConnection`with `com.box.sdk.BoxDeveloperEditionAPIConnection#getUserConnection`. + +### Example + +To create `com.box.sdk.BoxDeveloperEditionAPIConnection` configured for user access: + +```java +Reader reader = new FileReader("some-config.json"); +BoxConfig boxConfig = BoxConfig.readFrom(reader); + +BoxDeveloperEditionAPIConnection api = BoxDeveloperEditionAPIConnection.getUserConnection(boxConfig); +``` + +### Documentation + +You can read more on BoxDeveloperEditionAPIConnection [here](../../README.md#boxdevelopereditionapiconnectionasenterpriseuser). + +## MaxRequestAttempts + +The `MaxRequestAttempts` are removed from `com.box.sdk.BoxGlobalSettings` and replaced with `MaxRetryAttempts`. +However, if you have API connection stored with the deprecated `MaxRequestAttempts` value it will be restored into `MaxRetryAttempts`. + +# Removed deprecated methods and classes + +1. `com.box.sdk.BoxAPIRequest.BoxAPIRequest(java.net.URL, java.lang.String)` - use constuctor that accepts `com.box.sdk.BoxAPIConnection`. +2. `com.box.sdk.BoxUser.moveFolderToUser` - this method is removed as this operation is not allowed by API. You can only transfer root folder to another user using `com.box.sdk.BoxUser.transferContent`. + +# Replaced methods and classes + +## Getting thumbnail + +Method `com.box.sdk.BoxFile.getThumbnail` was removed. To get any file representation use `com.box.sdk.BoxFile.getRepresentationContent(java.lang.String, java.io.OutputStream)` +or `com.box.sdk.BoxFile.getRepresentationContent(java.lang.String, java.lang.String, java.io.OutputStream)`. + +### Example + +To read the PDF representation of file with id `12345`: + +```java +ByteArrayOutputStream output = new ByteArrayOutputStream(); + +BoxFile file = new BoxFile(api, "12345"); +file.getRepresentationContent("[pdf]", output); +``` + +### Documentation + +For more details on getting representation content go [here](../files.md#get-representation-content). + +## Shared links + +Removed variant of methods that do not use `com.box.sdk.sharedlink.BoxSharedLinkRequest`: + +1. `com.box.sdk.BoxItem.createSharedLink` +2. `com.box.sdk.BoxFile.createSharedLink` +3. `com.box.sdk.BoxFolder.createSharedLink` +4. `com.box.sdk.BoxWebLink.createSharedLink` + +### Example + +If you want to create a shared link, first create `com.box.sdk.sharedlink.BoxSharedLinkRequest`: + +```java +Date unsharedDate = ... +BoxFile file = new BoxFile(api, "id"); +BoxSharedLinkRequest sharedLinkRequest = new BoxSharedLinkRequest() + .access(OPEN) + .permissions(true, true) + .unsharedDate(unsharedDate); + +BoxSharedLink sharedLink = file.createSharedLink(sharedLinkRequest); +``` + +### Documentation + +For details on shared links, see: + +1. [Create shared link for file](../files.md#create-a-shared-link) +2. [Create shared link for folder](../folders.md#create-a-shared-link) +3. [Create shared link for web link](../weblinks.md#create-shared-link) + +## Retention Policies + +Removed variant of methods that were not using `com.box.sdk.BoxRetentionPolicy.BoxRetentionPolicyAction`: + +1. `com.box.sdk.BoxRetentionPolicy.createFinitePolicy` + +### Example + +If you want to create a finite retention policy: + +```java +BoxRetentionPolicy.createFinitePolicy(api, "My 30 days retention policy", 30, BoxRetentionPolicyAction.PermanentlyDelete); +``` + +### Documentation + +You can read more on creating retention policies [here](../retention_policies.md#create-retention-policy). + +## Enterprise Events + +Removed variant of methods that were not using `com.box.sdk.EnterpriseEventsRequest`: + +1. `com.box.sdk.EventLog.getEnterpriseEvents` + +### Example + +If you want to get historical enterprise events, first create `com.box.sdk.EnterpriseEventsRequest`: + +```java +EnterpriseEventsRequest request = new EnterpriseEventsRequest().limit(20); +EventLog.getEnterpriseEvents(api, request1); +// process recieved events +``` + +### Documentation + +You can read more on getting enterprise events [here](../events.md#enterprise--admin--events). + +## Search + +Method `com.box.sdk.BoxFolder.search` is replaced with class `com.box.sdk.BoxSearch`. + +### Example + +If you would like to find the first 10 files matching "taxes": + +```java +long offsetValue = 0; +long limitValue = 10; +BoxSearchParameters searchParams = new BoxSearchParameters(); +searchParams.setQuery("taxes"); +searchParams.setType("file"); + +BoxSearch boxSearch = new BoxSearch(api); +boxSearch.searchRange(offsetValue, limitValue, searchParams); +``` + +### Documentation + +You can read more on search [here](../search.md). + +## BoxGroup + +All methods that use `com.box.sdk.BoxGroupMembership.Role` were removed. Use ones that use `com.box.sdk.BoxGroupMembership.GroupRole`. +Also `com.box.sdk.BoxGroupMembership.Role` was replaced with `com.box.sdk.BoxGroupMembership.GroupRole`. + +### Example + +To add a new member to a group with specific role: + +```java +BoxUser user = ... +BoxGroup boxGroup = new BoxGroup(api, "group_id"); +boxGroup.addMembership(user, BoxGroupMembership.GroupRole.ADMIN); +``` + +To get membership role use `com.box.sdk.BoxGroupMembership.Info.getGroupRole`: + +```java +BoxGroupMembership membership = new BoxGroupMembership(api, "membership_id"); +membership.getInfo().getGroupRole(); +``` + +To change membership role use `com.box.sdk.BoxGroupMembership.Info.setGroupRole`: + +```java +BoxGroupMembership membership = new BoxGroupMembership(api, "membership_id"); +BoxGroupMembership.Info membershipInfo = membership.getInfo(); +membershipInfo.setGroupRole(BoxGroupMembership.GroupRole.MEMBER); +membership.updateInfo(membershipInfo); +``` + +### Documentation + +You can read more on groups [here](../groups.md). + +## MetadataTemplate + +In `com.box.sdk.MetadataTemplate` methods that do not use `com.box.sdk.MetadataQuery` were removed. + +### Example + +To execute a metadata query first create `com.box.sdk.MetadataQuery` instance. + +```java +MetadataQuery mQuery = new MetadataQuery("enterprise_341532.test"); +mQuery.setQuery("testfield = :arg"); +mQuery.setAncestorFolderId("0"); +mQuery.setOrderBy( + MetadataQuery.OrderBy.ascending("primarySortKey"), + MetadataQuery.OrderBy.ascending("secondarySortKey") +); +mQuery.addParameter("arg", "test"); +mQuery.setFields("metadata.enterprise_341532.test.customField"); +MetadataTemplate.executeMetadataQuery(api, mQuery); +``` + +### Documentation + +You can read more on how to execute metadata query [here](../metadata_template.md#execute-metadata-query). + +## Others + +| Old | New | +| :---------------------------------------------------- | :-------------------------------------------------- | +| `com.box.sdk.BoxEvent.getType` | `com.box.sdk.BoxEvent.getEventType` | +| `com.box.sdk.BoxEvent.Type` | `com.box.sdk.BoxEvent.EventType` | +| `com.box.sdk.BoxFile.uploadVersion` | `com.box.sdk.BoxFile.uploadNewVersion` | +| `com.box.sdk.BoxGlobalSettings.getMaxRequestAttempts` | `com.box.sdk.BoxGlobalSettings.getMaxRetryAttempts` | +| `com.box.sdk.BoxGlobalSettings.setMaxRequestAttempts` | `com.box.sdk.BoxGlobalSettings.setMaxRetryAttempts` | +| `com.box.sdk.BoxTask.Info.getAction` | `com.box.sdk.BoxTask.Info.getTaskType` | diff --git a/migration-guides/from-v4-to-v10.md b/migration-guides/from-v4-to-v10.md new file mode 100644 index 000000000..23c3773b5 --- /dev/null +++ b/migration-guides/from-v4-to-v10.md @@ -0,0 +1,67 @@ +# Migration guide from v4 to v10 version of `box-java-sdk` + + + + +- [Introduction](#introduction) +- [Installation](#installation) + - [Maven](#maven) + - [Gradle](#gradle) +- [Supported Environments](#supported-environments) +- [Highlighting the Key Differences](#highlighting-the-key-differences) + + + +## Introduction + +The v10 release of `box-java-sdk` library helps Java developers to conveniently integrate with Box API. +In the contrary to the previous versions (v4 or lower), it is not manually maintained, but auto-generated +based on Open API Specification. This means you can leverage the most up-to-date Box API features in your +applications without delay. We introduced this major version bump to reflect the significant codebase changes +and to align with other Box SDKs, which will also adopt generated code starting from their v10 releases. +More information and benefits of using the new can be found in the +[README](../README.md) file. + +## Installation + +To install v10 version of Box Java SDK, you can use Maven or Gradle. The library is available in the +[Maven Central Repository](https://search.maven.org/artifact/com.box/box-java-sdk). + +We have also introduced v5 version of Box Java SDK that consolidates both the manually maintained +`com.box.sdk` package from v4 and the new, auto-generated `com.box.sdkgen` package from v10. +If you would like to use a feature available only in the new SDK, you won't need to necessarily migrate all your code +to use generated SDK at once. You will be able to use a new feature from the `com.box.sdkgen` package, +while keeping the rest of your code unchanged. However, we recommend to fully migrate to the v10 of the SDK eventually. +More information about v4 version can be found in the [migration guide from v4 to v5](./from-v4-to-v5.md). + +### Maven + +To start using generated version of the SDK in you Maven project just bump the version of the Box Java SDK library +in `pom.xml`to 10.0.0 or higher: + +```xml + + com.box + box-java-sdk + 10.0.0 + +``` + +### Gradle + +To bump a dependency in your Gradle project, bump the version used in your `build.gradle` file: + +```groovy +implementation 'com.box:box-java-sdk:10.0.0' +``` + +## Supported Environments + +Both v4 and v10 of the Box Java SDK share the same Java version requirement: Java 8 or higher. +No changes to your environment are needed when upgrading from v4 to v10. + +## Highlighting the Key Differences + +There are important differences between the `com.box.sdk` (v4) and the generated `com.box.sdkgen` (v10) packages. +We have prepared a separate document that presents the main differences and provides guidance to help you migrate. +For side-by-side code examples, see: [Migration guide: migrate from `com.box.sdk` to `com.box.sdkgen` package](./from-com-box-sdk-to-com-box-sdkgen.md). diff --git a/migration-guides/from-v4-to-v5.md b/migration-guides/from-v4-to-v5.md new file mode 100644 index 000000000..ce7e0e127 --- /dev/null +++ b/migration-guides/from-v4-to-v5.md @@ -0,0 +1,109 @@ +# Migration guide from v4 to v5 version of `box-java-sdk` + + + + +- [Introduction](#introduction) +- [Installation](#installation) + - [Maven](#maven) + - [Gradle](#gradle) +- [Supported Environments](#supported-environments) +- [Highlighting the Key Differences](#highlighting-the-key-differences) + - [Using the Box Java SDK v5](#using-the-box-java-sdk-v5) + + + +## Introduction + +The v5 release of the Box Java SDK is a transitional version designed to help developers migrate from +the manually maintained v4 SDK to the modern, auto-generated v10+ SDK. + +This release combines two packages into a single artifact: + +- `com.box.sdk` - the manually maintained package from v4. +- `com.box.sdkgen` - the new, auto-generated module built from the official OpenAPI specification (and the sole component of the v10 SDK). + +This hybrid approach allows you to gradually adopt the new `com.box.sdkgen` features +while continuing to use your existing v4 integration, eliminating the need for an immediate full rewrite. + +## Installation + +To install v5 version of Box Java SDK, you can use Maven or Gradle. The library is available in the +[Maven Central Repository](https://search.maven.org/artifact/com.box/box-java-sdk). + +### Maven + +To upgrade from v4 to v5, in you Maven project just bump the version of the Box Java SDK library +in `pom.xml`to 5.0.0 or higher: + +```xml + + com.box + box-java-sdk + 5.0.0 + +``` + +### Gradle + +To upgrade from v4 to v5 of the Box Java SDK, simply update the library version in your Maven project’s `pom.xml` file +to 5.0.0 or higher: + +```groovy +implementation 'com.box:box-java-sdk:5.0.0' +``` + +## Supported Environments + +Both v4 and v5 of the Box Java SDK share the same Java version requirement: Java 8 or higher. +No changes to your environment are needed when upgrading from v4 to v5. + +## Highlighting the Key Differences + +The `com.box.sdk` package usage in v5 remains the same as in v4 and is not covered in this document. +If you are migrating code from `com.box.sdk` to `com.box.sdkgen`, which we recommend, +the key differences between the packages are documented in: + +- [Migration guide: com.box.sdk → com.box.sdkgen](./from-com-box-sdk-to-com-box-sdkgen.md) + +### Using the Box Java SDK v5 + +After migration to Box Java SDK v5, you can use both the manual Box Java SDK package `com.box.sdk` and the generated one `com.box.sdkgen`. +You just need to import the required classes from the appropriate package depending on which SDK you intend to use. +If both packages contain classes with the same name, you can use fully qualified names to resolve any naming conflicts. + +```java +import com.box.sdk.BoxConfig; +import com.box.sdk.BoxDeveloperEditionAPIConnection; + +import com.box.sdk.BoxFolder; +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.folders.UpdateFolderByIdRequestBody; +import com.box.sdkgen.schemas.folder.Folder; + +import java.io.FileReader; +import java.io.Reader; + +public class Main { + public static void main(String[] args) throws Exception { + + Reader reader = new FileReader("src/example/config/config.json"); + BoxConfig boxConfig = BoxConfig.readFrom(reader); + BoxDeveloperEditionAPIConnection api = BoxDeveloperEditionAPIConnection.getAppEnterpriseConnection(boxConfig); + + JWTConfig config = JWTConfig.fromConfigFile("src/example/config/config.json"); + BoxJWTAuth auth = new BoxJWTAuth(config); + BoxClient client = new BoxClient(auth); + + BoxFolder rootFolder = new BoxFolder(api, "0"); + BoxFolder.Info subfolder = rootFolder.createFolder("My Subfolder"); + Folder updatedFolder = client.getFolders().updateFolderById( + subfolder.getID(), + new UpdateFolderByIdRequestBody.Builder().name("My Updated Subfolder").build() + ); + System.out.println("Created folder with ID " + subfolder.getID() + " has been updated to " + updatedFolder.getName()); + } +} +``` diff --git a/migration-guides/from-v5-to-v10.md b/migration-guides/from-v5-to-v10.md new file mode 100644 index 000000000..91210c8dd --- /dev/null +++ b/migration-guides/from-v5-to-v10.md @@ -0,0 +1,61 @@ +# Migration guide from v5 to v10 version of `box-java-sdk` + + + + +- [Introduction](#introduction) +- [Installation](#installation) + - [Maven](#maven) + - [Gradle](#gradle) +- [Supported Environments](#supported-environments) +- [Migration Scope and Module Compatibility](#migration-scope-and-module-compatibility) + + + +## Introduction + +Version 10 of the Box Java SDK is a modern, fully auto-generated SDK built entirely from the `com.box.sdkgen` package. +In version 5, the SDK included two packages side by side: the manually maintained `com.box.sdk` and the generated `com.box.sdkgen`. +Starting with version 10, the `com.box.sdk` package has been removed, and only the `com.box.sdkgen` package remains. + +If you are migrating code from `com.box.sdk` to `com.box.sdkgen` package, detailed instructions are available in the dedicated +[Migration guide: migrate from `com.box.sdk` to `com.box.sdkgen` package](./from-com-box-sdk-to-com-box-sdkgen.md). + +## Installation + +To install v10 version of Box Java SDK, you can use Maven or Gradle. The library is available in the +[Maven Central Repository](https://search.maven.org/artifact/com.box/box-java-sdk). + +### Maven + +To start using generated version of the SDK in you Maven project just bump the version of the Box Java SDK library +in `pom.xml`to 10.0.0 or higher: + +```xml + + com.box + box-java-sdk + 10.0.0 + +``` + +### Gradle + +To bump a dependency in your Gradle project, bump the version used in your `build.gradle` file: + +```groovy +implementation 'com.box:box-java-sdk:10.0.0' +``` + +## Supported Environments + +Both v5 and v10 of the Box Java SDK share the same Java version requirement: Java 8 or higher. +No changes to your environment are needed when upgrading from v5 to v10. + +## Migration Scope and Module Compatibility + +If your project only uses the `com.box.sdkgen` package from v5, no code changes are required to migrate to v10. +The generated `com.box.sdkgen` package is the same in both v5 and v10. + +If your project still includes code that uses the legacy `com.box.sdk` module, follow the dedicated guide to update it: +[Migration guide: migrate from `com.box.sdk` to `com.box.sdkgen` package](./from-com-box-sdk-to-com-box-sdkgen.md). diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 000000000..264c73a60 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "box-java-sdk" diff --git a/src/example/java/com/box/sdk/example/Main.java b/src/example/java/com/box/sdk/example/Main.java deleted file mode 100644 index 8cac65118..000000000 --- a/src/example/java/com/box/sdk/example/Main.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.box.sdk.example; - -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.box.sdk.BoxAPIConnection; -import com.box.sdk.BoxFolder; -import com.box.sdk.BoxItem; -import com.box.sdk.BoxUser; - -public final class Main { - private static final String DEVELOPER_TOKEN = ""; - private static final int MAX_DEPTH = 1; - - private Main() { } - - public static void main(String[] args) { - // Turn off logging to prevent polluting the output. - Logger.getLogger("com.box.sdk").setLevel(Level.OFF); - - 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()); - - BoxFolder rootFolder = BoxFolder.getRootFolder(api); - listFolder(rootFolder, 0); - } - - private static void listFolder(BoxFolder folder, int depth) { - for (BoxItem.Info itemInfo : folder) { - String indent = ""; - for (int i = 0; i < depth; i++) { - indent += " "; - } - - 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/main/java/com/box/sdk/BackoffCounter.java b/src/main/java/com/box/sdk/BackoffCounter.java deleted file mode 100644 index 2b40b3e4a..000000000 --- a/src/main/java/com/box/sdk/BackoffCounter.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.box.sdk; - -import java.util.logging.Level; -import java.util.logging.Logger; - -class BackoffCounter { - private static final Logger LOGGER = Logger.getLogger(BackoffCounter.class.getName()); - private static final int MIN_EXPONENT = 10; - private static final int MAX_EXPONENT = 16; - - private final Time time; - - private int maxAttempts; - private int attemptsRemaining; - - public BackoffCounter() { - this.time = Time.getInstance(); - } - - public BackoffCounter(Time time) { - this.time = time; - } - - public int getAttemptsRemaining() { - return this.attemptsRemaining; - } - - public void waitBackoff() throws InterruptedException { - int delay = this.calculateDelay(); - if (this.attemptsRemaining > 1) { - LOGGER.log(Level.WARNING, String.format("Backing off for %d seconds before retrying %d more times.", - (delay / 1000), this.attemptsRemaining)); - } else { - LOGGER.log(Level.WARNING, String.format("Backing off for %d seconds before retrying %d more time.", - (delay / 1000), this.attemptsRemaining)); - } - - this.time.waitDuration(delay); - } - - public boolean decrement() { - this.attemptsRemaining--; - return (this.attemptsRemaining > 0); - } - - public void reset(int maxAttempts) { - this.maxAttempts = maxAttempts; - this.attemptsRemaining = maxAttempts; - } - - private int calculateDelay() { - int exponent = (MIN_EXPONENT + (this.maxAttempts - (this.attemptsRemaining + 1))); - if (exponent > MAX_EXPONENT) { - exponent = MAX_EXPONENT; - } - - return (2 << exponent); - } -} diff --git a/src/main/java/com/box/sdk/BoxAPIConnection.java b/src/main/java/com/box/sdk/BoxAPIConnection.java deleted file mode 100644 index a98d27c7a..000000000 --- a/src/main/java/com/box/sdk/BoxAPIConnection.java +++ /dev/null @@ -1,414 +0,0 @@ -package com.box.sdk; - -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.locks.ReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; - -import com.eclipsesource.json.JsonObject; - -/** - * 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.

- */ -public class BoxAPIConnection { - /** - * The default maximum number of times an API request will be tried when an error occurs. - */ - public static final int DEFAULT_MAX_ATTEMPTS = 3; - - private static final String TOKEN_URL_STRING = "https://www.box.com/api/oauth2/token"; - private static final String DEFAULT_BASE_URL = "https://api.box.com/2.0/"; - private static final String DEFAULT_BASE_UPLOAD_URL = "https://upload.box.com/api/2.0/"; - - /** - * 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; - - // 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 String userAgent; - private String accessToken; - private String refreshToken; - private String tokenURL; - private String baseURL; - private String baseUploadURL; - private boolean autoRefresh; - private int maxRequestAttempts; - private List listeners; - private RequestInterceptor interceptor; - - /** - * 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.tokenURL = TOKEN_URL_STRING; - this.baseURL = DEFAULT_BASE_URL; - this.baseUploadURL = DEFAULT_BASE_UPLOAD_URL; - this.autoRefresh = true; - this.maxRequestAttempts = DEFAULT_MAX_ATTEMPTS; - this.refreshLock = new ReentrantReadWriteLock(); - this.userAgent = "Box Java SDK v0.7.0"; - this.listeners = new ArrayList(); - } - - /** - * 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); - } - - /** - * 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 = null; - try { - url = new URL(this.tokenURL); - } 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 = String.format("grant_type=authorization_code&code=%s&client_id=%s&client_secret=%s", - authCode, this.clientID, this.clientSecret); - - BoxAPIRequest request = new BoxAPIRequest(url, "POST"); - request.addHeader("Content-Type", "application/x-www-form-urlencoded"); - request.setBody(urlParameters); - - BoxJSONResponse response = (BoxJSONResponse) request.send(); - String json = response.getJSON(); - - JsonObject jsonObject = JsonObject.readFrom(json); - 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; - } - - /** - * 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 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; - } - - /** - * Gets the token URL that's used to request access tokens. The default value is - * "https://www.box.com/api/oauth2/token". - * @return the token URL. - */ - public String getTokenURL() { - return this.tokenURL; - } - - /** - * Sets the token URL that's used to request access tokens. For example, the default token URL is - * "https://www.box.com/api/oauth2/token". - * @param tokenURL the token URL. - */ - public void setTokenURL(String tokenURL) { - this.tokenURL = tokenURL; - } - - /** - * Gets the base URL that's used when sending requests to the Box API. The default value is - * "https://api.box.com/2.0/". - * @return the base URL. - */ - public String getBaseURL() { - return this.baseURL; - } - - /** - * 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/2.0/". - * @param baseURL a base URL - */ - public void setBaseURL(String baseURL) { - this.baseURL = baseURL; - } - - /** - * Gets the base upload URL that's used when performing file uploads to Box. - * @return the base upload URL. - */ - public String getBaseUploadURL() { - return this.baseUploadURL; - } - - /** - * 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 = baseUploadURL; - } - - /** - * 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 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(); - } - } - - return this.accessToken; - } - - /** - * 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 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; - } - - /** - * 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 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; - } - - /** - * Gets the maximum number of times an API request will be tried when an error occurs. - * @return the maximum number of request attempts. - */ - public int getMaxRequestAttempts() { - return this.maxRequestAttempts; - } - - /** - * Sets the maximum number of times an API request will be tried when an error occurs. - * @param attempts the maximum number of request attempts. - */ - public void setMaxRequestAttempts(int attempts) { - this.maxRequestAttempts = attempts; - } - - /** - * 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(); - if (this.expires == 0) { - needsRefresh = false; - } else { - long now = System.currentTimeMillis(); - long tokenDuration = (now - this.lastRefresh); - needsRefresh = (tokenDuration >= this.expires - REFRESH_EPSILON); - } - 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(); - - if (!this.canRefresh()) { - this.refreshLock.writeLock().unlock(); - throw new IllegalStateException("The BoxAPIConnection cannot be refreshed because it doesn't have a " - + "refresh token."); - } - - URL url = null; - try { - url = new URL(this.tokenURL); - } catch (MalformedURLException e) { - this.refreshLock.writeLock().unlock(); - 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 = String.format("grant_type=refresh_token&refresh_token=%s&client_id=%s&client_secret=%s", - this.refreshToken, this.clientID, this.clientSecret); - - BoxAPIRequest request = new BoxAPIRequest(url, "POST"); - request.addHeader("Content-Type", "application/x-www-form-urlencoded"); - request.setBody(urlParameters); - - String json; - try { - BoxJSONResponse response = (BoxJSONResponse) request.send(); - json = response.getJSON(); - } catch (BoxAPIException e) { - this.refreshLock.writeLock().unlock(); - throw e; - } - - JsonObject jsonObject = JsonObject.readFrom(json); - 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; - - this.notifyRefresh(); - - this.refreshLock.writeLock().unlock(); - } - - /** - * Notifies refresh event to all the listeners. - */ - private void notifyRefresh() { - for (BoxAPIConnectionListener listener : this.listeners) { - listener.onRefresh(); - } - } - - /** - * 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; - } -} diff --git a/src/main/java/com/box/sdk/BoxAPIConnectionListener.java b/src/main/java/com/box/sdk/BoxAPIConnectionListener.java deleted file mode 100644 index c2f2996db..000000000 --- a/src/main/java/com/box/sdk/BoxAPIConnectionListener.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.box.sdk; - -/** - * Listener to listen to Box API connection events. - */ -public interface BoxAPIConnectionListener { - - /** - * Called when the Box API connection refreshes its tokens. - */ - void onRefresh(); -} diff --git a/src/main/java/com/box/sdk/BoxAPIException.java b/src/main/java/com/box/sdk/BoxAPIException.java deleted file mode 100644 index 4d30d6c97..000000000 --- a/src/main/java/com/box/sdk/BoxAPIException.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.box.sdk; - -/** - * 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 final int responseCode; - private final String response; - - /** - * 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; - } - - /** - * 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) { - super(message); - - this.responseCode = responseCode; - this.response = response; - } - - /** - * 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; - } - - /** - * 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; - } - - /** - * 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; - } - - /** - * 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; - } -} diff --git a/src/main/java/com/box/sdk/BoxAPIRequest.java b/src/main/java/com/box/sdk/BoxAPIRequest.java deleted file mode 100644 index ba1210ca8..000000000 --- a/src/main/java/com/box/sdk/BoxAPIRequest.java +++ /dev/null @@ -1,471 +0,0 @@ -package com.box.sdk; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.ProtocolException; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * 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.

- * - *

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 Logger LOGGER = Logger.getLogger(BoxAPIRequest.class.getName()); - private static final int BUFFER_SIZE = 8192; - private static final int MAX_REDIRECTS = 3; - - private final BoxAPIConnection api; - private final List headers; - private final String method; - - private URL url; - private BackoffCounter backoffCounter; - private int timeout; - private InputStream body; - private long bodyLength; - private Map> requestProperties; - private int numRedirects; - - /** - * Constructs an unauthenticated BoxAPIRequest. - * @param url the URL of the request. - * @param method the HTTP method of the request. - */ - public BoxAPIRequest(URL url, String method) { - this(null, url, method); - } - - /** - * 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 = api; - this.url = url; - this.method = method; - this.headers = new ArrayList(); - this.backoffCounter = new BackoffCounter(new Time()); - - this.addHeader("Accept-Encoding", "gzip"); - this.addHeader("Accept-Charset", "utf-8"); - } - - /** - * Adds an HTTP header to this request. - * @param key the header key. - * @param value the header value. - */ - public void addHeader(String key, String value) { - this.headers.add(new RequestHeader(key, value)); - } - - /** - * Sets a timeout for this request in milliseconds. - * @param timeout the timeout in milliseconds. - */ - public void setTimeout(int timeout) { - this.timeout = timeout; - } - - /** - * 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 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; - } - - /** - * 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); - } - - /** - * 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.

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

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. - * @throws BoxAPIException if the server returns an error code or if a network error occurs. - * @return a {@link BoxAPIResponse} containing the server's response. - */ - public BoxAPIResponse send(ProgressListener listener) { - if (this.api == null) { - this.backoffCounter.reset(BoxAPIConnection.DEFAULT_MAX_ATTEMPTS); - } else { - this.backoffCounter.reset(this.api.getMaxRequestAttempts()); - } - - while (this.backoffCounter.getAttemptsRemaining() > 0) { - try { - return this.trySend(listener); - } catch (BoxAPIException apiException) { - if (!this.backoffCounter.decrement() || !isResponseRetryable(apiException.getResponseCode())) { - throw apiException; - } - - try { - this.resetBody(); - } catch (IOException ioException) { - throw apiException; - } - - try { - this.backoffCounter.waitBackoff(); - } catch (InterruptedException interruptedException) { - Thread.currentThread().interrupt(); - 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() { - 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); - - for (Map.Entry> entry : this.requestProperties.entrySet()) { - List nonEmptyValues = new ArrayList(); - for (String value : entry.getValue()) { - if (value != null && value.trim().length() != 0) { - nonEmptyValues.add(value); - } - } - - if (nonEmptyValues.size() == 0) { - continue; - } - - builder.append(entry.getKey()); - builder.append(": "); - for (String value : nonEmptyValues) { - builder.append(value); - builder.append(", "); - } - - builder.delete(builder.length() - 2, builder.length()); - builder.append(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; - } - - /** - * Writes the body of this request to an HttpURLConnection. - * - *

Subclasses overriding this method must remember to close the connection's OutputStream after writing.

- * - * @param connection the connection to which the body should be written. - * @param listener an optional listener for monitoring the write progress. - * @throws BoxAPIException if an error occurs while writing to the connection. - */ - protected void writeBody(HttpURLConnection connection, ProgressListener listener) { - if (this.body == null) { - return; - } - - connection.setDoOutput(true); - try { - OutputStream output = connection.getOutputStream(); - if (listener != null) { - output = new ProgressOutputStream(output, listener, this.bodyLength); - } - int b = this.body.read(); - while (b != -1) { - output.write(b); - b = this.body.read(); - } - output.close(); - } catch (IOException e) { - throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", 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; - } - } - } - - HttpURLConnection connection = this.createConnection(); - - if (this.bodyLength > 0) { - connection.setFixedLengthStreamingMode((int) this.bodyLength); - connection.setDoOutput(true); - } - - if (this.api != null) { - connection.addRequestProperty("Authorization", "Bearer " + this.api.getAccessToken()); - connection.setRequestProperty("User-Agent", this.api.getUserAgent()); - - if (this.api instanceof SharedLinkAPIConnection) { - SharedLinkAPIConnection sharedItemAPI = (SharedLinkAPIConnection) this.api; - String sharedLink = sharedItemAPI.getSharedLink(); - String boxAPIValue = "shared_link=" + sharedLink; - String sharedLinkPassword = sharedItemAPI.getSharedLinkPassword(); - if (sharedLinkPassword != null) { - boxAPIValue += "&shared_link_password=" + sharedLinkPassword; - } - connection.addRequestProperty("BoxApi", boxAPIValue); - } - } - - this.requestProperties = connection.getRequestProperties(); - this.writeBody(connection, listener); - - // Ensure that we're connected in case writeBody() didn't write anything. - try { - connection.connect(); - } catch (IOException e) { - throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e); - } - - this.logRequest(connection); - - // We need to manually handle redirects by creating a new HttpURLConnection so that connection pooling happens - // correctly. There seems to be a bug in Oracle's Java implementation where automatically handled redirects will - // not keep the connection alive. - int responseCode; - try { - responseCode = connection.getResponseCode(); - } catch (IOException e) { - throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e); - } - if (isResponseRedirect(responseCode)) { - return this.handleRedirect(connection, listener); - } - - String contentType = connection.getContentType(); - BoxAPIResponse response; - if (contentType == null) { - response = new BoxAPIResponse(connection); - } else if (contentType.contains("application/json")) { - response = new BoxJSONResponse(connection); - } else { - response = new BoxAPIResponse(connection); - } - - return response; - } - - private BoxAPIResponse handleRedirect(HttpURLConnection connection, ProgressListener listener) { - if (this.numRedirects >= MAX_REDIRECTS) { - throw new BoxAPIException("The Box API responded with too many redirects."); - } - this.numRedirects++; - - // Even though the redirect response won't have a body, we need to read the InputStream so that Java will put - // the connection back in the connection pool. - try { - InputStream stream = connection.getInputStream(); - byte[] buffer = new byte[8192]; - int n = stream.read(buffer); - while (n != -1) { - n = stream.read(buffer); - } - stream.close(); - } catch (IOException e) { - throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e); - } - - String redirect = connection.getHeaderField("Location"); - try { - this.url = new URL(redirect); - } catch (MalformedURLException e) { - throw new BoxAPIException("The Box API responded with an invalid redirect.", e); - } - return this.trySend(listener); - } - - private void logRequest(HttpURLConnection connection) { - if (LOGGER.isLoggable(Level.FINE)) { - LOGGER.log(Level.FINE, this.toString()); - } - } - - private HttpURLConnection createConnection() { - HttpURLConnection connection = null; - - try { - connection = (HttpURLConnection) this.url.openConnection(); - } catch (IOException e) { - throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e); - } - - try { - connection.setRequestMethod(this.method); - } catch (ProtocolException e) { - throw new BoxAPIException("Couldn't connect to the Box API because the request's method was invalid.", e); - } - - connection.setConnectTimeout(this.timeout); - connection.setReadTimeout(this.timeout); - - // Don't allow HttpURLConnection to automatically redirect because it messes up the connection pool. See the - // trySend(ProgressListener) method for how we handle redirects. - connection.setInstanceFollowRedirects(false); - - for (RequestHeader header : this.headers) { - connection.addRequestProperty(header.getKey(), header.getValue()); - } - - return connection; - } - - private static boolean isResponseRetryable(int responseCode) { - return (responseCode >= 500 || responseCode == 429); - } - - private static boolean isResponseRedirect(int responseCode) { - return (responseCode == 301 || responseCode == 302); - } - - private final class RequestHeader { - private final String key; - private final String value; - - public RequestHeader(String key, String value) { - this.key = key; - this.value = value; - } - - public String getKey() { - return this.key; - } - - public String getValue() { - return this.value; - } - } -} diff --git a/src/main/java/com/box/sdk/BoxAPIResponse.java b/src/main/java/com/box/sdk/BoxAPIResponse.java deleted file mode 100644 index 0b1204481..000000000 --- a/src/main/java/com/box/sdk/BoxAPIResponse.java +++ /dev/null @@ -1,258 +0,0 @@ -package com.box.sdk; - -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.zip.GZIPInputStream; - -/** - * 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.

- * - *

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

- */ -public class BoxAPIResponse { - private static final Logger LOGGER = Logger.getLogger(BoxAPIResponse.class.getName()); - private static final int BUFFER_SIZE = 8192; - - private final HttpURLConnection connection; - - 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 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.connection = null; - } - - /** - * Constructs a BoxAPIResponse using an HttpURLConnection. - * @param connection a connection that has already sent a request to the API. - */ - public BoxAPIResponse(HttpURLConnection connection) { - this.connection = connection; - this.inputStream = null; - - try { - this.responseCode = this.connection.getResponseCode(); - } catch (IOException e) { - throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e); - } - - if (!isSuccess(this.responseCode)) { - this.logResponse(); - throw new BoxAPIException("The API returned an error code: " + this.responseCode, this.responseCode, - this.bodyToString()); - } - - this.logResponse(); - } - - /** - * Gets the response code returned by the API. - * @return the response code returned by the API. - */ - public int getResponseCode() { - return this.responseCode; - } - - /** - * 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.connection.getContentLength(); - } - - /** - * 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) { - String contentEncoding = this.connection.getContentEncoding(); - try { - if (this.rawInputStream == null) { - this.rawInputStream = this.connection.getInputStream(); - } - - if (listener == null) { - this.inputStream = this.rawInputStream; - } else { - this.inputStream = new ProgressInputStream(this.rawInputStream, listener, - this.getContentLength()); - } - - if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) { - this.inputStream = new GZIPInputStream(this.inputStream); - } - } catch (IOException e) { - throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e); - } - } - - return this.inputStream; - } - - /** - * 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() { - try { - if (this.rawInputStream == null) { - this.rawInputStream = this.connection.getInputStream(); - } - - // We need to manually read from the raw input stream in case there are any remaining bytes. There's a bug - // where a wrapping GZIPInputStream may not read to the end of a chunked response, causing Java to not - // return the connection to the connection pool. - byte[] buffer = new byte[BUFFER_SIZE]; - int n = this.rawInputStream.read(buffer); - while (n != -1) { - n = this.rawInputStream.read(buffer); - } - 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); - } - } - - @Override - public String toString() { - String lineSeparator = System.getProperty("line.separator"); - Map> headers = this.connection.getHeaderFields(); - StringBuilder builder = new StringBuilder(); - builder.append("Response"); - builder.append(lineSeparator); - builder.append(this.connection.getRequestMethod()); - builder.append(' '); - builder.append(this.connection.getURL().toString()); - builder.append(lineSeparator); - builder.append(headers.get(null).get(0)); - builder.append(lineSeparator); - - for (Map.Entry> entry : headers.entrySet()) { - String key = entry.getKey(); - if (key == null) { - continue; - } - - List nonEmptyValues = new ArrayList(); - for (String value : entry.getValue()) { - if (value != null && value.trim().length() != 0) { - nonEmptyValues.add(value); - } - } - - if (nonEmptyValues.size() == 0) { - continue; - } - - builder.append(key); - builder.append(": "); - for (String value : nonEmptyValues) { - builder.append(value); - builder.append(", "); - } - - builder.delete(builder.length() - 2, builder.length()); - builder.append(lineSeparator); - } - - String bodyString = this.bodyToString(); - if (bodyString != null && bodyString != "") { - builder.append(lineSeparator); - builder.append(bodyString); - } - - return builder.toString().trim(); - } - - /** - * 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. - * @return a string representation of this response's body. - */ - protected String bodyToString() { - if (this.bodyString == null && !isSuccess(this.responseCode)) { - this.bodyString = readErrorStream(this.connection.getErrorStream()); - } - - return this.bodyString; - } - - private void logResponse() { - if (LOGGER.isLoggable(Level.FINE)) { - LOGGER.log(Level.FINE, this.toString()); - } - } - - private static boolean isSuccess(int responseCode) { - return responseCode >= 200 && responseCode < 300; - } - - private static String readErrorStream(InputStream stream) { - if (stream == null) { - return null; - } - - InputStreamReader reader = new InputStreamReader(stream, 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); - } - - reader.close(); - } catch (IOException e) { - return null; - } - - return builder.toString(); - } -} diff --git a/src/main/java/com/box/sdk/BoxCollaboration.java b/src/main/java/com/box/sdk/BoxCollaboration.java deleted file mode 100644 index a80f39220..000000000 --- a/src/main/java/com/box/sdk/BoxCollaboration.java +++ /dev/null @@ -1,408 +0,0 @@ -package com.box.sdk; - -import java.net.URL; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; - -import com.eclipsesource.json.JsonArray; -import com.eclipsesource.json.JsonObject; -import com.eclipsesource.json.JsonValue; - -/** - * 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.

- */ -public class BoxCollaboration extends BoxResource { - private static final URLTemplate COLLABORATIONS_URL_TEMPLATE = new URLTemplate("collaborations"); - private static final URLTemplate PENDING_COLLABORATIONS_URL = new URLTemplate("collaborations?status=pending"); - private static final URLTemplate COLLABORATION_URL_TEMPLATE = new URLTemplate("collaborations/%s"); - - /** - * 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); - } - - /** - * 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) { - URL url = PENDING_COLLABORATIONS_URL.build(api.getBaseURL()); - - BoxAPIRequest request = new BoxAPIRequest(api, url, "GET"); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); - - 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 this collaboration. - * @return info about this collaboration. - */ - public Info getInfo() { - BoxAPIConnection api = this.getAPI(); - URL url = COLLABORATIONS_URL_TEMPLATE.build(api.getBaseURL()); - - BoxAPIRequest request = new BoxAPIRequest(api, url, "GET"); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - JsonObject jsonObject = JsonObject.readFrom(response.getJSON()); - return new Info(jsonObject); - } - - /** - * 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()); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - JsonObject jsonObject = JsonObject.readFrom(response.getJSON()); - 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"); - BoxAPIResponse response = request.send(); - response.disconnect(); - } - - /** - * 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 BoxFolder.Info item; - - /** - * 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; - } - - /** - * Gets the status of the collaboration. - * @return the status of the collaboration. - */ - 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()); - } - - /** - * 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; - } - - /** - * 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 folder the collaboration is related to. - * @return the folder the collaboration is related to. - */ - public BoxFolder.Info getItem() { - return this.item; - } - - @Override - public BoxCollaboration getResource() { - return BoxCollaboration.this; - } - - @Override - protected void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - - String memberName = member.getName(); - JsonValue value = member.getValue(); - try { - 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("expires_at")) { - this.expiresAt = BoxDateFormat.parse(value.asString()); - - } else if (memberName.equals("status")) { - String statusString = value.asString().toUpperCase(); - this.status = Status.valueOf(statusString); - - } else if (memberName.equals("accessible_by")) { - JsonObject userJSON = value.asObject(); - if (this.accessibleBy == null) { - String userID = userJSON.get("id").asString(); - BoxUser user = new BoxUser(getAPI(), userID); - BoxUser.Info userInfo = user.new Info(userJSON); - this.accessibleBy = userInfo; - } else { - this.accessibleBy.update(userJSON); - } - - } else if (memberName.equals("role")) { - this.role = Role.fromJSONString(value.asString()); - - } else if (memberName.equals("acknowledged_at")) { - this.acknowledgedAt = BoxDateFormat.parse(value.asString()); - - } else if (memberName.equals("item")) { - JsonObject folderJSON = value.asObject(); - if (this.item == null) { - String folderID = folderJSON.get("id").asString(); - BoxFolder folder = new BoxFolder(getAPI(), folderID); - this.item = folder.new Info(folderJSON); - } else { - this.item.update(folderJSON); - } - } - } catch (ParseException e) { - assert false : "A ParseException indicates a bug in the SDK."; - } - } - } - - /** - * 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 { - /** - * 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; - - private Role(String jsonValue) { - this.jsonValue = jsonValue; - } - - static Role fromJSONString(String jsonValue) { - if (jsonValue.equals("editor")) { - return EDITOR; - } else if (jsonValue.equals("viewer")) { - return VIEWER; - } else if (jsonValue.equals("previewer")) { - return PREVIEWER; - } else if (jsonValue.equals("uploader")) { - return UPLOADER; - } else if (jsonValue.equals("previewer uploader")) { - return PREVIEWER_UPLOADER; - } else if (jsonValue.equals("viewer uploader")) { - return VIEWER_UPLOADER; - } else if (jsonValue.equals("co-owner")) { - return CO_OWNER; - } else if (jsonValue.equals("owner")) { - return OWNER; - } else { - throw new IllegalArgumentException("The provided JSON value isn't a valid Role."); - } - } - - String toJSONString() { - return this.jsonValue; - } - } -} diff --git a/src/main/java/com/box/sdk/BoxCollaborator.java b/src/main/java/com/box/sdk/BoxCollaborator.java deleted file mode 100644 index f9ee21fc2..000000000 --- a/src/main/java/com/box/sdk/BoxCollaborator.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.box.sdk; - -import java.text.ParseException; -import java.util.Date; - -import com.eclipsesource.json.JsonObject; -import com.eclipsesource.json.JsonValue; - -/** - * 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); - } - - /** - * Contains information about a BoxCollaborator. - */ - public abstract class Info extends BoxResource.Info { - private String name; - 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); - } - - /** - * Constructs an Info object using an already parsed JSON object. - * @param jsonObject the parsed JSON object. - */ - Info(JsonObject jsonObject) { - super(jsonObject); - } - - /** - * 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); - } - - /** - * 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; - } - - @Override - protected void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - - try { - JsonValue value = member.getValue(); - String name = member.getName(); - if (name.equals("name")) { - this.name = value.asString(); - } else if (name.equals("created_at")) { - this.createdAt = BoxDateFormat.parse(value.asString()); - } else if (name.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/BoxComment.java b/src/main/java/com/box/sdk/BoxComment.java deleted file mode 100644 index 5b7e5a239..000000000 --- a/src/main/java/com/box/sdk/BoxComment.java +++ /dev/null @@ -1,299 +0,0 @@ -package com.box.sdk; - -import java.net.URL; -import java.text.ParseException; -import java.util.Date; -import java.util.regex.Pattern; - -import com.eclipsesource.json.JsonObject; -import com.eclipsesource.json.JsonValue; - -/** - * 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.

- */ -public class BoxComment extends BoxResource { - private static final Pattern MENTION_REGEX = Pattern.compile("@\\[.+:.+\\]"); - private static final URLTemplate ADD_COMMENT_URL_TEMPLATE = new URLTemplate("comments"); - private static final URLTemplate COMMENT_URL_TEMPLATE = new URLTemplate("comments/%s"); - - /** - * 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()); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - JsonObject jsonResponse = JsonObject.readFrom(response.getJSON()); - - 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()); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - JsonObject jsonResponse = JsonObject.readFrom(response.getJSON()); - - 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); - } - - URL url = ADD_COMMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL()); - BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST"); - request.setBody(requestJSON.toString()); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); - - 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"); - BoxAPIResponse response = request.send(); - response.disconnect(); - } - - /** - * 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; - - /** - * 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; - } - - /** - * 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; - } - - @Override - public BoxComment getResource() { - return BoxComment.this; - } - - @Override - protected void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - - try { - String memberName = member.getName(); - JsonValue value = member.getValue(); - 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); - } - } - } catch (ParseException e) { - assert false : "A ParseException indicates a bug in the SDK."; - } - } - - 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 updateItemAsComment(JsonObject itemJSON) { - String itemType = itemJSON.get("type").asString(); - 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/BoxDateFormat.java b/src/main/java/com/box/sdk/BoxDateFormat.java deleted file mode 100644 index 5d3571c09..000000000 --- a/src/main/java/com/box/sdk/BoxDateFormat.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.box.sdk; - -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; - -/** - * 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 = new ThreadLocal() { - @Override - protected DateFormat initialValue() { - return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); - } - }; - - 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 { - return THREAD_LOCAL_DATE_FORMAT.get().parse(fixIso8601TimeZone(dateString)); - } - - /** - * 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.get().format(date); - } - - /** - * Helper function to handle ISO 8601 strings of the following format: - * "2008-03-01T13:00:00+01:00". Note that the final colon (":") in the - * time zone is not supported by SimpleDateFormat's "Z" token. - * - * @param dateString a string containing the date. - * @return a date string that matches the date format. - */ - private static String fixIso8601TimeZone(String dateString) { - if (dateString.length() >= 24 && dateString.charAt(22) == ':') { - return dateString.substring(0, 22) + dateString.substring(23); - } - return dateString; - } -} diff --git a/src/main/java/com/box/sdk/BoxEvent.java b/src/main/java/com/box/sdk/BoxEvent.java deleted file mode 100644 index 58357f16c..000000000 --- a/src/main/java/com/box/sdk/BoxEvent.java +++ /dev/null @@ -1,214 +0,0 @@ -package com.box.sdk; - -import com.eclipsesource.json.JsonObject; -import com.eclipsesource.json.JsonValue; - -/** - * Represents an event that was fired off by the Box events API. - */ -public class BoxEvent extends BoxResource { - private BoxResource.Info sourceInfo; - private BoxEvent.Type type; - - /** - * 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, JsonObject.readFrom(json)); - } - - 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. - * @return info about the source of this event. - */ - public BoxResource.Info getSourceInfo() { - return this.sourceInfo; - } - - /** - * Gets the type of this event. - * @return the type of this event. - */ - public BoxEvent.Type getType() { - return this.type; - } - - void parseJsonMember(JsonObject.Member member) { - JsonValue value = member.getValue(); - if (value.isNull()) { - return; - } - - String memberName = member.getName(); - if (memberName.equals("source")) { - this.sourceInfo = BoxResource.parseInfo(this.getAPI(), value.asObject()); - - } else if (memberName.equals("event_type")) { - String stringValue = value.asString(); - for (Type t : Type.values()) { - if (t.name().equals(stringValue)) { - this.type = t; - break; - } - } - - if (this.type == null) { - this.type = Type.UNKNOWN; - } - } - } - - /** - * Enumerates the possible types for an event. - */ - public enum Type { - /** - * The type of the event is unknown. - */ - UNKNOWN, - - /** - * An file or folder was created. - */ - ITEM_CREATE, - - /** - * An file or folder was uploaded. - */ - ITEM_UPLOAD, - - /** - * A comment was created on a folder, file, or other comment. - */ - COMMENT_CREATE, - - /** - * An file or folder was downloaded. - */ - ITEM_DOWNLOAD, - - /** - * A file was previewed. - */ - ITEM_PREVIEW, - - /** - * A file or folder was moved. - */ - ITEM_MOVE, - - /** - * A file or folder was copied. - */ - ITEM_COPY, - - /** - * A task was assigned. - */ - TASK_ASSIGNMENT_CREATE, - - /** - * A file was locked. - */ - LOCK_CREATE, - - /** - * A file was unlocked. - */ - LOCK_DESTROY, - - /** - * A file or folder was deleted. - */ - ITEM_TRASH, - - /** - * A file or folder was recovered from the trash. - */ - ITEM_UNDELETE_VIA_TRASH, - - /** - * A collaborator was added to a folder. - */ - COLLAB_ADD_COLLABORATOR, - - /** - * A collaborator was removed from a folder. - */ - COLLAB_REMOVE_COLLABORATOR, - - /** - * A collaborator was invited to a folder. - */ - COLLAB_INVITE_COLLABORATOR, - - /** - * A collaborator's role was change in a folder. - */ - COLLAB_ROLE_CHANGE, - - /** - * A folder was marked for sync. - */ - ITEM_SYNC, - - /** - * A folder was un-marked for sync. - */ - ITEM_UNSYNC, - - /** - * A file or folder was renamed. - */ - ITEM_RENAME, - - /** - * A file or folder was enabled for sharing. - */ - ITEM_SHARED_CREATE, - - /** - * A file or folder was disabled for sharing. - */ - ITEM_SHARED_UNSHARE, - - /** - * A folder was shared. - */ - ITEM_SHARED, - - /** - * A tag was added to a file or folder. - */ - TAG_ITEM_CREATE, - - /** - * A user logged in from a new device. - */ - ADD_LOGIN_ACTIVITY_DEVICE, - - /** - * A user session associated with an app was invalidated. - */ - REMOVE_LOGIN_ACTIVITY_DEVICE, - - /** - * An admin role changed for a user. - */ - CHANGE_ADMIN_ROLE; - } -} diff --git a/src/main/java/com/box/sdk/BoxFile.java b/src/main/java/com/box/sdk/BoxFile.java deleted file mode 100644 index b08eacb18..000000000 --- a/src/main/java/com/box/sdk/BoxFile.java +++ /dev/null @@ -1,667 +0,0 @@ -package com.box.sdk; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.URL; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.EnumSet; -import java.util.List; - -import com.eclipsesource.json.JsonArray; -import com.eclipsesource.json.JsonObject; -import com.eclipsesource.json.JsonValue; - -/** - * 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.

- */ -public class BoxFile extends BoxItem { - /** - * An array of all possible file fields that can be requested when calling {@link #getInfo()}. - */ - 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"}; - - private static final URLTemplate FILE_URL_TEMPLATE = new URLTemplate("files/%s"); - private static final URLTemplate CONTENT_URL_TEMPLATE = new URLTemplate("files/%s/content"); - private static final URLTemplate VERSIONS_URL_TEMPLATE = new URLTemplate("files/%s/versions"); - private static final URLTemplate COPY_URL_TEMPLATE = new URLTemplate("files/%s/copy"); - private static final URLTemplate ADD_COMMENT_URL_TEMPLATE = new URLTemplate("comments"); - private static final URLTemplate GET_COMMENTS_URL_TEMPLATE = new URLTemplate("files/%s/comments"); - private static final URLTemplate METADATA_URL_TEMPLATE = new URLTemplate("files/%s/metadata/%s"); - private static final String DEFAULT_METADATA_TYPE = "properties"; - private static final int BUFFER_SIZE = 8192; - - /** - * 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); - } - - @Override - public BoxSharedLink createSharedLink(BoxSharedLink.Access access, Date unshareDate, - BoxSharedLink.Permissions permissions) { - - BoxSharedLink sharedLink = new BoxSharedLink(access, unshareDate, permissions); - Info info = new Info(); - info.setSharedLink(sharedLink); - - this.updateInfo(info); - return info.getSharedLink(); - } - - /** - * 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. - * @see the tagged_message field - * for including @mentions. - * @param message the comment's message. - * @return information about the newly added comment. - */ - 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()); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); - - BoxComment addedComment = new BoxComment(this.getAPI(), responseJSON.get("id").asString()); - return addedComment.new Info(responseJSON); - } - - /** - * 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 = CONTENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); - BoxAPIResponse response = request.send(); - InputStream input = response.getBody(listener); - - byte[] buffer = new byte[BUFFER_SIZE]; - try { - int n = input.read(buffer); - while (n != -1) { - output.write(buffer, 0, n); - n = input.read(buffer); - } - } catch (IOException e) { - throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e); - } - - response.disconnect(); - } - - /** - * 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 = CONTENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); - if (rangeEnd > 0) { - request.addHeader("Range", String.format("bytes=%s-%s", Long.toString(rangeStart), - Long.toString(rangeEnd))); - } else { - request.addHeader("Range", String.format("bytes=%s-", Long.toString(rangeStart))); - } - - BoxAPIResponse response = request.send(); - InputStream input = response.getBody(listener); - - byte[] buffer = new byte[BUFFER_SIZE]; - try { - int n = input.read(buffer); - while (n != -1) { - output.write(buffer, 0, n); - n = input.read(buffer); - } - } catch (IOException e) { - throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e); - } - - response.disconnect(); - } - - @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()); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); - 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"); - BoxAPIResponse response = request.send(); - response.disconnect(); - } - - @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()); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); - 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()); - BoxAPIResponse response = request.send(); - response.disconnect(); - } - - @Override - public BoxFile.Info getInfo() { - URL url = FILE_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - return new Info(response.getJSON()); - } - - @Override - public BoxFile.Info getInfo(String... fields) { - String queryString = new QueryStringBuilder().appendParam("fields", fields).toString(); - URL url = FILE_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID()); - - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - return new Info(response.getJSON()); - } - - /** - * 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()); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - JsonObject jsonObject = JsonObject.readFrom(response.getJSON()); - info.update(jsonObject); - } - - /** - * Gets any previous versions of this file. Note that only users with premium accounts will be able to retrieve - * previous versions of their files. - * @return a list of previous file versions. - */ - public Collection getVersions() { - URL url = VERSIONS_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - - JsonObject jsonObject = JsonObject.readFrom(response.getJSON()); - JsonArray entries = jsonObject.get("entries").asArray(); - Collection versions = new ArrayList(); - for (JsonValue entry : entries) { - versions.add(new BoxFileVersion(this.getAPI(), entry.asObject(), this.getID())); - } - - return versions; - } - - /** - * 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. - */ - public void uploadVersion(InputStream fileContent) { - this.uploadVersion(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 modified the date that the new version was modified. - */ - public void uploadVersion(InputStream fileContent, Date modified) { - this.uploadVersion(fileContent, modified, 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. - */ - public void uploadVersion(InputStream fileContent, Date modified, 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 (modified != null) { - request.putField("content_modified_at", modified); - } - - BoxAPIResponse response; - if (listener == null) { - response = request.send(); - } else { - response = request.send(listener); - } - response.disconnect(); - } - - /** - * 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()); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); - - 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; - } - - /** - * Creates metadata on this file. - * @param metadata The new metadata values. - * @return the metadata returned from the server. - */ - public Metadata createMetadata(Metadata metadata) { - return this.createMetadata(DEFAULT_METADATA_TYPE, metadata); - } - - /** - * Creates the metadata of specified type. - * @param typeName the metadata type name. - * @param metadata the new metadata values. - * @return the metadata returned from the server. - */ - public Metadata createMetadata(String typeName, Metadata metadata) { - URL url = METADATA_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), typeName); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "POST"); - request.addHeader("Content-Type", "application/json"); - request.setBody(metadata.toString()); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - return new Metadata(JsonObject.readFrom(response.getJSON())); - } - - /** - * Gets the file properties metadata. - * @return the metadata returned from the server. - */ - public Metadata getMetadata() { - return this.getMetadata(DEFAULT_METADATA_TYPE); - } - - /** - * Gets the file metadata of specified type. - * @param typeName the metadata type name. - * @return the metadata returned from the server. - */ - public Metadata getMetadata(String typeName) { - URL url = METADATA_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), typeName); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - return new Metadata(JsonObject.readFrom(response.getJSON())); - } - - /** - * Updates the file metadata. - * @param metadata the new metadata values. - * @return the metadata returned from the server. - */ - public Metadata updateMetadata(Metadata metadata) { - URL url = METADATA_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), metadata.getTypeName()); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "PUT"); - request.addHeader("Content-Type", "application/json-patch+json"); - request.setBody(metadata.getPatch()); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - return new Metadata(JsonObject.readFrom(response.getJSON())); - } - - /** - * Deletes the file properties metadata. - */ - public void deleteMetadata() { - this.deleteMetadata(DEFAULT_METADATA_TYPE); - } - - /** - * Deletes the file metadata of specified type. - * @param typeName the metadata type name. - */ - public void deleteMetadata(String typeName) { - URL url = METADATA_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), typeName); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); - request.send(); - } - - /** - * 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; - - /** - * 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 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 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; - } - - @Override - protected void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - - String memberName = member.getName(); - JsonValue value = member.getValue(); - if (memberName.equals("sha1")) { - this.sha1 = value.asString(); - } else if (memberName.equals("version_number")) { - this.versionNumber = value.asString(); - } else if (memberName.equals("comment_count")) { - this.commentCount = value.asLong(); - } else if (memberName.equals("permissions")) { - this.permissions = this.parsePermissions(value.asObject()); - } else if (memberName.equals("extension")) { - this.extension = value.asString(); - } else if (memberName.equals("is_package")) { - this.isPackage = value.asBoolean(); - } - } - - 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; - } - - String memberName = member.getName(); - if (memberName.equals("can_download")) { - permissions.add(Permission.CAN_DOWNLOAD); - } else if (memberName.equals("can_upload")) { - permissions.add(Permission.CAN_UPLOAD); - } else if (memberName.equals("can_rename")) { - permissions.add(Permission.CAN_RENAME); - } else if (memberName.equals("can_delete")) { - permissions.add(Permission.CAN_DELETE); - } else if (memberName.equals("can_share")) { - permissions.add(Permission.CAN_SHARE); - } else if (memberName.equals("can_set_share_access")) { - permissions.add(Permission.CAN_SET_SHARE_ACCESS); - } else if (memberName.equals("can_preview")) { - permissions.add(Permission.CAN_PREVIEW); - } else if (memberName.equals("can_comment")) { - permissions.add(Permission.CAN_COMMENT); - } - } - - return permissions; - } - } - - /** - * 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"); - - private final String jsonValue; - - private Permission(String jsonValue) { - this.jsonValue = jsonValue; - } - - static Permission fromJSONValue(String jsonValue) { - return Permission.valueOf(jsonValue.toUpperCase()); - } - - String toJSONValue() { - return this.jsonValue; - } - } -} diff --git a/src/main/java/com/box/sdk/BoxFileVersion.java b/src/main/java/com/box/sdk/BoxFileVersion.java deleted file mode 100644 index 0d68521dd..000000000 --- a/src/main/java/com/box/sdk/BoxFileVersion.java +++ /dev/null @@ -1,183 +0,0 @@ -package com.box.sdk; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.URL; -import java.text.ParseException; -import java.util.Date; - -import com.eclipsesource.json.JsonObject; -import com.eclipsesource.json.JsonValue; - -/** - * Represents a particular version of a file on Box. - */ -public class BoxFileVersion extends BoxResource { - private static final URLTemplate CONTENT_URL_TEMPLATE = new URLTemplate("files/%s/content?version=%s"); - private static final URLTemplate VERSION_URL_TEMPLATE = new URLTemplate("files/%s/versions/%s"); - private static final int BUFFER_SIZE = 8192; - - private final String fileID; - - private String sha1; - private String name; - private long size; - private Date createdAt; - private Date modifiedAt; - private BoxUser.Info modifiedBy; - - /** - * 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, JsonObject.readFrom(json), fileID); - } - - BoxFileVersion(BoxAPIConnection api, JsonObject jsonObject, String fileID) { - super(api, jsonObject.get("id").asString()); - - this.fileID = fileID; - for (JsonObject.Member member : jsonObject) { - JsonValue value = member.getValue(); - if (value.isNull()) { - continue; - } - - try { - String memberName = member.getName(); - 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("created_at")) { - this.createdAt = BoxDateFormat.parse(value.asString()); - } else if (memberName.equals("modified_at")) { - this.modifiedAt = BoxDateFormat.parse(value.asString()); - } 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); - } - } catch (ParseException e) { - assert false : "A ParseException indicates a bug in the SDK."; - } - } - } - - /** - * 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 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 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; - } - - /** - * 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"); - BoxAPIResponse response = request.send(); - response.disconnect(); - } - - /** - * 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"); - BoxAPIResponse response = request.send(); - InputStream input = response.getBody(listener); - - long totalRead = 0; - byte[] buffer = new byte[BUFFER_SIZE]; - try { - int n = input.read(buffer); - totalRead += n; - while (n != -1) { - output.write(buffer, 0, n); - n = input.read(buffer); - totalRead += n; - } - } catch (IOException e) { - throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e); - } - - response.disconnect(); - } - - /** - * Promotes this version of the file to be the latest version. - */ - public void promote() { - URL url = VERSION_URL_TEMPLATE.build(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()); - BoxAPIResponse response = request.send(); - response.disconnect(); - } -} diff --git a/src/main/java/com/box/sdk/BoxFolder.java b/src/main/java/com/box/sdk/BoxFolder.java deleted file mode 100644 index a87b75598..000000000 --- a/src/main/java/com/box/sdk/BoxFolder.java +++ /dev/null @@ -1,697 +0,0 @@ -package com.box.sdk; - -import java.io.InputStream; -import java.net.URL; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.EnumSet; -import java.util.Iterator; - -import com.eclipsesource.json.JsonArray; -import com.eclipsesource.json.JsonObject; -import com.eclipsesource.json.JsonValue; - -/** - * 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.

- */ -public class BoxFolder extends BoxItem implements Iterable { - /** - * An array of all possible folder fields that can be requested when calling {@link #getInfo()}. - */ - 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"}; - - private static final URLTemplate CREATE_FOLDER_URL = new URLTemplate("folders"); - private static final URLTemplate COPY_FOLDER_URL = new URLTemplate("folders/%s/copy"); - private static final URLTemplate DELETE_FOLDER_URL = new URLTemplate("folders/%s?recursive=%b"); - private static final URLTemplate FOLDER_INFO_URL_TEMPLATE = new URLTemplate("folders/%s"); - private static final URLTemplate UPLOAD_FILE_URL = new URLTemplate("files/content"); - private static final URLTemplate ADD_COLLABORATION_URL = new URLTemplate("collaborations"); - private static final URLTemplate GET_COLLABORATIONS_URL = new URLTemplate("folders/%s/collaborations"); - private static final URLTemplate GET_ITEMS_URL = new URLTemplate("folders/%s/items/"); - private static final URLTemplate SEARCH_URL_TEMPLATE = new URLTemplate("search"); - - /** - * 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"); - } - - /** - * 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 { - throw new IllegalArgumentException("The given collaborator is of an unknown type."); - } - - return this.collaborate(accessibleByField, role); - } - - /** - * 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); - } - - private BoxCollaboration.Info collaborate(JsonObject accessibleByField, BoxCollaboration.Role role) { - BoxAPIConnection api = this.getAPI(); - URL url = ADD_COLLABORATION_URL.build(api.getBaseURL()); - - JsonObject itemField = new JsonObject(); - itemField.add("id", this.getID()); - itemField.add("type", "folder"); - - JsonObject requestJSON = new JsonObject(); - requestJSON.add("item", itemField); - requestJSON.add("accessible_by", accessibleByField); - requestJSON.add("role", role.toJSONString()); - - BoxJSONRequest request = new BoxJSONRequest(api, url, "POST"); - request.setBody(requestJSON.toString()); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); - - BoxCollaboration newCollaboration = new BoxCollaboration(api, responseJSON.get("id").asString()); - BoxCollaboration.Info info = newCollaboration.new Info(responseJSON); - return info; - } - - @Override - public BoxSharedLink createSharedLink(BoxSharedLink.Access access, Date unshareDate, - BoxSharedLink.Permissions permissions) { - - BoxSharedLink sharedLink = new BoxSharedLink(access, unshareDate, permissions); - Info info = new Info(); - info.setSharedLink(sharedLink); - - this.updateInfo(info); - return info.getSharedLink(); - } - - /** - * Gets information about all of the collaborations for this folder. - * @return a collection of information about the collaborations for this folder. - */ - public Collection getCollaborations() { - BoxAPIConnection api = this.getAPI(); - URL url = GET_COLLABORATIONS_URL.build(api.getBaseURL(), this.getID()); - - BoxAPIRequest request = new BoxAPIRequest(api, url, "GET"); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); - - 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() { - URL url = FOLDER_INFO_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - return new Info(response.getJSON()); - } - - @Override - public BoxFolder.Info getInfo(String... fields) { - String queryString = new QueryStringBuilder().appendParam("fields", fields).toString(); - URL url = FOLDER_INFO_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID()); - - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); - BoxJSONResponse response = (BoxJSONResponse) 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()); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - JsonObject jsonObject = JsonObject.readFrom(response.getJSON()); - 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()); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); - 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()); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); - - 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.build(this.getAPI().getBaseURL(), this.getID(), recursive); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); - BoxAPIResponse response = request.send(); - response.disconnect(); - } - - @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()); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); - 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()); - BoxAPIResponse response = request.send(); - response.disconnect(); - } - - /** - * 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 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 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); - request.putField("parent_id", getID()); - - if (uploadParams.getSize() > 0) { - request.setFile(uploadParams.getContent(), uploadParams.getName(), uploadParams.getSize()); - } else { - request.setFile(uploadParams.getContent(), uploadParams.getName()); - } - - if (uploadParams.getCreated() != null) { - request.putField("content_created_at", uploadParams.getCreated()); - } - - if (uploadParams.getModified() != null) { - request.putField("content_modified_at", uploadParams.getModified()); - } - - BoxJSONResponse response; - if (uploadParams.getProgressListener() == null) { - response = (BoxJSONResponse) request.send(); - } else { - response = (BoxJSONResponse) request.send(uploadParams.getProgressListener()); - } - JsonObject collection = JsonObject.readFrom(response.getJSON()); - 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); - } - - /** - * 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 new Iterable() { - @Override - public Iterator iterator() { - String queryString = new QueryStringBuilder().appendParam("fields", fields).toString(); - URL url = GET_ITEMS_URL.buildWithQuery(getAPI().getBaseURL(), queryString, getID()); - return new BoxItemIterator(getAPI(), url); - } - }; - } - - /** - * 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).toString(); - } - - URL url = GET_ITEMS_URL.buildWithQuery(getAPI().getBaseURL(), builder.toString(), getID()); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); - - 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 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); - } - - /** - * Searches this folder and all descendant folders using a given query. - * @param query the search query. - * @return an Iterable containing the search results. - */ - public Iterable search(final String query) { - return new Iterable() { - @Override - public Iterator iterator() { - QueryStringBuilder builder = new QueryStringBuilder(); - builder.appendParam("query", query); - builder.appendParam("ancestor_folder_ids", getID()); - - URL url = SEARCH_URL_TEMPLATE.buildWithQuery(getAPI().getBaseURL(), builder.toString()); - return new BoxItemIterator(getAPI(), url); - } - }; - } - - /** - * 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; - - /** - * 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 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", 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; - } - - @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(); - if (memberName.equals("folder_upload_email")) { - if (this.uploadEmail == null) { - this.uploadEmail = new BoxUploadEmail(value.asObject()); - } else { - this.uploadEmail.update(value.asObject()); - } - - } else if (memberName.equals("has_collaborations")) { - this.hasCollaborations = value.asBoolean(); - - } else if (memberName.equals("sync_state")) { - this.syncState = SyncState.fromJSONValue(value.asString()); - - } else if (memberName.equals("permissions")) { - this.permissions = this.parsePermissions(value.asObject()); - - } else if (memberName.equals("can_non_owners_invite")) { - this.canNonOwnersInvite = value.asBoolean(); - } - } - - 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; - } - - String memberName = member.getName(); - if (memberName.equals("can_download")) { - permissions.add(Permission.CAN_DOWNLOAD); - } else if (memberName.equals("can_upload")) { - permissions.add(Permission.CAN_UPLOAD); - } else if (memberName.equals("can_rename")) { - permissions.add(Permission.CAN_RENAME); - } else if (memberName.equals("can_delete")) { - permissions.add(Permission.CAN_DELETE); - } else if (memberName.equals("can_share")) { - permissions.add(Permission.CAN_SHARE); - } else if (memberName.equals("can_invite_collaborator")) { - permissions.add(Permission.CAN_INVITE_COLLABORATOR); - } else if (memberName.equals("can_set_share_access")) { - permissions.add(Permission.CAN_SET_SHARE_ACCESS); - } - } - - return permissions; - } - } - - /** - * 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; - - private SyncState(String jsonValue) { - this.jsonValue = jsonValue; - } - - static SyncState fromJSONValue(String jsonValue) { - return SyncState.valueOf(jsonValue.toUpperCase()); - } - - String toJSONValue() { - return this.jsonValue; - } - } - - /** - * 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; - - private Permission(String jsonValue) { - this.jsonValue = jsonValue; - } - - static Permission fromJSONValue(String jsonValue) { - return Permission.valueOf(jsonValue.toUpperCase()); - } - - String toJSONValue() { - return this.jsonValue; - } - } -} diff --git a/src/main/java/com/box/sdk/BoxGroup.java b/src/main/java/com/box/sdk/BoxGroup.java deleted file mode 100644 index fd3a8eb04..000000000 --- a/src/main/java/com/box/sdk/BoxGroup.java +++ /dev/null @@ -1,116 +0,0 @@ -package com.box.sdk; - -import java.net.URL; -import java.util.Iterator; - -import com.eclipsesource.json.JsonObject; - -/** - * 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.

- */ -public class BoxGroup extends BoxCollaborator { - private static final URLTemplate GROUPS_URL_TEMPLATE = new URLTemplate("groups"); - private static final URLTemplate GROUP_URL_TEMPLATE = new URLTemplate("groups/%s"); - - /** - * 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) { - JsonObject requestJSON = new JsonObject(); - requestJSON.add("name", name); - - URL url = GROUPS_URL_TEMPLATE.build(api.getBaseURL()); - BoxJSONRequest request = new BoxJSONRequest(api, url, "POST"); - request.setBody(requestJSON.toString()); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); - - BoxGroup group = new BoxGroup(api, responseJSON.get("id").asString()); - return group.new Info(responseJSON); - } - - /** - * Gets an iterable of all the groups that the current user is a member of. - * @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 new Iterable() { - public Iterator iterator() { - URL url = GROUPS_URL_TEMPLATE.build(api.getBaseURL()); - return new BoxGroupIterator(api, url); - } - }; - } - - /** - * Gets information about this group. - * @return info about this group. - */ - public Info getInfo() { - URL url = GROUP_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); - return new Info(responseJSON); - } - - /** - * 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"); - BoxAPIResponse response = request.send(); - response.disconnect(); - } - - /** - * Contains information about a BoxGroup. - */ - public class Info extends BoxCollaborator.Info { - /** - * 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 BoxGroup getResource() { - return BoxGroup.this; - } - } -} diff --git a/src/main/java/com/box/sdk/BoxGroupIterator.java b/src/main/java/com/box/sdk/BoxGroupIterator.java deleted file mode 100644 index 19af1e0bf..000000000 --- a/src/main/java/com/box/sdk/BoxGroupIterator.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.box.sdk; - -import java.net.URL; -import java.util.Iterator; - -import com.eclipsesource.json.JsonObject; - -class BoxGroupIterator implements Iterator { - private static final long LIMIT = 1000; - - private final BoxAPIConnection api; - private final JSONIterator jsonIterator; - - BoxGroupIterator(BoxAPIConnection api, URL url) { - this.api = api; - this.jsonIterator = new JSONIterator(api, url, LIMIT); - } - - public boolean hasNext() { - return this.jsonIterator.hasNext(); - } - - 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); - } - - public void remove() { - throw new UnsupportedOperationException(); - } -} diff --git a/src/main/java/com/box/sdk/BoxItem.java b/src/main/java/com/box/sdk/BoxItem.java deleted file mode 100644 index d5fa5dfc1..000000000 --- a/src/main/java/com/box/sdk/BoxItem.java +++ /dev/null @@ -1,447 +0,0 @@ -package com.box.sdk; - -import java.net.URL; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import com.eclipsesource.json.JsonArray; -import com.eclipsesource.json.JsonObject; -import com.eclipsesource.json.JsonValue; - -/** - * 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()}. - */ - 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"}; - - private static final URLTemplate SHARED_ITEM_URL_TEMPLATE = new URLTemplate("shared_items"); - - /** - * 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. - * @return info about the shared item. - */ - public static BoxItem.Info getSharedItem(BoxAPIConnection api, String sharedLink, String password) { - BoxAPIConnection newAPI = new SharedLinkAPIConnection(api, sharedLink, password); - URL url = SHARED_ITEM_URL_TEMPLATE.build(newAPI.getBaseURL()); - BoxAPIRequest request = new BoxAPIRequest(newAPI, url, "GET"); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - JsonObject json = JsonObject.readFrom(response.getJSON()); - return (BoxItem.Info) BoxResource.parseInfo(newAPI, json); - } - - /** - * 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); - - /** - * Creates a new shared link for this item. - * - *

This method is a convenience method for manually creating a new shared link and applying it to this item with - * {@link Info#setSharedLink}. You may want to create the shared link manually so that it can be updated along with - * other changes to the item's info in a single network request, giving a boost to performance.

- * - * @param access the access level of the shared link. - * @param unshareDate the date and time at which the link will expire. Can be null to create a non-expiring link. - * @param permissions the permissions of the shared link. Can be null to use the default permissions. - * @return the created shared link. - */ - public abstract BoxSharedLink createSharedLink(BoxSharedLink.Access access, Date unshareDate, - BoxSharedLink.Permissions permissions); - - /** - * Gets information about this item. - * @return info about this item. - */ - public abstract BoxItem.Info getInfo(); - - /** - * 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); - - /** - * Contains information about a BoxItem. - */ - public abstract class Info extends BoxResource.Info { - 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; - - /** - * 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 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; - } - - /** - * 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 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; - } - - /** - * Sets a shared link for the item. - * @param sharedLink the shared link for the item. - */ - public void setSharedLink(BoxSharedLink sharedLink) { - if (this.sharedLink == sharedLink) { - return; - } - - this.removeChildObject("shared_link"); - this.sharedLink = sharedLink; - this.addChildObject("shared_link", sharedLink); - } - - /** - * 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 info about the parent folder of the item. - * @return info abou thte 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; - } - - @Override - protected void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - - try { - JsonValue value = member.getValue(); - String memberName = member.getName(); - if (memberName.equals("sequence_id")) { - this.sequenceID = value.asString(); - } else if (memberName.equals("etag")) { - this.etag = value.asString(); - } else if (memberName.equals("name")) { - this.name = 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("description")) { - this.description = value.asString(); - } else if (memberName.equals("size")) { - this.size = Double.valueOf(value.toString()).longValue(); - } else if (memberName.equals("trashed_at")) { - this.trashedAt = BoxDateFormat.parse(value.asString()); - } else if (memberName.equals("purged_at")) { - this.purgedAt = BoxDateFormat.parse(value.asString()); - } else if (memberName.equals("content_created_at")) { - this.contentCreatedAt = BoxDateFormat.parse(value.asString()); - } else if (memberName.equals("content_modified_at")) { - this.contentModifiedAt = BoxDateFormat.parse(value.asString()); - } else if (memberName.equals("path_collection")) { - this.pathCollection = this.parsePathCollection(value.asObject()); - } else if (memberName.equals("created_by")) { - this.createdBy = this.parseUserInfo(value.asObject()); - } else if (memberName.equals("modified_by")) { - this.modifiedBy = this.parseUserInfo(value.asObject()); - } else if (memberName.equals("owned_by")) { - this.ownedBy = this.parseUserInfo(value.asObject()); - } else if (memberName.equals("shared_link")) { - if (this.sharedLink == null) { - this.setSharedLink(new BoxSharedLink(value.asObject())); - } else { - this.sharedLink.update(value.asObject()); - } - } else if (memberName.equals("tags")) { - this.tags = this.parseTags(value.asArray()); - } else if (memberName.equals("parent")) { - JsonObject jsonObject = value.asObject(); - if (this.parent == null) { - String id = jsonObject.get("id").asString(); - BoxFolder parentFolder = new BoxFolder(getAPI(), id); - this.parent = parentFolder.new Info(jsonObject); - } else { - this.parent.update(jsonObject); - } - } else if (memberName.equals("item_status")) { - this.itemStatus = value.asString(); - } - } catch (ParseException e) { - assert false : "A ParseException indicates a bug in the SDK."; - } - } - - 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(); - pathCollection.add(new BoxFolder(getAPI(), id)); - } - - 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 List parseTags(JsonArray jsonArray) { - List tags = new ArrayList(jsonArray.size()); - for (JsonValue value : jsonArray) { - tags.add(value.asString()); - } - - return tags; - } - } -} diff --git a/src/main/java/com/box/sdk/BoxItemIterator.java b/src/main/java/com/box/sdk/BoxItemIterator.java deleted file mode 100644 index e6d0e8792..000000000 --- a/src/main/java/com/box/sdk/BoxItemIterator.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.box.sdk; - -import java.net.URL; -import java.util.Iterator; - -import com.eclipsesource.json.JsonObject; - -class BoxItemIterator implements Iterator { - private static final long LIMIT = 1000; - - private final BoxAPIConnection api; - private final JSONIterator jsonIterator; - - BoxItemIterator(BoxAPIConnection api, URL url) { - this.api = api; - - this.jsonIterator = new JSONIterator(api, url, LIMIT); - this.jsonIterator.setFilter(new Filter() { - @Override - public boolean shouldInclude(JsonObject jsonObject) { - String type = jsonObject.get("type").asString(); - return (type.equals("file") || type.equals("folder")); - } - }); - } - - public boolean hasNext() { - return this.jsonIterator.hasNext(); - } - - public BoxItem.Info next() { - JsonObject nextJSONObject = this.jsonIterator.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 { - assert false : "Unsupported item type: " + type; - throw new BoxAPIException("Unsupported item type: " + type); - } - - return nextItemInfo; - } - - 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 deleted file mode 100644 index 0b25372f8..000000000 --- a/src/main/java/com/box/sdk/BoxJSONObject.java +++ /dev/null @@ -1,174 +0,0 @@ -package com.box.sdk; - -import java.util.HashMap; -import java.util.Map; - -import com.eclipsesource.json.JsonObject; -import com.eclipsesource.json.JsonValue; - -/** - * 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 { - /** - * The JsonObject that contains any local pending changes. When getPendingChanges is called, this object will be - * encoded to a JSON string. - */ - private JsonObject pendingChanges; - - /** - * 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; - - /** - * 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(JsonObject.readFrom(json)); - } - - /** - * 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(); - } - - /** - * 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, JsonValue.valueOf(value)); - } - - void addChildObject(String fieldName, BoxJSONObject child) { - if (child == null) { - this.addPendingChange(fieldName, JsonValue.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. - * @param jsonObject the JSON object containing updated information. - */ - void update(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. - */ - private 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; - } -} diff --git a/src/main/java/com/box/sdk/BoxJSONRequest.java b/src/main/java/com/box/sdk/BoxJSONRequest.java deleted file mode 100644 index c67e51a40..000000000 --- a/src/main/java/com/box/sdk/BoxJSONRequest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.box.sdk; - -import java.net.URL; - -/** - * 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.

- */ -public class BoxJSONRequest extends BoxAPIRequest { - private String 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, String method) { - super(api, url, method); - - this.addHeader("Content-Type", "application/json"); - } - - /** - * 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.json = body; - } - - @Override - protected String bodyToString() { - return this.json; - } -} diff --git a/src/main/java/com/box/sdk/BoxJSONResponse.java b/src/main/java/com/box/sdk/BoxJSONResponse.java deleted file mode 100644 index eb7746f18..000000000 --- a/src/main/java/com/box/sdk/BoxJSONResponse.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.box.sdk; - -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; - -/** - * 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.

- */ -public class BoxJSONResponse extends BoxAPIResponse { - private static final int BUFFER_SIZE = 8192; - - private String json; - - /** - * Constructs a BoxJSONResponse using an HttpURLConnection. - * @param connection a connection that has already sent a request to the API. - */ - public BoxJSONResponse(HttpURLConnection connection) { - super(connection); - } - - /** - * 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.json != null) { - return this.json; - } - - 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.disconnect(); - reader.close(); - } catch (IOException e) { - throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e); - } - this.json = builder.toString(); - return this.json; - } - - @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/BoxMultipartRequest.java b/src/main/java/com/box/sdk/BoxMultipartRequest.java deleted file mode 100644 index c4fb01482..000000000 --- a/src/main/java/com/box/sdk/BoxMultipartRequest.java +++ /dev/null @@ -1,203 +0,0 @@ -package com.box.sdk; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * 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.

- * - */ -public class BoxMultipartRequest extends BoxAPIRequest { - private static final Logger LOGGER = Logger.getLogger(BoxMultipartRequest.class.getName()); - private static final String BOUNDARY = "da39a3ee5e6b4b0d3255bfef95601890afd80709"; - private static final int BUFFER_SIZE = 8192; - - private final StringBuilder loggedRequest = new StringBuilder(); - - private OutputStream outputStream; - private InputStream inputStream; - private String filename; - private long fileSize; - private Map fields; - private boolean firstBoundary; - - /** - * 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, "POST"); - - this.fields = new HashMap(); - this.firstBoundary = true; - - this.addHeader("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); - } - - /** - * 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 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. - */ - public void setFile(InputStream inputStream, String filename, long fileSize) { - this.setFile(inputStream, filename); - this.fileSize = fileSize; - } - - /** - * 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(); - } - - @Override - protected void writeBody(HttpURLConnection connection, ProgressListener listener) { - try { - connection.setChunkedStreamingMode(0); - connection.setDoOutput(true); - this.outputStream = connection.getOutputStream(); - - this.writePartHeader(new String[][] {{"name", "filename"}, {"filename", this.filename}}, - "application/octet-stream"); - - OutputStream fileContentsOutputStream = this.outputStream; - if (listener != null) { - fileContentsOutputStream = new ProgressOutputStream(this.outputStream, listener, this.fileSize); - } - byte[] buffer = new byte[BUFFER_SIZE]; - int n = this.inputStream.read(buffer); - while (n != -1) { - fileContentsOutputStream.write(buffer, 0, n); - n = this.inputStream.read(buffer); - } - - if (LOGGER.isLoggable(Level.FINE)) { - this.loggedRequest.append(""); - } - - for (Map.Entry entry : this.fields.entrySet()) { - this.writePartHeader(new String[][] {{"name", entry.getKey()}}); - this.writeOutput(entry.getValue()); - } - - this.writeBoundary(); - } catch (IOException e) { - throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e); - } - } - - @Override - protected void resetBody() throws IOException { - this.firstBoundary = true; - this.inputStream.reset(); - this.loggedRequest.setLength(0); - } - - @Override - protected String bodyToString() { - return this.loggedRequest.toString(); - } - - private void writeBoundary() throws IOException { - if (!this.firstBoundary) { - this.writeOutput("\r\n"); - } - - this.firstBoundary = false; - this.writeOutput("--"); - this.writeOutput(BOUNDARY); - } - - private void writePartHeader(String[][] formData) throws IOException { - this.writePartHeader(formData, null); - } - - private void writePartHeader(String[][] formData, String contentType) throws IOException { - this.writeBoundary(); - this.writeOutput("\r\n"); - this.writeOutput("Content-Disposition: form-data"); - for (int i = 0; i < formData.length; i++) { - this.writeOutput("; "); - this.writeOutput(formData[i][0]); - this.writeOutput("=\""); - this.writeOutput(formData[i][1]); - this.writeOutput("\""); - } - - if (contentType != null) { - this.writeOutput("\r\nContent-Type: "); - this.writeOutput(contentType); - } - - this.writeOutput("\r\n\r\n"); - } - - private void writeOutput(String s) throws IOException { - this.outputStream.write(s.getBytes(StandardCharsets.UTF_8)); - if (LOGGER.isLoggable(Level.FINE)) { - this.loggedRequest.append(s); - } - } - - private void writeOutput(int b) throws IOException { - this.outputStream.write(b); - } -} diff --git a/src/main/java/com/box/sdk/BoxResource.java b/src/main/java/com/box/sdk/BoxResource.java deleted file mode 100644 index c73bb0acc..000000000 --- a/src/main/java/com/box/sdk/BoxResource.java +++ /dev/null @@ -1,138 +0,0 @@ -package com.box.sdk; - -import com.eclipsesource.json.JsonObject; - -/** - * 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.

- */ -public abstract class BoxResource { - 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; - } - - static BoxResource.Info parseInfo(BoxAPIConnection api, JsonObject jsonObject) { - String type = jsonObject.get("type").asString(); - String id = jsonObject.get("id").asString(); - - if (type.equals("folder")) { - BoxFolder folder = new BoxFolder(api, id); - return folder.new Info(jsonObject); - } else if (type.equals("file")) { - BoxFile file = new BoxFile(api, id); - return file.new Info(jsonObject); - } else if (type.equals("comment")) { - BoxComment comment = new BoxComment(api, id); - return comment.new Info(jsonObject); - } else if (type.equals("collaboration")) { - BoxCollaboration collaboration = new BoxCollaboration(api, id); - return collaboration.new Info(jsonObject); - } else if (type.equals("user")) { - BoxUser user = new BoxUser(api, id); - return user.new Info(jsonObject); - } else if (type.equals("group")) { - BoxGroup group = new BoxGroup(api, id); - return group.new Info(jsonObject); - } else { - return null; - } - } - - /** - * 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; - } - - if (this.getClass().equals(other.getClass())) { - BoxResource otherResource = (BoxResource) other; - return this.getID().equals(otherResource.getID()); - } - - 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(); - } - - /** - * 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(); - } -} diff --git a/src/main/java/com/box/sdk/BoxSharedLink.java b/src/main/java/com/box/sdk/BoxSharedLink.java deleted file mode 100644 index c031eca53..000000000 --- a/src/main/java/com/box/sdk/BoxSharedLink.java +++ /dev/null @@ -1,291 +0,0 @@ -package com.box.sdk; - -import java.text.ParseException; -import java.util.Date; - -import com.eclipsesource.json.JsonObject; -import com.eclipsesource.json.JsonValue; - -/** - * 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 boolean isPasswordEnabled; - private Date unsharedAt; - private long downloadCount; - private long previewCount; - private Access access; - 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); - } - } - - /** - * 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; - } - - /** - * 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", unsharedDate.toString()); - } - - /** - * 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 acccess level of this shared link. - */ - public void setAccess(Access access) { - this.access = access; - this.addPendingChange("access", access.toJSONValue()); - } - - /** - * 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 == permissions) { - return; - } - - this.removeChildObject("permissions"); - this.permissions = permissions; - this.addChildObject("permissions", permissions); - } - - @Override - void parseJSONMember(JsonObject.Member member) { - JsonValue value = member.getValue(); - try { - String memberName = member.getName(); - 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("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")) { - String accessString = value.asString().toUpperCase(); - this.access = Access.valueOf(accessString); - } else if (memberName.equals("permissions")) { - if (this.permissions == null) { - this.setPermissions(new Permissions(value.asObject())); - } else { - this.permissions.update(value.asObject()); - } - } - } catch (ParseException e) { - assert false : "A ParseException indicates a bug in the SDK."; - } - } - - /** - * Contains permissions fields that can be set on a shared link. - */ - public static class Permissions extends BoxJSONObject { - private boolean canDownload; - private boolean canPreview; - - /** - * Constructs a Permissions object with all permissions disabled. - */ - public Permissions() { } - - /** - * 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 or not 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 or not 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 or not 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); - } - - @Override - void parseJSONMember(JsonObject.Member member) { - JsonValue value = member.getValue(); - String memberName = member.getName(); - if (memberName.equals("can_download")) { - this.canDownload = value.asBoolean(); - } else if (memberName.equals("can_preview")) { - this.canPreview = value.asBoolean(); - } - } - } - - /** - * 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; - - private Access(String jsonValue) { - this.jsonValue = jsonValue; - } - - String toJSONValue() { - return this.jsonValue; - } - } -} diff --git a/src/main/java/com/box/sdk/BoxTrash.java b/src/main/java/com/box/sdk/BoxTrash.java deleted file mode 100644 index a7814c898..000000000 --- a/src/main/java/com/box/sdk/BoxTrash.java +++ /dev/null @@ -1,219 +0,0 @@ -package com.box.sdk; - -import java.net.URL; -import java.util.Iterator; - -import com.eclipsesource.json.JsonObject; - -/** - * 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.

- */ -public class BoxTrash implements Iterable { - private static final long LIMIT = 1000; - private static final URLTemplate GET_ITEMS_URL = new URLTemplate("folders/trash/items/"); - private static final URLTemplate FOLDER_INFO_URL_TEMPLATE = new URLTemplate("folders/%s/trash"); - private static final URLTemplate FILE_INFO_URL_TEMPLATE = new URLTemplate("files/%s/trash"); - private static final URLTemplate RESTORE_FILE_URL_TEMPLATE = new URLTemplate("files/%s"); - private 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"); - BoxAPIResponse response = request.send(); - response.disconnect(); - } - - /** - * 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); - BoxAPIRequest request = new BoxAPIRequest(this.api, url, "GET"); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - JsonObject jsonObject = JsonObject.readFrom(response.getJSON()); - - 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); - BoxAPIRequest request = new BoxAPIRequest(this.api, url, "GET"); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - JsonObject jsonObject = JsonObject.readFrom(response.getJSON()); - - 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); - BoxAPIRequest request = new BoxAPIRequest(this.api, url, "POST"); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); - - 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); - } - - 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()); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); - - BoxFolder restoredFolder = new BoxFolder(this.api, responseJSON.get("id").asString()); - return restoredFolder.new Info(responseJSON); - } - - /** - * 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"); - BoxAPIResponse response = request.send(); - response.disconnect(); - } - - /** - * 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); - BoxAPIRequest request = new BoxAPIRequest(this.api, url, "GET"); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - JsonObject jsonObject = JsonObject.readFrom(response.getJSON()); - - BoxFile file = new BoxFile(this.api, jsonObject.get("id").asString()); - return file.new Info(response.getJSON()); - } - - /** - * 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); - BoxAPIRequest request = new BoxAPIRequest(this.api, url, "GET"); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - JsonObject jsonObject = JsonObject.readFrom(response.getJSON()); - - 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); - BoxAPIRequest request = new BoxAPIRequest(this.api, url, "POST"); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); - - BoxFile restoredFile = new BoxFile(this.api, responseJSON.get("id").asString()); - return restoredFile.new Info(responseJSON); - } - - /** - * 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"); - request.setBody(requestJSON.toString()); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - JsonObject responseJSON = JsonObject.readFrom(response.getJSON()); - - BoxFile restoredFile = new BoxFile(this.api, responseJSON.get("id").asString()); - return restoredFile.new Info(responseJSON); - } - - /** - * Returns an iterator over the items in the trash. - * @return an iterator over the items in the trash. - */ - public Iterator iterator() { - URL url = GET_ITEMS_URL.build(this.api.getBaseURL()); - return new BoxItemIterator(this.api, url); - } -} diff --git a/src/main/java/com/box/sdk/BoxUploadEmail.java b/src/main/java/com/box/sdk/BoxUploadEmail.java deleted file mode 100644 index f7551a0ca..000000000 --- a/src/main/java/com/box/sdk/BoxUploadEmail.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.box.sdk; - -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. - */ -public class BoxUploadEmail extends BoxJSONObject { - private Access access; - private String email; - - /** - * 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); - } - - 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; - } - - /** - * 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; - } - - @Override - void parseJSONMember(JsonObject.Member member) { - JsonValue value = member.getValue(); - String memberName = member.getName(); - if (memberName.equals("access")) { - this.access = Access.fromJSONValue(value.asString()); - } else if (memberName.equals("email")) { - this.email = value.asString(); - } - } - - /** - * 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"); - - private final String jsonValue; - - private Access(String jsonValue) { - this.jsonValue = jsonValue; - } - - static Access fromJSONValue(String jsonValue) { - return Access.valueOf(jsonValue.toUpperCase()); - } - - 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 deleted file mode 100644 index c00b8d53e..000000000 --- a/src/main/java/com/box/sdk/BoxUser.java +++ /dev/null @@ -1,263 +0,0 @@ -package com.box.sdk; - -import java.net.URL; - -import com.eclipsesource.json.JsonObject; -import com.eclipsesource.json.JsonValue; - -/** - * 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.

- */ -public class BoxUser extends BoxCollaborator { - private static final URLTemplate GET_USER_URL = new URLTemplate("users/%s"); - private static final URLTemplate GET_ME_URL = new URLTemplate("users/me"); - - /** - * 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); - } - - /** - * 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()); - BoxAPIRequest request = new BoxAPIRequest(api, url, "GET"); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - JsonObject jsonObject = JsonObject.readFrom(response.getJSON()); - return new BoxUser(api, jsonObject.get("id").asString()); - } - - /** - * Gets information about this user. - * @return info about this user. - */ - public BoxUser.Info getInfo() { - URL url = GET_USER_URL.build(this.getAPI().getBaseURL(), this.getID()); - BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - JsonObject jsonObject = JsonObject.readFrom(response.getJSON()); - return new Info(jsonObject); - } - - /** - * Enumerates the possible roles that a user can have within an enterprise. - */ - public enum Role { - /** - * The user is an administrator of their enterprise. - */ - ADMIN, - - /** - * The user is a co-administrator of their enterprise. - */ - COADMIN, - - /** - * The user is a regular user within their enterprise. - */ - USER - } - - /** - * Enumerates the possible statuses that a user's account can have. - */ - public enum Status { - /** - * The user's account is active. - */ - ACTIVE, - - /** - * The user's account is inactive. - */ - INACTIVE, - - /** - * The user's account cannot delete or edit content. - */ - CANNOT_DELETE_EDIT, - - /** - * The user's account cannot delete, edit, or upload content. - */ - CANNOT_DELETE_EDIT_UPLOAD - } - - /** - * 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 Status status; - private String jobTitle; - private String phone; - private String address; - private String avatarURL; - - 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; - } - - /** - * Gets the user's enterprise role. - * @return the user's enterprise role. - */ - public Role getRole() { - return this.role; - } - - /** - * Gets the language of the user. - * @return the language of the user. - */ - public String getLanguage() { - return this.language; - } - - /** - * Gets the timezone of the user. - * @return the timezone of the user. - */ - public String getTimezone() { - return this.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; - } - - /** - * 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; - } - - /** - * Gets the job title of the user. - * @return the job title of the user. - */ - public String getJobTitle() { - return this.jobTitle; - } - - /** - * Gets the phone number of the user. - * @return the phone number of the user. - */ - public String getPhone() { - return this.phone; - } - - /** - * Gets the address of the user. - * @return the address of the user. - */ - public String getAddress() { - return this.address; - } - - /** - * Gets the URL of the user's avatar. - * @return the URL of the user's avatar. - */ - public String getAvatarURL() { - return this.avatarURL; - } - - @Override - protected void parseJSONMember(JsonObject.Member member) { - super.parseJSONMember(member); - - JsonValue value = member.getValue(); - String memberName = member.getName(); - if (memberName.equals("login")) { - this.login = value.asString(); - } else if (memberName.equals("role")) { - this.role = this.parseRole(value); - } else if (memberName.equals("language")) { - this.language = value.asString(); - } else if (memberName.equals("timezone")) { - this.timezone = value.asString(); - } else if (memberName.equals("space_amount")) { - this.spaceAmount = Double.valueOf(value.toString()).longValue(); - } else if (memberName.equals("space_used")) { - this.spaceUsed = Double.valueOf(value.toString()).longValue(); - } else if (memberName.equals("max_upload_size")) { - this.maxUploadSize = Double.valueOf(value.toString()).longValue(); - } else if (memberName.equals("status")) { - this.status = this.parseStatus(value); - } else if (memberName.equals("job_title")) { - this.jobTitle = value.asString(); - } else if (memberName.equals("phone")) { - this.phone = value.asString(); - } else if (memberName.equals("address")) { - this.address = value.asString(); - } else if (memberName.equals("avatar_url")) { - this.avatarURL = value.asString(); - } - } - - private Role parseRole(JsonValue value) { - String roleString = value.asString().toUpperCase(); - return Role.valueOf(roleString); - } - - private Status parseStatus(JsonValue value) { - String statusString = value.asString().toUpperCase(); - return Status.valueOf(statusString); - } - } -} diff --git a/src/main/java/com/box/sdk/EventListener.java b/src/main/java/com/box/sdk/EventListener.java deleted file mode 100644 index daef86501..000000000 --- a/src/main/java/com/box/sdk/EventListener.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.box.sdk; - -/** - * 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 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); -} diff --git a/src/main/java/com/box/sdk/EventStream.java b/src/main/java/com/box/sdk/EventStream.java deleted file mode 100644 index f523aa732..000000000 --- a/src/main/java/com/box/sdk/EventStream.java +++ /dev/null @@ -1,206 +0,0 @@ -package com.box.sdk; - -import java.util.ArrayList; -import java.util.Collection; - -import com.eclipsesource.json.JsonArray; -import com.eclipsesource.json.JsonObject; -import com.eclipsesource.json.JsonValue; - -/** - * 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 or enterprise 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.

- * - */ -public class EventStream { - private static final int LIMIT = 800; - private static final URLTemplate EVENT_URL = new URLTemplate("events?limit=" + LIMIT + "&stream_position=%s"); - private static final int STREAM_POSITION_NOW = -1; - - private final BoxAPIConnection api; - private final long startingPosition; - 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); - } - - /** - * 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 = api; - this.startingPosition = startingPosition; - this.listeners = new ArrayList(); - this.listenerLock = new Object(); - } - - /** - * 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); - } - } - - /** - * 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."); - } - - 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."); - } - - final long initialPosition; - - if (this.startingPosition == STREAM_POSITION_NOW) { - BoxAPIRequest request = new BoxAPIRequest(this.api, EVENT_URL.build(this.api.getBaseURL(), "now"), "GET"); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - JsonObject jsonObject = JsonObject.readFrom(response.getJSON()); - initialPosition = jsonObject.get("next_stream_position").asLong(); - } else { - initialPosition = this.startingPosition; - } - - this.poller = new Poller(initialPosition); - - this.pollerThread = new Thread(this.poller); - this.pollerThread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { - public void uncaughtException(Thread t, Throwable 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 notifyNextPosition(long position) { - synchronized (this.listenerLock) { - for (EventListener listener : this.listeners) { - listener.onNextPosition(position); - } - } - } - - 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 void notifyException(Throwable e) { - if (e instanceof InterruptedException && !this.started) { - return; - } - - this.stop(); - synchronized (this.listenerLock) { - for (EventListener listener : this.listeners) { - if (listener.onException(e)) { - return; - } - } - } - } - - private class Poller implements Runnable { - private final long initialPosition; - - private RealtimeServerConnection server; - - public 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); - } - - if (this.server.waitForChange(position)) { - if (Thread.interrupted()) { - return; - } - - BoxAPIRequest request = new BoxAPIRequest(EventStream.this.api, - EVENT_URL.build(EventStream.this.api.getBaseURL(), position), "GET"); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - JsonObject jsonObject = JsonObject.readFrom(response.getJSON()); - 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); - } - } - } - } -} diff --git a/src/main/java/com/box/sdk/FileUploadParams.java b/src/main/java/com/box/sdk/FileUploadParams.java deleted file mode 100644 index 4836fe825..000000000 --- a/src/main/java/com/box/sdk/FileUploadParams.java +++ /dev/null @@ -1,129 +0,0 @@ -package com.box.sdk; - -import java.io.InputStream; -import java.util.Date; - -/** - * Contains parameters for configuring an upload to Box. - */ -public class FileUploadParams { - private InputStream content; - private String name; - private Date created; - private Date modified; - private long size; - private ProgressListener listener; - - /** - * 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; - } - - /** - * 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. - * @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. - * @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; - } -} diff --git a/src/main/java/com/box/sdk/Filter.java b/src/main/java/com/box/sdk/Filter.java deleted file mode 100644 index 795826582..000000000 --- a/src/main/java/com/box/sdk/Filter.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.box.sdk; - -interface Filter { - boolean shouldInclude(T object); -} diff --git a/src/main/java/com/box/sdk/JSONIterator.java b/src/main/java/com/box/sdk/JSONIterator.java deleted file mode 100644 index 8fc19a7c3..000000000 --- a/src/main/java/com/box/sdk/JSONIterator.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.box.sdk; - -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Iterator; -import java.util.NoSuchElementException; - -import com.eclipsesource.json.JsonArray; -import com.eclipsesource.json.JsonObject; -import com.eclipsesource.json.JsonValue; - -class JSONIterator implements Iterator { - private final BoxAPIConnection api; - private final URL url; - - private long limit; - private long offset; - private long totalCount; - private boolean hasMorePages; - private Iterator currentPage; - private JsonObject nextJsonObject; - private Filter filter; - - public JSONIterator(BoxAPIConnection api, URL url, long limit) { - this.api = api; - this.url = url; - this.limit = limit; - } - - public boolean hasNext() { - if (this.nextJsonObject == null) { - this.nextJsonObject = this.loadNextJsonObject(); - } - - return this.nextJsonObject != null; - } - - 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; - } - - public void remove() { - throw new UnsupportedOperationException(); - } - - public void setFilter(Filter filter) { - this.filter = filter; - } - - private void loadNextPage() { - String existingQuery = this.url.getQuery(); - QueryStringBuilder builder = new QueryStringBuilder(existingQuery); - builder.appendParam("limit", this.limit); - builder.appendParam("offset", this.offset); - - URL url; - try { - url = builder.addToURL(this.url); - } catch (MalformedURLException e) { - throw new BoxAPIException("Couldn't append a query string to the provided URL."); - } - - BoxAPIRequest request = new BoxAPIRequest(this.api, url, "GET"); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - String json = response.getJSON(); - - JsonObject jsonObject = JsonObject.readFrom(json); - String totalCountString = jsonObject.get("total_count").toString(); - this.totalCount = Double.valueOf(totalCountString).longValue(); - String offsetString = jsonObject.get("offset").toString(); - this.hasMorePages = (this.offset + this.limit) < this.totalCount; - this.offset = Double.valueOf(offsetString).longValue() + this.limit; - - JsonArray jsonArray = jsonObject.get("entries").asArray(); - this.currentPage = jsonArray.iterator(); - } - - 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.shouldInclude(jsonObject)) { - return jsonObject; - } - } - - 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 deleted file mode 100644 index 77e791e7f..000000000 --- a/src/main/java/com/box/sdk/LRUCache.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.box.sdk; - -import java.util.Iterator; -import java.util.LinkedHashSet; - -class LRUCache { - static final int MAX_SIZE = 512; - - private final LinkedHashSet linkedHashSet; - - public LRUCache() { - this.linkedHashSet = new LinkedHashSet(MAX_SIZE); - } - - boolean add(E item) { - boolean newItem = !this.linkedHashSet.remove(item); - this.linkedHashSet.add(item); - - 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/Metadata.java b/src/main/java/com/box/sdk/Metadata.java deleted file mode 100644 index 393fe1aee..000000000 --- a/src/main/java/com/box/sdk/Metadata.java +++ /dev/null @@ -1,172 +0,0 @@ -package com.box.sdk; - -import com.eclipsesource.json.JsonArray; -import com.eclipsesource.json.JsonObject; -import com.eclipsesource.json.JsonValue; - -/** - * The Metadata class represents one type instance of Box metadata. - * - * Learn more about Box metadata: - * https://developers.box.com/metadata-api/ - */ -public class Metadata { - private final JsonObject values; - private JsonArray operations; - - /** - * Creates an empty metadata. - */ - public Metadata() { - this.values = new JsonObject(); - } - - /** - * Creates a new metadata. - * @param values the initial metadata values. - */ - 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); - } - - /** - * Returns the 36 character UUID to identify the metadata object. - * @return the metadata ID. - */ - public String getID() { - return this.get("/$id"); - } - - /** - * Returns the metadata type. - * @return the metadata type. - */ - public String getTypeName() { - return this.get("/$type"); - } - - /** - * Returns the parent object ID (typically the file ID). - * @return the parent object ID. - */ - public String getParentID() { - return this.get("/$parent"); - } - - /** - * Adds a new metdata 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; - } - - /** - * Replaces an existing metdata 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; - } - - /** - * 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, 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; - } - - /** - * Returns a value. - * @param path the path that designates the key. Must be prefixed with a "/". - * @return the metadata property value. - */ - public String get(String path) { - final JsonValue value = this.values.get(this.pathToProperty(path)); - if (value == null) { - return null; - } - return value.asString(); - } - - /** - * 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 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); - } - - /** - * 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)); - } -} diff --git a/src/main/java/com/box/sdk/PartialCollection.java b/src/main/java/com/box/sdk/PartialCollection.java deleted file mode 100644 index db4274905..000000000 --- a/src/main/java/com/box/sdk/PartialCollection.java +++ /dev/null @@ -1,132 +0,0 @@ -package com.box.sdk; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; - -/** - * A collection that contains a subset of items that are a part of a larger collection. The items within a partial - * collection begin at an offset within the full collection and end at a specified limit. Note that the actual size of a - * partial collection may be less than its limit since the limit only specifies the maximum size. For example, if - * there's a full collection with a size of 3, then a partial collection with offset 0 and limit 3 would be equal to a - * partial collection with offset 0 and limit 100. - * @param the type of elements in this partial collection. - */ -public class PartialCollection implements Collection { - private final Collection collection; - private final long offset; - private final long limit; - private final long fullSize; - - /** - * Constructs a PartialCollection with a specified offset, limit, and full size. - * @param offset the offset within in the full collection. - * @param limit the maximum number of items after the offset. - * @param fullSize the total number of items in the full collection. - */ - public PartialCollection(long offset, long limit, long fullSize) { - this.collection = new ArrayList(); - this.offset = offset; - this.limit = limit; - this.fullSize = fullSize; - } - - /** - * Gets the offset within the full collection where this collection's items begin. - * @return the offset within the full collection where this collection's items begin. - */ - public long offset() { - return this.offset; - } - - /** - * Gets the maximum number of items within the full collection that begin at {@link #offset}. - * @return the maximum number of items within the full collection that begin at the offset. - */ - public long limit() { - return this.limit; - } - - /** - * Gets the size of the full collection that this partial collection is based off of. - * @return the size of the full collection that this partial collection is based off of. - */ - public long fullSize() { - return this.fullSize; - } - - @Override - public boolean add(E e) { - return this.collection.add(e); - } - - @Override - public boolean addAll(Collection c) { - return this.collection.addAll(c); - } - - @Override - public void clear() { - this.collection.clear(); - } - - @Override - public boolean contains(Object o) { - return this.collection.contains(o); - } - - @Override - public boolean containsAll(Collection c) { - return this.collection.containsAll(c); - } - - @Override - public boolean equals(Object o) { - return this.collection.equals(o); - } - - @Override - public int hashCode() { - return this.collection.hashCode(); - } - - @Override - public boolean isEmpty() { - return this.collection.isEmpty(); - } - - @Override - public Iterator iterator() { - return this.collection.iterator(); - } - - @Override - public boolean remove(Object o) { - return this.collection.remove(o); - } - - @Override - public boolean removeAll(Collection c) { - return this.collection.removeAll(c); - } - - @Override - public boolean retainAll(Collection c) { - return this.collection.retainAll(c); - } - - @Override - public int size() { - return this.collection.size(); - } - - @Override - public Object[] toArray() { - return this.collection.toArray(); - } - - @Override - public T[] toArray(T[] a) { - return this.collection.toArray(a); - } -} diff --git a/src/main/java/com/box/sdk/ProgressInputStream.java b/src/main/java/com/box/sdk/ProgressInputStream.java deleted file mode 100644 index 5cf468e71..000000000 --- a/src/main/java/com/box/sdk/ProgressInputStream.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.box.sdk; - -import java.io.IOException; -import java.io.InputStream; - -/** - * An {@link InputStream} that can report the progress of reading from another InputStream to a - * {@link ProgressListener}. - */ -class ProgressInputStream extends InputStream { - private final InputStream stream; - private final ProgressListener listener; - - private long total; - private long totalRead; - private int progress; - - /** - * Constructs a ProgressInputStream that wraps another InputStream. - * @param stream the stream whose progress will be monitored. - * @param listener the listener that will receive progress updates. - * @param total the total number of bytes that are expected to be read from the stream. - */ - public ProgressInputStream(InputStream stream, ProgressListener listener, long total) { - this.stream = stream; - this.listener = listener; - this.total = total; - } - - /** - * Gets the total number of bytes that are expected to be read from the stream. - * @return the total number of bytes. - */ - public long getTotal() { - return this.total; - } - - /** - * Sets the total number of bytes that are expected to be read from the stream. - * @param total the total number of bytes - */ - public void setTotal(long total) { - this.total = total; - } - - @Override - public void close() throws IOException { - this.stream.close(); - } - - @Override - public int read() throws IOException { - int read = this.stream.read(); - this.totalRead++; - this.listener.onProgressChanged(this.totalRead, this.total); - - return read; - } - - @Override - public int read(byte[] b, int off, int len) throws IOException { - int read = this.stream.read(b, off, len); - this.totalRead += read; - this.listener.onProgressChanged(this.totalRead, this.total); - - return read; - } -} diff --git a/src/main/java/com/box/sdk/ProgressListener.java b/src/main/java/com/box/sdk/ProgressListener.java deleted file mode 100644 index f6c4e584d..000000000 --- a/src/main/java/com/box/sdk/ProgressListener.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.box.sdk; - -/** - * The listener interface for monitoring the progress of a long-running API call. - */ -public interface ProgressListener { - - /** - * Invoked when the progress of the API call changes. - * @param numBytes the number of bytes completed. - * @param totalBytes the total number of bytes. - */ - void onProgressChanged(long numBytes, long totalBytes); -} diff --git a/src/main/java/com/box/sdk/ProgressOutputStream.java b/src/main/java/com/box/sdk/ProgressOutputStream.java deleted file mode 100644 index 58a1f9150..000000000 --- a/src/main/java/com/box/sdk/ProgressOutputStream.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.box.sdk; - -import java.io.IOException; -import java.io.OutputStream; - -/** - * An {@link OutputStream} that can report the progress of writing to another OutputStream to a - * {@link ProgressListener}. - */ -class ProgressOutputStream extends OutputStream { - private final OutputStream stream; - private final ProgressListener listener; - - private long total; - private long totalWritten; - private int progress; - - public ProgressOutputStream(OutputStream stream, ProgressListener listener, long total) { - this.stream = stream; - this.listener = listener; - this.total = total; - } - - public long getTotal() { - return this.total; - } - - public void setTotal(long total) { - this.total = total; - } - - @Override - public void close() throws IOException { - this.stream.close(); - } - - @Override - public void write(byte[] b) throws IOException { - this.stream.write(b); - this.totalWritten += b.length; - this.listener.onProgressChanged(this.totalWritten, this.total); - } - - @Override - public void write(byte[] b, int off, int len) throws IOException { - this.stream.write(b, off, len); - if (len < b.length) { - this.totalWritten += len; - } else { - this.totalWritten += b.length; - } - this.listener.onProgressChanged(this.totalWritten, this.total); - } - - @Override - public void write(int b) throws IOException { - this.stream.write(b); - this.totalWritten++; - this.listener.onProgressChanged(this.totalWritten, this.total); - } -} diff --git a/src/main/java/com/box/sdk/QueryStringBuilder.java b/src/main/java/com/box/sdk/QueryStringBuilder.java deleted file mode 100644 index 4b866727f..000000000 --- a/src/main/java/com/box/sdk/QueryStringBuilder.java +++ /dev/null @@ -1,131 +0,0 @@ -package com.box.sdk; - -import java.net.MalformedURLException; -import java.net.URL; - -class QueryStringBuilder { - private final StringBuilder stringBuilder; - - QueryStringBuilder() { - this.stringBuilder = new StringBuilder(); - } - - QueryStringBuilder(String existing) { - if (existing == null) { - this.stringBuilder = new StringBuilder(); - } else { - this.stringBuilder = new StringBuilder(existing); - } - } - - QueryStringBuilder appendParam(String key, String... fields) { - StringBuilder valuesBuilder = new StringBuilder(); - for (String field : fields) { - valuesBuilder.append(field); - valuesBuilder.append(","); - } - valuesBuilder.deleteCharAt(valuesBuilder.length() - 1); - - this.appendParam(key, valuesBuilder.toString()); - return this; - } - - QueryStringBuilder appendParam(String key, String value) { - if (this.stringBuilder.length() == 0) { - this.stringBuilder.append('?'); - } else { - this.stringBuilder.append('&'); - } - - this.stringBuilder.append(key); - this.stringBuilder.append('='); - this.stringBuilder.append(this.encode(value)); - return this; - } - - QueryStringBuilder appendParam(String key, long value) { - return this.appendParam(key, Long.toString(value)); - } - - URL addToURL(URL existing) throws MalformedURLException { - String existingQuery = existing.getQuery(); - if (existingQuery == null || existingQuery.equals("")) { - return new URL(existing.toString() + this.toString()); - } - - return new URL(existing.toString().replace(existingQuery, this.toString())); - } - - @Override - public String toString() { - return this.stringBuilder.toString(); - } - - private String encode(String unencoded) { - StringBuilder encodedBuilder = new StringBuilder(); - for (int i = 0, n = unencoded.length(); i < n; i++) { - char c = unencoded.charAt(i); - switch (c) { - case ' ': - encodedBuilder.append('+'); - break; - case '!': - encodedBuilder.append("%21"); - break; - case '#': - encodedBuilder.append("%23"); - break; - case '$': - encodedBuilder.append("%24"); - break; - case '&': - encodedBuilder.append("%26"); - break; - case '\'': - encodedBuilder.append("%27"); - break; - case '(': - encodedBuilder.append("%28"); - break; - case ')': - encodedBuilder.append("%29"); - break; - case '+': - encodedBuilder.append("%2b"); - break; - case ',': - encodedBuilder.append("%2c"); - break; - case '/': - encodedBuilder.append("%2f"); - break; - case ':': - encodedBuilder.append("%3a"); - break; - case ';': - encodedBuilder.append("%3b"); - break; - case '=': - encodedBuilder.append("%3d"); - break; - case '?': - encodedBuilder.append("%3f"); - break; - case '@': - encodedBuilder.append("%40"); - break; - case '[': - encodedBuilder.append("%5b"); - break; - case ']': - encodedBuilder.append("%5d"); - break; - default: - encodedBuilder.append(c); - break; - } - } - - return encodedBuilder.toString(); - } -} diff --git a/src/main/java/com/box/sdk/RealtimeServerConnection.java b/src/main/java/com/box/sdk/RealtimeServerConnection.java deleted file mode 100644 index 82e461ef0..000000000 --- a/src/main/java/com/box/sdk/RealtimeServerConnection.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.box.sdk; - -import java.net.MalformedURLException; -import java.net.URL; - -import com.eclipsesource.json.JsonArray; -import com.eclipsesource.json.JsonObject; - -class RealtimeServerConnection { - private static final URLTemplate EVENT_URL = new URLTemplate("events"); - private static final URLTemplate EVENT_POSITION_URL = new URLTemplate("events?stream_position=%s"); - - private final BoxAPIConnection api; - private final int timeout; - private final String serverURLString; - - private int retries; - private BoxJSONResponse response; - - RealtimeServerConnection(BoxAPIConnection api) { - BoxAPIRequest request = new BoxAPIRequest(api, EVENT_URL.build(api.getBaseURL()), "OPTIONS"); - BoxJSONResponse response = (BoxJSONResponse) request.send(); - JsonObject jsonObject = JsonObject.readFrom(response.getJSON()); - JsonArray entries = jsonObject.get("entries").asArray(); - JsonObject firstEntry = entries.get(0).asObject(); - this.serverURLString = firstEntry.get("url").asString(); - this.retries = Integer.parseInt(firstEntry.get("max_retries").asString()); - this.timeout = firstEntry.get("retry_timeout").asInt(); - this.api = api; - } - - int getRemainingRetries() { - return this.retries; - } - - boolean waitForChange(long position) { - if (this.retries < 1) { - throw new IllegalStateException("No more retries are allowed."); - } - - URL url; - try { - String u = this.serverURLString + "&stream_position=" + position; - url = new URL(u); - } catch (MalformedURLException e) { - throw new BoxAPIException("The long poll URL was malformed.", e); - } - - while (this.retries > 0) { - this.retries--; - try { - BoxAPIRequest request = new BoxAPIRequest(this.api, url, "GET"); - request.setTimeout(this.timeout * 1000); - this.response = (BoxJSONResponse) request.send(); - JsonObject jsonObject = JsonObject.readFrom(this.response.getJSON()); - String message = jsonObject.get("message").asString(); - if (message.equals("new_change")) { - return true; - } - } catch (BoxAPIException e) { - break; - } - } - - return false; - } -} diff --git a/src/main/java/com/box/sdk/RequestInterceptor.java b/src/main/java/com/box/sdk/RequestInterceptor.java deleted file mode 100644 index 40b4adafc..000000000 --- a/src/main/java/com/box/sdk/RequestInterceptor.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.box.sdk; - -/** - * The interface for intercepting requests to the Box API. - * - *

An interceptor may handle a request in any way it sees fit. It may update a request before it's sent, or it may - * choose to return a custom response. If an interceptor returns a null response, then the request will continue to be - * sent to the API along with any changes that the interceptor may have made to it.

- * - *
public BoxAPIResponse onRequest(BoxAPIRequest request) {
- *    request.addHeader("My-Header", "My-Value");
- *
- *    // Returning null means the request will be sent along with our new header.
- *    return null;
- *}
- * - *

However, if a response is returned, then the request won't be sent and the interceptor's response will take the - * place of the normal response.

- * - *
public BoxAPIResponse onRequest(BoxAPIRequest request) {
- *    // Returning our own response means the request won't be sent at all.
- *    return new BoxAPIResponse();
- *}
- * - *

A RequestInterceptor can be very useful for testing purposes. Requests to the Box API can be intercepted and fake - * responses can be returned, allowing you to effectively test your code without needing to actually communicate with - * the Box API.

- */ -public interface RequestInterceptor { - /** - * Invoked when a request is about to be sent to the API. - * @param request the request that is about to be sent. - * @return an optional response to the request. If the response is null, then the request will continue to - * be sent to the Box API. - */ - BoxAPIResponse onRequest(BoxAPIRequest request); -} diff --git a/src/main/java/com/box/sdk/SharedLinkAPIConnection.java b/src/main/java/com/box/sdk/SharedLinkAPIConnection.java deleted file mode 100644 index 0d5c0a693..000000000 --- a/src/main/java/com/box/sdk/SharedLinkAPIConnection.java +++ /dev/null @@ -1,134 +0,0 @@ -package com.box.sdk; - -/** - * This API connection uses a shared link (along with an optional password) to authenticate with the Box API. It wraps a - * preexisting BoxAPIConnection in order to provide additional access to items that are accessible with a shared link. - */ -class SharedLinkAPIConnection extends BoxAPIConnection { - private final BoxAPIConnection wrappedConnection; - private final String sharedLink; - private final String sharedLinkPassword; - - SharedLinkAPIConnection(BoxAPIConnection connection, String sharedLink) { - this(connection, sharedLink, null); - } - - SharedLinkAPIConnection(BoxAPIConnection connection, String sharedLink, String sharedLinkPassword) { - super(null); - - this.wrappedConnection = connection; - this.sharedLink = sharedLink; - this.sharedLinkPassword = sharedLinkPassword; - } - - @Override - public long getExpires() { - return this.wrappedConnection.getExpires(); - } - - @Override - public void setExpires(long milliseconds) { - this.wrappedConnection.setExpires(milliseconds); - } - - @Override - public String getBaseURL() { - return this.wrappedConnection.getBaseURL(); - } - - @Override - public void setBaseURL(String baseURL) { - this.wrappedConnection.setBaseURL(baseURL); - } - - @Override - public String getBaseUploadURL() { - return this.wrappedConnection.getBaseUploadURL(); - } - - @Override - public void setBaseUploadURL(String baseUploadURL) { - this.wrappedConnection.setBaseUploadURL(baseUploadURL); - } - - @Override - public String getUserAgent() { - return this.wrappedConnection.getUserAgent(); - } - - @Override - public void setUserAgent(String userAgent) { - this.wrappedConnection.setUserAgent(userAgent); - } - - @Override - public String getAccessToken() { - return this.wrappedConnection.getAccessToken(); - } - - @Override - public void setAccessToken(String accessToken) { - this.wrappedConnection.setAccessToken(accessToken); - } - - @Override - public String getRefreshToken() { - return this.wrappedConnection.getRefreshToken(); - } - - @Override - public void setRefreshToken(String refreshToken) { - this.wrappedConnection.setRefreshToken(refreshToken); - } - - @Override - public void setAutoRefresh(boolean autoRefresh) { - this.wrappedConnection.setAutoRefresh(autoRefresh); - } - - @Override - public boolean getAutoRefresh() { - return this.wrappedConnection.getAutoRefresh(); - } - - @Override - public int getMaxRequestAttempts() { - return this.wrappedConnection.getMaxRequestAttempts(); - } - - @Override - public void setMaxRequestAttempts(int attempts) { - this.wrappedConnection.setMaxRequestAttempts(attempts); - } - - @Override - public boolean canRefresh() { - return this.wrappedConnection.canRefresh(); - } - - @Override - public boolean needsRefresh() { - return this.wrappedConnection.needsRefresh(); - } - - @Override - public void refresh() { - this.wrappedConnection.refresh(); - } - - /** - * Gets the shared link used for accessing shared items. - * @return the shared link used for accessing shared items. - */ - String getSharedLink() { - return this.sharedLink; - } - - /** - * Gets the shared link password used for accessing shared items. - * @return the shared link password used for accessing shared items. - */ - String getSharedLinkPassword() { - return this.sharedLinkPassword; - } -} diff --git a/src/main/java/com/box/sdk/StandardCharsets.java b/src/main/java/com/box/sdk/StandardCharsets.java deleted file mode 100644 index 8b77db633..000000000 --- a/src/main/java/com/box/sdk/StandardCharsets.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.box.sdk; - -import java.nio.charset.Charset; - -/** - * Constant definitions for the standard Charsets. - * - * NB: Replace with java.nio.charset.StandardCharsets when we drop 1.6 support. - */ -public final class StandardCharsets { - - /** - * Eight-bit UCS Transformation Format. - */ - public static final Charset UTF_8 = Charset.forName("UTF-8"); - - private StandardCharsets() { - throw new UnsupportedOperationException(); - } -} diff --git a/src/main/java/com/box/sdk/Time.java b/src/main/java/com/box/sdk/Time.java deleted file mode 100644 index bc5881b2f..000000000 --- a/src/main/java/com/box/sdk/Time.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.box.sdk; - -class Time { - private static final ThreadLocal