From 95516d96c6502127697e3fd9cd20283e6ab1390b Mon Sep 17 00:00:00 2001 From: lsocha Date: Fri, 26 Sep 2025 14:07:39 +0200 Subject: [PATCH 01/19] wip --- .github/workflows/autoupdate-pr.yml | 39 + ...on-tests.yml => integration-tests-sdk.yml} | 18 +- ...daily.yml => integration-tests-sdkgen.yml} | 49 +- .github/workflows/releases.yml | 28 - .github/workflows/semantic-pr.yml | 2 + .github/workflows/spell-check-lint.yml | 8 +- .../{build-main.yml => unit-tests.yml} | 4 +- CHANGELOG.md | 2 +- build.gradle | 120 +- doc/sdk/ai.md | 148 --- doc/sdk/android.md | 97 -- doc/sdk/authentication.md | 271 ---- doc/sdk/classifications.md | 226 ---- doc/sdk/collaboration_allowlists.md | 147 --- doc/sdk/collaborations.md | 168 --- doc/sdk/collections.md | 104 -- doc/sdk/comments.md | 125 -- doc/sdk/configuration.md | 329 ----- doc/sdk/css/javadoc.css | 488 ------- doc/sdk/devices.md | 62 - doc/sdk/events.md | 244 ---- doc/sdk/file_requests.md | 77 -- doc/sdk/files.md | 1135 ----------------- doc/sdk/folders.md | 801 ------------ doc/sdk/groups.md | 218 ---- doc/sdk/legal_holds.md | 206 --- doc/sdk/logging.md | 101 -- doc/sdk/metadata_template.md | 189 --- doc/sdk/overview.md | 193 --- doc/sdk/recent_items.md | 33 - doc/sdk/retention_policies.md | 320 ----- doc/sdk/search.md | 52 - doc/sdk/shared-items.md | 32 - doc/sdk/sign_requests.md | 152 --- doc/sdk/sign_templates.md | 51 - doc/sdk/storage_policy.md | 132 -- doc/sdk/tasks.md | 182 --- doc/sdk/terms_of_service.md | 154 --- doc/sdk/trash.md | 189 --- doc/sdk/upgrading.md | 116 -- doc/sdk/users.md | 321 ----- doc/sdk/watermarking.md | 99 -- doc/sdk/webhooks.md | 156 --- doc/sdk/weblinks.md | 126 -- doc/sdk/zip_download.md | 58 - src/intTest/java/com/box/sdk/BoxAIIT.java | 4 +- .../box/sdk/BoxClassificationTemplateIT.java | 4 +- src/intTest/java/com/box/sdk/BoxFileIT.java | 3 +- .../resources/junit-platform.properties | 2 + .../java/com/box/sdk/BoxAPIConnection.java | 2 +- 50 files changed, 189 insertions(+), 7598 deletions(-) create mode 100644 .github/workflows/autoupdate-pr.yml rename .github/workflows/{integration-tests.yml => integration-tests-sdk.yml} (50%) rename .github/workflows/{build-and-test-daily.yml => integration-tests-sdkgen.yml} (55%) delete mode 100644 .github/workflows/releases.yml rename .github/workflows/{build-main.yml => unit-tests.yml} (93%) delete mode 100644 doc/sdk/ai.md delete mode 100644 doc/sdk/android.md delete mode 100644 doc/sdk/authentication.md delete mode 100644 doc/sdk/classifications.md delete mode 100644 doc/sdk/collaboration_allowlists.md delete mode 100644 doc/sdk/collaborations.md delete mode 100644 doc/sdk/collections.md delete mode 100644 doc/sdk/comments.md delete mode 100644 doc/sdk/configuration.md delete mode 100644 doc/sdk/css/javadoc.css delete mode 100644 doc/sdk/devices.md delete mode 100644 doc/sdk/events.md delete mode 100644 doc/sdk/file_requests.md delete mode 100644 doc/sdk/files.md delete mode 100644 doc/sdk/folders.md delete mode 100644 doc/sdk/groups.md delete mode 100644 doc/sdk/legal_holds.md delete mode 100644 doc/sdk/logging.md delete mode 100644 doc/sdk/metadata_template.md delete mode 100644 doc/sdk/overview.md delete mode 100644 doc/sdk/recent_items.md delete mode 100644 doc/sdk/retention_policies.md delete mode 100644 doc/sdk/search.md delete mode 100644 doc/sdk/shared-items.md delete mode 100644 doc/sdk/sign_requests.md delete mode 100644 doc/sdk/sign_templates.md delete mode 100644 doc/sdk/storage_policy.md delete mode 100644 doc/sdk/tasks.md delete mode 100644 doc/sdk/terms_of_service.md delete mode 100644 doc/sdk/trash.md delete mode 100644 doc/sdk/upgrading.md delete mode 100644 doc/sdk/users.md delete mode 100644 doc/sdk/watermarking.md delete mode 100644 doc/sdk/webhooks.md delete mode 100644 doc/sdk/weblinks.md delete mode 100644 doc/sdk/zip_download.md create mode 100644 src/intTest/resources/junit-platform.properties diff --git a/.github/workflows/autoupdate-pr.yml b/.github/workflows/autoupdate-pr.yml new file mode 100644 index 000000000..e387b2d40 --- /dev/null +++ b/.github/workflows/autoupdate-pr.yml @@ -0,0 +1,39 @@ +name: Autoupdate PR +on: + push: + branches: + - combined-sdk + +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" | jq -r '.[] | .head.ref') + for pr_branch in $PR_LIST; do + git checkout "$pr_branch" + if git merge origin/combined-sdk; 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/integration-tests.yml b/.github/workflows/integration-tests-sdk.yml similarity index 50% rename from .github/workflows/integration-tests.yml rename to .github/workflows/integration-tests-sdk.yml index 9c2a80b84..b6f5d0e87 100644 --- a/.github/workflows/integration-tests.yml +++ b/.github/workflows/integration-tests-sdk.yml @@ -3,10 +3,10 @@ name: Integration tests on: push: branches: - - main + - combined-sdk pull_request: branches: - - main + - combined-sdk jobs: core: @@ -19,11 +19,21 @@ jobs: with: distribution: 'temurin' java-version: '8' - - name: Run Tests + - name: All Tests + if: startsWith(github.head_ref, 'codegen-release') env: JAVA_COLLABORATOR_ID: ${{ secrets.JAVA_COLLABORATOR_ID }} JAVA_COLLABORATOR: ${{ secrets.JAVA_COLLABORATOR }} JAVA_ENTERPRISE_ID: ${{ secrets.JAVA_ENTERPRISE_ID }} JAVA_JWT_CONFIG: ${{ secrets.JAVA_JWT_CONFIG }} JAVA_USER_ID: ${{ secrets.JAVA_USER_ID }} - run: ./gradlew integrationTest + run: ./gradlew integrationTest --stacktrace + - name: Smoke Tests + if: "!startsWith(github.head_ref, 'codegen-release')" + env: + JAVA_COLLABORATOR_ID: ${{ secrets.JAVA_COLLABORATOR_ID }} + JAVA_COLLABORATOR: ${{ secrets.JAVA_COLLABORATOR }} + JAVA_ENTERPRISE_ID: ${{ secrets.JAVA_ENTERPRISE_ID }} + JAVA_JWT_CONFIG: ${{ secrets.JAVA_JWT_CONFIG }} + JAVA_USER_ID: ${{ secrets.JAVA_USER_ID }} + run: ./gradlew smokeTest --stacktrace diff --git a/.github/workflows/build-and-test-daily.yml b/.github/workflows/integration-tests-sdkgen.yml similarity index 55% rename from .github/workflows/build-and-test-daily.yml rename to .github/workflows/integration-tests-sdkgen.yml index ed50019ae..50f86782f 100644 --- a/.github/workflows/build-and-test-daily.yml +++ b/.github/workflows/integration-tests-sdkgen.yml @@ -1,28 +1,28 @@ -name: Build and Test daily (sdk-gen) +name: build on: - schedule: - - cron: "20 1 * * 1-5" + pull_request: + branches: + - combined-sdk jobs: build-and-test: runs-on: ubuntu-latest strategy: max-parallel: 1 matrix: - distribution: ["zulu", "temurin"] - java: ["8", "17"] + distribution: ['zulu', 'temurin'] + java: ['8', '17'] name: Java ${{ matrix.java }} (${{ matrix.distribution }}) steps: - name: Checkout uses: actions/checkout@v4 - with: - ref: sdk-gen - name: Setup Java uses: actions/setup-java@v4 with: distribution: ${{ matrix.distribution }} java-version: ${{ matrix.java }} - cache: "gradle" + cache: 'gradle' - name: All Tests + if: startsWith(github.head_ref, 'codegen-release') env: JWT_CONFIG_BASE_64: ${{ secrets.JWT_CONFIG_BASE_64 }} ADMIN_USER_ID: ${{ secrets.ADMIN_USER_ID }} @@ -40,28 +40,13 @@ jobs: 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 }} - run: ./gradlew check --stacktrace - - name: Coverage + run: ./gradlew integrationTestGen --stacktrace + - name: Smoke Tests + if: "!startsWith(github.head_ref, 'codegen-release')" 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" + 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 smokeTestGen --stacktrace \ No newline at end of file diff --git a/.github/workflows/releases.yml b/.github/workflows/releases.yml deleted file mode 100644 index 58c874f10..000000000 --- a/.github/workflows/releases.yml +++ /dev/null @@ -1,28 +0,0 @@ -# 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 - -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: - # There's really only 1 step, and i - - 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 index cbff636c5..67d2bb018 100644 --- a/.github/workflows/semantic-pr.yml +++ b/.github/workflows/semantic-pr.yml @@ -6,6 +6,8 @@ on: - opened - edited - synchronize + branches: + - combined-sdk jobs: main: diff --git a/.github/workflows/spell-check-lint.yml b/.github/workflows/spell-check-lint.yml index 3283b9f04..cff82f58d 100644 --- a/.github/workflows/spell-check-lint.yml +++ b/.github/workflows/spell-check-lint.yml @@ -1,17 +1,17 @@ name: spell-check-lint on: pull_request_target: - types: [ opened, synchronize, edited ] + types: [opened, synchronize, edited] branches: - - main + - combined-sdk jobs: spellcheck-request-title: runs-on: ubuntu-latest steps: - name: Checkout current repository - uses: actions/checkout@v4 + uses: actions/checkout@v2 - name: Checkout spellchecker - uses: actions/checkout@v4 + uses: actions/checkout@v2 with: ref: refs/heads/main repository: box/box-sdk-spellchecker diff --git a/.github/workflows/build-main.yml b/.github/workflows/unit-tests.yml similarity index 93% rename from .github/workflows/build-main.yml rename to .github/workflows/unit-tests.yml index 9df466a28..76aa983d4 100644 --- a/.github/workflows/build-main.yml +++ b/.github/workflows/unit-tests.yml @@ -1,10 +1,10 @@ -name: build-main +name: Unit tests and Coverage on: pull_request: types: [ opened, synchronize ] push: branches: - - main + - combined-sdk jobs: build-and-test: runs-on: ubuntu-latest diff --git a/CHANGELOG.md b/CHANGELOG.md index 8017bf864..f9f6a94cc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -288,7 +288,7 @@ The most important change this release includes is the replacement of the HTTP l * `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). +Migration details can be found [here](migration-guides/3.x.x%20to%204.x.x.md). ### New Features and Enhancements: diff --git a/build.gradle b/build.gradle index 9bf31e02d..4c6483b4c 100644 --- a/build.gradle +++ b/build.gradle @@ -1,7 +1,6 @@ plugins { id "com.github.nbaztec.coveralls-jacoco" version "1.2.14" id "com.diffplug.spotless" version "6.2.0" - id "checkstyle" id "jacoco" id "java" id "maven-publish" @@ -9,6 +8,7 @@ plugins { id "eclipse" id "idea" id 'org.jreleaser' version '1.18.0' + id "org.gradle.test-retry" version "1.5.6" } sourceCompatibility = 1.8 @@ -47,24 +47,28 @@ configurations { testsCommonImplementation.extendsFrom(implementation) testImplementation.extendsFrom(testsCommonImplementation) intTestImplementation.extendsFrom(testsCommonImplementation) - intTestRuntimeOnly.extendsFrom(runtimeOnly) + intTestRuntimeOnly.extendsFrom(testRuntimeOnly) } dependencies { implementation "com.eclipsesource.minimal-json:minimal-json:0.9.5" + implementation "com.fasterxml.jackson.core:jackson-annotations:2.17.2" + implementation "com.fasterxml.jackson.core:jackson-core:2.17.2" + implementation "com.fasterxml.jackson.core:jackson-databind:2.17.2" implementation "org.bitbucket.b_c:jose4j:0.9.4" implementation "org.bouncycastle:bcprov-jdk18on:1.78.1" implementation "org.bouncycastle:bcpkix-jdk18on:1.78.1" implementation "com.squareup.okhttp3:okhttp:4.12.0" implementation "com.github.luben:zstd-jni:1.5.7-2" testsCommonImplementation "junit:junit:4.13.2" + testsCommonImplementation "org.junit.jupiter:junit-jupiter-api:5.10.0" testsCommonImplementation "org.hamcrest:hamcrest-library:2.2" testsCommonImplementation "org.mockito:mockito-core:4.8.0" testsCommonImplementation "org.slf4j:slf4j-nop:2.0.3" + testRuntimeOnly "org.junit.vintage:junit-vintage-engine:5.10.0" + testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:5.10.0" testImplementation "com.github.tomakehurst:wiremock:2.27.2" exampleImplementation "com.eclipsesource.minimal-json:minimal-json:0.9.5" - // this is last version working under java 8 - checkstyle "com.puppycrawl.tools:checkstyle:9.3" } compileJava { @@ -75,7 +79,7 @@ compileJava { javadoc { options.windowTitle "Box Java SDK" options.noQualifiers "all" - options.stylesheetFile file("doc/css/javadoc.css") + options.stylesheetFile file("docs/sdk/css/javadoc.css") options.noTree true options.noIndex true options.noHelp true @@ -88,30 +92,117 @@ javadoc { options.links "https://docs.oracle.com/javase/8/docs/api/" } -task runExample(type: JavaExec, dependsOn: "exampleClasses") { +tasks.register('runExample', JavaExec) { + dependsOn "exampleClasses" classpath = sourceSets.example.runtimeClasspath mainClass = "com.box.sdk.example.Main" } -task runCreateAppUser(type: JavaExec, dependsOn: "exampleClasses") { +tasks.register('runCreateAppUser', JavaExec) { + dependsOn "exampleClasses" classpath = sourceSets.example.runtimeClasspath mainClass = "com.box.sdk.example.CreateAppUser" } -task runAccessAsAppUser(type: JavaExec, dependsOn: "exampleClasses") { +tasks.register('runAccessAsAppUser', JavaExec) { + dependsOn "exampleClasses" classpath = sourceSets.example.runtimeClasspath mainClass = "com.box.sdk.example.AccessAsAppUser" } -task integrationTest(type: Test) { - description = "Runs the integration tests." +tasks.register('integrationTest', Test) { + description = "Runs the integration tests in com.box.sdk" group = "Verification" testLogging.showStandardStreams = true testClassesDirs = sourceSets.intTest.output.classesDirs classpath = sourceSets.intTest.runtimeClasspath + useJUnitPlatform() + include '**/com/box/sdk/**' + retry { + maxRetries = 2 + failOnPassedAfterRetry = false + } +} + +tasks.register('integrationTestGen', Test) { + description = "Runs integration tests in com.box.sdkgen" + group = "Verification" + testLogging.showStandardStreams = true + testClassesDirs = sourceSets.intTest.output.classesDirs + classpath = sourceSets.intTest.runtimeClasspath + useJUnitPlatform() + include '**/com/box/sdkgen/**' + retry { + maxRetries = 2 + failOnPassedAfterRetry = false + } + + filter { + // Socket timeout + excludeTestsMatching 'com.box.sdkgen.transfer.TransferITest.testTransferUserContent' + } + + testLogging { + events = ['passed', 'failed', 'skipped'] + showStandardStreams = true + } +} + +tasks.register('smokeTest', Test) { + description = "Runs smoke integration tests in com.box.sdk" + group = "Verification" + testLogging.showStandardStreams = true + testClassesDirs = sourceSets.intTest.output.classesDirs + classpath = sourceSets.intTest.runtimeClasspath + useJUnitPlatform() + + filter { + includeTestsMatching 'com.box.sdk.BoxAPIConnectionIT' + includeTestsMatching 'com.box.sdk.BoxFileIT' + } + + retry { + maxRetries = 2 + failOnPassedAfterRetry = false + } +} + +tasks.register('smokeTestGen', Test) { + description = "Runs integration tests in com.box.sdkgen" + group = "Verification" + testLogging.showStandardStreams = true + testClassesDirs = sourceSets.intTest.output.classesDirs + classpath = sourceSets.intTest.runtimeClasspath + useJUnitPlatform() + include '**/com/box/sdkgen/**' + retry { + maxRetries = 2 + failOnPassedAfterRetry = false + } + + filter { + includeTestsMatching 'com.box.sdkgen.auth.AuthITest' + includeTestsMatching 'com.box.sdkgen.files.FilesITest' + includeTestsMatching 'com.box.sdkgen.uploads.UploadsITest' + includeTestsMatching 'com.box.sdkgen.downloads.DownloadsITest' + } + + testLogging { + events = ['passed', 'failed', 'skipped'] + showStandardStreams = true + } +} + + +// Combined task to run both sets +tasks.register('integrationTestsAll') { + dependsOn['integrationTest', 'integrationTestGen'] + description = "Runs all integration tests" + group = "Verification" } jacoco { + toolVersion = "0.8.10" reportsDirectory = file("$buildDir/reports/jacoco") } @@ -160,14 +251,7 @@ spotless { } test { - useJUnit { - excludeCategories "com.box.sdk.IntegrationTestJWT" - } -} - -checkstyle { - ignoreFailures = false - maxWarnings = 0 + useJUnitPlatform() } publishing { diff --git a/doc/sdk/ai.md b/doc/sdk/ai.md deleted file mode 100644 index fcc3a683e..000000000 --- a/doc/sdk/ai.md +++ /dev/null @@ -1,148 +0,0 @@ -AI -== - -AI allows to send an intelligence request to supported large language models and returns -an answer based on the provided prompt and items. - - - - -- [AI](#ai) - - [Send AI request](#send-ai-request) - - [Send AI text generation request](#send-ai-text-generation-request) - - [Get AI Agent default configuration](#get-ai-agent-default-configuration) - - [Extract metadata freeform](#extract-metadata-freeform) - - [Extract metadata structured](#extract-metadata-structured) - - - -Send AI request --------------------------- - -To send an AI request, call static -[`sendAIRequest(String prompt, List items, Mode mode)`][send-ai-request] method. -In the request you have to provide a prompt, a list of items that your prompt refers to and a mode of the request. -There are two modes available: `SINGLE_ITEM_QA` and `MULTI_ITEM_QA`, which specifies if this request refers to -for a single or multiple items. - - -```java -BoxAIResponse response = BoxAI.sendAIRequest( - api, - "What is the content of the file?", - Collections.singletonList("123456", BoxAIItem.Type.FILE), - BoxAI.Mode.SINGLE_ITEM_QA -); -``` - -You can also provide a list of dialogue history entries to provide additional context to the LLM in generating the response, AI Agent configuration and flag to indicate whether citations should be returned. - -NOTE: The AI endpoint may return a 412 status code if you use for your request a file which has just been updated to the box. -It usually takes a few seconds for the file to be indexed and available for the AI endpoint. - -[send-ai-request]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAI.html#sendAIRequest-com.box.sdk.BoxAPIConnection-java.lang.String-java.util.List-com.box.sdk.BoxAI.Mode- - -Send AI text generation request --------------- - -To send an AI request specifically focused on the creation of new text, call static -[`sendAITextGenRequest(String prompt, List items, List dialogueHistory)`][send-ai-text-gen-request] method. -In the request you have to provide a prompt, a list of items that your prompt refers to and optionally a dialogue history, -which provides additional context to the LLM in generating the response. - - -```java -List dialogueHistory = new ArrayList<>(); -dialogueHistory.add( - new BoxAIDialogueEntry( - "Make my email about public APIs sound more professional", - "Here is the first draft of your professional email about public APIs.", - BoxDateFormat.parse("2013-05-16T15:26:57-07:00") - ) - ); -BoxAIResponse response = BoxAI.sendAITextGenRequest( - api, - "Write an email to a client about the importance of public APIs.", - Collections.singletonList(new BoxAIItem("123456", BoxAIItem.Type.FILE)), - dialogueHistory -); -``` - -You can also provide an AI Agent configuration to customize the behavior of the AI response generation. - -[send-ai-text-gen-request]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAI.html#sendAITextGenRequest-com.box.sdk.BoxAPIConnection-java.lang.String-java.util.List-java.util.List- - -Get AI Agent default configuration --------------------------- - -To get the default configuration of the AI Agent, call static -[`getAiAgentDefaultConfig(BoxAPIConnection api, BoxAIAgent.Mode mode, String language, String model)`][get-ai-agent-default-config] method. -In the request you have to provide the mode of the AI Agent, the language and the model, with the model is required while the language and mode are optional. - - -```java -BoxAIAgentConfig config = BoxAI.getAiAgentDefaultConfig( - api, - BoxAIAgent.Mode.ASK, - "en", - "openai__gpt_3_5_turbo" -); -``` - -[get-ai-agent-default-config]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAI.html#getAiAgentDefaultConfig-com.box.sdk.BoxAPIConnection-com.box.sdk.ai.BoxAIAgent.Mode-java.lang.String-java.lang.String- - -Extract metadata freeform --------------------------- - -To send an AI request to supported Large Language Models (LLMs) and extract metadata in form of key-value pairs, call static -[`extractMetadataFreeform(BoxAPIConnection api, String prompt, List items)`][extract-metadata-freeform] method. -In the request you have to provide a prompt, a list of items that your prompt refers to and an optional agent configuration. - - -```java -BoxAIResponse response = BoxAI.extractMetadataFreeform( - api, - "firstName, lastName, location, yearOfBirth, company", - Collections.singletonList(new BoxAIItem("123456", BoxAIItem.Type.FILE)) -); -``` - -[extract-metadata-freeform]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAI.html#extractMetadataFreeform-com.box.sdk.BoxAPIConnection-java.lang.String-java.util.List- - -Extract metadata structured --------------------------- - -Sends an AI request to supported Large Language Models (LLMs) and returns extracted metadata as a set of key-value pairs. For this request, you need to use an already defined metadata template or define a schema yourself. - -To send an AI request to extract metadata from files with a predefined metadata template, call static -[`extractMetadataStructured extractMetadataStructured(BoxAPIConnection api, List items, BoxAIExtractMetadataTemplate template)`][extract-metadata-structured-metadata-template] method. - - -```java -BoxAIExtractMetadataTemplate template = new BoxAIExtractMetadataTemplate("templateKey", "enterprise"); -BoxAIExtractStructuredResponse result = BoxAI.extractMetadataStructured( - api, - Collections.singletonList(new BoxAIItem("123456", BoxAIItem.Type.FILE)), - template -); -JsonObject sourceJson = result.getSourceJson(); -``` - -To send an AI request to extract metadata from files with custom fields, call static -[`extractMetadataStructured extractMetadataStructured(BoxAPIConnection api, List items, List fields)`][extract-metadata-structured-fields] method. - - -```java -List fields = new ArrayList<>(); -fields.add(new BoxAIExtractField("firstName")); - -BoxAIExtractStructuredResponse result = BoxAI.extractMetadataStructured( - api, - Collections.singletonList(new BoxAIItem("123456", BoxAIItem.Type.FILE)), - fields -); -JsonObject sourceJson = result.getSourceJson(); -``` - -[extract-metadata-structured-metadata-template]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAI.html#extractMetadataStructured-com.box.sdk.BoxAPIConnection-java.util.List-com.box.sdk.ai.metadata.BoxAIExtractMetadataTemplate- -[extract-metadata-structured-fields]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAI.html#extractMetadataStructured-com.box.sdk.BoxAPIConnection-java.util.List-java.util.List- \ No newline at end of file diff --git a/doc/sdk/android.md b/doc/sdk/android.md deleted file mode 100644 index d03804c4e..000000000 --- a/doc/sdk/android.md +++ /dev/null @@ -1,97 +0,0 @@ -# Android - -The Java SDK should be compatible with modern Android applications written in both Java and Kotlin. - -To use the Java SDK in an android application add it to the project's gradle file in the `dependencies` block. - -For Groovy - -```groovy -// build.gradle - -dependencies { - implementation "com.box:box-java-sdk:3.8.0" -} -``` - -For Kotlin - -```kotlin -// build.gradle.kts - -dependencies { - implementation("com.box:box-java-sdk:3.8.0") -} -``` - -## Kotlin - -The Java SDK can also be used in Kotlin Android applications through interoperability thanks to the Kotlin design. -You can read more about Kotlin and Java interoperability [here](https://kotlinlang.org/docs/java-interop.html) - -The following example creates an API connection with a developer token: - -```kotlin -val api = BoxAPIConnection("myToken") -``` - -The following example shows how to get current user - -```kotlin -val userID = "33333" -val api = BoxAPIConnection("myToken") -val user = BoxUser(api, userID) -val userInfo = user.getInfo() -``` - -If you are using an IntelliJ-based IDE, you can copy our samples located in the [docs](/doc/) directory -and paste them into your file. The IDE should ask you to convert the pasted Java sample to Kotlin. Most samples still work after conversion using this approach. - -Note that the current Java SDK does not support Kotlin coroutines. By default, you cannot run network calls on the main thread -in an Android application. There are various ways to overcome this. For example, if you are in a viewModel context, you can run the SDK method as a -coroutine using viewModelScope. - -```kotlin -viewModelScope.launch { - val result = withContext(Dispatchers.IO) { - /* - SDK code goes here - */ - } - // here you can access the result and load it to the viewModel -} -``` - -The following example shows how to get the current items in the root folder, sorted by name in ascending order with additional -"created_by" and "name" fields returned from the API. The items are then loaded to the custom data class defined earlier. - -```kotlin -// data class definition used in viewModel -data class Item( - val isFolder: Boolean, - val name: String, - val createdBy: String -) - -// viewModel init code -viewModelScope.launch { - val result = withContext(Dispatchers.IO) { - val res = BoxFolder(BoxAPIConnection("myToken"), "0") - val iterator: Iterator = - res.getChildren("name", BoxFolder.SortDirection.ASC, "created_by", "name") - .iterator() - val items = mutableListOf() - - when (val itemInfo = iterator.next()) { - is BoxFile.Info -> items.add(Item(false, "File " + itemInfo.name, itemInfo.createdBy.name)) - is BoxFolder.Info -> items.add(Item(true, "Folder " + itemInfo.name, itemInfo.createdBy.name)) - } - items - } -} -``` - -If you are familiar with Kotlin syntax, you might have noticed that we could have used the `.map` function (or a similar function) to map the API result to a list of items. Due to current limitations, using `.map` and similar operations on collections is not always possible and may -lead to unexpected results. The preferred way is to use an explicit iterator to iterate over the collections returned by the SDK. - -If you find any problem related to the Java SDK in Kotlin-based app feel free to open an issue. \ No newline at end of file diff --git a/doc/sdk/authentication.md b/doc/sdk/authentication.md deleted file mode 100644 index a38c72001..000000000 --- a/doc/sdk/authentication.md +++ /dev/null @@ -1,271 +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](#ways-to-authenticate) - - [Developer Token](#developer-token) - - [Server Authentication with JWT](#server-authentication-with-jwt) - - [Standard 3-Legged Oauth 2.0](#standard-3-legged-oauth-20) - - [Box View Authentication with App Token](#box-view-authentication-with-app-token) - - [Client Credentials Grant](#client-credentials-grant) -- [Manual Token Creation](#manual-token-creation) -- [As User](#as-user) -- [Token Exchange](#token-exchange) -- [Revoke Token](#revoke-token) - - -## Ways to Authenticate - -### Developer Token - -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"); -``` - -### Server Authentication with JWT - - -App Users allows your application to provision and control Box accounts that do not have an associated login -and can only be accessed through the Content API by the controlling application. An App User is a Box account that -belongs to your Box Platform application and not an end-user of Box, like a [managed user](https://developer.box.com/v2.0/reference#user-object) -It is important to emphasize that unlike typical Box accounts, these accounts do not have an associated login and can only be accessed through the Box API. - -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://github.com/box/box-node-sdk/blob/main/docs/authentication.md#app-user-authentication) -for detailed instruction on how to use app auth. - -The Java SDK also has a convenient helper function `BoxConfig.readFrom()` to assist in constructing an API connection. -The `readFrom()` method takes in a stream constructed by the JSON config downloaded from the Developer Console seen -[here](https://developer.box.com/docs/setting-up-a-jwt-app#section-use-an-application-config-file). Once a `BoxConfig` -object has been created you can use that to create an API connection. - - -```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); -``` - -It is also possible to get an API connection for an app user or managed user: - - -```java -Reader reader = new FileReader("src/example/config/config.json"); -BoxConfig boxConfig = BoxConfig.readFrom(reader); - -IAccessTokenCache accessTokenCache = new InMemoryLRUAccessTokenCache(100); -BoxDeveloperEditionAPIConnection api = BoxDeveloperEditionAPIConnection.getUserConnection(userId, boxConfig, accessTokenCache); -``` - -However, if you would like to do a manual set up then that is also possible with the below options. - -App User example: -```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(); -``` - -Server authentication allows your application to authenticate itself with the Box API for a given enterprise. A -[Service Account](https://developer.box.com/v2.0/docs/service-account) always exists for a Box application. It is important to -note that a Service Account is separate from the Box accounts of the applicaton developer and the enterprise admin of any enterprise that has -authorized the app, meaning files stored in that account are not accessible in any other account by default. - -Service Account example: - - -```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); - -BoxConfig boxConfig = new BoxConfig("YOUR-CLIENT-ID", "YOUR-CLIENT-SECRET", "ENTERPRISE-ID", jwtPreferences); -IAccessTokenCache tokenCache = new InMemoryLRUAccessTokenCache(10); - -BoxDeveloperEditionAPIConnection api = BoxDeveloperEditionAPIConnection.getAppEnterpriseConnection(boxConfig, tokenCache); -``` - -### Standard 3-Legged Oauth 2.0 - -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"); -``` - -### Box View Authentication with App Token - -Allows applications that do not own content stored in Box (e.g. app-owned content) to be able to use Box as a service -provider rather than a content store. This is currently mostly used for previewing items. For scopes you can choose -between "item_preview", "item_upload", or "item_delete". See the -[Getting Started with the New Box View](https://developer.box.com/docs/getting-started-with-new-box-view) for detailed -instruction. - - -```java -BoxTransactionalAPIConnection api = new BoxTransactionalAPIConnection("YOUR-ACCESS-TOKEN"); -``` - -You can also request a specific scope of the transaction token by passing in: "item_preview", "item_upload", or "item_delete". - -```java -BoxAPIConnection api = BoxTransactionalAPIConnection.getTransactionConnection("YOUR-ACCESS-TOKEN", "item_preview"); -``` - -Lastly, you can choose to specify a resource to generate a token for with. If you're passing a token down to your client -this is a great way to restrict access on that token in turn locking down what the token has access to. - -```java -BoxAPIConnection api = BoxTransactionalAPIConnection.getTransactionConnection("YOUR-ACCESS-TOKEN", "item_preview", -"https://api.box.com/2.0/files/YOUR-FILE-ID"); -``` - -### Client Credentials Grant -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. - -The `BoxCCGAPIConnection` works the same way as the `BoxAPIConnection` so for example to get root folder you can do: - -```java -BoxCCGAPIConnection api = BoxCCGAPIConnection.userConnection( - "client_id", - "client_secret", - "user_id" -); -BoxFolder root = BoxFolder.getRootFolder(api); -``` - -Obtained token is valid for specified ammount of time and 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 -BoxCCGAPIConnection api = BoxCCGAPIConnection.applicationServiceAccountConnection( - "client_id", - "client_secret", - "enterprise_id" -); -``` - -#### Obtaining User token - -To obtain user account you will have to provide user ID with client id and secret - -```java -BoxCCGAPIConnection api = BoxCCGAPIConnection.userConnection( - "client_id", - "client_secret", - "user_id" -); -``` -In order to enable generating user token you have to go to your application configuration that can be found [here](https://app.box.com/developers/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. - -## Manual Token Creation - -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"); -``` - -## As User - -The purpose of as user is to be used by enterprise administrators to make API calls on behalf of their managed users. -This can also be used by a Service Account to make API calls for managed users or app users. This is only meant to be used -for `BoxAPIConnection`s and not `BoxDeveloperEditionAPIConnection`s. - -In order to invoke as user calls you can use - - -```java -BoxAPIConnection api = new BoxAPIConnection("YOUR-ACCESS-TOKEN"); -api.asUser("USER-ID"); -``` - -Once you are done making calls on behalf of a managed user or app user you can switch back to the admin or service account with - - -```java -api.asSelf(); -``` - -## Token Exchange - -You can exchange a API connection's access token for one with a lower scope, in order to restrict the permissions -or to pass to a less secure location (e.g. a browser-based app). This is useful if you want to use the -[Box UI Kits](https://developer.box.com/docs/box-ui-elements), since they generally do not need full read/write -permissions to run. - - -```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); -``` - -The above example will downscope an access token to only allow for previewing an item and uploading an item. - -Revoke Token ------------- - -At any point if you wish to revoke your tokens you can do so by calling the following. - - -```java -BoxAPIConnection api = new BoxAPIConnection("YOUR-ACCESS-TOKEN"); -api.revokeToken(); -``` diff --git a/doc/sdk/classifications.md b/doc/sdk/classifications.md deleted file mode 100644 index f468bd807..000000000 --- a/doc/sdk/classifications.md +++ /dev/null @@ -1,226 +0,0 @@ -Classifications -=============== - -Classfications are a type of metadata that allows users and applications -to define and assign a content classification to files and folders. - -Classifications use the metadata APIs to add and remove classifications, and -assign them to files. For more details on metadata templates please see the -[metadata documentation](./metadata.md). - - - - -- [Classifications](#classifications) - - [Add initial classifications](#add-initial-classifications) - - [List all classifications](#list-all-classifications) - - [Add another classification](#add-another-classification) - - [Update a classification](#update-a-classification) - - [Delete a classification](#delete-a-classification) - - [Delete all classifications](#delete-all-classifications) - - [Add classification to file](#add-classification-to-file) - - [Update classification on file](#update-classification-on-file) - - [Get classification on file](#get-classification-on-file) - - [Remove classification from file](#remove-classification-from-file) - - [Add classification to folder](#add-classification-to-folder) - - [Update classification on folder](#update-classification-on-folder) - - [Get classification on folder](#get-classification-on-folder) - - [Remove classification from folder](#remove-classification-from-folder) - - - -Add initial classifications ---------------------------- - -If an enterprise does not already have a classification defined, the first classification(s) -can be added with the [`createMetadataTemplate`][create-metadata-template] method. - - -```java -MetadataTemplate.Field classification = new MetadataTemplate.Field(); -classification.setType("enum"); -classification.setKey(Metadata.CLASSIFICATION_KEY); -classification.setDisplayName("Classification"); -classification.setHidden("false"); - -List options = new ArrayList(); -options.add("Top Secret"); -classification.setOptions(topSecret) - -List fields = new ArrayList(); -fields.add(classification); - -MetadataTemplate template = MetadataTemplate.createMetadataTemplate(api, Metadata.ENTERPRISE_METADATA_SCOPE, Metadata.CLASSIFICATION_TEMPLATE_KEY, "Classification", false, fields); -``` - -[create-metadata-template]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#createMetadataTemplate-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String-java.lang.String-boolean-java.util.List- - - -List all classifications ------------------------- - -To retrieve a list of all the classifications in an enterprise call the -[`getMetadataTemplate`][get-metadata-template] -method to get the classifciations template, which will contain a list of all the -classifications - - -```java -MetadataTemplate template = MetadataTemplate.getMetadataTemplate(api, Metadata.CLASSIFICATION_TEMPLATE_KEY); -``` - -[get-metadata-template]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#getMetadataTemplate-com.box.sdk.BoxAPIConnection- - -Add another classification --------------------------- - -To add another classification, call the [`updateMetadataTemplate`][update-metadata-template] -method with the an operation to add a new classification to the template. - - -```java -List updates = new ArrayList(); - -String update = "{\n op: \"addEnumOption\",\n fieldKey: \"Box__Security__Classification__Key\",\n data: {\n key: \"Sensitive\"\n }\n}"; - -updates.add(new MetadataTemplate.FieldOperation(addCategoryFieldJSON)); - -MetadataTemplate.updateMetadataTemplate(api, Metadata.ENTERPRISE_METADATA_SCOPE, Metadata.CLASSIFICATION_TEMPLATE_KEY, updates); -``` - -[update-metadata-template]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#updateMetadataTemplate-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String-java.util.List- - - -Update a classification ------------------------ - -To update an existing classification, call the -[`updateMetadataTemplate`][update-metadata-template] -method with the an operation to update the existing classification already present on the template. - - -```java -List updates = new ArrayList(); - -String update = "{\n op: \"editEnumOption\",\n fieldKey: \"Box__Security__Classification__Key\",\n enumOptionKey: \"Sensitive\",\n data: {\n key: \"Very Sensitive\"\n }\n}"; - -updates.add(new MetadataTemplate.FieldOperation(addCategoryFieldJSON)); - -MetadataTemplate.updateMetadataTemplate(api, Metadata.ENTERPRISE_METADATA_SCOPE, Metadata.CLASSIFICATION_TEMPLATE_KEY, updates); -``` - -Add classification to file --------------------------- - -To add a classification to a file, call [`setMetadata(String templateKey, String templateScope, Metadata properties)`][set-metadata] -with the name of the classification template, as well as the details of the classification -to add to the file. - - -```java -BoxFile file = new BoxFile(api, "id"); -Metadata metadata = new Metadata() -metadata.add(Metadata.CLASSIFICATION_KEY, "Sensitive") -file.setMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, Metadata.ENTERPRISE_METADATA_SCOPE, metadata); -``` - -[set-metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#setMetadata-java.lang.String-java.lang.String-com.box.sdk.Metadata- - -Update classification on file ------------------------------ - -To update a classification on a file, call -[`setMetadata(String templateKey, String templateScope, Metadata properties)`][set-metadata] -with the name of the classification template, as well as the details of the classification -to add to the file. - - -```java -BoxFile file = new BoxFile(api, "id"); -Metadata metadata = new Metadata() -metadata.add(Metadata.CLASSIFICATION_KEY, "Sensitive") -file.setMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, Metadata.ENTERPRISE_METADATA_SCOPE, metadata); -``` - -Get classification on file --------------------------- - -Retrieve the classification on a file by calling -[`getMetadata(String templateKey)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getMetadata-java.lang.String-) -with the ID of the file. - - -```java -BoxFile file = new BoxFile(api, "id"); -Metadata metadata = file.getMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY); -``` - -Remove classification from file -------------------------------- - -A classification can be removed from a file by calling -[`deleteMetadata`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#deleteMetadata--). - - -```java -BoxFile file = new BoxFile(api, "id"); -file.deleteMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY); -``` - -Add classification to folder ----------------------------- - -To add a classification to a folder, call [`setMetadata(String templateKey, String templateScope, Metadata properties)`][set-metadata] -with the name of the classification template, as well as the details of the classification -to add to the folder. - - -```java -BoxFolder folder = new BoxFolder(api, "id"); -Metadata metadata = new Metadata() -metadata.add(Metadata.CLASSIFICATION_KEY, "Sensitive") -folder.setMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, Metadata.ENTERPRISE_METADATA_SCOPE, metadata); -``` - -[set-metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#setMetadata-java.lang.String-java.lang.String-com.box.sdk.Metadata- - -Update classification on folder -------------------------------- - -To update a classification on a folder, call -[`setMetadata(String templateKey, String templateScope, Metadata properties)`][set-metadata] -with the name of the classification template, as well as the details of the classification -to add to the folder. - - -```java -BoxFolder folder = new BoxFolder(api, "id"); -Metadata metadata = new Metadata() -metadata.add(Metadata.CLASSIFICATION_KEY, "Sensitive") -folder.setMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, Metadata.ENTERPRISE_METADATA_SCOPE, metadata); -``` - -Get classification on folder ----------------------------- - -Retrieve the classification on a folder by calling -[`getMetadata(String templateKey)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getMetadata-java.lang.String-) -with the ID of the folder. - - -```java -BoxFolder folder = new BoxFolder(api, "id"); -Metadata metadata = folder.getMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY); -``` - -Remove classification from folder ---------------------------------- - -A classification can be removed from a folder by calling -[`deleteMetadata`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#deleteMetadata--). - - -```java -BoxFolder folder = new BoxFolder(api, "id"); -folder.deleteMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY); -``` \ No newline at end of file diff --git a/doc/sdk/collaboration_allowlists.md b/doc/sdk/collaboration_allowlists.md deleted file mode 100644 index 0b464a528..000000000 --- a/doc/sdk/collaboration_allowlists.md +++ /dev/null @@ -1,147 +0,0 @@ -Collaboration Allowlists -======================== - -Collaboration Allowlists are used to manage a set of approved domains or Box users that an enterprise -can collaborate with. - - - - - -- [Add a Collaboration Allowlist For a Domain](#add-a-collaboration-allowlist-for-a-domain) -- [Get a Collaboration Allowlist's Information for a Domain](#get-a-collaboration-allowlists-information-for-a-domain) -- [Get all Collaboration Allowlist's Information for Domain](#get-all-collaboration-allowlists-information-for-domain) -- [Remove a Collaboration Allowlist for a Domain](#remove-a-collaboration-allowlist-for-a-domain) -- [Add a Collaboration Allowlist for a User](#add-a-collaboration-allowlist-for-a-user) -- [Get a Collaboration Allowlist's Information for a User](#get-a-collaboration-allowlists-information-for-a-user) -- [Get all Collaboration Allowlist's Information for a User](#get-all-collaboration-allowlists-information-for-a-user) -- [Remove a Collaboration Allowlist for a User](#remove-a-collaboration-allowlist-for-a-user) - - - -Add a Collaboration Allowlist For a Domain ------------------------------------------- - -A collaboration allowlist can be created for a domain with -[`create(BoxAPIConnection api, String domain, AllowlistDirection direction)`][allowlist1]. -The `AllowlistDirection` parameter determines which way the allowlisting -applies. You can set the value to inbound, outbound, or both. - - -```java -BoxCollaborationAllowlist.create(api, "test.com", BoxCollaborationAllowlist.AllowlistDirection.BOTH); -``` - -[allowlist1]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaborationAllowlist.html#create-com.box.sdk.BoxAPIConnection-java.lang.String-com.box.sdk.BoxCollaborationAllowlist.AllowlistDirection- - -Get a Collaboration Allowlist's Information for a Domain --------------------------------------------------------- - -A specific collaboration allowlist for a domain can be retrieved with -[`getInfo()`][getAllowlistInfo] - - -```java -BoxCollaborationAllowlist domainAllowlist = new BoxCollaborationAllowlist(api, "id"); -domainAllowlist.getInfo(); -``` - -[getAllowlistInfo]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaborationAllowlist.html#getInfo-- - -Get all Collaboration Allowlist's Information for Domain --------------------------------------------------------- - -All domain collaboration allowlists associated with an enterprise can be -retrieved with [`getAll(BoxAPIConnection api)`][getAllAllowlists1] - - -```java -BoxCollaborationAllowlist.getAll(api); -``` - -To specify the number of allowlists to retrieve you can pass a limit on how -many allowlists to return to [`getAll(BoxAPIConnection api, int limit)`][getAllAllowlists2]. - -```java -BoxCollaborationAllowlist.getAll(api, 10); -``` - -[getAllAllowlists1]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaborationAllowlist.html#getAll-com.box.sdk.BoxAPIConnection-java.lang.String...- -[getAllAllowlists2]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaborationAllowlist.html#getAll-com.box.sdk.BoxAPIConnection-int-java.lang.String...- - -Remove a Collaboration Allowlist for a Domain ---------------------------------------------- - -To remove a collaboration allowlist you can call [`delete()`][deleteAllowlist] - - -```java -BoxCollaborationAllowlist domainToBeDeleted = new BoxCollaborationAllowlist(api, "allowlist-id"); -domainToBeDeleted.delete(); -``` - -[deleteAllowlist]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaborationAllowlist.html#delete-- - -Add a Collaboration Allowlist for a User ----------------------------------------- - -A collaboration allowlist can be created for a user with -[`create(BoxAPIConnection api, String userID)`][createExempt] - - -```java -String userID = "12345"; -BoxCollaborationAllowlistExemptTarget.create(api, userID); -``` - -[createExempt]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaborationAllowlistExemptTarget.html#create-com.box.sdk.BoxAPIConnection-java.lang.String- - -Get a Collaboration Allowlist's Information for a User ------------------------------------------------------- - -To retrieve information regarding a specific user collaboration allowlist use -[`getInfo()`][getInfoExempt] - - -```java -BoxCollaborationAllowlistExemptTarget userAllowlist = new BoxCollaborationAllowlistExemptTarget(api, "allowlistID"); -userAllowlist.getInfo(); -``` - -[getInfoExempt]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaborationAllowlistExemptTarget.html#getInfo-- - -Get all Collaboration Allowlist's Information for a User --------------------------------------------------------- - -To retrieve information regarding all user allowlists associated with an enterprise use -[`getAll(BoxAPIConnection api)`][getAllExempt1] - - -```java -BoxCollaborationAllowlistExemptTarget.getAll(api); -``` - -Alternatively you can specify the number of user allowlists to return with one -request by passing a the maximum number of records to return to -[`getAll(BoxApiConnection api, int limit)`][getAllExempt2] - -```java -BoxCollaborationAllowlistExemptTarget.getAll(api, 5); -``` - -[getAllExempt1]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaborationAllowlistExemptTarget.html#getAll-com.box.sdk.BoxAPIConnection-java.lang.String...- -[getAllExempt2]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaborationAllowlistExemptTarget.html#getAll-com.box.sdk.BoxAPIConnection-int-java.lang.String...- - -Remove a Collaboration Allowlist for a User -------------------------------------------- - -To remove a user collaboration allowlist entry from an enterprise use -[`delete()`][deleteExempt] - - -```java -BoxCollaborationAllowlistExemptTarget userAllowlist = new BoxCollaborationAllowlistExemptTarget(api, "allowlist_id"); -userAllowlist.delete(); -``` - -[deleteExempt]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaborationAllowlistExemptTarget.html#delete-- diff --git a/doc/sdk/collaborations.md b/doc/sdk/collaborations.md deleted file mode 100644 index 296e0bf65..000000000 --- a/doc/sdk/collaborations.md +++ /dev/null @@ -1,168 +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 the Collaborations on a File](#get-the-collaborations-on-a-file) -- [Get Pending Collaborations](#get-pending-collaborations) -- [Accept or Decline a Pending Collaboration](#accept-or-decline-a-pending-collaboration) - - - -Add a Collaboration -------------------- - -A collaboration can be added for an existing user or group with -[`collaborate(BoxCollaborator collaborator, BoxCollaboration.Role 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 BoxFolder(api, "folder-id"); -folder.collaborate(user, BoxCollaboration.Role.EDITOR); -``` - -You can also add a collaboration by providing an email address with -[`collaborate(String emailAddress, BoxCollaboration.Role role)`][collaborate2]. -If the recipient 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); -``` - -If you need to create a collaboration with a group, provide a group id. - - -```java -BoxCollaborator group = new BoxGroup(api, "group-id"); -BoxFolder folder = new BoxFolder(api, "folder-id"); -folder.collaborate(group, BoxCollaboration.Role.EDITOR); -``` - -[collaborate1]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#collaborate-com.box.sdk.BoxCollaborator-com.box.sdk.BoxCollaboration.Role- -[collaborate2]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#collaborate-java.lang.String-com.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 passing it to [`updateInfo(BoxCollaboration.Info fieldsToUpdate)`][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-fields] on a collaboration returns a snapshot of the -collaboration's info. - - -```java -BoxCollaboration collaboration = new BoxCollaboration(api, "id"); -BoxCollaboration.Info info = collaboration.getInfo(); -``` - -You can also choose to retrieve only specific fields of the collaboration by calling -[`getInfo(String... fields)`][get-info-fields] with a list of field names. - -```java -BoxCollaboration collaboration = new BoxCollaboration(api, "id"); -BoxCollaboration.Info info = collaboration.getInfo(BoxCollaboration.ALL_FIELDS); -``` - -[get-info-fields]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaboration.html#getInfo-java.lang.String...- - -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 BoxFolder(api, "id"); -Collection collaborations = folder.getCollaborations(); -``` - -[get-collaborations]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getCollaborations-- - -Get the Collaborations on a File --------------------------------- - -You can get an iterator over all of the collaborations on a file by calling -[`BoxFile#getAllFileCollaborations(String... fields)`][get-collaborations-file] -on the file. - - -```java -BoxFile file = new BoxFile(api, "id"); -Iterable collaborations = file.getAllFileCollaborations(); -``` - -[get-collaborations-file]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getAllFileCollaborations-java.lang.String...- - -Get Pending Collaborations --------------------------- - -A collection of all the user's pending collaborations can be retrieved with -[`getPendingCollaborations(BoxAPIConnection api)`][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- - -Accept or Decline a Pending Collaboration ------------------------------------------ - -To accept or decline a pending collaboration, update the info of the pending collaboration object -with the desired status. - - -```java -// Accept all pending collaborations -Collection pendingCollaborations = BoxCollaboration.getPendingCollaborations(api); -for (BoxCollaboration.Info collabInfo : pendingCollaborations) { - collabInfo.setStatus(BoxCollaboration.Status.ACCEPTED); - collabInfo.getResource().updateInfo(collabInfo); -} -``` diff --git a/doc/sdk/collections.md b/doc/sdk/collections.md deleted file mode 100644 index 3e5304bf4..000000000 --- a/doc/sdk/collections.md +++ /dev/null @@ -1,104 +0,0 @@ -Collections -=========== - -Collections contain information about the items contained inside of them, -including files and folders. The only collection available currently is a -“Favorites” collection. The contents of the collection are discovered in a -similar way in which the contents of a folder are discovered. - - - - - -- [Get Collections](#get-collections) -- [Get a Collection's Items](#get-a-collections-items) -- [Add Items to a Collection](#add-items-to-a-collection) -- [Remove Items from a Collection](#remove-items-from-a-collection) - - - -Get Collections ---------------- - -Existing collections can be retrieved by calling the -[`getAllCollections(BoxAPIConnection)`][get-collections] method. Currently only -"Favorites" collection is supported. - - -```java -Iterable collections = BoxCollection.getAllCollections(api); -for (BoxCollection.Info collectionInfo : collections) { - // Do something with the collection. -} -``` - -[get-collections]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollection.html#getAllCollections-com.box.sdk.BoxAPIConnection- - -Get a Collection's Items ------------------------- - -Every `BoxCollection` implements [`Iterable`][iterator] which allows -you to iterate over the collection'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.Info) { - BoxFolder.Info folderInfo = (BoxFolder.Info) itemInfo; - // Do something with the folder. - } -} -``` - -[iterator]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxCollection.html#iterator-- - -Add Items to a Collection -------------------------- - -Add an item to a collection by calling -[`setCollections(BoxCollection... collections)`][set-collections] on any `BoxItem`. Note that this -method will overwrite all collections that the item belongs to. - - -```java -BoxCollection favorites = null; -for (BoxCollection.Info info : BoxCollection.getAllCollections(api)) { - if (info.getCollectionType().equals("favorites")) { - favorites = info.getResource(); - break; - } -} -BoxFile file = new BoxFile(api, "id"); -file.setCollections(favorites); -``` - -Remove Items from a Collection ------------------------------- - -Remove an item from a collection by calling -[`setCollections(BoxCollection... collections)`][set-collections] on any `BoxItem` and exclude the -collection to wish to remove it from. - - -```java -BoxFile file = new BoxFile(api, "id"); -BoxFile.Info info = file.getInfo("collections"); - -ArrayList collections = new ArrayList(); -for (BoxCollection.Info info : info.getCollections(api)) { - // Include every existing collection except for favorites to remove the file - // from the favorites collection. - if (!info.getCollectionType().equals("favorites")) { - collections.add(info.getResource()); - } -} -file.setCollections(collections.toArray()); -``` - -[set-collections]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxItem.html#setCollections-com.box.sdk.BoxCollection...- diff --git a/doc/sdk/comments.md b/doc/sdk/comments.md deleted file mode 100644 index 6681330fd..000000000 --- a/doc/sdk/comments.md +++ /dev/null @@ -1,125 +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 message)`][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 message)`][reply] method. - - -```java -BoxComment comment = new BoxComment(api, "id"); -comment.reply("I agree with this!"); -``` - - -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 -BoxComment comment = new BoxComment(api, "id"); -comment.reply("@[1234:user@box.com] I agree with this!"); -``` - -[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 message)`][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/sdk/configuration.md b/doc/sdk/configuration.md deleted file mode 100644 index 030b9d171..000000000 --- a/doc/sdk/configuration.md +++ /dev/null @@ -1,329 +0,0 @@ -# Configuration - -- [Proxy configuration](#proxy-configuration) - - [Custom proxy authenticator](#custom-proxy-authenticator) - - [Example: NTLM authenticator](#example-ntlm-authenticator) -- [Configure retries of calls and timeouts](#configure-retries-of-calls-and-timeouts) - - [Maximum retries](#maximum-retries) - - [Connection timeout](#connection-timeout) - - [Read timeout](#read-timeout) -- [URLs configuration](#urls-configuration) - - [Base URL](#base-url) - - [Base Upload URL](#base-upload-url) - - [Base App URL](#base-app-url) - - [Token URL](#token-url-deprecated) - - [Revoke URL](#revoke-url-deprecated) -- [SSL configuration](#ssl-configuration) -- [Instrumenation of OpenTelemetry](#instrumenation-of-opentelemetry) - -# Proxy configuration - -To set up proxy -use [BoxApiConnection.setProxy](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html#setProxy-java.net.Proxy-) -to set proxy address -and [BoxApiConnection.setProxyBasicAuthentication][set-basic-proxy-auth] -to set username and password required by proxy: - -```java -BoxAPIConnection api=new BoxAPIConnection("access_token"); -Proxy proxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress("proxy_url",8888)); -// You can use any subclass of BoxAPIConnection -api.setProxy(proxy); -api.setProxyBasicAuthentication("proxyUsername", "proxyPassword"); -``` -Proxy username and password will be used only if provided `SocketAddress` is an instance of -`InetSocketAddress`. If you would like to use a custom `SocketAddress` you can provide your own -`okhttp3.Authenticator` using [BoxApiConnection.setProxyAuthenticator(Authenticator)][set-proxy-authenticator] - - -## Custom proxy authenticator -By using [BoxApiConnection.setProxyBasicAuthentication][set-basic-proxy-auth] you can enable default -proxy authenticator that handles only Basic authentication. But you can provide your own authenticator by using -[BoxApiConnection.setProxyAuthenticator(Authenticator)][set-proxy-authenticator]. - -To do that you will need to add a dependency to your project: -``` -"com.squareup.okhttp3:okhttp:XXX" -``` -Please match the version with what SDK is using by checking `build.gradle` -and looking for entry `implementation "com.squareup.okhttp3:okhttp:"`. - -Now you can add an authenticator. by calling - -```java -BoxAPIConnection api = new BoxAPIConnection("access_token"); -Proxy proxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress("proxy_url",8888)); -api.setProxy(proxy); -api.setProxyAuthenticator((route, response) -> response - .request() - .newBuilder() - .addHeader("Proxy-Authorization", "My custom authenticator") - .build() -); -``` - -### Example: NTLM authenticator - -For example, you can add NTLM authorization. This is example NTLM authenticator that -is using parts from Apache Http Client 5. - -```java -import okhttp3.Authenticator; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.Route; -import org.apache.hc.client5.http.impl.auth.NTLMEngineException; - -public class NTLMAuthenticator implements Authenticator { - final NTLMEngineImpl engine = new NTLMEngineImpl(); - private final String domain; - private final String username; - private final String password; - private final String ntlmMsg1; - - public NTLMAuthenticator(String username, String password, String domain) { - this.domain = domain; - this.username = username; - this.password = password; - String localNtlmMsg1 = null; - try { - localNtlmMsg1 = engine.generateType1Msg(null, null); - } catch (Exception e) { - e.printStackTrace(); - } - ntlmMsg1 = localNtlmMsg1; - } - - @Override - public Request authenticate(Route route, Response response) { - if(response.code() == 407 && "Proxy authorization required".equals(response.message())) { - String ntlmChallenge = response.headers("Proxy-Authenticate") - .stream() - .filter(h -> h.startsWith("NTLM ")) - .findFirst().orElse(""); - if(ntlmChallenge.length() > 5) { - try { - String ntlmMsg3 = engine.generateType3Msg(username, password.toCharArray(), domain, "ok-http-example-ntlm", ntlmChallenge.substring(5)); - return response.request().newBuilder().header("proxy-Authorization", "NTLM " + ntlmMsg3).build(); - } catch (NTLMEngineException e) { - throw new RuntimeException(e); - } - } - return response.request().newBuilder().header("proxy-Authorization", "NTLM " + ntlmMsg1).build(); - } - return response.request(); - } -} -``` - -The `NTLMEngineImpl` could be created by using Apache implementation that can be found -[here](https://github.com/apache/httpcomponents-client/blob/master/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/NTLMEngineImpl.java). -You can add a dependency to `org.apache.httpcomponents.client5:httpclient5:5.1.3`. -Copy the `NTLMEngineImpl` class and add it to your source. - -Now you can use custom NTML Authenticator in your `BoxAPIConnection`: -```java -BoxAPIConnection api = new BoxAPIConnection("access_token"); -Proxy proxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress("proxy_url",8888)); -api.setProxy(proxy); -api.setProxyAuthenticator(new NTLMAuthenticator("some proxy username", "some proxy password", "proxy workgroup")); -``` - -[set-basic-proxy-auth]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html#setProxyBasicAuthentication-java.lang.String-java.lang.String- -[set-proxy-authenticator]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html#setProxyAuthenticator-okhttp3.Authenticator- - -# Configure retries of calls and timeouts -SDK can retry failed calls when: - - failed writting request body - - when recieved HTTP response code: - - 429 - rate limit exceeded - - 5XX - internal server error - - 400 error with error that `exp` claim has expired. This usially means there is a clock skew. - -SDK is using exponnetial strategy to calculate time between retries. - If response contains `Retry-After` header its value will be used as a wait time between calls. -You can check details in `com.box.sdk.BoxAPIRequest.send(com.box.sdk.ProgressListener)` method. - -## Maximum retries - -To configure how many times API will retry calls -use [BoxApiConnection.setMaxRetryAttempts](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html#setMaxRetryAttempts-int-): - -```java -// You can use any subclass of BoxAPIConnection -api.setMaxRetryAttempts(10); -``` - -default value for retry attempts is `5`. - -## Connection timeout - -To set up how log (in milliseconds) API waits to establish connection -use [BoxApiConnection.setConnectTimeout](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html#setConnectTimeout-int-): - -```java -// You can use any subclass of BoxAPIConnection -int connectionTimeout = 100; // timeout in milliseconds -api.setConnectTimeout(connectionTimeout); -``` - -default value is `0` which mean API waits forever to establish connection. - -## Read timeout - -To set up how log (in milliseconds) API waits to read data from connection -use [BoxApiConnection.setReadTimeout](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html#setReadTimeout-int-): - -```java -// You can use any subclass of BoxAPIConnection -int readTimeout = 100; // timeout in milliseconds -api.setReadTimeout(readTimeout); -``` - -default value is `0` which mean API waits forever to read data from connection. - -# URLs configuration - -### Base URL -The default base URL used for making API calls to Box can be changed by calling `BoxAPIConnection#setBaseURL(String)` -method on `BoxApiConnection`. Default value is `https://api.box.com/`. - -```java -BoxAPIConnection api = new BoxAPIConnection("YOUR-DEVELOPER-TOKEN"); - -api.setBaseURL("https://example.com"); -String baseUrl = api.getBaseURL(); // will produce "https://example.com/2.0/" -``` - -Setting Base URL changes the Token and Revoke URL as well: -```java -BoxAPIConnection api = new BoxAPIConnection("YOUR-DEVELOPER-TOKEN"); - -api.setBaseURL("https://example.com"); - -String baseUrl = api.getBaseURL(); // will produce "https://example.com/2.0/" -String tokenUrl = api.getRevokeURL(); // will produce "https://example.com/oauth2/revoke" -String revokeUrl = api.getTokenURL(); // will produce "https://example.com/oauth2/token" -``` - -### Base Upload URL -The default URL used for uploads can be changed by calling `BoxAPIConnection#setBaseUploadURL(String)` method on `BoxApiConnection`. -Default value is `https://upload.box.com/api/`. - -```java -BoxAPIConnection api = new BoxAPIConnection("YOUR-DEVELOPER-TOKEN"); - -api.setBaseUploadURL("https://upload.example.com"); -api.getBaseUploadURL(); // will produce "https://upload.example.com/2.0/" -``` - -### Base App URL -The default base app URL can be changed by calling `BoxAPIConnection#setBaseAppUrl()` method on `BoxApiConnection`. -Default value is https://app.box.com. - -```java -BoxAPIConnection api = new BoxAPIConnection("YOUR-DEVELOPER-TOKEN"); - -api.setBaseAppUrl("https://example.app.com"); -api.getBaseAppUrl(); // will produce "https://app.example.com" -``` - -### Token URL (deprecated) -The default URL used for getting token can be changed by calling `setTokenURL()` method on `BoxApiConnection`. -Default value is https://api.box.com/oauth2/token. This method is deprecated. Use `BoxAPIConnection#setBaseURL(String)` -instead. - -```java -BoxAPIConnection api = new BoxAPIConnection("YOUR-DEVELOPER-TOKEN"); - -api.setTokenURL("https://example.com/token"); -``` - -If you use `setTokenUrl` this URL will be used over the one coming from `setBaseUrl` when doing authentication. - -### Revoke URL (deprecated) -The default URL used for invalidating token can be changed by calling `setRevokeURL()` method on `BoxApiConnection`. -Default value is https://api.box.com/oauth2/revoke. This method is deprecated. Use `BoxAPIConnection#setBaseURL(String)` -instead. - -```java -BoxAPIConnection api = new BoxAPIConnection("YOUR-DEVELOPER-TOKEN"); - -api.setRevokeURL("https://example.com/revoke"); -``` - -If you use `setRevokeUrl` this URL will be used over the one coming from`setBaseUrl` when doing authentication. - -# SSL configuration -You can override default settings used to verify SSL certificates. -This can be used to allow using self-signed certificates. For example: -```java -BoxAPIConnection api = new BoxAPIConnection(...); - -// to allow self-signed certificates -X509TrustManager trustManager = new X509TrustManager() { - @Override - public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) { - } - - @Override - public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) { - } - - @Override - public java.security.cert.X509Certificate[] getAcceptedIssuers() { - return new java.security.cert.X509Certificate[]{}; - } -}; - -// to allow self-signed certificates created for localhost -HostnameVerifier hostnameVerifier = (hostname, session) -> true; - -api.configureSslCertificatesValidation(trustManager, hostnameVerifier); -``` - -If you just need to provide trust manager use `BoxAPIConnection.DEFAULT_HOSTNAME_VERIFIER` as a hostname verifier. -The same goes for hostname verifier. If you need just to provide it use -`BoxAPIConnection.DEFAULT_TRUST_MANAGER` as a trust manager. -Example: -```java -BoxAPIConnection api = new BoxAPIConnection(...); -X509TrustManager trustManager = ... -api.configureSslCertificatesValidation(trustManager, BoxAPIConnection.DEFAULT_HOSTNAME_VERIFIER); -``` - -# Instrumenation of OpenTelemetry - -OpenTelemetry is an observability framework and toolkit for creating and managing telemetry data, such as traces, -metrics, and logs. The Box Java SDK can be instrumented with OpenTelemetry to collect telemetry data about the -requests made by the SDK. - -To start, add the [opentelemetry-okhttp-3.0](https://mvnrepository.com/artifact/io.opentelemetry.instrumentation/opentelemetry-okhttp-3.0) dependency to your project. -Next, create a custom class that extends BoxAPIConnection and integrates telemetry in the overridden `createNewCall` method. -Here's an example implementation: -```java -public class BoxAPIConnectionWithTelemetry extends BoxAPIConnection { - - private OkHttpTelemetry telemetry; - - public BoxAPIConnectionWithTelemetry(String accessToken) { - super(accessToken); - } - - /** - * Add required constructors - */ - - public void setTelemetry(OpenTelemetry openTelemetry) { - this.telemetry = OkHttpTelemetry.builder(openTelemetry).build(); - } - - protected Call createNewCall(OkHttpClient httpClient, Request request) { - return this.telemetry.newCallFactory(httpClient).newCall(request); - } -} - -``` - -Please note that you should not modify either `httpClient` or `request` parameters in the createNewCall method. -Altering these parameters can discard the BoxAPIConnection configuration and lead to unexpected behavior. \ No newline at end of file diff --git a/doc/sdk/css/javadoc.css b/doc/sdk/css/javadoc.css deleted file mode 100644 index ad7887e4d..000000000 --- a/doc/sdk/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/sdk/devices.md b/doc/sdk/devices.md deleted file mode 100644 index 9ed133093..000000000 --- a/doc/sdk/devices.md +++ /dev/null @@ -1,62 +0,0 @@ -Devices -====== - -Device pinning is a feature that allows enterprise admins to pin their user’s -corporate-managed Box account to a particular mobile device or Box Sync client. - - - - - -- [Get Enterprise Device Pins](#get-enterprise-device-pins) -- [Get Device Pin](#get-device-pin) -- [Delete Device Pin](#delete-device-pin) - - - -Get Enterprise Device Pins --------------------------- - -Calling the static [`getEnterpriceDevicePins(BoxAPIConnection api, String enterpriseID, String... fields)`][get-enterprise-device-pins] -will return an iterable that will page through all of the device pins belongs to -enterprise with given ID. It is possible to specify maximum number of retrieved -items per single response by passing the maxiumum number of records to retrieve to -[`getEnterpriceDevicePins(BoxAPIConnection api, String enterpriseID, int limit, String... fields)`][get-enterprise-device-pins-with-limit] - - -```java -Iterable enterpriseDevicePins = BoxDevicePin.getEnterpriceDevicePins(api, id); -for (BoxDevicePin.Info devicePin : enterpriseDevicePins) { - // Do something with the device pin. -} -``` - -[get-enterprise-device-pins]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxDevicePin.html#getEnterpriceDevicePins-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String...- -[get-enterprise-device-pins-with-limit]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxDevicePin.html#getEnterpriceDevicePins-com.box.sdk.BoxAPIConnection-java.lang.String-int-java.lang.String...- - -Get Device Pin --------------- - -Existing collections can be retrieved by calling the [`getInfo(String... fields)`][get-device-pin] method. -Optional parameters can be used to retrieve specific fields of the Device Pin object. - - -```java -BoxDevicePin devicePin = new BoxDevicePin(api, id); -BoxDevicePin.Info devicePinInfo = devicePin.getInfo(); -``` - -[get-device-pin]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxDevicePin.html#getInfo-java.lang.String...- - -Delete Device Pin --------------- - -A device pin can be deleted by calling the [`delete()`][delete] method. - - -```java -BoxDevicePin devicePin = new BoxDevicePin(api, id); -devicePin.delete(); -``` - -[delete]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxDevicePin.html#delete-- diff --git a/doc/sdk/events.md b/doc/sdk/events.md deleted file mode 100644 index 0bf1f8826..000000000 --- a/doc/sdk/events.md +++ /dev/null @@ -1,244 +0,0 @@ -# Events - -The Box API provides an events endpoint that utilizes long-polling to send user -events in real-time. The SDK provides an `EventStream` class that automatically -handles long-polling and deduplicating events. - - - - - -- [User Events](#user-events) - - [Deduplicating Events](#deduplicating-events) -- [Enterprise (Admin) Events](#enterprise-admin-events) - - [Historical Querying](#historical-querying) - - [Live Monitoring](#live-monitoring) - - - -## User Events - -Subscribing to user events works by creating an `EventStream` and attaching -listeners for the events that are fetched in near-real time from the API. - -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 as a -[`BoxEvent`][box-event] object. - -To create an `EventStream` starting from the current point in time, use -the [`EventStream(BoxAPIConnection api)`][event-stream] constructor. To -start from a known stream position, pass the stream position to the -[`EventStream(BoxAPIConnection api, long streamPosition)`][event-stream-position] -constructor. - - -```java -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. - -[event-stream]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/EventStream.html#EventStream-com.box.sdk.BoxAPIConnection- -[event-stream-position]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/EventStream.html#EventStream-com.box.sdk.BoxAPIConnection-long- -[box-event]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxEvent.html - -### 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. - -## Enterprise (Admin) Events - -### Historical Querying - -The Box API provides an `EventLog` class and a -`getEnterpriseEvents(BoxAPIConnection api, EnterpriseEventsRequest enterpriseEventsRequest)` method -that reads from the `admin-logs` stream and returns an `Iterable` over -Enterprise [`BoxEvent`][box-event] records. The emphasis for this stream is on completeness over latency, -which means that Box will deliver admin events in chronological order and without duplicates, -but with higher latency. You can specify start and end time/dates. This method -will only work with an API connection for an enterprise admin account or service account with a manage enterprise properties. - - -```java -// get the last two hours of unfiltered enterprise events -Date startDate = new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 2)); -Date endDate = new Date(System.currentTimeMillis()); -EnterpriseEventsRequest request = new EnterpriseEventsRequest() - .after(startDate) - .before(endDate); -EventLog eventLog = EventLog.getEnterpriseEvents(api, request); -for (BoxEvent event : eventLog) { - System.out.println("Enterprise Event Created by User: " - + event.getCreatedBy().getName() - + " Login: " + event.getCreatedBy().getLogin() - + " Event Type: " + event.getEventType() - + " Created at: " + event.getCreatedAt().toString() - ); -}; -``` - -Additionally, you can set a limit of the number of enterprise events to be retrieved per response by specifying the -limit field. - -```java -// get first 20 events -EnterpriseEventsRequest request = new EnterpriseEventsRequest() - .limit(20); -EventLog eventLog = EventLog.getEnterpriseEvents(api, request); -for (BoxEvent event : eventLog) { - System.out.println("Enterprise Event Created by User: " - + event.getCreatedBy().getName() - + " Login: " + event.getCreatedBy().getLogin() - + " Event Type: " + event.getEventType() - + " Created at: " + event.getCreatedAt().toString() - ); -}; -``` - - -You can also filter events by type. -```java -// filter events by type -EnterpriseEventsRequest request = new EnterpriseEventsRequest() - .types(EventType.ITEM_CREATE, EventType.ITEM_OPEN); -EventLog eventLog = EventLog.getEnterpriseEvents(api, request); -for (BoxEvent event : eventLog){ - System.out.println("Enterprise Event Created by User: " - + event.getCreatedBy().getName() - + " Login: " + event.getCreatedBy().getLogin() - + " Event Type: " + event.getEventType() - + " Created at: " + event.getCreatedAt().toString() - ); -}; -``` - -You can also filter events by type name. This is usefull if a new event type is introduced and is not mapped to -`BoxEvent.EventType`. -```java -// filter events by type name -EnterpriseEventsRequest request = new EnterpriseEventsRequest() - .typeNames("ITEM_CREATE", "ITEM_OPEN"); -EventLog eventLog = EventLog.getEnterpriseEvents(api, request); -for (BoxEvent event : eventLog){ - System.out.println("Enterprise Event Created by User: " - + event.getCreatedBy().getName() - + " Login: " + event.getCreatedBy().getLogin() - + " Event Type: " + event.getEventType() - + " Event Type Name: " + event.getTypeName() - + " Created at: " + event.getCreatedAt().toString() - ); -}; -``` - -Bear in mind that if an event type is not mapped to `BoxEvent.EventType` the value of `BoxEvent#getEventType()` will -be `BoxEvent.EventType.UNKNOWN` but `BoxEvent#getTypeName()` will return its name. - -If you want to progress within a stream you can use position parameter: -```java -EnterpriseEventsRequest request1 = new EnterpriseEventsRequest().limit(20); -EventLog eventLog1 = EventLog.getEnterpriseEvents(api, request1); -// process revieved events -EnterpriseEventsRequest request2 = new EnterpriseEventsRequest().limit(20) - .position(eventLog1.getNextStreamPosition()); // get events from the next position -EventLog eventLog2 = EventLog.getEnterpriseEvents(api, request2); -// process revieved events -``` - -### Live Monitoring -To monitor recent events that have been generated within Box across the enterprise use -`EventLog#getEnterpriseEventsStream(BoxAPIConnection api, EnterpriseEventsStreamRequest enterpriseEventsStreamRequest)`, -method that reads from the `admin-logs-streaming` stream and returns an `Iterable` over -Enterprise [`BoxEvent`][box-event] records. -The emphasis for this feed is on low latency rather than chronological accuracy, which means that Box may return -events more than once and out of chronological order. Events are returned via the API around 12 seconds after they -are processed by Box (the 12 seconds buffer ensures that new events are not written after your cursor position). -Only two weeks of events are available via this feed, and you cannot set start and end time/dates. This method -will only work with an API connection for an enterprise admin account or service account with a manage enterprise properties. - - -```java -EnterpriseEventsStreamRequest request = new EnterpriseEventsStreamRequest() -EventLog eventLog = EventLog.getEnterpriseEventsStream(api, request); -for (BoxEvent event : eventLog) { - System.out.println("Enterprise Event Created by User: " - + event.getCreatedBy().getName() - + " Login: " + event.getCreatedBy().getLogin() - + " Event Type: " + event.getEventType() - + " Created at: " + event.getCreatedAt().toString() - ); -}; -``` - -You can limit number of events returned. -```java -// get first 20 events -EnterpriseEventsStreamRequest request = new EnterpriseEventsStreamRequest() - .limit(20) -EventLog eventLog = EventLog.getEnterpriseEventsStream(api, request); -``` - - -You can also filter events by type. -```java -// filter events by type -EnterpriseEventsStreamRequest request = new EnterpriseEventsStreamRequest() - .types(EventType.ITEM_CREATE, EventType.ITEM_OPEN); -EventLog eventLog = EventLog.getEnterpriseEventsStream(api, request); -for (BoxEvent event : eventLog){ - System.out.println("Enterprise Event Created by User: " - + event.getCreatedBy().getName() - + " Login: " + event.getCreatedBy().getLogin() - + " Event Type: " + event.getEventType() - + " Created at: " + event.getCreatedAt().toString() - ); -}; -``` - -You can also filter events by type name. This is usefull if a new event type is introduced and is not mapped to -`BoxEvent.EventType`. -```java -// filter events by type name -EnterpriseEventsRequest request = new EnterpriseEventsStreamRequest() - .typeNames("ITEM_CREATE", "ITEM_OPEN"); -EventLog eventLog = EventLog.getEnterpriseEventsStream(api, request); -for (BoxEvent event : eventLog){ - System.out.println("Enterprise Event Created by User: " - + event.getCreatedBy().getName() - + " Login: " + event.getCreatedBy().getLogin() - + " Event Type: " + event.getEventType() - + " Event Type Name: " + event.getTypeName() - + " Created at: " + event.getCreatedAt().toString() - ); -}; -``` - -Bear in mind that if an event type is not mapped to `BoxEvent.EventType` the value of `BoxEvent#getEventType()` will -be `BoxEvent.EventType.UNKNOWN` but `BoxEvent#getTypeName()` will return its name. - -If you want to progress within a stream you can use position parameter: -```java -EnterpriseEventsStreamRequest request1 = new EnterpriseEventsStreamRequest().limit(20); -EventLog eventLog1 = EventLog.getEnterpriseEventsStream(api, request1); -// process revieved events -EnterpriseEventsStreamRequest request2 = new EnterpriseEventsStreamRequest().limit(20) - .position(eventLog1.getNextStreamPosition()); // get events from the next position -EventLog eventLog2 = EventLog.getEnterpriseEventsStream(api, request2); -// process revieved events -``` - -If you have the next stream position, and make a subsequent call, the API will return immediately -even when there are no events, the next stream position will be returned. -If you have a stream position that is older than two weeks than API will return no events and next -stream position. diff --git a/doc/sdk/file_requests.md b/doc/sdk/file_requests.md deleted file mode 100644 index ca6021f4d..000000000 --- a/doc/sdk/file_requests.md +++ /dev/null @@ -1,77 +0,0 @@ -File Requests -============= - -File request objects represent a file request associated with a folder. - - - - -- [Get a File Request's Information](#get-a-file-requests-information) -- [Copy a File Request's Information](#copy-a-file-requests-information) -- [Update a File Request's Information](#update-a-file-requests-information) -- [Delete a File Request](#delete-a-file-request) - - - -Get a File Request's Information ------------------------- - -Calling [`getInfo()`][get-info] returns information on a file request. - - -```java -BoxFileRequest fileRequest = new BoxFileRequest(api, "id"); -BoxFileRequest.Info fileRequestInfo = fileRequest.getInfo(); -``` - -[get-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileRequest.html#getInfo - -Copy a File Request's Information ---------------------------- - -Calling [`copyInfo(String folderId)`][copy-info] copies an existing file request that is already present -on one folder, and applies it to another folder. If you want to set certain fields of the newly copied file request when it is created, -set those fields in the `BoxFileRequest.Info` that you pass into this method [`copyInfo(BoxFileRequest.Info info, String folderId)`][copy-info]. - - -```java -BoxFileRequest fileRequest = new BoxFileRequest(api, "id"); -BoxFileRequest.Info fileRequestInfo = fileRequest.new Info(); -fileRequestInfo.setDescription("Following documents are requested for your process"); -fileRequestInfo.setIsDescriptionRequired(true); -fileRequestInfo.setStatus(BoxFileRequest.Status.ACTIVE); -fileRequestInfo = fileRequest.copyInfo(fileRequestInfo, "folderId"); -``` - -[copy-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTask.html#copyInfo - -Update a File Request's Information ---------------------------- - -Calling [`updateInfo(BoxFileRequest.Info info)`][update-info] updates a file request. This can be used to activate -or deactivate a file request. - - -```java -BoxFileRequest fileRequest = new BoxFileRequest(api, "id"); -BoxFileRequest.Info fileRequestInfo = fileRequest.new Info(); -fileRequestInfo.setDescription("Following documents are requested for your process"); -fileRequestInfo.setIsDescriptionRequired(true); -fileRequestInfo.setStatus(BoxFileRequest.Status.ACTIVE); -fileRequestInfo = fileRequest.updateInfo(fileRequestInfo); -``` - -[update-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileRequest.html#updateInfo - -Delete a File Request -------------- - -Calling [`delete()`][delete] deletes a file request permanently. - - -```java -BoxFileRequest fileRequest = new BoxFileRequest(api, "id"); -fileRequest.delete(); -``` - -[delete]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFileRequest.html#delete diff --git a/doc/sdk/files.md b/doc/sdk/files.md deleted file mode 100644 index f275b256c..000000000 --- a/doc/sdk/files.md +++ /dev/null @@ -1,1135 +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) -- [Upload Preflight Check](#upload-preflight-check) -- [Upload a Large File in Chunks](#upload-a-large-file-in-chunks) -- [Upload a Large File in Chunks Including Attributes](#upload-a-large-file-in-chunks-including-attributes) -- [Upload a Large File Version in Chunks](#upload-a-large-file-version-in-chunks) -- [Upload a Large File Version in Chunks Including Attributes](#upload-a-large-file-version-in-chunks-including-attributes) -- [Upload a Large File Or File Version Manually](#upload-a-large-file-or-file-version-manually) -- [Move a File](#move-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) -- [Lock a File](#lock-a-file) -- [Unlock a File](#unlock-a-file) -- [Find File for Shared Link](#find-file-for-shared-link) -- [Download File for Shared Link](#download-file-for-shared-link) -- [Create a Shared Link](#create-a-shared-link) -- [Get a Shared Link](#get-a-shared-link) -- [Update a Shared Link](#update-a-shared-link) -- [Remove a Shared Link](#remove-a-shared-link) -- [Add a Collaborator](#add-a-collaborator) -- [Get an Embed Link](#get-an-embed-link) -- [Create Metadata](#create-metadata) -- [Set Metadata](#set-metadata) -- [Get Metadata](#get-metadata) -- [Update Metadata](#update-metadata) -- [Delete Metadata](#delete-metadata) -- [Get All Metadata on File](#get-all-metadata-on-file) -- [Set Classification on File](#set-classification-on-file) -- [Get Classification on File](#get-classification-on-file) -- [Remove Classification on File](#remove-classification-on-file) -- [Get File Representations](#get-file-representations) -- [Get Representation Content](#get-representation-content) - - - -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... fields)`][get-info] -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-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 fieldsToUpdate)`][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 stream)`][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`][progress] -to [`download(OutputStream stream, ProgressListener progress)`][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-com.box.sdk.ProgressListener- -[progress]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/ProgressListener.html - -Upload a File -------------- - -Files are uploaded to a folder by calling the -[`uploadFile(InputStream fileContents, String fileName)`][upload] method -on the [`BoxFolder`][box-folder] you want to upload the file into. - - -```java -BoxFolder rootFolder = BoxFolder.getRootFolder(api); -FileInputStream stream = new FileInputStream("My File.txt"); -BoxFile.Info newFileInfo = rootFolder.uploadFile(stream, "My File.txt"); -stream.close(); -``` - -Note that using `FileInputStream` allows you to read the content of the file only once. -If the first upload attempt fails, the stream will become exhausted, -and request retry with no content might be performed. To retry an upload, you would have to -create a new `FileInputStream` and call `uploadFile()` method again. - -If you want the SDK to automatically retry the upload in case of any error, you need to provide an -`InputStream` class that supports the `reset()` operation. For example, you can read all bytes from your file into -a `ByteArrayInputStream` and then use it for the upload method. Be aware that this approach will load the whole file -into memory, so it is not recommended for large files, as it can exhaust easily your memory. - -```java -BoxFolder rootFolder = BoxFolder.getRootFolder(api); -InputStream stream = new ByteArrayInputStream(Files.readAllBytes(new File(path).toPath())); -BoxFile.Info newFileInfo = rootFolder.uploadFile(stream, "My File.txt"); -stream.close(); -``` - -Upload progress can be tracked by providing the size of the file and a -[`ProgressListener`][progress] to -[`uploadFile(InputStream fileContents, String fileName, long fileSize, ProgressListener progress)`][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"); -BoxFile.Info newFileInfo = rootFolder.uploadFile(stream, "My File.txt", 1024, new ProgressListener() { - public void onProgressChanged(long numBytes, long totalBytes) { - double percentComplete = numBytes / totalBytes; - } -}); -stream.close(); -``` - -We also support the ability to attach a description of the file upon upload by calling the -[`uploadFile(InputStream fileContents, String fileName, String fileDescription)`][upload3] method. - -```java -BoxFolder rootFolder = BoxFolder.getRootFolder(api); -FileInputStream stream = new FileInputStream("My File.txt"); -BoxFile.Info newFileInfo = rootFolder.uploadFile(stream, "My File.txt", "File Description"); -stream.close(); -``` - -[upload]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#uploadFile-java.io.InputStream-java.lang.String- -[upload2]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#uploadFile-java.io.InputStream-java.lang.String-long-com.box.sdk.ProgressListener- -[upload3]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#uploadFile-java.io.InputStream-java.lang.String-java.lang.String- -[box-folder]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html - -Upload Preflight Check ----------------------- - -You may want to check if a file can be successfully uploaded before beginning -the file transfer, in order to the time and bandwidth of sending the file over -the network if the upload would not have succeeded. Calling the -[`BoxFolder#canUpload(String fileName, long fileSize)`][upload-preflight] method -on the folder you want to upload a new file into will verify that there is no -name conflict and that the account has enough storage space for the file. - - -```java -String fileName = "My Doc.pdf"; -BoxFolder rootFolder = BoxFolder.getRootFolder(api); -try { - folder.canUpload(fileName, 98734576); - - // If the file upload would not have succeeded, it will not be attempted - folder.uploadFile(fileContents, fileName); -} catch (BoxAPIException ex) ( - -) -``` - -[upload-preflight]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#canUpload-java.lang.String-long- - -Upload a Large File in Chunks ------------------------------ - -A large file can be uploaded with the -[`uploadLargeFile(InputStream fileContents, String fileName, long fileSize)`][upload-large-file] -method on the folder to upload the new file into. This will upload the file in -parts with integrity checks on each part, to ensure that network errors -mid-upload do not fail the entire operation. - - -```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()); -``` - -[upload-large-file]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#uploadLargeFile-java.io.InputStream-java.lang.String-long- - -Upload a Large File in Chunks Including Attributes --------------------------------------------------- - -A large file can be uploaded, including attributes, with the -[`uploadLargeFile(InputStream fileContents, String fileName, long fileSize, Map fileAttributes)`][upload-large-file-including-attributes] -method on the folder to upload the new file into. This will upload the file in -parts with integrity checks on each part, to ensure that network errors -mid-upload do not fail the entire operation. - -```java -File myFile = new File("My Large_File.txt"); -FileInputStream stream = new FileInputStream(myFile); -Map fileAttributes = new HashMap(); -fileAttributes.put("content_modified_at", "2017-04-08T00:58:08Z"); - -BoxFolder rootFolder = BoxFolder.getRootFolder(api); -BoxFile.Info fileInfo = rootFolder.uploadLargeFile(inputStream, "My_Large_File.txt", myFile.length(), fileAttributes); -``` - -[upload-large-file-including-attributes]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#uploadLargeFile-java.io.InputStream-java.lang.String-long-java.util.Map- - -Upload a Large File Version in Chunks -------------------------------------- - -To upload a new file version for a large file, call the -[`uploadLargeFile(InputStream fileContents, long fileSize)`][upload-large-file-version] -method on the file to be updated. This will upload the new version of the file -in parts with integrity checks on each part, to ensure that network errors -mid-upload do not fail the entire operation. - - -```java -File myFile = new File("My Large_File.txt"); -FileInputStream stream = new FileInputStream(myFile); - -String fileID = "12345"; -BoxFile file = new BoxFile(api, fileID); -BoxFile.Info fileInfo = file.uploadLargeFile(inputStream, myFile.length()); -``` - -[upload-large-file-version]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#uploadLargeFile-java.io.InputStream-long- - -Upload a Large File Version in Chunks Including Attributes ----------------------------------------------------------- - -To upload a new file version for a large file, including attributes, call the -[`uploadLargeFile(InputStream fileContents, long fileSize, Map fileAttributes)`][upload-large-file-version-including-attributes] -method on the file to be updated. This will upload the new version of the file -in parts with integrity checks on each part, to ensure that network errors -mid-upload do not fail the entire operation. - -```java -File myFile = new File("My Large_File.txt"); -FileInputStream stream = new FileInputStream(myFile); -Map fileAttributes = new HashMap(); -fileAttributes.put("content_modified_at", "2017-04-08T00:58:08Z"); - -String fileID = "12345"; -BoxFile file = new BoxFile(api, fileID); -BoxFile.Info fileInfo = file.uploadLargeFile(inputStream, myFile.length(), fileAttributes); -``` - -[upload-large-file-version-including-attributes]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#uploadLargeFile-java.io.InputStream-long-java.util.Map- - -Upload a Large File Or File Version Manually --------------------------------------------- - -To start the process of uploading a large file or file version, first create a -new upload session with -[`BoxFolder#createUploadSession(String fileName, String fileSize)`][create-upload-session] -for a new file, or -[`BoxFile#createUploadSession(long fileSize)`][create-upload-session-version] -for a new file version. Once the upload session is created, all other steps -are identical for both cases. - - -```java -BoxFileUploadSession.Info sessionInfo; -if (/* uploading a new file */) { - // Create the upload session for a new file - BoxFolder rootFolder = BoxFolder.getRootFolder(api); - sessionInfo = rootFolder.createUploadSession("New Large File.pdf", fileSize); -} else if (/* uploading a new version of an exiting file */) { - // Create the uplaod session for a new version of an existing file - String fileID = "93465"; - BoxFile file = new BoxFile(api, fileID); - sessionInfo = file.createUploadSession(fileSize); -} - -//Get the session resource from the session info -BoxFileUploadSession session = sessionInfo.getResource(); - -//Create the Message Digest for the whole file -MessageDigest digest = null; -try { - digest = MessageDigest.getInstance("SHA1"); -} catch (NoSuchAlgorithmException ae) { - throw new BoxAPIException("Digest algorithm not found", ae); -} -``` - -Both of these methods will return a - -Once the upload session is created, the large file can be uploaded in chunks with the -[`uploadPart(InputStream stream, long offset, int partSize, long totalSizeOfFile)`][upload-part] -method of the session instance. If there is a failure in uploading any of the -parts, the failed part can be uploaded again without affecting the other parts. - - -```java -//Reading a large file -FileInputStream fis = new FileInputStream("My_Large_File.txt"); -//Create the digest input stream to calculate the digest for the whole file. -DigestInputStream dis = new DigestInputStream(fis, digest); - -List parts = new ArrayList(); - -//Get the part size. Each uploaded part should match the part size returned as part of the upload session. -//The last part of the file can be less than part size if the remaining bytes of the last part is less than -//the given part size -long partSize = sessionInfo.getPartSize(); -//Start byte of the part -long offset = 0; -//Overall of bytes processed so far -long processed = 0; -while (processed < fileSize) { - long diff = fileSize - processed; - //The size last part of the file can be less than the part size. - if (diff < partSize) { - partSize = diff; - } - - //Upload a part. It can be uploaded asynchorously - BoxFileUploadSessionPart part = session.uploadPart(dis, offset, (int)partSize, fileSize); - parts.add(part); - - //Increase the offset and proceesed bytes to calculate the Content-Range header. - processed += partSize; - offset += partSize; -} -``` - -At any point in time, the list of parts that have been uploaded successfully can be retrieved with the -[`listParts(int offset, int limit)`][list-parts] method of the session instance. - - -```java -//The following snippet retrives first 1000 parts that are uploaded. -BoxFileUploadSessionPartList partList = session.listParts(0, 1000); -List parts = partList.getEntries(); -``` - -Once all the parts are uploaded successfully, the upload session can be committed with the -[`commit(String digest, List parts, Map attributes, String ifMatch, String ifNoneMatch)`][upload-session-commit] method. - - -```java -//Creates the file hash -byte[] digestBytes = digest.digest(); -//Base64 encoding of the hash -String digestStr = Base64.encode(digestBytes); - -//Commit the upload session. If there is a failure, abort the commit. -BoxFile.Info fileInfo = session.commit(digestStr, parts, null, null, null); -``` - -The upload session can be aborted at any time with the -[`abort()`][upload-session-abort] method of the session instance. This will -cancel the upload and any parts that were already uploaded will be lost. - - -```java -session.abort(); -``` - -The upload session status can be retrieved at any time with the [`getStatus()`][upload-session-status] method. -This call will update the parts processed and other information in the session info instance. - - -```java -BoxFileUploadSession.Info updatedSessionInfo = session.getStatus(); -``` - -[create-upload-session]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#createUploadSession-java.lang.String-long- -[create-upload-session-version]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#createUploadSession-long- -[upload-part]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileUploadSession.html#uploadPart-java.io.InputStream-long-int-long- -[list-parts]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileUploadSession.html#listParts-int-int- -[upload-session-commit]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileUploadSession.html#commit-java.lang.String-java.util.List-java.util.Map-java.lang.String-java.lang.String- -[upload-session-abort]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileUploadSession.html#abort-- -[upload-session-status]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileUploadSession.html#getStatus-- - -Move a File ------------ - -To move a file from one folder into another, call -[`move(BoxFolder destination)`][move] on the file to be moved with the -destination folder. - -```java -String fileID = "1234"; -String destinationFolderID = "5678"; -BoxFile file = new BoxFile(api, fileID); -BoxFolder destinationFolder = new BoxFolder(destinationFolderID); -file.move(destinationFolder) -``` - -To avoid name conflicts in the destination folder, you can optionally provide a -new name for the file to [`move(BoxFolder destination, String newName)`][move-rename]. The file -will be placed into the destination folder with the new name. - -```java -String fileID = "1234"; -String destinationFolderID = "5678"; -BoxFile file = new BoxFile(api, fileID); -BoxFolder destinationFolder = new BoxFolder(destinationFolderID); -file.move(destinationFolder, "Vacation Photo (1).jpg"); -``` - -[move]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#move-com.box.sdk.BoxFolder- -[move-rename]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#move-com.box.sdk.BoxFolder-java.lang.String- - -Copy a File ------------ - -A file can be copied to a new folder and optionally be renamed with the -[`copy(BoxFolder destination)`][copy] and -[`copy(BoxFolder destination, String newName)`][copy2] methods. - - -```java -// Copy a file into the user's root folder -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-java.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. By default, it will return up to 1000 file versions with all default fields set. - - -```java -BoxFile file = new BoxFile(api, "id"); -Collection versions = file.getVersions(); -for (BoxFileVersion version : versions) { - System.out.format("SHA1 of \"%s\": %s\n", file.getInfo().getName(), version.getSha1()); -} -``` - -File versions can be retrieved with specified starting position with the -[`getVersionsRange(long offset, long limit)`][get-versions-range] method. -You can use the `limit` and `offset` parameters to page through the all available file versions. - -```java -BoxFile file = new BoxFile(api, "id"); -Collection versions = file.getVersionsRange(1000, 2000); -for (BoxFileVersion version : versions) { - System.out.format("SHA1 of \"%s\": %s\n", file.getInfo().getName(), version.getSha1()); -} -``` - -You can specify selected fields to be returned while getting versions information. -Assume we want to get version SHA1 and version number: -```java -BoxFile file = new BoxFile(api, "id"); -Collection versions = file.getVersions("sha1", "version_number"); -for (BoxFileVersion version : versions) { - System.out.format("SHA1 of \"%d\": %s\n", version.getVersionNumber(), version.getSha1()); -} -``` -You can find a list of available fields at [`BoxFile.ALL_VERSION_FIELDS`][versions-fields]. - -[get-versions]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getVersions-- -[versions-fields]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#ALL_VERSION_FIELDS-- - -Upload a New Version of a File ------------------------------- - -New versions of a file can be uploaded with the -[`uploadNewVersion(InputStream fileContents)`][upload-new-version] -method. - - -```java -BoxFile file = new BoxFile(api, "id"); -FileInputStream stream = new FileInputStream("My File.txt"); -file.uploadNewVersion(stream); -``` - -[upload-new-version]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#uploadNewVersion-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 output)`][download-version]. - - -```java -BoxFile file = new BoxFile(api, "id"); -Collection versions = file.getVersions(); -BoxFileVersion firstVersion = versions.iterator().next(); - -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"); -Collection versions = file.getVersions(); -BoxFileVersion firstVersion = versions.iterator().next(); -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"); -Collection versions = file.getVersions(); -BoxFileVersion firstVersion = versions.iterator().next(); -firstVersion.delete(); -``` - -[delete-version]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileVersion.html#delete-- - -Lock a File ------------ - -A file can be locked indefinitely by calling [`lock()`][lock] on the file to -be locked. A locked file cannot be modified by any other user until it is -unlocked. This is useful if you want to "check out" a file while you're working -on it, to ensure that other collaborators do not make changes while your changes -are in progress. - -```java -BoxFile file = new BoxFile(api, "id"); -file.lock(); -``` - -When locking a file, you can optionally prevent other users from downloading the -file in addition to prevent changes by calling -[`lock(boolean preventDownload)`][lock-download] with `true`. - -```java -// Lock the file and prevent downloading -BoxFile file = new BoxFile(api, "id"); -file.lock(true); -``` - -You can also set a date when the lock will automatically be released by -calling [`lock(Date expirationDate)`][lock-expires] with the date on -which the lock should expire. This is recommended to prevent a file -from accidentally being locked longer than intended. - -```java -final long ONE_WEEK_MILLIS = 1000 * 60 * 60 * 24 * 7; -long expirationTimestamp = System.currentTimeMillis() + ONE_WEEK_MILLIS; -Date expirationTime = new Date(expirationTimestamp); -BoxFile file = new BoxFile(api, "id"); -file.lock(expirationTime); -``` - -Both options can be passed together to -[`lock(boolean preventDownload, Date expireTime)`][lock-both]. - -[lock]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#lock-java.util.Date- -[lock-download]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#lock-boolean- -[lock-expires]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#lock-java.util.Date- -[lock-both]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#lock-java.util.Date-boolean- - -Unlock a File -------------- - -A file can be unlocked by calling [`unlock()`][unlock]. - -```java -BoxFile file = new BoxFile(api, "id"); -file.unlock(); -``` - -[unlock]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#unlock-- - -Find File for Shared Link -------------------------- - -To get the file information for a shared link, you can call -[`BoxItem.getSharedItem(BoxAPIConnection api, String sharedLink)`][get-shared-item] -with the shared link to get information about the file behind it. - -```java -String sharedLink = "https://app.box.com/s/abcdefghijklmnopqrstuvwxyz123456"; -BoxItem.Info itemInfo = BoxItem.getSharedItem(api, sharedLink); -``` - -If the shared link is password-protected, call -[`BoxItem.getSharedItem(BoxAPIConnection api, String sharedLink, String password)`][get-shared-item-password] -with the shared link and password. - - -```java -String sharedLink = "https://app.box.com/s/abcdefghijklmnopqrstuvwxyz123456"; -String password = "letmein"; -BoxItem.Info itemInfo = BoxItem.getSharedItem(api, sharedLink, password); -``` - -[get-shared-item]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxItem.html#getSharedItem-com.box.sdk.BoxAPIConnection-java.lang.String- -[get-shared-item-password]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxItem.html#getSharedItem-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String- - -Download File from Shared Link ---------------- - -A file can be downloaded via a shared link -by calling [`downloadFromSharedLink(BoxAPIConnection api, OutputStream output, String sharedLink)`][download-from-shared-link] -and providing an `OutputStream` where the file's contents will be written and shared link of the file. - -If the shared link is password-protected, call -[`downloadFromSharedLink(BoxAPIConnection api, OutputStream output, String sharedLink, String password)`][download-from-shared-link-password] -method. - -```java -FileOutputStream stream = new FileOutputStream("My File.txt"); -String sharedLink = "https://cloud.box.com/s/12339wbq4c7y2xd3drg4j9j9wer3ptt6n"; -String password = "Secret123@"; -BoxFile.downloadFromSharedLink(api, stream, sharedLink, password); -stream.close(); -``` - -Download progress can be tracked by providing a [`ProgressListener`][progress] -to [` downloadFromSharedLink(BoxAPIConnection api, OutputStream output, String sharedLink, String password, ProgressListener listener)`][download-from-shared-link-password-progress]. -The `ProgressListener` will then receive progress updates as the download -completes. - -```java -FileOutputStream stream = new FileOutputStream("My File.txt"); -// Provide a ProgressListener to monitor the progress of the download. -BoxFile.downloadFromSharedLink(api, stream, sharedLink, password, new ProgressListener() { - public void onProgressChanged(long numBytes, long totalBytes) { - double percentComplete = numBytes / totalBytes; - } -}); -stream.close(); -``` -[download-from-shared-link]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#downloadFromSharedLink-com.box.sdk.BoxAPIConnection-java.io.OutputStream-java.lang.String- -[download-from-shared-link-password]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#downloadFromSharedLink-com.box.sdk.BoxAPIConnection-java.io.OutputStream-java.lang.String-java.lang.String- -[download-from-shared-link-password-progress]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#downloadFromSharedLink-com.box.sdk.BoxAPIConnection-java.io.OutputStream-java.lang.String-java.lang.String-com.box.sdk.ProgressListener- - -Create a Shared Link --------------------- - -A shared link for a file can be generated by calling -[`createSharedLink(BoxSharedLinkRequest sharedLinkRequest)`][create-shared-link]. - - -```java -// Optionally we can calculate and set the date when shared link will automatically be disabled -final long ONE_WEEK_MILLIS = 1000 * 60 * 60 * 24 * 7; -long unsharedTimestamp = System.currentTimeMillis() + ONE_WEEK_MILLIS; -Date unsharedDate = new Date(unsharedTimestamp); - -BoxFile file = new BoxFile(api, "id"); -BoxSharedLinkRequest sharedLinkRequest = new BoxSharedLinkRequest() - .access(OPEN) - .permissions(true, true) - .unsharedDate(unsharedDate); -BoxSharedLink sharedLink = file.createSharedLink(sharedLinkRequest); -``` - -A set of shared link access level constants are available through the SDK for convenience: -* `BoxSharedLink.Access.OPEN` -* `BoxSharedLink.Access.COLLABORATORS` -* `BoxSharedLink.Access.COMPANY` -* `BoxSharedLink.Access.DEFAULT` - -[create-shared-link]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#createSharedLink-com.box.sdk.sharedlink.BoxSharedLinkRequest- - -Get a Shared Link ------------------ - -Retrieve the shared link for a file by calling -[`getSharedLink()`][get-shared-link]. - - -```java -BoxFile file = new BoxFile(api, "id"); -BoxFile.Info info = file.getInfo(); -BoxSharedLink link = info.getSharedLink(); -String url = link.getUrl(); -``` - -[get-shared-link]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxItem.Info.html#getSharedLink-- - -Update a Shared Link --------------------- - -A shared link for a file can be updated by calling the same method as used when creating a shared link, -[`createSharedLink(BoxSharedLinkRequest sharedLinkRequest)`][create-shared-link]. - - -```java -BoxFile file = new BoxFile(api, "id"); -BoxSharedLinkRequest sharedLinkRequest = new BoxSharedLinkRequest() - .access(OPEN) - .permissions(true, true); -BoxSharedLink sharedLink = file.createSharedLink(sharedLinkRequest); -``` - -Remove a Shared Link --------------------- - -A shared link for a file can be removed by calling [`removeSharedLink()`][remove-shared-link]. - - -```java -BoxFile file = new BoxFile(api, "12345"); -BoxFile.Info info = file.getInfo(); -info.removeSharedLink(); -file.updateInfo(info); -``` - -[remove-shared-link]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#removeSharedLink-- - -Add a Collaborator ------------------- - -You can invite another person to collaborate on a file by email with -[`collaborate(String emailAddress, BoxCollaboration.Role role, Boolean notify, Boolean canViewPath, Date expiresAt, Boolean isAccessOnly)`][share-a-file]. - -The `notify` parameter will determine if the user or group will receive an -email notification when being added as a collaborator. This option is only -available to enterprise administrators. - -The `canViewPath` parameter allows the invitee to see the entire list of ancestor -folders of the associated file. The user will not gain privileges in any ancestor -folder, but will be able to see the whole path to that file in the owner's account. - -The `expiresAt` parameter allows the owner to set a date-time in the future when -the collaboration should expire. - -The `isAccessOnly` parameter allows the owner to set the collaboration to be -access only collaboration. - -The `notify`, `canViewPath`, `expiresAt` and `isAccessOnly` parameters can be left as `null`. - -```java -BoxFile file = new BoxFile(api, "id"); -BoxCollaboration.Info collabInfo = file.collaborate("testuser@example.com", BoxCollaboration.Role.EDITOR, true, true); -``` - -Alternatively, if you know the user's ID, you can invite them directly -without needing to know their email address with the -[`collaborate(BoxCollaborator user, BoxCollaboration.Role role, Boolean notify, Boolean canViewPath, Date expiresAt, Boolean isAccessOnly)`][share-a-file-userID] - -```java -BoxUser collaborator = new BoxUser(api, "user-id"); -BoxFile file = new BoxFile(api, "file-id"); -BoxCollaboration.Info collabInfo = file.collaborate(collaborator, BoxCollaboration.Role.EDITOR, true, true); -``` - -[share-a-file]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#collaborate-java.lang.String-com.box.sdk.BoxCollaboration.Role-java.lang.Boolean-java.lang.Boolean-java.lang.String-java.util.Date-java.lang.Boolean- -[share-a-file-userID]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#collaborate-com.box.sdk.BoxCollaborator-com.box.sdk.BoxCollaboration.Role-java.lang.Boolean-java.lang.Boolean-java.lang.String-java.util.Date-java.lang.Boolean- - - -Get an Embed Link ------------------ - -A file embed link can be generated by calling [`getPreviewLink()`][get-preview-link]. - -```java -BoxFile file = new BoxFile(api, "id"); -URL embedLink = file.getPreviewLink(); -``` - -[get-preview-link]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getPreviewLink-- - -Create Metadata ---------------- - -Metadata can be created on a file by calling -[`createMetadata(Metadata metadata)`][create-metadata], -[`createMetadata(String typeName, Metadata metadata)`][create-metadata-2], or -[`createMetadata(String typeName, String scope, Metadata metadata)`][create-metadata-3]. - - -```java -// Add property "foo" with value "bar" to the default metadata properties -BoxFile file = new BoxFile(api, "id"); -file.createMetadata(new Metadata().add("/foo", "bar")); -``` - -Note: This method will only succeed if the provided metadata template is not currently applied to the file, otherwise -it will fail with a Conflict error. To get to know how to edit existing metadata please -go to [set metadata](#set-metadata) and [update metadata](#update-metadata) sections. - -[create-metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#createMetadata-com.box.sdk.Metadata- -[create-metadata-2]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#createMetadata-java.lang.String-com.box.sdk.Metadata- -[create-metadata-3]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#createMetadata-java.lang.String-java.lang.String-com.box.sdk.Metadata- -[update-metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#updateMetadata-com.box.sdk.Metadata- - -Set Metadata ------------- - -To set metadata on a file, call [`setMetadata(String templateName, String scope, Metadata metadata)`][set-metadata]. -This method will try to create provided metadata on a file. However, if metadata has already been applied to this file, -it will overwrite values of metadata keys specified in the `metadata` parameter. The metadata keys not specified in -the `metadata` parameter will remain unchanged. - -```java -BoxFile file = new BoxFile(api, "id"); -file.setMetadata("test_template", "enterprise", new Metadata().add("/foo", "bar")); -``` - -Note: If you want to set new metadata on a file including hard reset of the current metadata -(also removing keys not specified in the `metadata` param): -first delete metadata as specified in [delete metadata](#delete-metadata) section and then set new metadata again. - -[set-metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#setMetadata-java.lang.String-java.lang.String-com.box.sdk.Metadata- - -Get Metadata ------------- - -Retrieve a file's Metadata by calling [`getMetadata()`][get-metadata], -[`getMetadata(String typeName)`][get-metadata-2], or -[`getMetadata(String typeName, String scope)`][get-metadata-3]. -These methods return a [`Metadata`][metadata] object, which allows access to metadata values. - - -```java -// Get the default free-form metadata properties -BoxFile file = new BoxFile(api, "id"); -Metadata metadata = file.getMetadata(); - -// Unknown type metadata field, you can test for type or try to get as any type -JsonValue unknownValue = metadata.getValue("/someField"); - -// String or Enum metadata fields -String stringValue = metadata.getString("/author"); - -// Float metadata fields can be interpreted as any numeric type -float floatValue = metadata.getFloat("/price"); - -// Date metadata fields -Date dateValue = metadata.getDate("/deadline"); - -// Multiselect metadata fields -List multiSelectValues = metadata.getMultiSelect("/categories"); -``` - -[metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/Metadata.html -[get-metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getMetadata-- -[get-metadata-2]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getMetadata-java.lang.String- -[get-metadata-3]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getMetadata-java.lang.String-java.lang.String- - -Update Metadata ---------------- - -Update a file's Metadata by calling [`updateMetadata(Metadata properties)`][update-metadata]. - -Note: This method will only succeed if the provided metadata template has already been applied to the file. If the file -does not have existing metadata, this method will fail with a Not Found error. This is useful in cases where you know -the file will already have metadata applied, since it will save an API call compared to `setMetadata()`. - - -```java -BoxFile file = new BoxFile(api, "id"); -file.updateMetadata(new Metadata("templateScope", "templateKey").add("/foo", "bar")); -``` - -Also, it is possible to add multi-select fields for your file metadata by calling -[`updateMetadata(Metadata properties)`][update-metadata] with a list of values. - -```java -BoxFile file = new BoxFile(api, "id"); -List valueList = new ArrayList(); -valueList.add("bar"); -valueList.add("qux"); -file.updateMetadata(new Metadata("templateScope", "templateKey").add("/foo", valueList)); -``` - -If you wanted to replace all selected fields for a specified key you can use the -[`replace(String path, List values)`][replace-metadata]. - -```java -BoxFile file = new BoxFile(api, "id"); -List valueList = new ArrayList(); -valueList.add("bar"); -valueList.add("qux"); -file.updateMetadata(new Metadata("templateScope", "templateKey").replace("/foo", valueList)); -``` - -If you wanted to remove a metadata value for a specified key you can use the -[`remove(String path)`][remove-metadata]. - -```java -BoxFile file = new BoxFile(api, "id"); -file.updateMetadata(new Metadata("templateScope", "templateKey").remove("/foo")); -``` - -[update-metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#updateMetadata-com.box.sdk.Metadata- -[replace-metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/Metadata.html#replace-java.lang.String-java.util.List- -[remove-metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/Metadata.html#remove-java.lang.String- - -Delete Metadata ---------------- - -A file's Metadata can be deleted by calling -[`deleteMetadata()`][delete-metadata], -[`deleteMetadata(String typeName)`][delete-metadata-2], or -[`deleteMetadata(String typeName, String scope)`][delete-metadata-3]. - - -```java -BoxFile file = new BoxFile(api, "id"); -file.deleteMetadata("myMetadataTemplate"); -``` - -[delete-metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#deleteMetadata-- -[delete-metadata-2]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#deleteMetadata-java.lang.String- -[delete-metadata-3]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#deleteMetadata-java.lang.String-java.lang.String- - -Get All Metadata on File --------------- - -Calling the [`getAllMetadata()`][get-all-metadata] method on a file will return -an iterable that will page through all of the metadata associated with the file. - - -```java -BoxFile file = new BoxFile(api, "id"); -Iterable metadataList = file.getAllMetadata(); -for (Metadata metadata : metadataList) { - // Do something with the metadata. -} -``` - -[get-all-metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getAllMetadata-java.lang.String...- - -Set Classification on File --------------------------- - -Calling the [`setClassification(String classificationType)`][set-classification] method on a file will add a -classification template on the file. This method will return the classification type applied on the file. The -classification types include `Public`, `Internal`, and `Confidential`. `Public` being the most available permission, -`Internal` which restricts the specified file to company and collaborators only, and finally, `Confidential`, which is -for collaborators only. - -```java -BoxFile file = new BoxFile(api, "id"); -String classificationType = file.setClassification("Public"); -``` - -It is important to note that this call will attempt to create a classification on the file first, if one already exists -then it will do the update. If you already know that a classification exists on the file and would like to save an API -call, we encourage you to use the [`updateClassification(String classificationType)`][update-classification] method. - -```java -BoxFile file = new BoxFile(api, "id"); -String classificationType = file.updateClassification("Public"); -``` - -[set-classification]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#setClassification-java.lang.String...- -[update-classification]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#updateClassification-java.lang.String...- - -Get Classification on File --------------------------- - -To retrieve the classification assigned on the file, use the [`getClassification()`][get-classification] method. This -will return the classification type on the file. - -```java -BoxFile file = new BoxFile(api, "id"); -String classificationType = file.getClassification(); -``` - -[get-classification]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getClassification-java.lang.String...- - -Remove Classification on File ------------------------------ - -To remove classification from the file, use the [`deleteClassification()`][delete-classification] method. - -```java -BoxFile file = new BoxFile(api, "id"); -file.deleteClassification(); -``` - -[delete-classification]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#deleteClassification-- - -Get File Representations ------------------------- - -To get the preview representations of a file, call the -[`getInfoWithRepresentations(String representationHints, String... fields)`][get-reps] -method with the [representation hints][rep-hints] to fetch, along with any other -fields on the file object to fetch simultaneously. This method returns a [`BoxFile.Info`][box-file-info] -object that contains the representations as a list of [`Representation`][rep-obj] objects. - -Note that this method only provides information about a set of available representations; your -application will need to handle checking the status of the representations and downlaoding them -via the provided content URL template. - -```java -BoxFile file = new BoxFile(api, "1234"); - -// Get the PDF representation and file name -String repHints = "[pdf]"; -BoxFile.Info fileInfo = file.getInfoWithRepresentations(repHints, "name"); -List representations = fileInfo.getRepresentations(); -String name = fileInfo.getName(); -``` - -[get-reps]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getInfoWithRepresentations-java.lang.String-java.lang.String...- -[rep-hints]: https://developer.box.com/v2.0/reference/#section-x-rep-hints-header -[rep-obj]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/Representation.html - -Get Representation Content --------------------------- - -To write the contents of a single file representation to an `OutputStream`, call the -[`getRepresentationContent(String representationHint, OutputStream output)`][get-rep-content] -method with an [X-Rep-Hints value][rep-hints] specifying the representation you want. - -> __Note:__ This method only supports getting the contents of a single representation; if your -> X-Rep-Hints value specifies multiple representations, an arbitrary one of them will be fetched. - -```java -// Read the PDF representation of file 12345 into memory -ByteArrayOutputStream output = new ByteArrayOutputStream(); - -BoxFile file = new BoxFile(api, "12345"); -file.getRepresentationContent("[pdf]", output); -``` - -For representations with multiple files, e.g. multi-page images, you will need to pass an `assetPath` -parameter to specify which file you want to fetch. - -```java -// If file 12345 is a document, its PNG representation will consist of one image per page of the document -// Get the image of the first page of the document and write it to a file -FileOutputStream output = new FileOutputStream("/path/to/file.png"); -BoxFile file = new BoxFile(api, "12345"); -file.getRepresentationContent("[png?dimensions=1024x1024]", "1.png", output); -``` - -Generating a representation for the selected file is an asynchronous operation and may take some time. -Therefore, by default, the `getRepresentationContent` method periodically checks the status of the generated file and downloads it when it is ready. -With the `maxRetries` parameter in [`getRepresentationContent(String representationHint, String assetPath, OutputStream output, int maxRetries)`][get-rep-content-overloaded], you can define -the number of status checks for the generated file, which will be performed at intervals of 100 ms. - -If this number is exceeded, a `BoxApiException` will be thrown. - -```java -FileOutputStream output = new FileOutputStream("/path/to/file.png"); -BoxFile file = new BoxFile(api, "12345"); -file.getRepresentationContent("[png?dimensions=1024x1024]", "1.png", output, 10); -``` - - -[get-rep-content]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getRepresentationContent-java.lang.String-java.lang.String-java.io.OutputStream- -[get-rep-content-overloaded]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getRepresentationContent-java.lang.String-java.lang.String-java.io.OutputStream-int- diff --git a/doc/sdk/folders.md b/doc/sdk/folders.md deleted file mode 100644 index e5bb6eb0d..000000000 --- a/doc/sdk/folders.md +++ /dev/null @@ -1,801 +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) - - [SortParameters and Using PagingParameters](#sortparameters-and-using-pagingparameters) -- [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) -- [Find Folder for Shared Link](#find-folder-for-shared-link) -- [Create a Shared Link](#create-a-shared-link) -- [Get a Shared Link](#get-a-shared-link) -- [Update a Shared Link](#update-a-shared-link) -- [Remove a Shared Link](#remove-a-shared-link) -- [Share a Folder](#share-a-folder) -- [Get All Collaborations for a Folder](#get-all-collaborations-for-a-folder) -- [Create Metadata](#create-metadata) -- [Set Metadata](#set-metadata) -- [Get Metadata](#get-metadata) -- [Update Metadata](#update-metadata) -- [Delete Metadata](#delete-metadata) -- [Get All Metadata on Folder](#get-all-metadata-on-folder) -- [Get Metadata for Multiple Files](#get-metadata-for-multiple-files) -- [Set Classification on Folder](#set-classification-on-folder) -- [Get Classification on Folder](#get-classification-on-folder) -- [Remove Classification on Folder](#remove-classification-on-folder) -- [Create Cascade Policy On Folder](#create-cascade-policy-on-folder) -- [Get a Cascade Policy's Information](#get-a-cascade-policys-information) -- [Get All Cascade Policies on Folder](#get-all-cascade-policies-on-folder) -- [Force Apply Cascade Policy on Folder](#force-apply-cascade-policy-on-folder) -- [Delete Cascade Policy](#delete-cascade-policy) -- [Lock a Folder](#lock-a-folder) -- [Get All Locks on a Folder](#get-all-locks-on-a-folder) -- [Delete a Lock on a Folder](#delete-a-lock-on-a-folder) - - - -Get the User's Root Folder --------------------------- - -The user's root folder can be accessed with the static -[`getRootFolder(BoxAPIConnection api)`][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 API calls to load more data 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.Info) { - 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()); -} -``` - -We also allow users to sort the results of the folder items by `name`, `id`, or `date`. This will maintain the integrity -of the ordering when you retrieve the items for a folder. You can do this by calling the -[`getChildren(String sortField, BoxFolder.SortDirection sortDirection, String... fields)`][get-items-with-sort] method. - -```java -BoxFolder folder = new BoxFolder(this.api, "12345"); -Iterator itemIterator = folder.getChildren("name", BoxFolder.SortDirection.ASC).iterator(); -while (itemIterator.hasNext()) { - BoxItem.Info itemInfo = itemIterator.next(); - // Do something -} -``` - -### SortParameters and Using PagingParameters - -`SortParameters` is an abstraction hiding way that SDK is doing sorting. -`PagingParameters` is an abstraction hiding way that SDK is doing pagination. -If you want to start offset based pagination: - -```java -BoxFolder folder = new BoxFolder(this.api, "12345"); -// setup ascending sorting by name -SortParameters sorting = SortParameters.ascending("name"); -// setup paging with offset 0 and limit 100 -long offset = 0; -long limit = 100; -PagingParameters paging = PagingParameters.offset(offset, limit) -Iterable itemIterator = childFolder.getChildren(sorting, paging); -while (itemIterator.hasNext()) { - BoxItem.Info itemInfo=itemIterator.next(); - // Do something -} -``` - -With offset pagination you cannot set offset larger than 300000. -With marker based pagination you can iterate over folders containing more than 300000 elements. -With marker based pagination you cannot use sorting. Use `SortParameters.none()` to turn off sort. -If you want to use PagingParameters to start marker based pagination do: -```java -BoxFolder folder = new BoxFolder(this.api, "12345"); -// disable sorting -SortParameters sorting = SortParameters.none(); -// setup paging with makred based pagination and limit 100 -long limit = 100; -PagingParameters paging = PagingParameters.marker(limit) -Iterable itemIterator = childFolder.getChildren(sorting, paging); -while (itemIterator.hasNext()) { - BoxItem.Info itemInfo=itemIterator.next(); - // Do something -} -``` - -[iterator]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#iterator-- -[get-items-with-sort]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getChildren-java.lang.String-com.box.sdk.BoxFolder.SortDirection-java.lang.String...- - -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... fields)`][get-info] -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-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 fieldsToUpdate)`][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 folderName)`][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 destination)`][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 destination, String newName)`][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-java.lang.String- - -Move a Folder -------------- - -Call the [`move(BoxFolder destination)`][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 newName)`][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 recursive)`][delete] method. Passing -`true` to this method indicates that the folder and its contents should be -recursively deleted. - - -```java -// Delete the folder and all its contents -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- - -Find Folder for Shared Link -------------------------- - -To get the folder information for a shared link, you can call -[`BoxItem.getSharedItem(BoxAPIConnection api, String sharedLink)`][get-shared-item] -with the shared link to get information about the folder behind it. - -```java -String sharedLink = "https://app.box.com/s/abcdefghijklmnopqrstuvwxyz123456"; -BoxItem.Info itemInfo = BoxItem.getSharedItem(api, sharedLink); -``` - -If the shared link is password-protected, call -[`BoxItem.getSharedItem(BoxAPIConnection api, String sharedLink, String password)`][get-shared-item-password] -with the shared link and password. - - -```java -String sharedLink = "https://app.box.com/s/abcdefghijklmnopqrstuvwxyz123456"; -String password = "letmein"; -BoxItem.Info itemInfo = BoxItem.getSharedItem(api, sharedLink, password); -``` - -[get-shared-item]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxItem.html#getSharedItem-com.box.sdk.BoxAPIConnection-java.lang.String- -[get-shared-item-password]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxItem.html#getSharedItem-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String- - -Create a Shared Link --------------------- - -A shared link for a folder can be generated by calling -[`createSharedLink(BoxSharedLinkRequest sharedLinkRequest)`][create-shared-link]. - - -```java -// Optionally we can calculate and set the date when shared link will automatically be disabled -final long ONE_WEEK_MILLIS = 1000 * 60 * 60 * 24 * 7; -long unsharedTimestamp = System.currentTimeMillis() + ONE_WEEK_MILLIS; -Date unsharedDate = new Date(unsharedTimestamp); - -BoxFolder folder = new BoxFolder(api, "id"); -BoxSharedLinkRequest sharedLinkRequest = new BoxSharedLinkRequest() - .access(OPEN) - .permissions(true, true) - .unsharedDate(unsharedDate); -BoxSharedLink sharedLink = folder.createSharedLink(sharedLinkRequest); -``` - -A set of shared link access level constants are available through the SDK for convenience: -* `BoxSharedLink.Access.OPEN` -* `BoxSharedLink.Access.COLLABORATORS` -* `BoxSharedLink.Access.COMPANY` -* `BoxSharedLink.Access.DEFAULT` - -[create-shared-link]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#createSharedLink-com.box.sdk.sharedlink.BoxSharedLinkRequest- - -Get a Shared Link ------------------ - -Retrieve the shared link for a folder by calling -[`getSharedLink()`][get-shared-link]. - - -```java -BoxFolder folder = new BoxFolder(api, "id"); -BoxFolder.Info info = folder.getInfo() -BoxSharedLink link = info.getSharedLink() -String url = link.getUrl() -``` - -[get-shared-link]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxItem.Info.html#getSharedLink-- - -Update a Shared Link --------------------- - -A shared link for a folder can be updated by calling the same method as used when creating a shared link, -[`createSharedLink(BoxSharedLinkRequest sharedLinkRequest)`][create-shared-link]. - - -```java -BoxFolder folder = new BoxFolder(api, "id"); -BoxSharedLinkRequest sharedLinkRequest = new BoxSharedLinkRequest() - .access(OPEN) - .permissions(true, true); - -BoxSharedLink sharedLink = folder.createSharedLink(sharedLinkRequest); -``` - -Remove a Shared Link --------------------- - -A shared link for a folder can be removed by calling [`removeSharedLink()`][remove-shared-link]. - - -```java -BoxFolder folder = new BoxFolder(api, "12345"); -BoxFolder.Info info = folder.getInfo(); -info.removeSharedLink(); -folder.updateInfo(info); -``` - -[remove-shared-link]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#removeSharedLink-- - -Share a Folder --------------- - -You can invite another person to collaborate on a folder with the -[`collaborate(String emailAddress, BoxCollaboration.Role 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 user, BoxCollaboration.Role 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); -``` - -You can also create a collaboration with all properties set at once by using the -[`collaborate(BoxCollaborator user, BoxCollaboration.Role role, Boolean notify, Boolean canViewPath, Date expiresAt, Boolean isAccessOnly)`][collaborate3] method. - -The `notify` parameter will determine if the user or group will receive an -email notification when being added as a collaborator. This option is only -available to enterprise administrators. - -The `canViewPath` parameter allows the invitee to see the entire list of ancestor -folders of the associated file. The user will not gain privileges in any ancestor -folder, but will be able to see the whole path to that file in the owner's account. - -The `expiresAt` parameter allows the owner to set a date-time in the future when -the collaboration should expire. - -The `isAccessOnly` parameter allows the owner to set the collaboration to be -access only collaboration. - -The `notify`, `canViewPath`, `expiresAt` and `isAccessOnly` parameters can be left as `null`. - -[collaborate]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#collaborate-java.lang.String-com.box.sdk.BoxCollaboration.Role- -[collaborate2]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#collaborate-com.box.sdk.BoxCollaborator-com.box.sdk.BoxCollaboration.Role- -[collaborate3]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#collaborate-com.box.sdk.BoxCollaborator-com.box.sdk.BoxCollaboration.Role-java.lang.Boolean-java.lang.Boolean-java.util.Date-java.lang.Boolean- - -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-- - -Create Metadata ---------------- - -Metadata can be created on a folder by calling -[`createMetadata(Metadata metadata)`][create-metadata], -[`createMetadata(String templateName, Metadata metadata)`][create-metadata-2], or -[`createMetadata(String templateName, String scope, Metadata metadata)`][create-metadata-3] - - -```java -BoxFolder folder = new BoxFolder(api, "id"); -folder.createMetadata(new Metadata().add("/foo", "bar")); -``` - -Note: This method will only succeed if the provided metadata template is not currently applied to the folder, otherwise -it will fail with a Conflict error. To get to know how to edit existing metadata please -go to [set metadata](#set-metadata) and [update metadata](#update-metadata) sections. - -[create-metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#createMetadata-com.box.sdk.Metadata- -[create-metadata-2]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#createMetadata-java.lang.String-com.box.sdk.Metadata- -[create-metadata-3]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#createMetadata-java.lang.String-java.lang.String-com.box.sdk.Metadata- - -Set Metadata ------------- - -To set metadata on a folder, call [`setMetadata(String templateName, String scope, Metadata metadata)`][set-metadata]. -This method will try to create provided metadata on a folder. However, if metadata has already been applied to this folder, -it will overwrite values of metadata keys specified in the `metadata` parameter. The metadata keys not specified in -the `metadata` parameter will remain unchanged. - -```java -BoxFolder folder = new BoxFolder(api, "id"); -folder.setMetadata("test_template", "enterprise", new Metadata().add("/foo", "bar")); -``` - -Note: If you want to set new metadata on a folder including hard reset of the current metadata -(also removing keys not specified in the `metadata` param): -first delete metadata as specified in [delete metadata](#delete-metadata) section and then set new metadata again. - -[set-metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#setMetadata-java.lang.String-java.lang.String-com.box.sdk.Metadata- - -Get Metadata ------------- - -Retrieve a folder's metadata by calling [`getMetadata()`][get-metadata], -[`getMetadata(String templateName)`][get-metadata-2], or -[`getMetadata(String templateName, String scope)`][get-metadata-3]. -These methods return a [`Metadata`][metadata] object, which allows access to metadata values. - - -```java -BoxFolder folder = new BoxFolder(api, "id"); -Metadata metadata = folder.getMetadata(); - -// Unknown type metadata field, you can test for type or try to get as any type -JsonValue unknownValue = metadata.getValue("/someField"); - -// String or Enum metadata fields -String stringValue = metadata.getString("/author"); - -// Float metadata fields can be interpreted as any numeric type -float floatValue = metadata.getFloat("/price"); - -// Date metadata fields -Date dateValue = metadata.getDate("/deadline"); -``` - -[metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/Metadata.html -[get-metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getMetadata-- -[get-metadata-2]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getMetadata-java.lang.String- -[get-metadata-3]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getMetadata-java.lang.String-java.lang.String- - -Update Metadata ---------------- - -Update a folder's metadata by calling [`updateMetadata(Metadata properties)`][update-metadata]. - -Note: This method will only succeed if the provided metadata template has already been applied to the folder. If the folder -does not have existing metadata, this method will fail with a Not Found error. This is useful in cases where you know -the folder will already have metadata applied, since it will save an API call compared to `setMetadata()`. - - -```java -BoxFolder folder = new BoxFolder(api, "id"); -folder.updateMetadata(new Metadata().add("/foo", "bar")); -``` - -Also, it is possible to add multi-select fields for your folder metadata by calling -[`updateMetadata(Metadata properties)`][update-metadata] with a list of values. - -```java -BoxFolder folder = new BoxFolder(api, "id"); -List valueList = new ArrayList(); -valueList.add("bar"); -valueList.add("qux"); -folder.updateMetadata(new Metadata().add("/foo", valueList)); -``` - -If you wanted to replace all selected fields for a specified key you can use the -[`replace(String key, List values)`][replace-metadata]. - -```java -BoxFolder folder = new BoxFolder(api, "id"); -List valueList = new ArrayList(); -valueList.add("bar"); -valueList.add("qux"); -folder.updateMetadata(new Metadata().replace("/foo", valueList)); -``` - -[update-metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#updateMetadata-com.box.sdk.Metadata- -[replace-metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/Metadata.html#replace-java.lang.String-java.util.List- - -Delete Metadata ---------------- - -A folder's metadata can be deleted by calling -[`deleteMetadata()`][delete-metadata], -[`deleteMetadata(String templateName)`][delete-metadata-2], or -[`deleteMetadata(String templateName, String scope)`][delete-metadata-3]. - - -```java -BoxFolder folder = new BoxFolder(api, "id"); -folder.deleteMetadata("myMetadataTemplate"); -``` - -[delete-metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#deleteMetadata-- -[delete-metadata-2]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#deleteMetadata-java.lang.String- -[delete-metadata-3]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#deleteMetadata-java.lang.String-java.lang.String- - -Get All Metadata on Folder -------------------------- - -[`getAllMetadata()`][get-all-metadata] method will return an iterable that will page through all of the metadata associated with the folder. - - -```java -BoxFolder file = new BoxFolder(api, "id"); -Iterable metadataList = folder.getAllMetadata(); -for (Metadata metadata : metadataList) { - // Do something with the metadata. -} -``` - -[get-all-metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getAllMetadata-java.lang.String...- - -Get Metadata for Multiple Files -------------------------------- - -When fetching a large number of items, for example the items in a folder, it would -often be impractical to fetch the metadata for each of those items individually. -Instead, you can get the metadata for all of the items in a single API call by -requesting the `metadata` field on those items: - -> __Note:__ The field name should have the form `metadata..` - -```java -BoxFolder root = BoxFolder.getRootFolder(); -Iterable itemsInFolder = root.getChildren("metadata.global.properties") -for (BoxItem.Info itemInfo : itemsInFolder) { - if (itemInfo instanceof BoxFile.Info) { - BoxFile.Info fileInfo = (BoxFile.Info) itemInfo; - Metadata itemMetadata = fileInfo.getMetadata("properties", "global"); - } else if (itemInfo instanceof BoxFolder.Info) { - BoxFolder.Info folderInfo = (BoxFolder.Info) itemInfo; - Metadata itemMetadata = folderInfo.getMetadata("properties", "global"); - } -} -``` - -Set Classification on Folder ----------------------------- - -Calling the [`setClassification(String classificationType)`][set-classification] method on a folder will add a -classification template on the folder. This method will return the classification type applied on the folder. The -classification types include `Public`, `Internal`, and `Confidential`. `Public` being the most available permission, -`Internal` which restricts the specified file to company and collaborators only, and finally, `Confidential`, which -is for collaborators only. - -```java -BoxFolder folder = new BoxFolder(api, "id"); -String classificationType = folder.setClassification("Public"); -``` - -It is important to note that this call will attempt to create a classification on the folder first, if one already -exists then it will do the update. If you already know that a classification exists on the folder and would like to save -an API call, we encourage you to use the [`updateClassification(String classificationType)`][update-classification] -method. - -```java -BoxFolder folder = new BoxFolder(api, "id"); -String classificationType = folder.updateClassification("Public"); -``` - -[set-classification]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#setClassification-java.lang.String...- -[update-classification]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#updateClassification-java.lang.String...- - -Get Classification on Folder ----------------------------- - -To retrieve the classification assigned on the folder, use the [`getClassification()`][get-classification] method. This -will return the classification type on the folder. - -```java -BoxFolder folder = new BoxFolder(api, "id"); -String classificationType = folder.getClassification(); -``` - -[get-classification]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getClassification-java.lang.String...- - -Remove Classification on Folder -------------------------------- - -To remove classification from the folder, use the [`deleteClassification()`][delete-classification] method. - -```java -BoxFolder folder = new BoxFolder(api, "id"); -folder.deleteClassification(); -``` - -[delete-classification]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#deleteClassification-- - -Create Cascade Policy On Folder -------------------------------- - -To set a metadata policy, which applies metadata values on a folder to new items in the folder, call -[`BoxFolder.addMetadataCascadePolicy(String scope, String template)`][create-cascade-policy-on-folder]. - -```java -String scope = "global"; -String templateKey = "template"; -String folderId = "12345"; -BoxFolder folder = new BoxFolder(api, folderId); -BoxMetadataCascadePolicy.Info cascadePolicyInfo = folder.addMetadataCascadePolicy(scope, template); -``` - -[create-cascade-policy-on-folder]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#addMetadataCascadePolicy-java.lang.String-java.lang.String- - -Get a Cascade Policy's Information ----------------------------------- - -To retrieve information about a specific metadata cascade policy, call -[`getInfo()`][get-info] - - -```java -String cascadePolicyID = "1234"; -BoxMetadataCascadePolicy metadataCascadePolicy = new BoxMetadataCascadePolicy(api, cascadePolicyID); -BoxMetadataCascadePolicy.Info metadataCascadePolicyInfo = metadataCascadePolicy.getInfo(); -``` - -[get-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxMetadataCascadePolicy.html#getInfo-- - -Get All Cascade Policies on Folder ----------------------------------- - -To get a list of all cascade policies on a folder, which show the metadata templates that are being applied to all -items in the folder, call [`getMetadataCascadePolicies()`][get-all] on that folder. - - -```java -String folderID = "2222"; -BoxFolder folder = new BoxFolder(api, folderID); -Iterable metadataCascadePolicies = folder.getMetadataCascadePolicies(); -for (BoxMetadataCascadePolicy.Info policyInfo : metadataCascadePolicies) { - // take action on policy here -} -``` - -You can also call [`getMetadataCascadePolicies(String enterpriseID, int limit, String... fields)`][get-all-with-limit] -and set the `enterpriseID` option to retrieve metadata cascade policies from another enterprise. - -```java -String folderID = "2222"; -String enterpriseID = "3333"; -int limit = 50; -BoxFolder folder = new BoxFolder(api, folderID); -Iterable metadataCascadePolicies = folder.getMetadataCascadePolicies(enterpriseID, limit); -for (BoxMetadataCascadePolicy.Info policyInfo : metadataCascadePolicies) { - // take action on policy here -} -``` - -[get-all]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getMetadataCascadePolicies-- -[get-all-with-limit]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getMetadataCascadePolicies-java.lang.String-int- - -Force Apply Cascade Policy on Folder ------------------------------------- - -To force apply a metadata template policy and apply metadata values to all existing items in an affected folder, call -[`forceApply(String conflictResolution)`][force-apply] with the conflict resolution method for dealing with items that already have a metadata value that conflicts with the folder. Specifying a resolution value of `none` will preserve the existing values on items, and specifying `overwrite` will overwrite values on items in the folder with the metadata value from the folder. - - -```java -String cascadePolicyID = "e4392a41-7de5-4232-bdf7-15e0d6bba067"; -BoxMetadataCascadePolicy policy = new BoxMetadataCascadePolicy(api, cascadePolicyID); -policy.forceApply("none"); -``` - -[force-apply]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxMetadataCascadePolicy.html#forceApply-java.lang.String- - -Delete Cascade Policy ---------------------- - -To remove a cascade policy and stop applying metadata from a folder to items in the folder, -call [`delete()`][delete-cascade-policy]. - - -```java -String cascadePolicyID = "e4392a41-7de5-4232-bdf7-15e0d6bba067"; -BoxMetadataCascadePolicy policyToDelete = new BoxMetadataCascadePolicy(api, cascadePolicyID); -policyToDelete.delete(); -``` - -[delete-cascade-policy]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxMetadataCascadePolicy.html#delete-- - -Lock a Folder ------------------------------ - -To lock a folder and prevent it from being moved and/or deleted, call [`lock()`][lock] on a folder. - -```java -BoxFolder folder = new BoxFolder(api, "id"); -FolderLock.Info folderLock = folder.lock(); -``` - -[lock]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#lock-- - -Get All Locks on a Folder ------------------------------ - -To get all locks on a folder, call [`getlock()`][get-locks] on folder. - -```java -BoxFolder folder = new BoxFolder(this.api, "id"); -Iterable locks = folder.getLocks(); -for (BoxFolderLock.Info lockInfo : locks) { - // Do something with each lockInfo here -} -``` - -[get-locks]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getLocks-- - -Delete a Lock on a Folder ------------------------------ - -To delete a lock on a folder, call [`delete()`][delete-lock] on a BoxFolderLock object. This cannot be called on a BoxFolder object. - -```java -BoxFolderLock folderLock = new BoxFolderLock(this.api, "folderLockID"); -folderLock.delete(); -``` - -[delete-lock]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolderLock.html#delete-- diff --git a/doc/sdk/groups.md b/doc/sdk/groups.md deleted file mode 100644 index 7d5113e20..000000000 --- a/doc/sdk/groups.md +++ /dev/null @@ -1,218 +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) -- [Get Information About a Group](#get-information-about-a-group) -- [Update a Group](#update-a-group) -- [Delete a Group](#delete-a-group) -- [Get first page of a Group's Collaborations](#get-a-groups-collaborations) -- [Get all of a Group's Collaborations](#get-all-a-groups-collaborations) -- [Create Membership](#create-membership) -- [Get Membership](#get-membership) -- [Update Membership](#update-membership) -- [Delete Membership](#delete-membership) -- [Get Memberships for Group](#get-memberships-for-group) -- [Get Memberships for User](#get-memberships-for-user) - - - -Get All Groups --------------- - -Calling the static [`getAllGroups(BoxAPIConnection api)`][get-all-groups] will -return an iterable that will page through all of the user's groups. - - -```java -Iterable groups = BoxGroup.getAllGroups(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 api, String name)`][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-java.lang.String- - -Get Information About a Group ------------------------------ - -To look up the information about a group by the group's ID, instantiate the [`BoxGroup`][group-object] -object with the group ID and then call [`getInfo()`][get-info-fields] on the group. You can optionally call -[`getInfo(String... fields)`][get-info-fields] to specify the list of fields to retrieve for the group, -which can result in reduced payload size. - - -```java -String groupID = "92875"; -BoxGroup.Info groupInfo = new BoxGroup(api, groupID).getInfo(); -``` - -[group-object]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroup.html -[get-info-fields]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroup.html#getInfo-java.lang.String...- - -Update a Group --------------- - -To update a group, call [`updateInfo(BoxGroup.Info fieldsToUpdate)`][update-group] method. - - -```java -BoxGroup group = new BoxGroup(api, id); -BoxGroup.Info groupInfo = group.getInfo(); -groupInfo.setName("New name for My Group"); -group.updateInfo(groupInfo); -``` - -[update-group]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroup.html#updateInfo-com.box.sdk.BoxGroup.Info- - - -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-- - -Get first page of a Group's Collaborations ---------------------------- - -The first page of a group's collaborations can be retrieved by calling the [`getCollaborations()`][get-collaborations] method. - - -```java -BoxGroup group = new BoxGroup(api, "id"); -Collection collaborations = group.getCollaborations(); -``` - -[get-collaborations]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroup.html#getCollaborations-- - -Get all of a Group's Collaborations ---------------------------- - -All of a group's collaborations can be retrieved by calling the [`getAllCollaborations(String... fields)`][get-all-collaborations] method. -An iterable is returned to allow a user to iterate until the last collaboration. - -```java -BoxGroup group = new BoxGroup(api, "id"); -Iterable collaborations = group.getAllCollaborations(); -``` - -[get-all-collaborations]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroup.html#getAllCollaborations-- - -Create Membership ---------------- - -Membership for the group can be created by calling the -[`addMembership(BoxUser user)`][add-membership] and -[`addMembership(BoxUser user, BoxGroupMembership.GroupRole role)`][add-membership2] methods. - - -```java -BoxGroup group = new BoxGroup(api, "groupID"); -BoxUser user = new BoxUser(api, "userID"); -BoxGroupMembership.Info groupMembershipInfo = group.addMembership(user); -``` - -[add-membership]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroup.html#addMembership-com.box.sdk.BoxUser- -[add-membership2]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroup.html#addMembership-com.box.sdk.BoxUser-com.box.sdk.BoxGroupMembership.GroupRole- - -Get Membership ---------------- - -A groups membership can be retrieved by calling the [`BoxGroupMembership.getInfo()`][get-membership] method. - - -```java -BoxGroupMembership membership = new BoxGroupMembership(api, id); -BoxGroupMembership.Info groupMembershipInfo = membership.getInfo(); -``` - -[get-membership]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroupMembership.html#getInfo-- - -Update Membership ---------------- - -A groups membership can be updated by calling the -[`BoxGroupMembership.updateInfo(BoxGroupMembership.Info fieldsToUpdate)`][update-membership] method. - - -```java -BoxGroupMembership membership = new BoxGroupMembership(api, id); -BoxGroupMembership.Info info = membership.new Info(); -info.setGroupRole(BoxGroupMembership.GroupRole.MEMBER); -membership.updateInfo(info); -``` - -[update-membership]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroupMembership.html#updateInfo-com.box.sdk.BoxGroupMembership.Info- - -Delete Membership ---------------- - -A group can be deleted by calling the [`BoxGroupMembership.delete()`][delete-membership] method. - - -```java -BoxGroupMembership membership = new BoxGroupMembership(api, id); -membership.delete(); -``` - -[delete-membership]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroupMembership.html#delete-- - -Get Memberships for Group ---------------- - -Calling the [`getAllMemberships(String... fields)`][get-memberships-for-group] will return an iterable that will page through all of the group's memberships. -Optional parameters can be used to retrieve specific fields of the Group Membership object. - - -```java -BoxGroup group = new BoxGroup(api, id); -Iterable memberships = group.getAllMemberships(); -for (BoxGroupMembership.Info membershipInfo : memberships) { - // Do something with the membership. -} -``` - -[get-memberships-for-group]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroup.html#getAllMemberships-java.lang.String...- - -Get Memberships for User ---------------- - -Calling the [`BoxUser.getAllMemberships(String... fields)`][get-memberships-for-user] will return an iterable that will page through all of the user's memberships. -Optional parameters can be used to retrieve specific fields of the Group Membership object. - - -```java -BoxUser user = new BoxUser(api, id); -Iterable memberships = user.getAllMemberships(); -for (BoxGroupMembership.Info membershipInfo : memberships) { - // Do something with the membership. -} -``` - -[get-memberships-for-user]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getAllMemberships-java.lang.String...- diff --git a/doc/sdk/legal_holds.md b/doc/sdk/legal_holds.md deleted file mode 100644 index 189df8981..000000000 --- a/doc/sdk/legal_holds.md +++ /dev/null @@ -1,206 +0,0 @@ -Legal Holds Policy -================== - -Legal Hold Policy information describes the basic characteristics of the Policy, -such as name, description, and filter dates. - - - - - -- [Get Legal Hold Policy](#get-legal-hold-policy) -- [Get List of Legal Hold Policies](#get-list-of-legal-hold-policies) -- [Create New Legal Hold Policy](#create-new-legal-hold-policy) -- [Update Existing Legal Hold Policy](#update-existing-legal-hold-policy) -- [Delete Legal Hold Policy](#delete-legal-hold-policy) -- [Get Assignment](#get-assignment) -- [Get List of Assignments](#get-list-of-assignments) -- [Create New Assignment](#create-new-assignment) -- [Delete Assignment](#delete-assignment) -- [Get File Version Legal Hold](#get-file-version-legal-hold) -- [Get List of File Version Legal Holds](#get-list-of-file-version-legal-holds) - - - -Get Legal Hold Policy ---------------------- - -Calling [`getInfo(String...)`][get-info] will return a BoxLegalHoldPolicy.Info object -containing information about the legal hold policy. If necessary to retrieve -limited set of fields, it is possible to specify them using param. - - -```java -BoxLegalHoldPolicy policy = new BoxLegalHoldPolicy(api, id); -BoxLegalHoldPolicy.Info policyInfo = policy.getInfo(); -``` - -[get-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#getInfo-java.lang.String...- - -Get List of Legal Hold Policies -------------------------------- - -Calling the static [`getAll(BoxAPIConnection)`][get-list-of-legal-hold-policies] -will return an iterable that will page through all of the legal hold policies. -It is possible to specify name of legal hold policy, maximum number of items per -response and fields to retrieve by calling the static -[`getAll(BoxAPIConnection, String, int, String...)`][get-list-of-legal-hold-policies-with-fields] method. - - -```java -Iterable policies = BoxLegalHoldPolicy.getAll(api); -for (BoxLegalHoldPolicy.Info policyInfo : policies) { - // Do something with the legal hold policy. -} -``` - -[get-list-of-legal-hold-policies]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#getAll-com.box.sdk.BoxAPIConnection- -[get-list-of-legal-hold-policies-with-fields]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#getAll-com.box.sdk.BoxAPIConnection-java.lang.String-int-java.lang.String...- - -Create New Legal Hold Policy ----------------------------- - -The static [`create(BoxAPIConnection api, String name, String description, Date startDate, Date endDate)`][create-new-legal-hold-policy-with-dates] -method will let you create a new legal hold policy with a specified name, description, start and end dates. - - -```java -BoxLegalHoldPolicy.Info policyInfo = BoxLegalHoldPolicy.create(api, name, description, startedAt, endedAt); -``` - -If you wish to create an ongoing Legal Hold Policy with no end date and a description, call [`createOngoing(BoxAPIConnection api, String name, String description)`][create-ongoing]. - -```java -BoxLegalHoldPolicy.Info policyInfo = BoxLegalHoldPolicy.createOngoing(api, name, description); -``` - -[create-new-legal-hold-policy]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#create-com.box.sdk.BoxAPIConnection-java.lang.String- -[create-new-legal-hold-policy-with-dates]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#create-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String-java.util.Date-java.util.Date- -[create-ongoing]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#createOngoing-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String- - -Update Existing Legal Hold Policy ---------------------------------- - -Updating a legal hold policy's information is done by calling -[`updateInfo(BoxLegalHoldPolicy.Info fieldsToUpdate)`][update-info]. - - -```java -BoxLegalHoldPolicy policy = new BoxLegalHoldPolicy(api, id); -BoxLegalHoldPolicy.Info policyInfo = policy.new Info(); -info.setDescription("new description"); -info.setPolicyName("new policy name"); -policy.updateInfo(info); -``` - -[update-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#updateInfo-com.box.sdk.BoxLegalHoldPolicy.Info- - -Delete Legal Hold Policy ------------------------- - -A legal hold policy can be deleted by calling the [`delete()`][delete] method. - - -```java -BoxLegalHoldPolicy policy = new BoxLegalHoldPolicy(api, id); -policy.delete(); -``` - -[delete]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#delete-- - -Get Assignment --------------- - -Calling [`getInfo(String... fields)`][get-assignment] will return a BoxLegalHoldAssignment.Info -object containing information about the legal hold policy assignment. - - -```java -BoxLegalHoldAssignment assignment = new BoxLegalHoldAssignment(api, id); -BoxLegalHoldAssignment.Info info = assignment.getInfo("assigned_by"); -``` - -[get-assignment]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldAssignment.html#getInfo-java.lang.String...- - -Get List of Assignments --------------- - -Calling the static [`getAssignments(String... fields)`][get-list-of-assignments] will return -an iterable that will page through all of the assignments of the legal hold policy. -It is possible to specify filters for type and id, maximum number of items per single -response and fields to retrieve by calling -[`getAssignments(String type, String id, int limit, String... fields)`][get-list-of-assignments-with-params]. - - -```java -BoxLegalHoldPolicy policy = new BoxLegalHoldPolicy(api, id); -Iterable assignments = policy.getAssignments(BoxResource.getResourceType(BoxFolder.class), null, 50, "assigned_at"); -for (BoxLegalHoldAssignment.Info assignmentInfo : assignments) { - // Do something with the legal hold policy assignment. -} -``` - -[get-list-of-assignments]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#getAssignments-java.lang.String...- -[get-list-of-assignments-with-params]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#getAssignments-java.lang.String-java.lang.String-int-java.lang.String...- - -Create New Assignment ---------------------- - -To create new legal hold policy assignment call [`assignTo(BoxResource target)`][create-assignment] method. -Currently only BoxFile, BoxFileVersion, BoxFolder and BoxUser objects are supported as a parameter. - - -```java -BoxLegalHoldPolicy policy = new BoxLegalHoldPolicy(api, policyID); -BoxFolder folder = new BoxFolder(api, folderID); -policy.assignTo(folder); -``` - -[create-assignment]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#assignTo-com.box.sdk.BoxResource- - -Delete Assignment --------------- - -A legal hold policy assignment can be deleted by calling the [`delete()`][delete-assignment] method -of BoxLegalHoldAssignment object. - - -```java -BoxLegalHoldAssignment assignment = new BoxLegalHoldAssignment(api, id); -assignment.delete(); -``` - -[delete-assignment]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldAssignment.html#delete-- - -Get File Version Legal Hold --------------- - -Calling [`getInfo(String... fields)`][get-file-version-legal-hold] will return -a BoxFileVersionLegalHold.Info object containing information about the file version legal hold policy. - - -```java -BoxFileVersionLegalHold hold = new BoxFileVersionLegalHold(api, id); -hold.getInfo("file"); -``` - -[get-file-version-legal-hold]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileVersionLegalHold.html#getInfo-java.lang.String...- - -Get List of File Version Legal Holds --------------- -To get an iterable with all non-deleted file version legal holds for current -legal hold policy, call [`getFileVersionHolds(String... fields)`][get-lest-of-file-version-legal-holds]. -It is possible to specify maximum number of items per single response by calling -[`getFileVersionHolds(int limit, String... fields)`][get-lest-of-file-version-legal-holds-with-limit]. - - -```java -BoxLegalHoldPolicy policy = new BoxLegalHoldPolicy(api, id); -Iterable fileVersionHolds = policy.getFileVersionHolds(); -for (BoxFileVersionLegalHold.Info fileVersionHold : fileVersionHolds) { - // Do something with the file version legal hold. -} -``` - -[get-lest-of-file-version-legal-holds]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#getFileVersionHolds-java.lang.String...- -[get-lest-of-file-version-legal-holds-with-limit]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#getFileVersionHolds-int-java.lang.String...- diff --git a/doc/sdk/logging.md b/doc/sdk/logging.md deleted file mode 100644 index 30f39a10f..000000000 --- a/doc/sdk/logging.md +++ /dev/null @@ -1,101 +0,0 @@ -# Logging in SDK - -We are using `Java Util Logging` within Box Java SDK. You can read about details of this -approach [here](https://docs.oracle.com/javase/8/docs/technotes/guides/logging/overview.html). - -## Logging Levels - -We are using only few of the logging levels: - -- `FINE` - when logging debugging information, like success responses, -- `WARNING` - when API returned 4xx response code, -- `SEVERE` - when API returned 5XX response code. - -By default, the `Java Util Logging` prints to console output only messages that are logged at least at `INFO` level. You -can limit what is being logged by setting desired level on `com.box.sdk` logger like this: - -```java -import com.box.sdk.BoxLogger; - -BoxLogger.defaultLogger().setLevelToError(); -``` - -Example above will limit printed logs to `SEVERE` level only. - -### Getting FINE (ALL) logs printed - -By default `FINE` level logs are not printed to the console. There are several ways to do that. -One way is to define custom handler: - -```java -import java.util.logging.ConsoleHandler; -import java.util.logging.Handler; -import java.util.logging.Level; -import java.util.logging.Logger; - -Logger sdkLogger = BoxLogger.defaultLogger(); -Handler systemOut = new ConsoleHandler(); -// this handler will print any message to System.out -systemOut.setLevel(Level.ALL); -sdkLogger.addHandler(systemOut); -// allow sdk logger to print FINE logs -sdkLogger.setLevelToAll(); -// prevent logs from being processed by default Console handler -sdkLogger.setUseParentHandlers(false); -``` - -you can do this in your aplication initialization. - -### Turn logging off - -To disable logging use `BoxLogger.defaultLogger().turnLoggingOff()`. - -### Reset to default logging level - -To reset to default logging level use `BoxLogger.defaultLogger().resetToDefaultLevel()`. - - -## Putting SDK logs into application logs - -If you are using different logging solution like Log4J2 or Logstash you can use SLF4J and proper bridgge to get your -logs into desired solution. Below is an example of adding SDK logs into Logstash. First you will need to add -SLF4j and Logstash binaries: - -```groovy -implementation 'org.slf4j:jul-to-slf4j:1.7.32' // bridge from Java Util Logging to SLF4J API -implementation 'org.slf4j:slf4j-api:1.7.32' // define SLF4J API -implementation 'ch.qos.logback:logback-core:1.2.7' // use the Logback logging framework -implementation 'ch.qos.logback:logback-classic:1.2.7' // get bindings between SLF4J and Logback -``` - -Now when initializing application you will need to make Java Util Logging to use SLF4J. This sample is based on -description provided [here](http://www.slf4j.org/api/org/slf4j/bridge/SLF4JBridgeHandler.html): - -```java -import org.slf4j.bridge.SLF4JBridgeHandler; - -// Remove existing handlers attached to JUL root logger -SLF4JBridgeHandler.removeHandlersForRootLogger(); -// add SLF4JBridgeHandler to JUL's root logger -SLF4JBridgeHandler.install(); -``` - -Now all logs generated by SDK will be captured by Logback. If you want to see debug logs from SDK you will need to add -this configuration to your logback.xml file: - -```xml - -``` - -Below is a list of log levels used by SDK and coresponding Logback levels: - -| SDK | Logback | -:------:|:-------: -| ALL | ALL | -| OFF | OFF | -| FINE | DEBUG | -| INFO | INFO | -| WARN | WARN | -| SEVERE | ERROR | - -You can read more on java Util Logging to SLF4J bridge [here](http://www.slf4j.org/legacy.html#jul-to-slf4j). diff --git a/doc/sdk/metadata_template.md b/doc/sdk/metadata_template.md deleted file mode 100644 index 42d0d49b4..000000000 --- a/doc/sdk/metadata_template.md +++ /dev/null @@ -1,189 +0,0 @@ -Metadata Templates -================== - -Metadata that belongs to a file is grouped by templates. Templates allow the metadata service to provide a multitude of services, such as pre-defining sets of key:value pairs or schema enforcement on specific fields. - - - - - -- [Create Metadata Template](#create-metadata-template) -- [Update Metadata Template](#update-metadata-template) -- [Get Metadata Template](#get-metadata-template) - - [Get by scope and template key](#get-by-scope-and-template-key) - - [Get by ID](#get-by-id) -- [Get Enterprise Metadata Templates](#get-enterprise-metadata-templates) -- [Delete a Metadata Template](#delete-a-metadata-template) -- [Execute Metadata Query](#execute-metadata-query) - - - -Create Metadata Template ------------------------- - -The [`createMetadataTemplate(BoxAPIConnection api, String templateScope, String templateKey, String displayName, Boolean hidden, List fields)`][create-metadata-template] -method will create a metadata template schema. - -You can create custom metadata fields that will be associated with the metadata template. - - -```java -MetadataTemplate.Field metadataField = new MetadataTemplate.Field(); -metadataField.setType("string"); -metadataField.setKey("text"); -metadataField.setDisplayName("Text"); - -List fields = new ArrayList(); -fields.add(metadataField); - -MetadataTemplate template = MetadataTemplate.createMetadataTemplate(api, "enterprise", "CustomField", "Custom Field", false, fields); - -final JsonObject jsonObject = new JsonObject(); -jsonObject.add("text", "This is a test text"); - -Metadata metadata = new Metadata(jsonObject); -boxFile.createMetadata("CustomField", metadata); -``` - -[create-metadata-template]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#createMetadataTemplate-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String-java.lang.String-boolean-java.util.List- - -Update Metadata Template ------------------------- - -To update an existing metadata template, call the -[`updateMetadataTemplate(BoxAPIConnection api, String scope, String template, List fieldOperations)`][update-metadata-template] -method with the scope and key of the template, and the list of field operations to perform: - - -```java -List updates = new ArrayList(); - -String addCategoryFieldJSON = "{\"op\":\"addField\","\"data\":{" - + "\"displayName\":\"Category\",\"key\":\"category\",\"hidden\":false,\"type\":\"string\"}}"; -updates.add(new MetadataTemplate.FieldOperation(addCategoryFieldJSON)); - -String changeTemplateNameJSON = "{\"op\":\"editTemplate\",\"data\":{" - + "\"displayName\":\"My Metadata\"}}"; -updates.add(new MetadataTemplate.FieldOperation(changeTemplateNameJSON)); - -MetadataTemplate.updateMetadataTemplate(api, "enterprise", "myData", updates); -``` - -[update-metadata-template]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#updateMetadataTemplate-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String-java.util.List- - -Get Metadata Template ---------------------- - -### Get by scope and template key - -The [`getMetadataTemplate(BoxAPIConnection api)`][get-metadata-template-1] -method will return information about default metadata schema. Also, -[`getMetadataTemplate(BoxAPIConnection api, String templateKey)`][get-metadata-template-2] and -[`getMetadataTemplate(BoxAPIConnection api, String templateKey, String templateScope, String... fields)`][get-metadata-template-3] -can be used to set metadata template name, metadata scope and fields to retrieve. - - -```java -MetadataTemplate template = MetadataTemplate.getMetadataTemplate(api, "templateName"); -``` - -[get-metadata-template-1]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#getMetadataTemplate-com.box.sdk.BoxAPIConnection- -[get-metadata-template-2]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#getMetadataTemplate-com.box.sdk.BoxAPIConnection-java.lang.String- -[get-metadata-template-3]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#getMetadataTemplate-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String-java.lang.String...- - -### Get by ID - -The static [`MetadataTemplate.getMetadataTemplateByID(BoxAPIConnection api, String templateID)`][get-template-by-id] -method will return a specific metadata template. - - -```java -MetadataTemplate template = MetadataTemplate.getMetadataTemplateByID(api, "37c0204b-3fe1-4a32-b9da-f28e88f4c4c6"); -``` - -[get-template-by-id]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#getMetadataTemplateByID-com.box.sdk.BoxAPIConnection-java.lang.String- - -Get Enterprise Metadata Templates ---------------------------------- - -Calling the static -[`getEnterpriseMetadataTemplates(BoxAPIConnection api, String... fields)`][get-enterprise-metadata-1] -will return an iterable that will page through all metadata templates within a user's enterprise. -Also, [`getEnterpriseMetadataTemplates(String templateScope, BoxAPIConnection api, String... fields)`][get-enterprise-metadata-2] and -[`getEnterpriseMetadataTemplates(String templateScope, int limit, BoxAPIConnection api, String... fields)`][get-enterprise-metadata-3] -can be used to set metadata scope, limit of items per single response. - - -```java -Iterable templates = MetadataTemplate.getEnterpriseMetadataTemplates(api); -for (MetadataTemplate templateInfo : templates) { - // Do something with the metadata template. -} -``` - -To return the metadata templates available to all enterprises pass in the -`global` scope. - - -```java -Iterable templates = MetadataTemplate.getEnterpriseMetadataTemplates('global', api); -for (MetadataTemplate templateInfo : templates) { - // Do something with the metadata template. -} -``` - -[get-enterprise-metadata-1]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#getEnterpriseMetadataTemplates-com.box.sdk.BoxAPIConnection-java.lang.String...- -[get-enterprise-metadata-2]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#getEnterpriseMetadataTemplates-java.lang.String-com.box.sdk.BoxAPIConnection-java.lang.String...- -[get-enterprise-metadata-3]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#getEnterpriseMetadataTemplates-java.lang.String-int-com.box.sdk.BoxAPIConnection-java.lang.String...- - -Delete a Metadata Template --------------------------- - -The [`deleteMetadataTemplate(BoxAPIConnection api, String scope, String template)`][delete-metadata-template] -method will remove a metadata template schema from an enterprise. - - -```java -MetadataTemplate.deleteMetadataTemplate(api, "enterprise", "templateName"); -``` - -[delete-metadata-template]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#deleteMetadataTemplate-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String- - -Execute Metadata Query --------------------------- - -The [`executeMetadataQuery(BoxAPIConnection api, MetadataQuery queryBody)`][execute-metadata-query] method queries files and folders based on their metadata. - - -```java -String from = "enterprise_341532.test"; -String query = "testfield = :arg"; -String ancestorFolderId = "0"; -MetadataQuery.OrderBy primaryOrderBy = MetadataQuery.OrderBy.ascending("primarySortKey"); -MetadataQuery.OrderBy secondaryOrderBy = MetadataQuery.OrderBy.ascending("secondarySortKey"); - -MetadataQuery mQuery = new MetadataQuery(from); -mQuery.setQuery(query); -mQuery.setAncestorFolderId(ancestorFolderId); -mQuery.setOrderBy(primaryOrderBy, secondaryOrderBy); -mQuery.addParameter("arg", "test"); -mQuery.setFields("metadata.enterprise_341532.test.customField"); -BoxResourceIterable results = MetadataTemplate.executeMetadataQuery(api, mQuery); - -for (BoxItem.Info r: results) { - if (r instanceof BoxFile.Info) { - BoxFile.Info fileInfo = (BoxFile.Info) r; - Metadata fileMetadata = fileInfo.getMetadata("test", "enterprise_341532"); - String customFieldValue = fileMetadata.getString("/customField"); - System.out.println(customFieldValue); - } else if (r instanceof BoxFolder.Info) { - BoxFolder.Info folderInfo = (BoxFolder.Info) r; - Metadata folderMetadata = folderInfo.getMetadata("test", "enterprise_341532"); - String customFieldValue = folderMetadata.getString("/customField"); - System.out.println(customFieldValue); - } -} - -``` - -[execute-metadata-query]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#executeMetadataQuery-com.box.sdk.BoxAPIConnection-com.box.sdk.MetadataQuery- diff --git a/doc/sdk/overview.md b/doc/sdk/overview.md deleted file mode 100644 index 50c6e3518..000000000 --- a/doc/sdk/overview.md +++ /dev/null @@ -1,193 +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) -* [As-User](#as-user) -* [Suppressing Notifications](#suppressing-notifications) - -Authentication --------------- - -The first step in using the SDK is always authenticating and connecting to the -API. The SDK does this through the [`BoxAPIConnection`][box-api-connection] 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`. - -[box-api-connection]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html - -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 - -As-User -------- - -As-User is used by enterprise administrators to make API calls for their managed -users. It can also be used by a Service Account to make API calls for managed users -or app users. - -As-User state is set on the [`BoxAPIConnection`][box-api-connection] instance with -[`asUser(String userID)`][as-user] and will be used for all requests made from that -API connection going forward, until the state is removed with [`asSelf()`][as-self]. - -```java -String userID = "12345"; -String fileID = "98765"; - -BoxAPIConnection api = new BoxAPIConnection("ACCESS_TOKEN"); - -BoxFile file = new BoxFile(api, fileID); - -// API call made as user associated with access token -BoxFile.Info info = file.getInfo(); - -api.asUser(userID); - -// API call made as user associated with userID -info = file.getInfo(); - -api.asSelf(); - -// API call made as user associated with access token again -BoxFile.Info info = file.getInfo(); -``` - -[as-user]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html#asUser-java.lang.String- -[as-self]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html#asSelf-- - -Suppressing 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. - -To turn on notification suppression for all calls made through a [`BoxAPIConnection`][box-api-connection] -instance, call [`suppressNotifications()`][suppress-notifications]. To re-enable notifications on an API -connection, call [`enableNotifications`][enable-notifications]. - -```java -String userID = "12345"; -String fileID = "98765"; -OutputStream downloadStream; - -BoxAPIConnection api = new BoxAPIConnection("ACCESS_TOKEN"); - -BoxFile file = new BoxFile(api, fileID); - -// Notifications are sent by default -downlaodStream = file.download(); - -api.suppressNotifications(); - -// Notifications are suppressed -downlaodStream = file.download(); - -api.enableNotifications(); - -// Notifications are sent again -downlaodStream = file.download(); -``` - -[suppress-notifications]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html#suppressNotifications-- -[enable-notifications]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html#enableNotifications-- diff --git a/doc/sdk/recent_items.md b/doc/sdk/recent_items.md deleted file mode 100644 index fd13016b8..000000000 --- a/doc/sdk/recent_items.md +++ /dev/null @@ -1,33 +0,0 @@ -Recent Items -============ - -Recent Items returns information about files that have been accessed by a user not long ago. It keeps track of items -that were accessed either in the last 90 days or the last 1000 items accessed (both conditions must be met). - - - - - -- [Get a User's Recent Items](#get-a-users-recent-items) - - - - -Get a User's Recent Items -------------------------- - -Get a list of all recent items the user has by calling -[`BoxRecents.getRecentItems(BoxAPIConnection api, int limit, String... fields)`][get-recents]. -This returns an ordered iterable of the [`BoxRecentItem`][recent-item] records, -which describe which item the user interacted with, when they interacted with it, -and what type of interaction it was. Any `fields` specified relate to the items -themselves (e.g. the recent files and folders). - - -```java -// Get the latest 100 items the user has interacted with -Iterable recentItems = BoxRecents.getRecentItems(api, 100); -``` - -[get-recents]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRecents.html#getRecentItems-com.box.sdk.BoxAPIConnection-int-java.lang.String...- -[recent-item]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRecentItem.html diff --git a/doc/sdk/retention_policies.md b/doc/sdk/retention_policies.md deleted file mode 100644 index 5c8801e64..000000000 --- a/doc/sdk/retention_policies.md +++ /dev/null @@ -1,320 +0,0 @@ -Retention Policies -====== - -A retention policy blocks permanent deletion of content for a specified amount of time. Admins can create retention policies and then later assign them to specific folders or their entire enterprise. - - - - -- [Create Retention Policy](#create-retention-policy) - - [Indefinite Retention Policies](#indefinite-policies) - - [Finite Retention Policies](#finite-policies) - - [Optional parameters](#optional-parameters) -- [Get Retention Policy](#get-retention-policy) -- [Update Retention Policy](#update-retention-policy) -- [Get Retention Policies](#get-retention-policies) -- [Get Retention Policy Assignments](#get-retention-policy-assignments) -- [Create Retention Policy Assignment](#create-retention-policy-assignment) -- [Get Retention Policy Assignment](#get-retention-policy-assignment) -- [Delete Retention Policy Assignment](#delete-retention-policy-assignment) -- [Get File Version Retention](#get-file-version-retention) -- [Get File Version Retentions](#get-file-version-retentions) -- [Get Files Under Retention For Assignment](#get-files-under-retention-for-assignment) -- [Get File Versions Under Retention For Assignment](#get-file-versions-under-retention-for-assignment) -- [Extend retention for a file](#extend-retention-for-a-file) - - - - -## Create Retention Policy - -### Indefinite policies -The static [`createIndefinitePolicy(BoxAPIConnection api, String name)`][create-indefinite-retention-policy] -method will let you create a new indefinite retention policy with a specified name. - - -```java -BoxRetentionPolicy.createIndefinitePolicy(api, name); -``` - -### Finite policies -The static [`BoxRetentionPolicy.createFinitePolicy(com.box.sdk.BoxAPIConnection, java.lang.String, int, com.box.sdk.BoxRetentionPolicy.BoxRetentionPolicyAction)`][create-finite-retention-policy] -method will let you create a new finite retention policy with a specified name, -amount of time to apply the retention policy (in days) and a disposition action. - -```java -BoxRetentionPolicy.createFinitePolicy(api, name, length, PermanentlyDelete); -``` - -### Optional parameters -Both finite and indefinite policies allow you to specify optional parameters using the [`RetentionPolicyParams`][policy-params] -object. - -```java -String notifiedUserID = "12345"; -String description = "Policy to retain all reports"; -RetentionPolicyParams optionalParams = new RetentionPolicyParams(); -optionalParams.setCanOwnerExtendRetention(true); -optionalParams.setAreOwnersNotified(true); -optionalParams.setDescription(description); -optionalParams.addCustomNotificationRecipient(notifiedUserID); - -// Create indefinite policy with optional parameters -BoxRetentionPolicy.createIndefinitePolicy(api, "Retain Stuff Forever", optionalParams); - -// Create finite policy with optional parameters -BoxRetentionPolicy.createFinitePolicy(api, "Keep One Year", 365, BoxRetentionPolicyAction.RemoveRetention, optionalParams); -``` - -[create-indefinite-retention-policy]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#createIndefinitePolicy-com.box.sdk.BoxAPIConnection-java.lang.String- -[create-finite-retention-policy]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#createFinitePolicy-com.box.sdk.BoxAPIConnection-java.lang.String-int-com.box.sdk.BoxRetentionPolicy.BoxRetentionPolicyAction- -[policy-params]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/RetentionPolicyParams.html - -## Get Retention Policy - -Calling [`getInfo(String... fields)`][get-info] will return a -[`BoxRetentionPolicy.Info'][retention-policy-info] object containing information -about the retention policy. If necessary to retrieve limited set of fields, it -is possible to specify them using the `fields` parameter. - - -```java -// Get the policy name and status for a given retention policy -BoxRetentionPolicy policy = new BoxRetentionPolicy(api, id); -policy.getInfo("policy_name", "status"); -``` - -[get-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#getInfo-java.lang.String...- -[retention-policy-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.Info.html - -## Update Retention Policy - -Updating a retention policy's information is done by calling -[`updateInfo(BoxRetentionPolicy.Info fieldsToUpdate)`][update-info]. - - -```java -BoxRetentionPolicy policy = new BoxRetentionPolicy(api, id); -BoxRetentionPolicy.Info policyInfo = policy.new Info(); -policyInfo.setPolicyName("new policy name"); -policy.updateInfo(policyInfo); -``` - -[update-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#updateInfo-com.box.sdk.BoxRetentionPolicy.Info- - -## Get Retention Policies - -Calling the static [`getAll(BoxAPIConnection api, String... fields)`][get-retention-policies] -will return an iterable that will page through all of the retention policies. -It is possible to specify filter for the name of retention policy, filter for -the type of the policy, filter for the id of user, limit of items per single -response and fields to retrieve by calling the static -[`getAll(String name, String type, String userID, int limit, BoxAPIConnection api, String... fields)`][get-retention-policies-with-fields] -method. - - -```java -Iterable policies = BoxRetentionPolicy.getAll(api); -for (BoxRetentionPolicy.Info policyInfo : policies) { - // Do something with the retention policy. -} -``` - -[get-retention-policies]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#getAll-com.box.sdk.BoxAPIConnection-java.lang.String...- -[get-retention-policies-with-fields]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#getAll-java.lang.String-java.lang.String-java.lang.String-int-com.box.sdk.BoxAPIConnection-java.lang.String...- - -## Get Retention Policy Assignments - -Calling [`getAllAssignments(String... fields)`][get-all-assignments] will return -an iterable that will page through all of the assignments of the retention -policy. It is possible to specify maximum number of items per single response -and fields to retrieve by calling -[`getAllAssignments(int limit, String... fields)`][get-all-assignments-with-params]. -If it is necessary to retrieve only assignments of certain type, you can call -[`getFolderAssignments(int limit, String... fields)`][get-folder-assignments] or -[`getEnterpriseAssignments(int limit, String... fields)`][get-enterprise-assignments]. - - -```java -BoxRetentionPolicy policy = new BoxRetentionPolicy(api, id); -Iterable allAssignments = policy.getAllAssignments("assigned_by"); -Iterable folderAssignments = policy.getFolderAssignments(50, "assigned_by"); -Iterable enterpriseAssignments = policy.getEnterpriseAssignments(); -for (BoxRetentionPolicyAssignments.Info assignmentInfo : allAssignments) { - // Do something with the assignment. -} -for (BoxRetentionPolicyAssignments.Info assignmentInfo : folderAssignments) { - // Do something with the assignment. -} -for (BoxRetentionPolicyAssignments.Info assignmentInfo : enterpriseAssignments) { - // Do something with the assignment. -} -``` - -[get-all-assignments]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#getAllAssignments-java.lang.String...- -[get-all-assignments-with-params]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#getAllAssignments-int-java.lang.String...- -[get-folder-assignments]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#getFolderAssignments-int-java.lang.String...- -[get-enterprise-assignments]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#getEnterpriseAssignments-int-java.lang.String...- - -## Create Retention Policy Assignment - -To create new retention policy assignment call [`assignTo(BoxFolder target)`][create-assignment] method to assign the policy -to a specific folder, [`assignToEnterprise()`][create-assignment-to-enterprise] to assign the retention policy to the -entire enterprise, or [`assignToMetadataTemplate(String templateID, String startDateField, MetadataFieldFilter... filterFields)`][assign-to-metadata] -to assign the policy to items with a specific metadata template. - - -```java -// Assign the policy to the entire enterprise -BoxRetentionPolicy policy = new BoxRetentionPolicy(api, policyID); -policy.assignToEnterprise(); - -// Assign the policy to a single folder -BoxFolder folder = new BoxFolder(api, folderID); -policy.assignTo(folderID); - -// Assign the policy to all items with metadata template -String metadataTemplateID = "f0dce190-8106-43ca-9d67-7dce9b10a55e"; -policy.assignToMetadataTemplate(metadataTemplateID); -// You can also pass an optional `startDateField` parameter containing the ID of the metadata template's `date` field -String dateFieldID = "fb523725-04b1-4502-b871-eac305274533"; -policy.assignToMetadataTemplate(metadataTemplateID, dateFieldID); -``` - -[create-assignment]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#assignTo-com.box.sdk.BoxFolder- -[create-assignment-to-enterprise]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#assignToEnterprise-- -[assign-to-metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#assignToMetadataTemplate-java.lang.String-com.box.sdk.MetadataFieldFilter- - -## Get Retention Policy Assignment - -Calling [`getInfo(String... fields)`][get-assignment] will return a -[`BoxRetentionPolicyAssignment.Info`][policy-assignment-info] object containing -information about the retention policy assignment. - - -```java -BoxRetentionPolicyAssignment assignment = new BoxRetentionPolicyAssignment(api, id); -BoxRetentionPolicyAssignment.Info assignmentInfo = assignment.getInfo("assigned_to"); -``` - -[get-assignment]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicyAssignment.html#getInfo-java.lang.String...- -[policy-assignment-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicyAssignment.Info.html - -## Delete Retention Policy Assignment - -To delete Retention Policy Assignment call [`delete()`][delete-assignment] method. - - -```java -BoxRetentionPolicyAssignment assignment = new BoxRetentionPolicyAssignment(api, id); -assignment.delete(); -``` - -[delete-assignment]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicyAssignment.html#delete() - - -## Get File Version Retention - -Calling [`getInfo(String... fields)`][get-file-version-retention] will return a -[`BoxFileVersionRetention.Info`][version-retention-info] object containing -information about the file version retention policy. - - -```java -BoxFileVersionRetention policy = new BoxFileVersionRetention(api, id); -BoxFileVersionRetention.Info policyInfo = policy.getInfo(); -``` - -[get-file-version-retention]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileVersionRetention.html#getInfo-java.lang.String...- -[version-retention-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileVersionRetention.Info.html - -## Get File Version Retentions - -To get an iterable with all file version retentions for the current retention -policy, call the static [`getAll(BoxAPIConnection api, String... fields)`][get-all-file-version-retentions] -method. It is possible to add filters to query passing a -[`BoxFileVersionRetention.QueryFilter`][query-filter] object as a parameter to -[`getRetentions(BoxAPIConnection api, BoxFileVersionRetention.QueryFilter filter, String... fields)`][get-all-file-version-retentions-with-filter]. - - -```java -BoxFileVersionRetention.QueryFilter filter = new BoxFileVersionRetention.QueryFilter() - .addFileID("0") - .addFileVersionID("1") - .addPolicyID("2") - .addDispositionAction(BoxRetentionPolicy.ACTION_PERMANENTLY_DELETE) - .addDispositionBefore(BoxDateFormat.parse("2016-09-15T13:15:35+0000")) - .addDispositionAfter(BoxDateFormat.parse("2014-09-15T13:15:35+0000")); -Iterable retentions - = BoxFileVersionRetention.getRetentions(api, filter, "file", "applied_at"); -for (BoxFileVersionRetention.Info retentionInfo : retentions) { - // Do something with the file version retention. -} -``` - -[get-all-file-version-retentions]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileVersionRetention.html#getAll-com.box.sdk.BoxAPIConnection-java.lang.String...- -[query-filter]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileVersionRetention.QueryFilter.html -[get-all-file-version-retentions-with-filter]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileVersionRetention.html#getRetentions-com.box.sdk.BoxAPIConnection-com.box.sdk.BoxFileVersionRetention.QueryFilter-java.lang.String...- - -## Get Files Under Retention For Assignment - -To get an iterable with all files under retention for assignment -policy, call the [`getFilesUnderRetention(BoxAPIConnection api, int limit, String... fields)`][get-files-under-retention-for-assignment] -method. This will return an interable with [`BoxFile.Info`][file] objects containing information about the files. - - -```java -BoxRetentionPolicyAssignment policyAssignment = new BoxRetentionPolicyAssignment(api, id); -Iterable filesUnderRetention = policyAssignment.getFilesUnderRetention(); -for (BoxFile.Info item : filesUnderRetention){ - // Do something with the files under retention. -} -``` - -[get-files-under-retention-for-assignment]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicyAssignment.html#getFilesUnderRetention-com.box.sdk.BoxAPIConnection-java.lang.String...- -[file]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.Info.html - -Get File Versions Under Retention For Assignment ------------------------------------------------- - -To get an iterable with all file versions under retention for assignment -policy, call the [`getFileVersionsUnderRetention(BoxAPIConnection api, int limit, String... fields)`][get-file-versions-under-retention-for-assignment] -method. This will return an interable with [`BoxFile.Info`][file] objects containing information about the file. -You can get version by calling [`BoxFile.Info#getVersion()`][file-version]. - - -```java -BoxRetentionPolicyAssignment policyAssignment = new BoxRetentionPolicyAssignment(api, id); -Iterable fileVersionsUnderRetention = policyAssignment.getFileVersionsUnderRetention(); -for (BoxFile.Info file : fileVersionsUnderRetention){ - BoxFileVersion version = file.getVersion(); - // Do something with the file version under retention. -} -``` - -[get-file-versions-under-retention-for-assignment]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicyAssignment.html#getFileVersionsUnderRetention-com.box.sdk.BoxAPIConnection-java.lang.String...- -[file-version]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileVersion.html - -## Extend retention for a file - -Once you create retention policy and assign it to a folder all files and subfolders will have same policy applied. -If you need to extend retention for some file you can change it's `dispositionAt` value: - -```java -BoxFile.Info info = someFile.getInfo(); -// to read current disposition date coming from retention policy -BoxFile.Info info = someFile.getInfo("disposition_at"); -Date currentDispositionDate = info.getDispositionAt(); - -// calculate new disposition date -Date dispositionAt = Date.from( - LocalDateTime.ofInstant(currentDispositionDate.toInstant(), ZoneId.of("Z")) - .plusDays(30) - .toInstant(UTC) -); - -// to change disposition date on a file you need to updateInfo -info.setDispositionAt(dispositionAt); -uploadedFile.updateInfo(info); - -``` diff --git a/doc/sdk/search.md b/doc/sdk/search.md deleted file mode 100644 index 54bc3abac..000000000 --- a/doc/sdk/search.md +++ /dev/null @@ -1,52 +0,0 @@ -Search -====== - -Different examples of search which have been implemented in the example [SearchExamplesAsAppUser.java](https://github.com/box/box-java-sdk/blob/main/src/example/java/com/box/sdk/example/SearchExamplesAsAppUser.java) - -For more information refer to the -[Search API documentation](https://developer.box.com/v2.0/reference#searching-for-content). - - - - - -- [Search](#search) - - - -Search ------- - -A search can be performed in your Box instance with specified starting position with -[`searchRange(long offset, long limit, BoxSearchParameters queryParams)`][search] - -You can use the `limit` and `offset` parameters to page through the search results. - - -```java -// Find the first 10 files matching "taxes" -long offsetValue = 0; -long limitValue = 10; -BoxSearch boxSearch = new BoxSearch(api); -BoxSearchParameters searchParams = new BoxSearchParameters(); -searchParams.setQuery("taxes"); -searchParams.setType("file"); -PartialCollection searchResults = boxSearch.searchRange(offsetValue, limitValue, searchParams); -``` - -You can also sort the search results with the `sort` and `direction` flags passed into BoxSearch. This allows for the -order of items returned to be maintained. The `sort` field can only be set to `modified_at` currently. For direction you -can specify either `DESC` for descending order or `ASC` for ascending order to sort the results. - -```java -long offsetValue = 0; -long limitValue = 10; -BoxSearch boxSearch = new BoxSearch(api); -BoxSearchParameters searchParams = new BoxSearchParameters(); -searchParams.setQuery("taxes"); -searchParams.setSort("modified_at"); -searchParams.setDirection("DESC"); -PartialCollection searchResults = boxSearch.searchRange(offsetValue, limitValue, searchParams); -``` - -[search]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSearch.html#searchRange-long-long-com.box.sdk.BoxSearchParameters- diff --git a/doc/sdk/shared-items.md b/doc/sdk/shared-items.md deleted file mode 100644 index 33c580ac9..000000000 --- a/doc/sdk/shared-items.md +++ /dev/null @@ -1,32 +0,0 @@ -Shared Items -============ - -Shared Items represent files and folders on Box accessed via a shared link. - -* [Get a Shared Item](#get-a-shared-item) - -Get a Shared Item ------------------ - -To get the file or folder information for a shared link, you can call -[`BoxItem.getSharedItem(BoxAPIConnection api, String sharedLink)`][get-shared-item] -with the shared link to get information about the item behind it. - -```java -String sharedLink = "https://app.box.com/s/abcdefghijklmnopqrstuvwxyz123456"; -BoxItem.Info itemInfo = BoxItem.getSharedItem(api, sharedLink); -``` - -If the shared link is password-protected, call -[`BoxItem.getSharedItem(BoxAPIConnection api, String sharedLink, String password)`][get-shared-item-password] -with the shared link and password. - - -```java -String sharedLink = "https://app.box.com/s/abcdefghijklmnopqrstuvwxyz123456"; -String password = "foo"; -BoxItem.Info itemInfo = BoxItem.getSharedItem(api, sharedLink, password); -``` - -[get-shared-item]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxItem.html#getSharedItem-com.box.sdk.BoxAPIConnection-java.lang.String- -[get-shared-item-password]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxItem.html#getSharedItem-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String- diff --git a/doc/sdk/sign_requests.md b/doc/sdk/sign_requests.md deleted file mode 100644 index 1469867d5..000000000 --- a/doc/sdk/sign_requests.md +++ /dev/null @@ -1,152 +0,0 @@ -Sign Requests -================== - -Sign Requests are used to request e-signatures on documents from signers. -A Sign Request can refer to one or more Box Files and can be sent to one or more Box Sign Request Signers. - - - - -- [Create Sign Request](#create-sign-request) -- [Get all Sign Requests](#get-all-sign-requests) -- [Get Sign Request by ID](#get-sign-request-by-id) -- [Cancel Sign Request](#cancel-sign-request) -- [Resend Sign Request](#resend-sign-request) - - - -Create Sign Request ------------------------- - -The [`createSignRequest(BoxAPIConnection api, List signers, List files, String parentFolderId)`][create-sign-request] -method will create a Sign Request. - -You need to provide 1 to 10 files (from which the signing document will be created) and at least one signer to receive the Sign Request. You can use [`BoxSignRequestFile`][box-sign-request-file] -and [`BoxSignRequestSigner`][box-sign-request-signer] classes to provide the necessary data. - - -```java -List files = new ArrayList(); -BoxSignRequestFile file = new BoxSignRequestFile("12345"); -files.add(file); - -// you can also use specific version of the file -BoxFile file = new BoxFile(api, "12345"); -List versions = file.getVersions(); -BoxFileVersion firstVersion = versions.get(0); -BoxSignRequestFile file = new BoxSignRequestFile(firstVersion.getFileID(), firstVersion.getVersionID()); - -List signers = new ArrayList(); -BoxSignRequestSigner newSigner = new BoxSignRequestSigner("signer@mail.com"); -signers.add(newSigner); - -String destinationParentFolderId = "55555"; - -BoxSignRequest.Info signRequestInfo = BoxSignRequest.createSignRequest(api, files, - signers, destinationParentFolderId); -``` - -[`createSignRequest`][create-sign-request] allows you to specify optional parameters using the [`BoxSignRequestCreateParams`][sign-request-create-params] -object. - -```java -List files = new ArrayList(); - BoxSignRequestFile file = new BoxSignRequestFile("12345"); - files.add(file); - -List signers = new ArrayList(); -BoxSignRequestSigner newSigner = new BoxSignRequestSigner("signer@mail.com"); -signers.add(newSigner); - -String destinationParentFolderId = "55555"; - -BoxSignRequestCreateParams createParams = new BoxSignRequestCreateParams() - .setIsDocumentPreparationNeeded(true); - -BoxSignRequest.Info signRequestInfo = BoxSignRequest.createSignRequest(api, files, - signers, destinationParentFolderId, createParams); -``` - -If you set ```isDocumentPreparationNeeded``` flag to true, you need to visit ```prepareUrl``` before the Sign Request will be sent. -For more information on ```isDocumentPreparationNeeded``` and the other ```BoxSignRequestCreateParams``` available, please refer to the [developer documentation](https://developer.box.com/guides/box-sign/). - -[sign-request-create-params]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignRequestCreateParams.html -[create-sign-request]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignRequest.html#createSignRequest-com.box.sdk.BoxAPIConnection-java.util.List-java.util.List-java.lang.String- -[box-sign-request-signer]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignRequestSigner.html -[box-sign-request-file]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignRequestFile.html - -Get All Sign Requests ------------------------- - -Calling the static [`getAll(BoxAPIConnection api, String... fields)`][get-all-sign-requests] -will return an iterable that will page through all the Sign Requests. - -The static -[`getAll(int limit, BoxAPIConnection api, String... fields)`][get-all-sign-requests-with-fields] -method offers `limit` and `fields` parameters. The `limit` parameter specifies the maximum number of items to be returned in a single response. The `fields` parameter is used to specify what additional properties should be returned on the `BoxSignRequest.Info` objects. For more information on what `fields` are available, please refer to the [developer documentation](https://developer.box.com/guides/box-sign/). - - -```java -Iterable signRequests = BoxSignRequest.getAll(api); -for (BoxSignRequest.Info signRequestInfo : signRequests) { - // Do something with each `signRequestInfo`. -} -``` - -[get-all-sign-requests]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignRequest.html#getAll-com.box.sdk.BoxAPIConnection-java.lang.String...- -[get-all-sign-requests-with-fields]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignRequest.html#getAll-int-com.box.sdk.BoxAPIConnection-java.lang.String...- - -Get Sign Request by ID ------------------------- - -Calling [`getInfo(String fields ...)`][get-sign-request-by-id] will return a [`BoxSignRequest.Info`][box-sign-request-info] object -containing information about the Sign Request. -The `fields` parameter is used to specify what additional properties should be returned on the `BoxSignRequest.Info` objects. - - -```java -BoxSignRequest signRequest = new BoxSignRequest(api, id); -BoxSignRequest.Info signRequestInfo = signRequest.getInfo(); - -//using `fields` parameter -BoxSignRequest.Info signRequestInfoWithFields = signRequest.getInfo("status") - -``` - -[get-sign-request-by-id]:http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignRequest.html#getInfo-java.lang.String...- -[box-sign-request-info]:http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignRequest.Info.html - - -Cancel Sign Request ------------------------- - -Calling [`cancel()`][cancel-sign-request] will cancel a created Sign Request. - - -```java -BoxSignRequest signRequest = new BoxSignRequest(api, id); -BoxSignRequest.Info signRequestInfo = signRequest.getInfo(); - -signRequestInfo.cancel(); -``` - -[cancel-sign-request]:http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignRequest.html#cancel-- - - -Resend Sign Request ------------------------- - -Calling [`resend()`][resend-sign-request] will resend a Sign Request to all signers that have not signed it yet. -There is an 10-minute cooling-off period between re-sending reminder emails. If this method is called during the -cooling-off period, a [`BoxAPIException`][box-api-exception] will be thrown. - - -```java -BoxSignRequest signRequest = new BoxSignRequest(api, id); -BoxSignRequest.Info signRequestInfo = signRequest.getInfo(); - -signRequestInfo.resend(); -``` - -[resend-sign-request]:http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignRequest.html#resend-- -[box-api-exception]:http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIException.html diff --git a/doc/sdk/sign_templates.md b/doc/sdk/sign_templates.md deleted file mode 100644 index 9f2e5d192..000000000 --- a/doc/sdk/sign_templates.md +++ /dev/null @@ -1,51 +0,0 @@ -Sign Templates -================== - -Box Sign enables you to create templates so you can automatically add the same fields and formatting to requests for signature. With templates, you don't need to repetitively add the same fields to each request every time you send a new document for signature. - -Making and testing a template takes a few minutes, but when done it makes working with Box Sign easier and faster. - - - - -- [Get all Sign Templates](#get-all-sign-templates) -- [Get Sign Template by ID](#get-sign-template-by-id) - - - -Get All Sign Templates ------------------------- - -Calling the static [`getAll(BoxAPIConnection api)`][get-all-sign-templates] -will return an iterable that will page through all the Sign Templates. - -The static -[`getAll(BoxAPIConnection api, int limit)`][get-all-sign-templates-with-limit] -method offers `limit` parameter. The `limit` parameter specifies the maximum number of items to be returned in a single response. - - -```java -Iterable signTemplates = BoxSignTemplate.getAll(api); -for (BoxSignTemplate.Info signTemplateInfo : signTemplates) { - // Do something with each `signTemplateInfo`. -} -``` - -[get-all-sign-templates]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignTemplate.html#getAll-com.box.sdk.BoxAPIConnection- -[get-all-sign-templates-with-limit]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignTemplate.html#getAll-com.box.sdk.BoxAPIConnection-int- - -Get Sign Template by ID ------------------------- - -Calling [`getInfo()`][get-sign-template-by-id] will return a [`BoxSignTemplate.Info`][box-sign-template-info] object -containing information about the Sign Template. - - - -```java -BoxSignTemplate signTemplate = new BoxSignTemplate(api, id); -BoxSignTemplate.Info signTemplateInfo = signTemplate.getInfo(); -``` - -[get-sign-template-by-id]:http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignTemplate.html#getInfo- -[box-sign-template-info]:http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignTemplate.Info.html diff --git a/doc/sdk/storage_policy.md b/doc/sdk/storage_policy.md deleted file mode 100644 index 1da7c9baf..000000000 --- a/doc/sdk/storage_policy.md +++ /dev/null @@ -1,132 +0,0 @@ -Storage Policy -============== - -Allows the enterprise admin to manage the Storage Policies for users in their -enterprise. Used for an enterprise to decide storage location for users based on -where they work/reside. - -* [Get Storage Policy](#get-storage-policy) -* [Get List of Storage Policies](#get-list-of-storage-policies) -* [Create New Assignment](#create-new-assignment) -* [Get Assignment](#get-assignment) -* [Get Assignment For Target](#get-assignment-for-target) -* [Update Existing Assignment](#update-existing-assignment) -* [Assign Storage Policy](#assign-storage-policy) -* [Delete Assignment](#delete-assignment) - -Get Storage Policy ------------------- - -Calling [`getInfo(String fields ...)`][get-info] will return BoxStoragePolicy.Info object -containing information about the storage policy. If necessary to retrieve -limited set of fields. It is possible to specify them using param. - - -```java -BoxStoragePolicy storagePolicy = new BoxStoragePolicy(api, id); -BoxStoragePolicy.Info storagePolicyInfo = storagePolicy.getInfo(); -``` - -[get-info]:http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxStoragePolicy.html#getInfo-- - -Get List of Storage Policies ----------------------------- - -Calling the static [`getAll(BoxAPIConnection api)`][get-list-of-storage-policies] -will return an iterable that will page through all of the storage policies. -It is possible to specify maximum number of items per response and fields to retrieve by -calling the static [`getAll(BoxAPIConnection api, int limit, String fields ...)`][get-list-of-storage-policies-with-fields] method. - - -```java -Iterable storagePolicies = BoxStoragePolicy.getAll(api); -for (BoxStoragePolicy.Info storagePolicyInfo : storagePolicies) { - //Do something with the storage policy. -} -``` - -[get-list-of-storage-policies]:http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxStoragePolicy.html#getAll-- -[get-list-of-storage-policies-with-fields]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxStoragePolicy.html#getAll-java.lang.String...- - -Create New Assignment ---------------------- - -To create new storage policy assignment call [`create(BoxAPIConnection api, String policyID, String userID)`][create] method. - - -```java -BoxStoragePolicyAssignment.Info assignmentInfo = BoxStoragePolicyAssignment.create(api, policyID, userID); -``` - -[create]:http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxStoragePolicyAssignment.html#create-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String- - -Update Existing Assignment --------------------------- - -Updating a storage policy assignment information is done by calling -[`updateInfo(BoxStoragePolicyAssignment.Info updatedInfo)`][update-info]. - - -```java -BoxStoragePolicyAssignment storagePolicyAssignment = new BoxStoragePolicyAssignment(api, "ASSIGNMENT_ID"); -BoxStoragePolicyAssignment.Info assignmentInfo = storagePolicyAssignment.new Info(); -assignmentInfo.setStoragePolicyID("NEW_STORAGE_POLICY_ID"); -storagePolicyAssignment.updateInfo(assignmentInfo); -``` - -[update-info]:http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxStoragePolicyAssignment.html#updateInfo-com.box.sdk.BoxStoragePolicyAssignment.Info- - -Get Assignment --------------- - -Calling [`getInfo(String fields ...)`][get-assignment] will return a BoxStoragePolicyAssignment.Info object containing information -about the storage policy assignment. - - -```java -BoxStoragePolicyAssignment storagePolicyAssignment = new BoxStoragePolicyAssignment(api, id); -BoxStoragePolicyAssignment.Info assignmentInfo = storagePolicyAssignment.getInfo(); -``` - -[get-assignment]:http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxStoragePolicyAssignment.html#getInfo-- - -Get Assignment for Target -------------------------- - -Calling [`getAssignmentForTarget(BoxAPIConnection api, String resolvedForType, String resolvedForID)`][get-assignment-for-target] will return a BoxStorageAssignment.Info -object containing information about the storage policy assignment. - - -```java -BoxStoragePolicyAssignment.Info assignmentInfo = BoxStoragePolicyAssignment.getAssignmentForTarget(api, "user", "1234") -``` - -[get-assignment-for-target]:http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxStoragePolicyAssignment.html#getAssignmentForTarget-com.box.BoxAPIConnection-java.lang.String-java.lang.String- - -Assign Storage Policy ---------------------- - -Calling [`assign(BoxAPIConnection api, String storagePolicyID, String userID)`][assign] will check if this user already has storage policy assigned to them. If not then a new -this user will be assigned the specified storage policy. - - -```java -BoxStoragePolicyAssignment.Info assignmentInfo = BoxStoragePolicyAssignment.assign(api, "1234", "5678"); -``` - -[assign]:http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxStoragePolicyAssigbment.html#assign-com.box.BoxAPIConnection-java.lang.String-java.lang.String- - -Delete Assignment ------------------ - -Calling [`delete()`][delete] will remove the storage policy assignment from the user. - - -```java -BoxStoragePolicyAssignment assignment = new BoxStoragePolicyAssignment(api, "dXNlcl8xMjM0"); -assignment.delete(); -``` - -[delete]:http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxStoragePolicyAssignment.html#delete-- - - diff --git a/doc/sdk/tasks.md b/doc/sdk/tasks.md deleted file mode 100644 index de1927f14..000000000 --- a/doc/sdk/tasks.md +++ /dev/null @@ -1,182 +0,0 @@ -Tasks -===== - -Task objects represent a user-created task on a file. - - - - - -- [Get a Task's Information](#get-a-tasks-information) -- [Get the Tasks on a File](#get-the-tasks-on-a-file) -- [Add a Task to a File](#add-a-task-to-a-file) -- [Update a Task's Information](#update-a-tasks-information) -- [Delete a Task](#delete-a-task) -- [Get a Task's Assignments](#get-a-tasks-assignments) -- [Get Information About a Task Assignment](#get-information-about-a-task-assignment) -- [Add a Task Assignment](#add-a-task-assignment) -- [Delete a Task Assignment](#delete-a-task-assignment) -- [Update a Task Assignment](#update-a-task-assignment) - - - -Get a Task's Information ------------------------- - -Calling [`getInfo()`][get-info] on a task returns a snapshot of the task's -info. - - -```java -BoxTask task = new BoxTask(api, "id"); -BoxTask.Info info = task.getInfo(); -``` - -[get-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTask.html#getInfo-- - -Get the Tasks on a File ------------------------ - -You can get all of the tasks on a file by calling the -[`getTasks()`][get-tasks] method. - - -```java -BoxFile file = new BoxFile(api, "id"); -List tasks = file.getTasks(); -``` - -[get-tasks]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getTasks-- - -Add a Task to a File --------------------- - -A task can be added to a file with the -[`addTask(BoxTask.Action action, String message, Date dueAt)`][add-task] method. - - -```java -BoxFile file = new BoxFile(api, "id"); -Date dueAt = new Date(); -file.addTask(BoxTask.Action.REVIEW, "Please review this file.", dueAt); -``` - -[add-task]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#addTask-com.box.sdk.BoxTask.Action-java.lang.String-java.util.Date- - -Update a Task's Information ---------------------------- - -The message of a task can be changed with the -[`updateInfo(BoxTask.Info fieldsToUpdate)`][update-info] method. - - -```java -BoxTask task = new BoxTask(api, "id"); -BoxTask.Info info = task.new Info(); -info.setMessage("An edited message."); -task.updateInfo(info); -``` - -[update-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTask.html#updateInfo-com.box.sdk.BoxTask.Info- - -Delete a Task -------------- - -A task can be deleted with the [`delete()`][delete] method. - - -```java -BoxTask task = new BoxTask(api, "id"); -task.delete(); -``` - -[delete]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxTask.html#delete-- - -Get a Task's Assignments ------------------------- - -Retreive a tasks assignments with the [`getAssignments()`][get-assignments] method. - - -```java -BoxTask task = new BoxTask(api, "id"); -task.getAssignments(); -``` - -[get-assignments]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxTask.html#getAssignments-- - -Get Information About a Task Assignment ---------------------------------------- - -To look up information about a task assignment by its ID, instantiate the -[`BoxTaskAssignment`][task-assignment-object] object with the ID, and call [`getInfo()`][get-assignment-info] -on the assignment. To retrieve only specific fields on the task assignment, call -[`getInfo(String... fields)`][get-assignment-fields] with the fields to retrieve. - - -```java -String assignmentID = "4256974"; -BoxTaskAssignment.Info assignmentInfo = new BoxTaskAssignment(api, assignmentID).getInfo(); -``` - -[task-assignment-object]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTaskAssignment.html -[get-assignment-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTaskAssignment.html#getInfo-- -[get-assignment-fields]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTaskAssignment.html#getInfo-java.lang.String...- - -Add a Task Assignment ---------------------- - -An assignment can be added to a task with the -[`addAssignment(BoxUser assignee)`][add-assignment] method. - - -```java -BoxUser user = new BoxUser(api, "user-id") -BoxTask task = new BoxTask(api, "id"); -task.addAssignment(user); -``` - -[add-assignment]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTask.html#addAssignment-com.box.sdk.BoxUser- - -Delete a Task Assignment ------------------------- - -An assignment can be deleted from a task with the -[`delete()`][delete-assignment] method on a [`BoxTaskAssignment`][task-assignment-object] -instance. - - -```java -BoxTaskAssignment taskAssignment = new BoxTaskAssignment(api, "id"); -taskAssignment.delete(); -``` - -[delete-assignment]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTaskAssignment.html#delete-- - -Update a Task Assignment ------------------------- - -A task assignment can be updated with the -[`updateInfo(BoxTask.Info fieldsToUpdate)`][update-assignment] method. - -Updating the resolution state: - -```java -String assignmentID = "12345"; -BoxTaskAssignment taskAssignment = new BoxTaskAssignment(api, assignmentID); -BoxTaskAssignment.Info info = taskAssignment.getInfo(); -info.setResolutionState(BoxTaskAssignment.ResolutionState.APPROVED); -taskAssignment.updateInfo(info); -``` - -Updating the message: - -```java -String assignmentID = "12345"; -BoxTaskAssignment taskAssignment = new BoxTaskAssignment(api, assignmentID); -BoxTaskAssignment.Info info = taskAssignment.getInfo(); -info.setMessage("Please review the meeting notes"); -taskAssignment.updateInfo(info); -``` - -[update-assignment]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTaskAssignment.html#updateInfo-com.box.sdk.BoxTaskAssignment.Info- diff --git a/doc/sdk/terms_of_service.md b/doc/sdk/terms_of_service.md deleted file mode 100644 index 6ec68cc66..000000000 --- a/doc/sdk/terms_of_service.md +++ /dev/null @@ -1,154 +0,0 @@ -Terms of Service -================ - -Terms of Service allows Box Admins to configure a custom Terms of Service for end users to -accept/re-accept/decline for platform applications - - - - - -- [Terms of Service](#terms-of-service) - - [Create a Terms of Service](#create-a-terms-of-service) - - [Edit a Terms of Service](#edit-a-terms-of-service) - - [Get a Terms of Service](#get-a-terms-of-service) - - [Get All Terms of Services](#get-all-terms-of-services) - - [Accept or Decline a Terms of Service for New User](#accept-or-decline-a-terms-of-service-for-new-user) - - [Accept or Decline a Terms of Service for Existing User](#accept-or-decline-a-terms-of-service-for-existing-user) - - [Get User Status on a Terms of Service](#get-user-status-on-a-terms-of-service) - - - -Create a Terms of Service -------------------------- - -A terms of service can be created in an enterprise. Please note that only two can be created. One external -and one managed. If a terms of service already exists please use the update call to change the current -terms of service. - -You can create a custom terms of service by calling -[`create(BoxAPIConnection api, BoxTermsOfService.TermsOfServiceStatus status, BoxTermsOfService.TermsOfServiceType type, String text)`][createTermsOfService]. - - -```java -BoxTermsOfService.Info newTOS = BoxTermsOfService.create( - api, - BoxTermsOfService.TermsOfServiceStatus.ENABLED, - BoxTermsOfService.TermsOfServiceType.EXTERNAL, - "Terms of Service..." -); -``` - -[createTermsOfService]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTermsOfService.html#create-com.box.sdk.BoxAPIConnection-com.box.sdk.BoxTermsOfService.TermsOfServiceStatus-com.box.sdk.BoxTermsOfService.TermsOfServiceType-java.lang.String- - -Edit a Terms of Service ------------------------ - -You can update a terms of service status and text after you have created them by calling -[`updateInfo(BoxTermsOfService.Info fieldsToUpdate)`][update-terms-of-service] - - -```java -BoxTermsOfService termsOfService = new BoxTermsOfService(api, "tos-id"); -BoxTermsOfService.Info termsOfServiceInfo = termsOfService.new Info(); -termsOfServiceInfo.setStatus(BoxTermsOfService.TermsOfServiceStatus.DISABLED); -termsOfServiceInfo.setText("New Terms of Service Text"); -termsOfService.updateInfo(termsOfService); -``` - -[update-terms-of-service]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTermsOfService.html#updateInfo-com.box.sdk.BoxTermsOfService.Info- - -Get a Terms of Service ----------------------- - -You can retrieve a terms of service by providing the ID and calling -[`getInfo()`][getTermsOfServiceInfo]. - - -```java -BoxTermsOfService termsOfService = new BoxTermsOfService(api, "tos-id"); -BoxTermsOfService.Info tosInfo = termsOfService.getInfo(); -``` - -[getTermsOfServiceInfo]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTermsOfService.html#getInfo-- - -Get All Terms of Services -------------------------- - -You can also retrieve all terms of service in your enterprise by calling -[`getAllTermsOfServices(BoxAPIConnection api)`][get-all-terms-of-services1]. -This will return an iterable that will page through all of the enterprises terms of services. - - -```java -List termsOfServices = BoxTermsOfService.getAllTermsOfServices(api); -for(BoxTermsOfService.Info termsOfServiceInfo : termsOfServices){ - // Do something with the terms of service. -} -``` - -You can also filter by managed or external terms of service by calling -[`getAllTermsOfServices(BoxAPIConnection api, BoxTermsOfService.TermsOfServiceType type)`][get-all-terms-of-services2]. - -[get-all-terms-of-services1]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTermsOfService.html#getAllTermsOfServices-com.box.sdk.BoxAPIConnection- -[get-all-terms-of-services2]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTermsOfService.html#getAllTermsOfServices-com.box.sdk.BoxAPIConnection-com.box.sdk.BoxTermsOfService.TermsOfServiceType- - - -Accept or Decline a Terms of Service for New User -------------------------------------------------- - -For new users you can accept or decline a terms of service by calling -[`create(BoxAPIConnection api, String tosID, Boolean accepted, String userID)`][create-user-status] - - -```java -BoxTermsOfService.Info newUserStatus = BoxTermsOfServiceUserStatus.create(api, "tos-id", true, "user-id"); -``` - -You can only create a new user status on a terms of service if the user has never accepted/declined a terms of service. -If they have then you will need to make the update call. - -[create-user-status]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTermsOfServiceUserStatus.html#create-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.Boolean-java.lang.String- - -Accept or Decline a Terms of Service for Existing User ------------------------------------------------------- - -For an existing user you can accept or decline a terms of service by calling -[`updateInfo(BoxTermsOfService.Info fieldsToUpdate)`][update-user-status]. - - -```java -BoxTermsOfServiceUserStatus tosUserStatus = new BoxTermsOfServiceUserStatus(api, "tos-user-status-id"); -BoxTermOfServiceUserStatus.Info tosUserStatusInfo = tosUserStatus.new Info(); -tosUserStatusInfo.setStatus(newStatus); -tosUserStatus.updateInfo(tosUSerStatusInfo); -``` - -[update-user-status]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTermsOfServiceUserStatus.html#updateInfo-com.box.sdk.BoxTermsOfServiceUserStatus.Info- - -Get User Status on a Terms of Service -------------------------------------- - -You can retrieve the terms of service status for a user by calling -[`getInfo(BoxAPIConnection api, String tosID, String userID)`][get-user-status1] - - -```java -List tosUserStatusInfo = BoxTermsOfServiceUserStatus.getInfo(api, "tos-id", "user-id"); -for(BoxTermsOfServiceUserStatus.Info info : toUserStatusInfo){ - // Do something with the user status on terms of service. -} -``` - -Alternatively you can get the user status by the ID of the terms of service by -calling [`getInfo(BoxAPIConnection api, String tosID)`][get-user-status2]. - -```java -List tosUserStatusInfo = BoxTermsOfServiceUserStatus.getInfo(api, "tos-id"); -for(BoxTermsOfServiceUserStatus.Info info : toUserStatusInfo){ - // Do something with the user status on terms of service. -} -``` - -[get-user-status1]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTermsOfServiceUserStatus.html#getInfo-com.box.sdk.BoxAPIConnection-java.lang.String- -[get-user-status2]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTermsOfServiceUserStatus.html#getInfo-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String- diff --git a/doc/sdk/trash.md b/doc/sdk/trash.md deleted file mode 100644 index ea4f83044..000000000 --- a/doc/sdk/trash.md +++ /dev/null @@ -1,189 +0,0 @@ -Trash -===== - -Under normal circumstances, when an item in Box is deleted, it is not actually erased immediately. Instead, it is -moved to the Trash. The Trash allows you to recover files and folders that have been deleted. By default, items in -the Trash will be purged after 30 days. - - - - - -- [Get Trashed Items](#get-trashed-items) -- [Get Trashed File Information](#get-trashed-file-information) -- [Get Trashed Folder Information](#get-trashed-folder-information) -- [Permanently Delete File From Trash](#permanently-delete-file-from-trash) -- [Permanently Delete Folder From Trash](#permanently-delete-folder-from-trash) -- [Restore a File from the Trash](#restore-a-file-from-the-trash) -- [Restore a Folder from the Trash](#restore-a-folder-from-the-trash) - - - -Get Trashed Items ------------------ - -The [`BoxTrash`][trash-object] implements `Iterable`, so to get -the collection of items currently in the trash, simply iterate over it. - - -```java -BoxTrash trash = new BoxTrash(api); -for (BoxItem.Info itemInfo : trash) { - // Process the item -} -``` - -Alternatively you can specify sort order, limit, use marker based pagination or specify which fields you want to extract with -[`BoxTrash#items`][trash-items]. - -To use sorting you have to use offset based pagination: -```java -BoxTrash trash = new BoxTrash(api); -Iterable trashEntries = trash.items( - SortParameters.ascending("name"), - PagingParameters.offset(0, 500) -); -for (BoxItem.Info trashEntry : trashEntries) { - // Process the item -} -``` -If you have a lot of items in trash and offset value is in tens of thousands it is better to use marker based pagination. -However, marker based pagination cannot be used with sorting. To disable sorting use `SortParameters.none()`: -```java -BoxTrash trash = new BoxTrash(api); -Iterable trashEntries = trash.items( - SortParameters.none(), - PagingParameters.marker(500) -); -for (BoxItem.Info trashEntry : trashEntries) { - // Process the item -} -``` - -[trash-object]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTrash.html -[trash-items]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTrash.html#items-com.box.sdk.SortParameters-com.box.sdk.PagingParameters-java.lang.String...- - -Get Trashed File Information ----------------------------- - -Ordinarily, trying to call [`getInfo()`][file-get-info] on a file that is in -the trash will return a 404 error. To get the information of a file in the -trash, you must instead call -[`BoxTrash#getFileInfo(String fileID)`][get-trashed-file] with the ID of the trashed file. You can optionally -pass a specific list of fields to retrieve to [`getFileInfo(String fileID, String... fields)`][get-trashed-file-fields], -which will return only the specified fields to reduce payload size. - - -```java -String fileID = "9873459"; -BoxTrash trash = new BoxTrash(api); -BoxFile.Info fileInfo = trash.getFileInfo(fileID); -``` -[file-get-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getInfo-java.lang.String...- -[get-trashed-file]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTrash.html#getFileInfo-java.lang.String- -[get-trashed-file-fields]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTrash.html#getFileInfo-java.lang.String-java.lang.String...- - -Get Trashed Folder Information ------------------------------- - -Ordinarily, trying to call [`getInfo()`][folder-get-info] on a folder that is in the trash will return a 404 error. -To get the information of a folder in the trash, you must instead call -[`BoxTrash#getFolderInfo(String fileID)`][get-trashed-folder] with the ID of the trashed folder. You can optionally -pass a specific list of fields to retrieve to -[`getFileInfo(String folderID, String... fields)`][get-trashed-folder-fields], which will return only the specified -fields to reduce payload size. - - -```java -String folderID = "2345343"; -BoxTrash trash = new BoxTrash(api); -BoxFolder.Info folderInfo = trash.getFolderInfo(folderInfo); -``` -[folders-get-info]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getInfo-java.lang.String...- -[get-trashed-folder]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTrash.html#getFolderInfo-java.lang.String- -[get-trashed-folder-fields]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTrash.html#getFolderInfo-java.lang.String-java.lang.String...- - - -Permanently Delete File From Trash ----------------------------------- - -To delete a file from the trash, call [`BoxTrash#deleteFile(String fileID)`][delete-file] with the ID of the file to -delete. - -> __Note:__ This will permanently delete the file, and cannot be undone. - - -```java -String fileID = "87398"; -BoxTrash trash = new BoxTrash(api); -trash.deleteFile(fileID); -``` - -[delete-file]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTrash.html#deleteFile-java.lang.String- - - -Permanently Delete Folder From Trash ----------------------------------- - -To delete a folder from the trash, call [`BoxTrash#deleteFolder(String fileID)`][delete-folder] with the ID of the -folder to delete. - -> __Note:__ This will permanently delete the folder, and cannot be undone. - - -```java -String folder = "123456"; -BoxTrash trash = new BoxTrash(api); -trash.deleteFolder(folderID); -``` - -[delete-folder]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTrash.html#deleteFolder-java.lang.String- - -Restore a File from the Trash ------------------------------ - -To restore a file from the trash, effectively undeleting it, call [`BoxTrash#restoreFile(String fileID)`][restore-file] -with the ID of the file. To avoid scenarios where the parent folder that previously contained the file is no longer available, -the user does not have permission to create items in that folder, or that folder has an item with the same name as the one -being restored; you can pass a new parent folder ID and/or file name to -[`BoxTrash#restoreFile(String fileID, String newName, String newParentID)`][restore-file-safe]. The new name -and parent will only be used if a conflict is encountered while trying to restore the file to its original location. - - -```java -String fileID = "125367"; -String newName = "Presentation 2018 ORIGINAL.pptx"; -String newParentID = "98765"; - -BoxTrash trash = new BoxTrash(api); -// Avoid conflicts at the original location -trash.restoreFile(fileID, newName, newParentID); -``` - -[restore-file]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTrash.html#restoreFile-java.lang.String- -[restore-file-safe]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTrash.html#restoreFile-java.lang.String-java.lang.String-java.lang.String- - -Restore a Folder from the Trash -------------------------------- - -To restore a folder from the trash, effectively undeleting it, call -[`BoxTrash#restoreFolder(String folderID)`][restore-folder] with the ID of the folder. To avoid scenarios where the -parent folder that previously contained the folder to be restored is no longer available, the user -does not have permission to create items in that folder, or that folder has an item with the same name as the one -being restored; you can pass a new parent folder ID and/or folder name to -[`BoxTrash#restoreFolder(String folderID, String newName, String newParentID)`][restore-folder-safe]. The new name -and parent will only be used if a conflict is encountered while trying to restore the folder to its original location. - - -```java -String folderID = "125367"; -String newName = "My Documents ORIGINAL"; -String newParentID = "98765"; - -BoxTrash trash = new BoxTrash(api); -// Avoid conflicts at the original location -trash.restoreFolder(folderID, newName, newParentID); -``` - -[restore-folder]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTrash.html#restoreFolder-java.lang.String- -[restore-folder-safe]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTrash.html#restoreFolder-java.lang.String-java.lang.String-java.lang.String- diff --git a/doc/sdk/upgrading.md b/doc/sdk/upgrading.md deleted file mode 100644 index ed966930f..000000000 --- a/doc/sdk/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") -BoxJSONRequest request = new BoxJSONRequest(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/sdk/users.md b/doc/sdk/users.md deleted file mode 100644 index 047dd478c..000000000 --- a/doc/sdk/users.md +++ /dev/null @@ -1,321 +0,0 @@ -# Users - -Users represent an individual's account on Box. - - - - - -- [Get the Current User's Information](#get-the-current-users-information) -- [Get User Information](#get-user-information) -- [Get Avatar for a User](#get-avatar-for-a-user) -- [Add or update user avatar](#add-or-update-user-avatar) -- [Delete user avatar](#delete-user-avatar) -- [Create An Enterprise User](#create-an-enterprise-user) -- [Create An App User](#create-an-app-user) -- [Update User](#update-user) -- [Delete User](#delete-user) -- [Invite User](#invite-user) -- [Get Email Aliases](#get-email-aliases) -- [Add Email Alias](#add-email-alias) -- [Delete Email Alias](#delete-email-alias) -- [Get Enterprise Users](#get-enterprise-users) -- [Get Enterprise Users (Marker Pagination)](#get-enterprise-users-marker-pagination) -- [Get App Users By External App User ID](#get-app-users-by-external-app-user-id) -- [Get App Users By External App User ID (Marker Pagination)](#get-app-users-by-external-app-user-id-marker-pagination) -- [Move User's Folder](#move-users-folder) - - - -## Get the Current User's Information - -To get the current user, call the static -[`getCurrentUser(BoxAPIConnection api)`][get-current-user] method. -Then use [`getInfo(String... fields)`][get-info] to get information about the user. - - -```java -BoxUser user = BoxUser.getCurrentUser(api); -BoxUser.Info info = user.getInfo(); -``` - -[get-current-user]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getCurrentUser-com.box.sdk.BoxAPIConnection- -[get-info]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getInfo-java.lang.String...- - -## Get User Information - -To get information about a user, call the [`getInfo()`][get-info] method on the user object. - - -```java -String userID = "33333"; -BoxUser user = new BoxUser(api, userID); -BoxUser.Info userInfo = user.getInfo(); -``` - -## Get Avatar for a User - -To retrieve the avatar for a User, call the [`downloadAvatar(OutputStream stream)`][download-avatar] method on the user object. - - -```java -String userID = "33333"; -// some stream do download avatar -try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()){ - BoxUser user=new BoxUser(api,userID); - user.downloadAvatar(outputStream); -} catch (IOException e) { - throw new RuntimeException(e); -} -``` - -## Add or update user avatar - -To add or update the avatar for a User, call the [`uploadAvatar(File)`][upload-avatar-1] method on the user object. - - -```java -String userID = "33333"; -BoxUser user = new BoxUser(api, userID); -AvatarUploadResponse response = user.uploadAvatar(new File("path_to_avatar_file")); -``` -In return, you will get an object with links to several representations of an avatar within Box account. -Your image file should have correct extension, it is used to determine image type used in upload. -Supported formats are JPG and PNG. The image size cannot exceed 1024 * 1024 pixels or 1MB. - -You can upload avatart using `InputStream` with [`uploadAvatar(InputStream, String)`][upload-avatar-2]: - -```java -String userID = "33333"; -BoxUser user = new BoxUser(api, userID); -AvatarUploadResponse response = user.uploadAvatar(Files.newInputStream(Paths.get("path_to_avatar_file")), "file_name.jpeg"); -``` - -Both upload methods supports [`ProgressListener`][progress-listener]. - -## Delete user avatar - -To delete User avatar image use [`deleteAvatar()`][delete-avatar] method on the user object: - - -```java -String userID = "33333"; -BoxUser user = new BoxUser(api, userID); -user.deleteAvatar(); -``` - -[download-avatar]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#downloadAvatar-java.io.OutputStream- -[upload-avatar-1]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#uploadAvatar-java.io.File- -[upload-avatar-2]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#uploadAvatar-java.io.InputStream-java.lang.String- -[delete-avatar]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#deleteAvatar-- -[progress-listener]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/ProgressListener.html - -## Create An Enterprise User - -To create an enterprise user, call the -[`createEnterpriseUser(BoxAPIConnection api, String loginEmail, String userName, String... fields)`][create-enterprise-user]. -To pass additional optional parameters, use the -[`createEnterpriseUser(BoxAPIConnection api, String loginEmail, String userName, CreateUserParams options, String... fields)`][create-enterprise-user-2] -method. - - -```java -BoxUser.Info createdUserInfo = BoxUser.createEnterpriseUser(api, "user@example.com", "A User"); -``` - -[create-enterprise-user]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#createEnterpriseUser-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String-java.lang.String...- -[create-enterprise-user-2]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#createAppUser-com.box.sdk.BoxAPIConnection-java.lang.String-com.box.sdk.CreateUserParams-java.lang.String...- - -## Create An App User - -To create an app user, call the -[`createAppUser(BoxAPIConnection api, String userName, String... fields)`][create-app-user] method. -To pass additional optional parameters, use the -[`createAppUser(BoxAPIConnection api, String userName, CreateUserParams options, String... fields)`][create-app-user-2] method. - - -```java -BoxUser.Info createdUserInfo = BoxUser.createAppUser(api, "A User"); -``` - -```java -CreateUserParams params = new CreateUserParams(); -params.setExternalAppUserId("An Identifier Like Login"); -BoxUser.Info createdUserInfo = BoxUser.createAppUser(api, "A User", params); -``` - -[create-app-user]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#createAppUser-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String...- -[create-app-user-2]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#createAppUser-com.box.sdk.BoxAPIConnection-java.lang.String-com.box.sdk.CreateUserParams-java.lang.String...- - - -## Update User - -To update a user call the [`updateInfo(BoxUser.Info fieldsToUpdate, String... fields)`][update-info] method. - - -```java -BoxUser user = new BoxUser(api, "0"); -BoxUser.Info info = user.new Info(); -info.setName(name); -user.updateInfo(info); -``` - -[update-info]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#updateInfo-com.box.sdk.BoxUser.Info-java.lang.String...- - -## Delete User - -To delete a user call the [`delete(boolean notifyUser, boolean force)`][deleteWithParams] method or one that -uses API default parameters [`delete()][delete] - -The `notifyUser` determines whether the user should receive an email about the deletion, -and the `force` parameter will cause the user to be deleted even if they still have files -in their account. - - -```java -BoxUser user = new BoxUser(api, "0"); -user.delete(false, false); -``` - -[deleteWithParams]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#delete-boolean-boolean- -[delete]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#delete-- - -## Invite User - -To invite an existing user to join an Enterprise call the -[`inviteUser(String enterpriseID, String userEmail)`][invite] method. - - -```java -BoxUser user = new BoxUser(api, "0"); -user.invite("Enterprise ID", "Invited User Login"); -``` - -[invite]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#inviteUser-java.lang.String-java.lang.String- - -## Get Email Aliases - -To get a user's email aliases call the [`getEmailAliases()`][get-email-aliases] method. - - -```java -BoxUser user = new BoxUser(api, "0"); -Collection emailAliases = user.getEmailAliases(); -``` - -[get-email-aliases]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getEmailAliases-- - -## Add Email Alias - -To add an email alias for a user, call the -[`addEmailAlias(String emailAddress)`][add-email-alias] method. - - -```java -BoxUser user = new BoxUser(api, "0"); -user.addEmailAlias("user+alias@example.com"); -``` - -Enterprise admins can automatically confirm the new email alias by calling the -[`addEmailAlias(String emailAddress, boolean confirm)`][add-email-alias2] method: - -```java -BoxUser user = new BoxUser(api, "0"); -user.addEmailAlias("user+alias@eexample.com", true); -``` - -[add-email-alias]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#addEmailAlias-java.lang.String- -[add-email-alias2]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#addEmailAlias-java.lang.String-boolean- - -## Delete Email Alias - -To delete a users email alias call the -[`deleteEmailAlias(String emailAliasID)`][delete-email-alias] method. - - -```java -BoxUser user = new BoxUser(api, "0"); -user.deleteEmailAlias("123"); -``` - -[delete-email-alias]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#deleteEmailAlias-java.lang.String- - -## Get Enterprise Users - -To get an enterprise's users call the -[`getAllEnterpriseUsers(BoxAPIConnection api)`][get-all-enterprise-users], -[`getAllEnterpriseUsers(BoxAPIConnection api, String filterTerm, String... fields)`][get-all-enterprise-users-2], or -[`getAllEnterpriseOrExternalUsers(BoxAPIConnection api, String filterTerm, String... fields)`][get-all-enterprise-users-3] method. - - -```java -Iterable users = BoxUser.getAllEnterpriseUsers(api); -``` - -[get-all-enterprise-users]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getAllEnterpriseUsers-com.box.sdk.BoxAPIConnection- -[get-all-enterprise-users-2]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getAllEnterpriseUsers-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String...- -[get-all-enterprise-users-3]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getAllEnterpriseOrExternalUsers-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String...- - -## Get Enterprise Users (Marker Pagination) - -To get a list of all users in an enterprise, call the -[`getAllEnterpriseUsers(BoxAPIConnection api, boolean usemarker, String marker)`][get-all-enterprise-users], -[`getAllEnterpriseUsers(BoxAPIConnection api, String filterTerm, boolean usemarker, String marker, String... fields)`][get-all-enterprise-users-2], or -[`getAllEnterpriseOrExternalUsers(BoxAPIConnection api, String filterTerm, boolean usemarker, String marker, String... fields)`][get-all-enterprise-users-3] method. -To get a list of users starting from the first page of results, set the `usemarker` parameter as `true` and the `marker` parameter as `null`. If you would like to get the marker for the next page of results from the page the iterator is currently on, you must cast the iterable to `BoxResourseIterable` and call `getNextMarker()` on that iterable. For more information on marker pagination, look here: https://developer.box.com/en/guides/api-calls/pagination/marker-based/. - - -```java -Iterable users = BoxUser.getAllEnterpriseUsers(api, true, null); - -// Get marker -String marker = ((BoxResourceIterable) users).getNextMarker(); -``` - -[get-all-enterprise-users]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getAllEnterpriseUsers-com.box.sdk.BoxAPIConnection- -[get-all-enterprise-users-2]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getAllEnterpriseUsers-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String...- -[get-all-enterprise-users-3]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getAllEnterpriseOrExternalUsers-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String...- - -## Get App Users By External App User ID - -To get app user using external app user ID, call the -[`getAppUsersByExternalAppUserID(BoxAPIConnection api, String externalID, String... fields)`][get-app-users-by-external-app-user-id]. -This method allows you to easily associate Box app users with your application's -identifiers for those users. - -```java -Iterable users = BoxUser.getAppUsersByExternalAppUserID(api, "external_app_user_id"); -``` - -[get-app-users-by-external-app-user-id]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getAppUsersByExternalAppUserID-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String...- - -## Get App Users By External App User ID (Marker Pagination) - -To get app user using external app user ID, call the -[`getAppUsersByExternalAppUserID(BoxAPIConnection api, String externalID, boolean usemarker, String marker, String... fields)`][get-app-users-by-external-app-user-id]. -This method allows you to easily associate Box app users with your application's -identifiers for those users. To get a list of users starting from the first page of results, set the `usemarker` parameter as `true` and the `marker` parameter as `null`. If you would like to get the marker for the next page of results from the page the iterator is currently on, you must cast the iterable to `BoxResourseIterable` and call `getNextMarker()` on that iterable. For more information on marker pagination, look here: https://developer.box.com/en/guides/api-calls/pagination/marker-based/. - -```java -Iterable users = BoxUser.getAppUsersByExternalAppUserID(api, "external_app_user_id"); - -// Get marker -String marker = ((BoxResourceIterable) users).getNextMarker(); -``` - -[get-app-users-by-external-app-user-id]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getAppUsersByExternalAppUserID-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String...- - -## Move User's Folder - -To move all of a user's content to another user, call the -[`transferContent(String destinationUserID)`][transfer-folder-to-new-user] method. - - -```java -String sourceUserID = "11111"; -String destinationUserID = "22222"; -BoxUser sourceUser = new BoxUser(api, sourceUserID); -BoxFolder.Info transferredFolderInfo = sourceUser.transferContent(destinationUserID); -``` - -[transfer-folder-to-new-user]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#transferContent-java.lang.String- diff --git a/doc/sdk/watermarking.md b/doc/sdk/watermarking.md deleted file mode 100644 index 65d28f86d..000000000 --- a/doc/sdk/watermarking.md +++ /dev/null @@ -1,99 +0,0 @@ -Watermarking -====== - -The ability to watermark files and folders is represented as a sub-resource on the Files and Folders resources, respectively. You can think of the sub-resource as a "label" marking whether the file or folder is watermarked or not. If you apply a watermark label to a folder, then all files inside of it will be protected by the watermark (e.g. previews will be watermarked). However, those files' watermark sub-resource is independent from the folder that got watermarked. This allows you to watermark files and folders independently. - - - - - -- [Get Watermark on File](#get-watermark-on-file) -- [Apply Watermark on File](#apply-watermark-on-file) -- [Remove Watermark on File](#remove-watermark-on-file) -- [Get Watermark on Folder](#get-watermark-on-folder) -- [Apply Watermark on Folder](#apply-watermark-on-folder) -- [Remove Watermark on Folder](#remove-watermark-on-folder) - - - -Get Watermark on File --------------- - -Calling [`getWatermark(String... fields)`][get-watermark-on-file] will return a BoxWatermark object containing information about the watermark associated for this file. If the file does not have a watermark applied on it, a 404 Not Found will be returned. - - -```java -BoxFile file = new BoxFile(api, id); -BoxWatermark watermark = file.getWatermark(); -``` - -[get-watermark-on-file]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getWatermark-java.lang.String...- - -Apply Watermark on File --------------- - -To apply watermark on file, call [`applyWatermark()`][apply-watermark-on-file] method. While the endpoint accepts a JSON body describing the watermark to apply, custom watermarks are not supported yet. -The method will return a BoxWatermark object containing information about the watermark applied on this file. - - -```java -BoxFile file = new BoxFile(api, id); -file.applyWatermark(); -``` - -[apply-watermark-on-file]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#applyWatermark-- - -Remove Watermark on File --------------- - -A watermark can be removed by calling the [`removeWatermark()`][remove-watermark-on-file] method. -If the file did not have a watermark applied on it, a 404 Not Found will be returned by API. - - -```java -BoxFile file = new BoxFile(api, id); -file.removeWatermark(); -``` - -[remove-watermark-on-file]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#removeWatermark-- - -Get Watermark on Folder --------------- - -Calling [`getWatermark(String... fields)`][get-watermark-on-folder] will return a BoxWatermark object containing information about the watermark associated for this folder. If the folder does not have a watermark applied on it, a 404 Not Found will be returned. - - -```java -BoxFolder folder = new BoxFolder(api, id); -BoxWatermark watermark = folder.getWatermark(); -``` - -[get-watermark-on-folder]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getWatermark-java.lang.String...- - -Apply Watermark on Folder --------------- - -To apply watermark on folder, call [`applyWatermark()`][apply-watermark-on-folder] method. -The method will return a BoxWatermark object containing information about the watermark applied on this folder. - - -```java -BoxFolder folder = new BoxFolder(api, id); -fodler.applyWatermark(); -``` - -[apply-watermark-on-folder]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#applyWatermark-- - -Remove Watermark on Folder --------------- - -A watermark can be removed by calling the [`removeWatermark()`][remove-watermark-on-folder] method. -If the folder did not have a watermark applied on it, a 404 Not Found will be returned by API. - - -```java -BoxFolder folder = new BoxFolder(api, id); -folder.removeWatermark(); -``` - -[remove-watermark-on-folder]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#removeWatermark-- diff --git a/doc/sdk/webhooks.md b/doc/sdk/webhooks.md deleted file mode 100644 index 1597e4f6a..000000000 --- a/doc/sdk/webhooks.md +++ /dev/null @@ -1,156 +0,0 @@ -Webhooks -====== - -Webhooks enable you to attach event triggers to Box files and folders. Event triggers monitor events on Box objects and notify your application when they occur. A webhook notifies your application by sending HTTP requests to a URL of your choosing. - - - - - -- [Get a Webhook](#get-a-webhook) -- [Get All Webhooks](#get-all-webhooks) -- [Create a Webhook](#create-a-webhook) -- [Delete a Webhook](#delete-a-webhook) -- [Update a Webhook](#update-a-webhook) -- [Verify a Webhook Message](#verify-a-webhook-message) - - - -Get a Webhook -------------- - -A webhook infocan be retrieved by calling the [`getInfo(String... fields)`][get-info] method. - - -```java -BoxWebHook webhook = new BoxWebHook(api, id); -BoxWebHook.Info info = webhook.getInfo(); -``` - -[get-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxWebHook.html#getInfo-java.lang.String...- - -Get All Webhooks ----------------- - -Calling the static [`all(BoxAPIConnection api, String... fields)`][all] will -return an iterable that will page through all defined webhooks for the -requesting application and user. - - -```java -Iterable webhooks = BoxWebHook.all(api); -for (BoxWebHook.Info webhookInfo: webhooks) { - // Do something with the webhook. -} -``` - -[all]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxWebHook.html#all-com.box.sdk.BoxAPIConnection-java.lang.String...- - -Create a Webhook ----------------- - -The static [`create(BoxResource targetItem, URL callbackURL, BoxWebHook.Trigger... triggerEvents)`][create-webhook] -method will let you create a new webhook for a specified target object. - - -```java -// Listen for preview events for a file -BoxFile file = new BoxFile(api, id); -BoxWebHook.Info webhookInfo = BoxWebHook.create(file, url, BoxWebHook.Trigger.FILE.PREVIEWED); -``` - - -```java -// Listen for file upload events in the specified folder -BoxFolder folder = new BoxFolder(api, id); -BoxWebHook.Info webhookInfo = BoxWebHook.create(folder, url, BoxWebHook.Trigger.FILE_UPLOADED); -``` - -[create-webhook]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxWebHook.html#create-com.box.sdk.BoxResource-java.net.URL-com.box.sdk.BoxWebHook.Trigger...- - -Delete a Webhook ----------------- - -A webhook can be deleted by calling the [`delete()`][delete] method. - - -```java -BoxWebHook webhook = new BoxWebHook(api, id); -webhook.delete(); -``` - -[delete]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxWebHook.html#delete-- - -Update a Webhook ----------------- - -A webhook can be updated by calling the [`update(BoxWebHook.Info fieldsToUpdate)`][update] method. - - -```java -BoxWebHook webhook = new BoxWebHook(api, id); -BoxWebHook.Info info = webhook.new Info(); -info.setAddress(url); -webhook.update(info); -``` - -[update]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxWebHook.html#updateInfo-com.box.sdk.BoxWebHook.Info- - -Verify a Webhook Message ------------------------- - -When you receive a webhook message from Box, you should validate that it actually came from Box by calling -[`BoxWebHookSignatureVerifier#verify(String sigVersion, String sigAlgorithm, String primarySignature, String secondarySignature, String payload, String deliveryTimestamp)`][verify] - -> __Note:__ It is recommended to ensure that your application and verifier use both a primary and secondary key -> to ensure that these keys can be safely rotated. - - -```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") -); - -if (isValidMessage) { - // Message is valid, handle it -} else { - // Message is invalid, reject it -} -``` - -[verify]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxWebHookSignatureVerifier.html#verify-java.lang.String-java.lang.String-java.lang.String-java.lang.String-java.lang.String-java.lang.String- diff --git a/doc/sdk/weblinks.md b/doc/sdk/weblinks.md deleted file mode 100644 index 8fa09b4de..000000000 --- a/doc/sdk/weblinks.md +++ /dev/null @@ -1,126 +0,0 @@ -Web Links -====== - -Web links are objects that point to URLs. These objects are also known as -bookmarks within the Box web application. Web link objects are treated -similarly to file objects. - - - - - -- [Create Web Link](#create-web-link) -- [Get Web Link](#get-web-link) -- [Update Web Link](#update-web-link) -- [Delete Web Link](#delete-web-link) -- [Create Shared Link](#create-shared-link) -- [Remove Shared Link](#remove-shared-link) - - - -Create Web Link ---------------- - -Calling [`BoxFolder.createWebLink(String name, URL url, String description)`][create-web-link] will let you create a new web link with a specified name and description. - - -```java -BoxFolder folder = new BoxFolder(api, id); -URL url = new URL("https://www.example.com"); -folder.createWebLink("Link to Example", url, "This goes to an example page"); -``` - -Name and description params are optional, so it is possible to create web link -with only one of them or with URL only: -[`BoxFolder.createWebLink(URL url)`][create-web-link2] - -```java -BoxFolder folder = new BoxFolder(api, id); -URL url = new URL("https://www.example.com"); -BoxWebLink.Info webLinkInfo = folder.createWebLink(url); -``` - -[create-web-link]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#createWebLink-java.lang.String-java.net.URL-java.lang.String- -[create-web-link2]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#createWebLink-java.net.URL- - -Get Web Link ------------- - -A web link info can be retrieved by calling the [`getInfo(String... fields)`][get-web-link] method. -Optional parameters can be used to retrieve specific fields of the Device Pin object. - - -```java -BoxWebLink webLink = new BoxWebLink(api, id); -BoxWebLink.Info webLinkInfo = webLink.getInfo(); -``` - -[get-web-link]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxWebLink.html#getInfo-java.lang.String...- - -Update Web Link ---------------- - -A web link can be updated by calling the -[`updateInfo(BoxWebLink.Info fieldsToUpdate)`][update-web-link] method. - - -```java -BoxWebLink webLink = new BoxWebLink(api, id); -BoxWebLink.Info webLinkInfo = webLink.new Info(); -webLinkInfo.setName("new name for weblink"); -webLink.updateInfo(webLinkInfo); -``` - -[update-web-link]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxWebLink.html#updateInfo-com.box.sdk.BoxWebLink.Info- - -Delete Web Link ---------------- - -A web link can be deleted by calling the [`delete()`][delete] method. - - -```java -BoxWebLink webLink = new BoxWebLink(api, id); -webLink.delete(); -``` - -[delete]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxWebLink.html#delete-- - -Create Shared Link --------------------- - -You can create a shared link for a web link by calling the -[`createSharedLink(BoxSharedLinkWithoutPermissionsRequest sharedLinkRequest)`][create-shared-link] -method. - - -```java -// Optionally we can calculate and set the date when shared link will automatically be disabled -final long ONE_WEEK_MILLIS = 1000 * 60 * 60 * 24 * 7; -long unsharedTimestamp = System.currentTimeMillis() + ONE_WEEK_MILLIS; -Date unsharedDate = new Date(unsharedTimestamp); - -BoxWebLink webLink = new BoxWebLink(api, "id"); -BoxSharedLinkWithoutPermissionsRequest sharedLinkRequest = new BoxSharedLinkWithoutPermissionsRequest() - .access(OPEN) - .unsharedDate(unsharedDate); -BoxSharedLink sharedLink = webLink.createSharedLink(sharedLinkRequest); -``` - -[create-shared-link]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxWebLink.html#createSharedLink-com.box.sdk.sharedlink.BoxSharedLinkWithoutPermissionsRequest- - -Remove Shared Link --------------------- - -You can remove a shared link for a web link by calling the [`removeSharedLink`](remove-shared-link) method. - - -```java -BoxWebLink webLink = new BoxWebLink(api, "12345"); -BoxWebLink.Info webLinkInfo = webLink.getInfo(); -info.removeSharedLink() -webLink.updateInfo(info) -``` - -[remove-shared-link]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxWebLink.html#removeSharedLink-- - diff --git a/doc/sdk/zip_download.md b/doc/sdk/zip_download.md deleted file mode 100644 index 32262f155..000000000 --- a/doc/sdk/zip_download.md +++ /dev/null @@ -1,58 +0,0 @@ -Zip Download -====== - -Allows you to create a temporary zip file of Box files and folders and download them. - - - - - -- [Create a Zip File](#create-a-zip-file) -- [Download a Zip File](#download-a-zip-file) - - - -Create a Zip File ---------------- - -Calling [`BoxZip.create(String name, List items)`][create-a-zip-file] will let you create a new zip file with the specified name and -with the specified items and will return a `BoxZipInfo` object with the download link. This file does not show up in your Box account, but will be temporarily -available for download. - - -```java -ArrayList items = new ArrayList(); -BoxZipItem file = new BoxZipItem("file", "12345"); -BoxZipItem folder = new BoxZipItem("folder", "156472"); -items.add(file); -items.add(folder); -BoxZip zip = new BoxZip(api); -BoxZipInfo zipInfo = zip.create("Awesome Zip File", items); -``` - -[create-a-zip-file]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxZip.html - -Download a Zip File ------------- - -Calling [`BoxZip.download(String name, List items, OutputStream output)`][download-a-zip-file] will let you create a new zip file -with the specified name and with the specified items and download it to the stream that is passed in. The return object is a `BoxZipDownloadStatus` -object that contains information about the download, including whether it was successful. The created zip file does not show up in your Box account. - - -```java -ArrayList items = new ArrayList(); -BoxZipItem file = new BoxZipItem("file", "12345"); -BoxZipItem folder = new BoxZipItem("folder", "156472"); -items.add(file); -items.add(folder); -BoxZip zip = new BoxZip(api); -FileOutputStream stream = new FileOutputStream(); -BoxZipDownloadStatus zipDownloadStatus = zip.download("Another Awesome Zip File", items, stream); -stream.close(); -if (zipDownloadStatus.getState() == BoxZipDownloadStatus.State.SUCCEEDED) { - System.out.println("Zip downloaded successfully"); -} -``` - -[download-a-zip-file]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxZip.html diff --git a/src/intTest/java/com/box/sdk/BoxAIIT.java b/src/intTest/java/com/box/sdk/BoxAIIT.java index 25465058e..46eef47d2 100644 --- a/src/intTest/java/com/box/sdk/BoxAIIT.java +++ b/src/intTest/java/com/box/sdk/BoxAIIT.java @@ -55,7 +55,7 @@ public void askAISingleItem() throws InterruptedException { Collections.singletonList( new BoxAIItem(uploadedFileInfo.getID(), BoxAIItem.Type.FILE)), BoxAI.Mode.SINGLE_ITEM_QA); - assertThat(response.getAnswer(), containsString("Test file")); + assertThat(response.getAnswer(), containsString("Test File")); assert response.getCreatedAt().before(new Date(System.currentTimeMillis())); assertThat(response.getCompletionReason(), equalTo("done")); }, @@ -190,7 +190,7 @@ public void askAISingleItemWithAgent() throws InterruptedException { null, askAgent, true); - assertThat(response.getAnswer(), containsString("Test file")); + assertThat(response.getAnswer(), containsString("Test File")); assert response.getCreatedAt().before(new Date(System.currentTimeMillis())); assertThat(response.getCompletionReason(), equalTo("done")); }, diff --git a/src/intTest/java/com/box/sdk/BoxClassificationTemplateIT.java b/src/intTest/java/com/box/sdk/BoxClassificationTemplateIT.java index fdc879f8b..9b7cfd6ce 100644 --- a/src/intTest/java/com/box/sdk/BoxClassificationTemplateIT.java +++ b/src/intTest/java/com/box/sdk/BoxClassificationTemplateIT.java @@ -75,7 +75,7 @@ public void getUpdateClassificationTemplate() { api, Metadata.ENTERPRISE_METADATA_SCOPE, Metadata.CLASSIFICATION_TEMPLATE_KEY, updates); MetadataTemplate.Option updatedOption = updatedTemplate.getFields().get(0).getOptionsObjects().get(0); - assertEquals(updatedOption.getKey(), "Sensitive"); + assertEquals(optionKey, updatedOption.getKey()); assertEquals( updatedOption .getStaticConfig() @@ -111,7 +111,7 @@ public void getUpdateClassificationTemplate() { MetadataTemplate.updateMetadataTemplate( api, Metadata.ENTERPRISE_METADATA_SCOPE, Metadata.CLASSIFICATION_TEMPLATE_KEY, updates); updatedOption = updatedTemplate.getFields().get(0).getOptionsObjects().get(0); - assertEquals(updatedOption.getKey(), "Sensitive"); + assertEquals(optionKey, updatedOption.getKey()); assertEquals( updatedOption .getStaticConfig() diff --git a/src/intTest/java/com/box/sdk/BoxFileIT.java b/src/intTest/java/com/box/sdk/BoxFileIT.java index c2bc26934..a236705b5 100644 --- a/src/intTest/java/com/box/sdk/BoxFileIT.java +++ b/src/intTest/java/com/box/sdk/BoxFileIT.java @@ -228,8 +228,7 @@ public void uploadAndDownloadFileSucceeds() throws IOException { folder, hasItem(Matchers.hasProperty("ID", equalTo(uploadedFile.getID())))); verify(mockUploadListener, atLeastOnce()) .onProgressChanged(anyLong(), longThat(is(equalTo(fileSize)))); - verify(mockDownloadListener, atLeastOnce()) - .onProgressChanged(anyLong(), longThat(is(equalTo(fileSize)))); + verify(mockDownloadListener, atLeastOnce()).onProgressChanged(anyLong(), anyLong()); } finally { deleteFile(uploadedFile); } diff --git a/src/intTest/resources/junit-platform.properties b/src/intTest/resources/junit-platform.properties new file mode 100644 index 000000000..82de190bf --- /dev/null +++ b/src/intTest/resources/junit-platform.properties @@ -0,0 +1,2 @@ +junit.jupiter.execution.parallel.enabled = true +junit.jupiter.execution.parallel.mode.default = concurrent \ No newline at end of file diff --git a/src/main/java/com/box/sdk/BoxAPIConnection.java b/src/main/java/com/box/sdk/BoxAPIConnection.java index fd5d69a61..b1fb86fb8 100644 --- a/src/main/java/com/box/sdk/BoxAPIConnection.java +++ b/src/main/java/com/box/sdk/BoxAPIConnection.java @@ -1272,7 +1272,7 @@ public void asSelf() { /** * Used to override default SSL certification handling. For example, you can provide your own * trust manager or hostname verifier to allow self-signed certificates. You can check examples here. + * href="https://github.com/box/box-java-sdk/blob/combined-sdk/docs/sdk/configuration.md#ssl-configuration">here. * * @param trustManager TrustManager that verifies certificates are valid. * @param hostnameVerifier HostnameVerifier that allows you to specify what hostnames are allowed. From dd19b9a7f4f5f237507a2d959002704bf2face33 Mon Sep 17 00:00:00 2001 From: lsocha Date: Fri, 26 Sep 2025 14:11:17 +0200 Subject: [PATCH 02/19] fix --- .github/workflows/integration-tests-sdk.yml | 7 +------ .github/workflows/integration-tests-sdkgen.yml | 2 +- 2 files changed, 2 insertions(+), 7 deletions(-) diff --git a/.github/workflows/integration-tests-sdk.yml b/.github/workflows/integration-tests-sdk.yml index b6f5d0e87..1162827a4 100644 --- a/.github/workflows/integration-tests-sdk.yml +++ b/.github/workflows/integration-tests-sdk.yml @@ -1,13 +1,8 @@ -name: Integration tests - +name: Integration tests sdk on: - push: - branches: - - combined-sdk pull_request: branches: - combined-sdk - jobs: core: runs-on: ubuntu-latest diff --git a/.github/workflows/integration-tests-sdkgen.yml b/.github/workflows/integration-tests-sdkgen.yml index 50f86782f..0d2489acb 100644 --- a/.github/workflows/integration-tests-sdkgen.yml +++ b/.github/workflows/integration-tests-sdkgen.yml @@ -1,4 +1,4 @@ -name: build +name: Integration tests sdkgen on: pull_request: branches: From 8e8edfab7064afba58bb9afede5a3de2d8f2c92c Mon Sep 17 00:00:00 2001 From: lsocha Date: Fri, 26 Sep 2025 17:12:18 +0200 Subject: [PATCH 03/19] fix12 --- build.gradle | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/build.gradle b/build.gradle index 9bf31e02d..8581442af 100644 --- a/build.gradle +++ b/build.gradle @@ -111,17 +111,6 @@ task integrationTest(type: Test) { classpath = sourceSets.intTest.runtimeClasspath } -jacoco { - reportsDirectory = file("$buildDir/reports/jacoco") -} - -jacocoTestReport { - reports { - xml.required = true // coveralls plugin depends on xml format report - html.required = true - } -} - tasks.withType(JavaCompile) { options.compilerArgs << "-Xlint:all" @@ -148,6 +137,17 @@ tasks.withType(GenerateModuleMetadata) { enabled = false } +jacoco { + reportsDirectory = file("$buildDir/reports/jacoco") +} + +jacocoTestReport { + reports { + xml.required = true // coveralls plugin depends on xml format report + html.required = true + } +} + artifacts { archives sourcesJar, javadocJar } From 0ad592e07987c42dd2d562aa78bba1898f7e2077 Mon Sep 17 00:00:00 2001 From: lsocha Date: Fri, 26 Sep 2025 17:23:12 +0200 Subject: [PATCH 04/19] add docs --- docs/sdk/ai.md | 148 ++++ docs/sdk/android.md | 97 +++ docs/sdk/authentication.md | 271 ++++++ docs/sdk/classifications.md | 226 +++++ docs/sdk/collaboration_allowlists.md | 147 ++++ docs/sdk/collaborations.md | 168 ++++ docs/sdk/collections.md | 104 +++ docs/sdk/comments.md | 125 +++ docs/sdk/configuration.md | 329 ++++++++ docs/sdk/css/javadoc.css | 488 +++++++++++ docs/sdk/devices.md | 62 ++ docs/sdk/events.md | 244 ++++++ docs/sdk/file_requests.md | 77 ++ docs/sdk/files.md | 1135 ++++++++++++++++++++++++++ docs/sdk/folders.md | 801 ++++++++++++++++++ docs/sdk/groups.md | 218 +++++ docs/sdk/legal_holds.md | 206 +++++ docs/sdk/logging.md | 101 +++ docs/sdk/metadata_template.md | 189 +++++ docs/sdk/overview.md | 193 +++++ docs/sdk/recent_items.md | 33 + docs/sdk/retention_policies.md | 320 ++++++++ docs/sdk/search.md | 52 ++ docs/sdk/shared-items.md | 32 + docs/sdk/sign_requests.md | 152 ++++ docs/sdk/sign_templates.md | 51 ++ docs/sdk/storage_policy.md | 132 +++ docs/sdk/tasks.md | 182 +++++ docs/sdk/terms_of_service.md | 154 ++++ docs/sdk/trash.md | 189 +++++ docs/sdk/upgrading.md | 116 +++ docs/sdk/users.md | 321 ++++++++ docs/sdk/watermarking.md | 99 +++ docs/sdk/webhooks.md | 156 ++++ docs/sdk/weblinks.md | 126 +++ docs/sdk/zip_download.md | 58 ++ 36 files changed, 7502 insertions(+) create mode 100644 docs/sdk/ai.md create mode 100644 docs/sdk/android.md create mode 100644 docs/sdk/authentication.md create mode 100644 docs/sdk/classifications.md create mode 100644 docs/sdk/collaboration_allowlists.md create mode 100644 docs/sdk/collaborations.md create mode 100644 docs/sdk/collections.md create mode 100644 docs/sdk/comments.md create mode 100644 docs/sdk/configuration.md create mode 100644 docs/sdk/css/javadoc.css create mode 100644 docs/sdk/devices.md create mode 100644 docs/sdk/events.md create mode 100644 docs/sdk/file_requests.md create mode 100644 docs/sdk/files.md create mode 100644 docs/sdk/folders.md create mode 100644 docs/sdk/groups.md create mode 100644 docs/sdk/legal_holds.md create mode 100644 docs/sdk/logging.md create mode 100644 docs/sdk/metadata_template.md create mode 100644 docs/sdk/overview.md create mode 100644 docs/sdk/recent_items.md create mode 100644 docs/sdk/retention_policies.md create mode 100644 docs/sdk/search.md create mode 100644 docs/sdk/shared-items.md create mode 100644 docs/sdk/sign_requests.md create mode 100644 docs/sdk/sign_templates.md create mode 100644 docs/sdk/storage_policy.md create mode 100644 docs/sdk/tasks.md create mode 100644 docs/sdk/terms_of_service.md create mode 100644 docs/sdk/trash.md create mode 100644 docs/sdk/upgrading.md create mode 100644 docs/sdk/users.md create mode 100644 docs/sdk/watermarking.md create mode 100644 docs/sdk/webhooks.md create mode 100644 docs/sdk/weblinks.md create mode 100644 docs/sdk/zip_download.md diff --git a/docs/sdk/ai.md b/docs/sdk/ai.md new file mode 100644 index 000000000..fcc3a683e --- /dev/null +++ b/docs/sdk/ai.md @@ -0,0 +1,148 @@ +AI +== + +AI allows to send an intelligence request to supported large language models and returns +an answer based on the provided prompt and items. + + + + +- [AI](#ai) + - [Send AI request](#send-ai-request) + - [Send AI text generation request](#send-ai-text-generation-request) + - [Get AI Agent default configuration](#get-ai-agent-default-configuration) + - [Extract metadata freeform](#extract-metadata-freeform) + - [Extract metadata structured](#extract-metadata-structured) + + + +Send AI request +-------------------------- + +To send an AI request, call static +[`sendAIRequest(String prompt, List items, Mode mode)`][send-ai-request] method. +In the request you have to provide a prompt, a list of items that your prompt refers to and a mode of the request. +There are two modes available: `SINGLE_ITEM_QA` and `MULTI_ITEM_QA`, which specifies if this request refers to +for a single or multiple items. + + +```java +BoxAIResponse response = BoxAI.sendAIRequest( + api, + "What is the content of the file?", + Collections.singletonList("123456", BoxAIItem.Type.FILE), + BoxAI.Mode.SINGLE_ITEM_QA +); +``` + +You can also provide a list of dialogue history entries to provide additional context to the LLM in generating the response, AI Agent configuration and flag to indicate whether citations should be returned. + +NOTE: The AI endpoint may return a 412 status code if you use for your request a file which has just been updated to the box. +It usually takes a few seconds for the file to be indexed and available for the AI endpoint. + +[send-ai-request]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAI.html#sendAIRequest-com.box.sdk.BoxAPIConnection-java.lang.String-java.util.List-com.box.sdk.BoxAI.Mode- + +Send AI text generation request +-------------- + +To send an AI request specifically focused on the creation of new text, call static +[`sendAITextGenRequest(String prompt, List items, List dialogueHistory)`][send-ai-text-gen-request] method. +In the request you have to provide a prompt, a list of items that your prompt refers to and optionally a dialogue history, +which provides additional context to the LLM in generating the response. + + +```java +List dialogueHistory = new ArrayList<>(); +dialogueHistory.add( + new BoxAIDialogueEntry( + "Make my email about public APIs sound more professional", + "Here is the first draft of your professional email about public APIs.", + BoxDateFormat.parse("2013-05-16T15:26:57-07:00") + ) + ); +BoxAIResponse response = BoxAI.sendAITextGenRequest( + api, + "Write an email to a client about the importance of public APIs.", + Collections.singletonList(new BoxAIItem("123456", BoxAIItem.Type.FILE)), + dialogueHistory +); +``` + +You can also provide an AI Agent configuration to customize the behavior of the AI response generation. + +[send-ai-text-gen-request]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAI.html#sendAITextGenRequest-com.box.sdk.BoxAPIConnection-java.lang.String-java.util.List-java.util.List- + +Get AI Agent default configuration +-------------------------- + +To get the default configuration of the AI Agent, call static +[`getAiAgentDefaultConfig(BoxAPIConnection api, BoxAIAgent.Mode mode, String language, String model)`][get-ai-agent-default-config] method. +In the request you have to provide the mode of the AI Agent, the language and the model, with the model is required while the language and mode are optional. + + +```java +BoxAIAgentConfig config = BoxAI.getAiAgentDefaultConfig( + api, + BoxAIAgent.Mode.ASK, + "en", + "openai__gpt_3_5_turbo" +); +``` + +[get-ai-agent-default-config]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAI.html#getAiAgentDefaultConfig-com.box.sdk.BoxAPIConnection-com.box.sdk.ai.BoxAIAgent.Mode-java.lang.String-java.lang.String- + +Extract metadata freeform +-------------------------- + +To send an AI request to supported Large Language Models (LLMs) and extract metadata in form of key-value pairs, call static +[`extractMetadataFreeform(BoxAPIConnection api, String prompt, List items)`][extract-metadata-freeform] method. +In the request you have to provide a prompt, a list of items that your prompt refers to and an optional agent configuration. + + +```java +BoxAIResponse response = BoxAI.extractMetadataFreeform( + api, + "firstName, lastName, location, yearOfBirth, company", + Collections.singletonList(new BoxAIItem("123456", BoxAIItem.Type.FILE)) +); +``` + +[extract-metadata-freeform]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAI.html#extractMetadataFreeform-com.box.sdk.BoxAPIConnection-java.lang.String-java.util.List- + +Extract metadata structured +-------------------------- + +Sends an AI request to supported Large Language Models (LLMs) and returns extracted metadata as a set of key-value pairs. For this request, you need to use an already defined metadata template or define a schema yourself. + +To send an AI request to extract metadata from files with a predefined metadata template, call static +[`extractMetadataStructured extractMetadataStructured(BoxAPIConnection api, List items, BoxAIExtractMetadataTemplate template)`][extract-metadata-structured-metadata-template] method. + + +```java +BoxAIExtractMetadataTemplate template = new BoxAIExtractMetadataTemplate("templateKey", "enterprise"); +BoxAIExtractStructuredResponse result = BoxAI.extractMetadataStructured( + api, + Collections.singletonList(new BoxAIItem("123456", BoxAIItem.Type.FILE)), + template +); +JsonObject sourceJson = result.getSourceJson(); +``` + +To send an AI request to extract metadata from files with custom fields, call static +[`extractMetadataStructured extractMetadataStructured(BoxAPIConnection api, List items, List fields)`][extract-metadata-structured-fields] method. + + +```java +List fields = new ArrayList<>(); +fields.add(new BoxAIExtractField("firstName")); + +BoxAIExtractStructuredResponse result = BoxAI.extractMetadataStructured( + api, + Collections.singletonList(new BoxAIItem("123456", BoxAIItem.Type.FILE)), + fields +); +JsonObject sourceJson = result.getSourceJson(); +``` + +[extract-metadata-structured-metadata-template]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAI.html#extractMetadataStructured-com.box.sdk.BoxAPIConnection-java.util.List-com.box.sdk.ai.metadata.BoxAIExtractMetadataTemplate- +[extract-metadata-structured-fields]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAI.html#extractMetadataStructured-com.box.sdk.BoxAPIConnection-java.util.List-java.util.List- \ No newline at end of file diff --git a/docs/sdk/android.md b/docs/sdk/android.md new file mode 100644 index 000000000..d03804c4e --- /dev/null +++ b/docs/sdk/android.md @@ -0,0 +1,97 @@ +# Android + +The Java SDK should be compatible with modern Android applications written in both Java and Kotlin. + +To use the Java SDK in an android application add it to the project's gradle file in the `dependencies` block. + +For Groovy + +```groovy +// build.gradle + +dependencies { + implementation "com.box:box-java-sdk:3.8.0" +} +``` + +For Kotlin + +```kotlin +// build.gradle.kts + +dependencies { + implementation("com.box:box-java-sdk:3.8.0") +} +``` + +## Kotlin + +The Java SDK can also be used in Kotlin Android applications through interoperability thanks to the Kotlin design. +You can read more about Kotlin and Java interoperability [here](https://kotlinlang.org/docs/java-interop.html) + +The following example creates an API connection with a developer token: + +```kotlin +val api = BoxAPIConnection("myToken") +``` + +The following example shows how to get current user + +```kotlin +val userID = "33333" +val api = BoxAPIConnection("myToken") +val user = BoxUser(api, userID) +val userInfo = user.getInfo() +``` + +If you are using an IntelliJ-based IDE, you can copy our samples located in the [docs](/doc/) directory +and paste them into your file. The IDE should ask you to convert the pasted Java sample to Kotlin. Most samples still work after conversion using this approach. + +Note that the current Java SDK does not support Kotlin coroutines. By default, you cannot run network calls on the main thread +in an Android application. There are various ways to overcome this. For example, if you are in a viewModel context, you can run the SDK method as a +coroutine using viewModelScope. + +```kotlin +viewModelScope.launch { + val result = withContext(Dispatchers.IO) { + /* + SDK code goes here + */ + } + // here you can access the result and load it to the viewModel +} +``` + +The following example shows how to get the current items in the root folder, sorted by name in ascending order with additional +"created_by" and "name" fields returned from the API. The items are then loaded to the custom data class defined earlier. + +```kotlin +// data class definition used in viewModel +data class Item( + val isFolder: Boolean, + val name: String, + val createdBy: String +) + +// viewModel init code +viewModelScope.launch { + val result = withContext(Dispatchers.IO) { + val res = BoxFolder(BoxAPIConnection("myToken"), "0") + val iterator: Iterator = + res.getChildren("name", BoxFolder.SortDirection.ASC, "created_by", "name") + .iterator() + val items = mutableListOf() + + when (val itemInfo = iterator.next()) { + is BoxFile.Info -> items.add(Item(false, "File " + itemInfo.name, itemInfo.createdBy.name)) + is BoxFolder.Info -> items.add(Item(true, "Folder " + itemInfo.name, itemInfo.createdBy.name)) + } + items + } +} +``` + +If you are familiar with Kotlin syntax, you might have noticed that we could have used the `.map` function (or a similar function) to map the API result to a list of items. Due to current limitations, using `.map` and similar operations on collections is not always possible and may +lead to unexpected results. The preferred way is to use an explicit iterator to iterate over the collections returned by the SDK. + +If you find any problem related to the Java SDK in Kotlin-based app feel free to open an issue. \ No newline at end of file diff --git a/docs/sdk/authentication.md b/docs/sdk/authentication.md new file mode 100644 index 000000000..a38c72001 --- /dev/null +++ b/docs/sdk/authentication.md @@ -0,0 +1,271 @@ +# 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](#ways-to-authenticate) + - [Developer Token](#developer-token) + - [Server Authentication with JWT](#server-authentication-with-jwt) + - [Standard 3-Legged Oauth 2.0](#standard-3-legged-oauth-20) + - [Box View Authentication with App Token](#box-view-authentication-with-app-token) + - [Client Credentials Grant](#client-credentials-grant) +- [Manual Token Creation](#manual-token-creation) +- [As User](#as-user) +- [Token Exchange](#token-exchange) +- [Revoke Token](#revoke-token) + + +## Ways to Authenticate + +### Developer Token + +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"); +``` + +### Server Authentication with JWT + + +App Users allows your application to provision and control Box accounts that do not have an associated login +and can only be accessed through the Content API by the controlling application. An App User is a Box account that +belongs to your Box Platform application and not an end-user of Box, like a [managed user](https://developer.box.com/v2.0/reference#user-object) +It is important to emphasize that unlike typical Box accounts, these accounts do not have an associated login and can only be accessed through the Box API. + +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://github.com/box/box-node-sdk/blob/main/docs/authentication.md#app-user-authentication) +for detailed instruction on how to use app auth. + +The Java SDK also has a convenient helper function `BoxConfig.readFrom()` to assist in constructing an API connection. +The `readFrom()` method takes in a stream constructed by the JSON config downloaded from the Developer Console seen +[here](https://developer.box.com/docs/setting-up-a-jwt-app#section-use-an-application-config-file). Once a `BoxConfig` +object has been created you can use that to create an API connection. + + +```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); +``` + +It is also possible to get an API connection for an app user or managed user: + + +```java +Reader reader = new FileReader("src/example/config/config.json"); +BoxConfig boxConfig = BoxConfig.readFrom(reader); + +IAccessTokenCache accessTokenCache = new InMemoryLRUAccessTokenCache(100); +BoxDeveloperEditionAPIConnection api = BoxDeveloperEditionAPIConnection.getUserConnection(userId, boxConfig, accessTokenCache); +``` + +However, if you would like to do a manual set up then that is also possible with the below options. + +App User example: +```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(); +``` + +Server authentication allows your application to authenticate itself with the Box API for a given enterprise. A +[Service Account](https://developer.box.com/v2.0/docs/service-account) always exists for a Box application. It is important to +note that a Service Account is separate from the Box accounts of the applicaton developer and the enterprise admin of any enterprise that has +authorized the app, meaning files stored in that account are not accessible in any other account by default. + +Service Account example: + + +```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); + +BoxConfig boxConfig = new BoxConfig("YOUR-CLIENT-ID", "YOUR-CLIENT-SECRET", "ENTERPRISE-ID", jwtPreferences); +IAccessTokenCache tokenCache = new InMemoryLRUAccessTokenCache(10); + +BoxDeveloperEditionAPIConnection api = BoxDeveloperEditionAPIConnection.getAppEnterpriseConnection(boxConfig, tokenCache); +``` + +### Standard 3-Legged Oauth 2.0 + +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"); +``` + +### Box View Authentication with App Token + +Allows applications that do not own content stored in Box (e.g. app-owned content) to be able to use Box as a service +provider rather than a content store. This is currently mostly used for previewing items. For scopes you can choose +between "item_preview", "item_upload", or "item_delete". See the +[Getting Started with the New Box View](https://developer.box.com/docs/getting-started-with-new-box-view) for detailed +instruction. + + +```java +BoxTransactionalAPIConnection api = new BoxTransactionalAPIConnection("YOUR-ACCESS-TOKEN"); +``` + +You can also request a specific scope of the transaction token by passing in: "item_preview", "item_upload", or "item_delete". + +```java +BoxAPIConnection api = BoxTransactionalAPIConnection.getTransactionConnection("YOUR-ACCESS-TOKEN", "item_preview"); +``` + +Lastly, you can choose to specify a resource to generate a token for with. If you're passing a token down to your client +this is a great way to restrict access on that token in turn locking down what the token has access to. + +```java +BoxAPIConnection api = BoxTransactionalAPIConnection.getTransactionConnection("YOUR-ACCESS-TOKEN", "item_preview", +"https://api.box.com/2.0/files/YOUR-FILE-ID"); +``` + +### Client Credentials Grant +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. + +The `BoxCCGAPIConnection` works the same way as the `BoxAPIConnection` so for example to get root folder you can do: + +```java +BoxCCGAPIConnection api = BoxCCGAPIConnection.userConnection( + "client_id", + "client_secret", + "user_id" +); +BoxFolder root = BoxFolder.getRootFolder(api); +``` + +Obtained token is valid for specified ammount of time and 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 +BoxCCGAPIConnection api = BoxCCGAPIConnection.applicationServiceAccountConnection( + "client_id", + "client_secret", + "enterprise_id" +); +``` + +#### Obtaining User token + +To obtain user account you will have to provide user ID with client id and secret + +```java +BoxCCGAPIConnection api = BoxCCGAPIConnection.userConnection( + "client_id", + "client_secret", + "user_id" +); +``` +In order to enable generating user token you have to go to your application configuration that can be found [here](https://app.box.com/developers/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. + +## Manual Token Creation + +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"); +``` + +## As User + +The purpose of as user is to be used by enterprise administrators to make API calls on behalf of their managed users. +This can also be used by a Service Account to make API calls for managed users or app users. This is only meant to be used +for `BoxAPIConnection`s and not `BoxDeveloperEditionAPIConnection`s. + +In order to invoke as user calls you can use + + +```java +BoxAPIConnection api = new BoxAPIConnection("YOUR-ACCESS-TOKEN"); +api.asUser("USER-ID"); +``` + +Once you are done making calls on behalf of a managed user or app user you can switch back to the admin or service account with + + +```java +api.asSelf(); +``` + +## Token Exchange + +You can exchange a API connection's access token for one with a lower scope, in order to restrict the permissions +or to pass to a less secure location (e.g. a browser-based app). This is useful if you want to use the +[Box UI Kits](https://developer.box.com/docs/box-ui-elements), since they generally do not need full read/write +permissions to run. + + +```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); +``` + +The above example will downscope an access token to only allow for previewing an item and uploading an item. + +Revoke Token +------------ + +At any point if you wish to revoke your tokens you can do so by calling the following. + + +```java +BoxAPIConnection api = new BoxAPIConnection("YOUR-ACCESS-TOKEN"); +api.revokeToken(); +``` diff --git a/docs/sdk/classifications.md b/docs/sdk/classifications.md new file mode 100644 index 000000000..f468bd807 --- /dev/null +++ b/docs/sdk/classifications.md @@ -0,0 +1,226 @@ +Classifications +=============== + +Classfications are a type of metadata that allows users and applications +to define and assign a content classification to files and folders. + +Classifications use the metadata APIs to add and remove classifications, and +assign them to files. For more details on metadata templates please see the +[metadata documentation](./metadata.md). + + + + +- [Classifications](#classifications) + - [Add initial classifications](#add-initial-classifications) + - [List all classifications](#list-all-classifications) + - [Add another classification](#add-another-classification) + - [Update a classification](#update-a-classification) + - [Delete a classification](#delete-a-classification) + - [Delete all classifications](#delete-all-classifications) + - [Add classification to file](#add-classification-to-file) + - [Update classification on file](#update-classification-on-file) + - [Get classification on file](#get-classification-on-file) + - [Remove classification from file](#remove-classification-from-file) + - [Add classification to folder](#add-classification-to-folder) + - [Update classification on folder](#update-classification-on-folder) + - [Get classification on folder](#get-classification-on-folder) + - [Remove classification from folder](#remove-classification-from-folder) + + + +Add initial classifications +--------------------------- + +If an enterprise does not already have a classification defined, the first classification(s) +can be added with the [`createMetadataTemplate`][create-metadata-template] method. + + +```java +MetadataTemplate.Field classification = new MetadataTemplate.Field(); +classification.setType("enum"); +classification.setKey(Metadata.CLASSIFICATION_KEY); +classification.setDisplayName("Classification"); +classification.setHidden("false"); + +List options = new ArrayList(); +options.add("Top Secret"); +classification.setOptions(topSecret) + +List fields = new ArrayList(); +fields.add(classification); + +MetadataTemplate template = MetadataTemplate.createMetadataTemplate(api, Metadata.ENTERPRISE_METADATA_SCOPE, Metadata.CLASSIFICATION_TEMPLATE_KEY, "Classification", false, fields); +``` + +[create-metadata-template]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#createMetadataTemplate-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String-java.lang.String-boolean-java.util.List- + + +List all classifications +------------------------ + +To retrieve a list of all the classifications in an enterprise call the +[`getMetadataTemplate`][get-metadata-template] +method to get the classifciations template, which will contain a list of all the +classifications + + +```java +MetadataTemplate template = MetadataTemplate.getMetadataTemplate(api, Metadata.CLASSIFICATION_TEMPLATE_KEY); +``` + +[get-metadata-template]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#getMetadataTemplate-com.box.sdk.BoxAPIConnection- + +Add another classification +-------------------------- + +To add another classification, call the [`updateMetadataTemplate`][update-metadata-template] +method with the an operation to add a new classification to the template. + + +```java +List updates = new ArrayList(); + +String update = "{\n op: \"addEnumOption\",\n fieldKey: \"Box__Security__Classification__Key\",\n data: {\n key: \"Sensitive\"\n }\n}"; + +updates.add(new MetadataTemplate.FieldOperation(addCategoryFieldJSON)); + +MetadataTemplate.updateMetadataTemplate(api, Metadata.ENTERPRISE_METADATA_SCOPE, Metadata.CLASSIFICATION_TEMPLATE_KEY, updates); +``` + +[update-metadata-template]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#updateMetadataTemplate-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String-java.util.List- + + +Update a classification +----------------------- + +To update an existing classification, call the +[`updateMetadataTemplate`][update-metadata-template] +method with the an operation to update the existing classification already present on the template. + + +```java +List updates = new ArrayList(); + +String update = "{\n op: \"editEnumOption\",\n fieldKey: \"Box__Security__Classification__Key\",\n enumOptionKey: \"Sensitive\",\n data: {\n key: \"Very Sensitive\"\n }\n}"; + +updates.add(new MetadataTemplate.FieldOperation(addCategoryFieldJSON)); + +MetadataTemplate.updateMetadataTemplate(api, Metadata.ENTERPRISE_METADATA_SCOPE, Metadata.CLASSIFICATION_TEMPLATE_KEY, updates); +``` + +Add classification to file +-------------------------- + +To add a classification to a file, call [`setMetadata(String templateKey, String templateScope, Metadata properties)`][set-metadata] +with the name of the classification template, as well as the details of the classification +to add to the file. + + +```java +BoxFile file = new BoxFile(api, "id"); +Metadata metadata = new Metadata() +metadata.add(Metadata.CLASSIFICATION_KEY, "Sensitive") +file.setMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, Metadata.ENTERPRISE_METADATA_SCOPE, metadata); +``` + +[set-metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#setMetadata-java.lang.String-java.lang.String-com.box.sdk.Metadata- + +Update classification on file +----------------------------- + +To update a classification on a file, call +[`setMetadata(String templateKey, String templateScope, Metadata properties)`][set-metadata] +with the name of the classification template, as well as the details of the classification +to add to the file. + + +```java +BoxFile file = new BoxFile(api, "id"); +Metadata metadata = new Metadata() +metadata.add(Metadata.CLASSIFICATION_KEY, "Sensitive") +file.setMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, Metadata.ENTERPRISE_METADATA_SCOPE, metadata); +``` + +Get classification on file +-------------------------- + +Retrieve the classification on a file by calling +[`getMetadata(String templateKey)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getMetadata-java.lang.String-) +with the ID of the file. + + +```java +BoxFile file = new BoxFile(api, "id"); +Metadata metadata = file.getMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY); +``` + +Remove classification from file +------------------------------- + +A classification can be removed from a file by calling +[`deleteMetadata`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#deleteMetadata--). + + +```java +BoxFile file = new BoxFile(api, "id"); +file.deleteMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY); +``` + +Add classification to folder +---------------------------- + +To add a classification to a folder, call [`setMetadata(String templateKey, String templateScope, Metadata properties)`][set-metadata] +with the name of the classification template, as well as the details of the classification +to add to the folder. + + +```java +BoxFolder folder = new BoxFolder(api, "id"); +Metadata metadata = new Metadata() +metadata.add(Metadata.CLASSIFICATION_KEY, "Sensitive") +folder.setMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, Metadata.ENTERPRISE_METADATA_SCOPE, metadata); +``` + +[set-metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#setMetadata-java.lang.String-java.lang.String-com.box.sdk.Metadata- + +Update classification on folder +------------------------------- + +To update a classification on a folder, call +[`setMetadata(String templateKey, String templateScope, Metadata properties)`][set-metadata] +with the name of the classification template, as well as the details of the classification +to add to the folder. + + +```java +BoxFolder folder = new BoxFolder(api, "id"); +Metadata metadata = new Metadata() +metadata.add(Metadata.CLASSIFICATION_KEY, "Sensitive") +folder.setMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, Metadata.ENTERPRISE_METADATA_SCOPE, metadata); +``` + +Get classification on folder +---------------------------- + +Retrieve the classification on a folder by calling +[`getMetadata(String templateKey)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getMetadata-java.lang.String-) +with the ID of the folder. + + +```java +BoxFolder folder = new BoxFolder(api, "id"); +Metadata metadata = folder.getMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY); +``` + +Remove classification from folder +--------------------------------- + +A classification can be removed from a folder by calling +[`deleteMetadata`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#deleteMetadata--). + + +```java +BoxFolder folder = new BoxFolder(api, "id"); +folder.deleteMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY); +``` \ No newline at end of file diff --git a/docs/sdk/collaboration_allowlists.md b/docs/sdk/collaboration_allowlists.md new file mode 100644 index 000000000..0b464a528 --- /dev/null +++ b/docs/sdk/collaboration_allowlists.md @@ -0,0 +1,147 @@ +Collaboration Allowlists +======================== + +Collaboration Allowlists are used to manage a set of approved domains or Box users that an enterprise +can collaborate with. + + + + + +- [Add a Collaboration Allowlist For a Domain](#add-a-collaboration-allowlist-for-a-domain) +- [Get a Collaboration Allowlist's Information for a Domain](#get-a-collaboration-allowlists-information-for-a-domain) +- [Get all Collaboration Allowlist's Information for Domain](#get-all-collaboration-allowlists-information-for-domain) +- [Remove a Collaboration Allowlist for a Domain](#remove-a-collaboration-allowlist-for-a-domain) +- [Add a Collaboration Allowlist for a User](#add-a-collaboration-allowlist-for-a-user) +- [Get a Collaboration Allowlist's Information for a User](#get-a-collaboration-allowlists-information-for-a-user) +- [Get all Collaboration Allowlist's Information for a User](#get-all-collaboration-allowlists-information-for-a-user) +- [Remove a Collaboration Allowlist for a User](#remove-a-collaboration-allowlist-for-a-user) + + + +Add a Collaboration Allowlist For a Domain +------------------------------------------ + +A collaboration allowlist can be created for a domain with +[`create(BoxAPIConnection api, String domain, AllowlistDirection direction)`][allowlist1]. +The `AllowlistDirection` parameter determines which way the allowlisting +applies. You can set the value to inbound, outbound, or both. + + +```java +BoxCollaborationAllowlist.create(api, "test.com", BoxCollaborationAllowlist.AllowlistDirection.BOTH); +``` + +[allowlist1]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaborationAllowlist.html#create-com.box.sdk.BoxAPIConnection-java.lang.String-com.box.sdk.BoxCollaborationAllowlist.AllowlistDirection- + +Get a Collaboration Allowlist's Information for a Domain +-------------------------------------------------------- + +A specific collaboration allowlist for a domain can be retrieved with +[`getInfo()`][getAllowlistInfo] + + +```java +BoxCollaborationAllowlist domainAllowlist = new BoxCollaborationAllowlist(api, "id"); +domainAllowlist.getInfo(); +``` + +[getAllowlistInfo]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaborationAllowlist.html#getInfo-- + +Get all Collaboration Allowlist's Information for Domain +-------------------------------------------------------- + +All domain collaboration allowlists associated with an enterprise can be +retrieved with [`getAll(BoxAPIConnection api)`][getAllAllowlists1] + + +```java +BoxCollaborationAllowlist.getAll(api); +``` + +To specify the number of allowlists to retrieve you can pass a limit on how +many allowlists to return to [`getAll(BoxAPIConnection api, int limit)`][getAllAllowlists2]. + +```java +BoxCollaborationAllowlist.getAll(api, 10); +``` + +[getAllAllowlists1]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaborationAllowlist.html#getAll-com.box.sdk.BoxAPIConnection-java.lang.String...- +[getAllAllowlists2]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaborationAllowlist.html#getAll-com.box.sdk.BoxAPIConnection-int-java.lang.String...- + +Remove a Collaboration Allowlist for a Domain +--------------------------------------------- + +To remove a collaboration allowlist you can call [`delete()`][deleteAllowlist] + + +```java +BoxCollaborationAllowlist domainToBeDeleted = new BoxCollaborationAllowlist(api, "allowlist-id"); +domainToBeDeleted.delete(); +``` + +[deleteAllowlist]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaborationAllowlist.html#delete-- + +Add a Collaboration Allowlist for a User +---------------------------------------- + +A collaboration allowlist can be created for a user with +[`create(BoxAPIConnection api, String userID)`][createExempt] + + +```java +String userID = "12345"; +BoxCollaborationAllowlistExemptTarget.create(api, userID); +``` + +[createExempt]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaborationAllowlistExemptTarget.html#create-com.box.sdk.BoxAPIConnection-java.lang.String- + +Get a Collaboration Allowlist's Information for a User +------------------------------------------------------ + +To retrieve information regarding a specific user collaboration allowlist use +[`getInfo()`][getInfoExempt] + + +```java +BoxCollaborationAllowlistExemptTarget userAllowlist = new BoxCollaborationAllowlistExemptTarget(api, "allowlistID"); +userAllowlist.getInfo(); +``` + +[getInfoExempt]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaborationAllowlistExemptTarget.html#getInfo-- + +Get all Collaboration Allowlist's Information for a User +-------------------------------------------------------- + +To retrieve information regarding all user allowlists associated with an enterprise use +[`getAll(BoxAPIConnection api)`][getAllExempt1] + + +```java +BoxCollaborationAllowlistExemptTarget.getAll(api); +``` + +Alternatively you can specify the number of user allowlists to return with one +request by passing a the maximum number of records to return to +[`getAll(BoxApiConnection api, int limit)`][getAllExempt2] + +```java +BoxCollaborationAllowlistExemptTarget.getAll(api, 5); +``` + +[getAllExempt1]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaborationAllowlistExemptTarget.html#getAll-com.box.sdk.BoxAPIConnection-java.lang.String...- +[getAllExempt2]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaborationAllowlistExemptTarget.html#getAll-com.box.sdk.BoxAPIConnection-int-java.lang.String...- + +Remove a Collaboration Allowlist for a User +------------------------------------------- + +To remove a user collaboration allowlist entry from an enterprise use +[`delete()`][deleteExempt] + + +```java +BoxCollaborationAllowlistExemptTarget userAllowlist = new BoxCollaborationAllowlistExemptTarget(api, "allowlist_id"); +userAllowlist.delete(); +``` + +[deleteExempt]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaborationAllowlistExemptTarget.html#delete-- diff --git a/docs/sdk/collaborations.md b/docs/sdk/collaborations.md new file mode 100644 index 000000000..296e0bf65 --- /dev/null +++ b/docs/sdk/collaborations.md @@ -0,0 +1,168 @@ +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 the Collaborations on a File](#get-the-collaborations-on-a-file) +- [Get Pending Collaborations](#get-pending-collaborations) +- [Accept or Decline a Pending Collaboration](#accept-or-decline-a-pending-collaboration) + + + +Add a Collaboration +------------------- + +A collaboration can be added for an existing user or group with +[`collaborate(BoxCollaborator collaborator, BoxCollaboration.Role 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 BoxFolder(api, "folder-id"); +folder.collaborate(user, BoxCollaboration.Role.EDITOR); +``` + +You can also add a collaboration by providing an email address with +[`collaborate(String emailAddress, BoxCollaboration.Role role)`][collaborate2]. +If the recipient 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); +``` + +If you need to create a collaboration with a group, provide a group id. + + +```java +BoxCollaborator group = new BoxGroup(api, "group-id"); +BoxFolder folder = new BoxFolder(api, "folder-id"); +folder.collaborate(group, BoxCollaboration.Role.EDITOR); +``` + +[collaborate1]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#collaborate-com.box.sdk.BoxCollaborator-com.box.sdk.BoxCollaboration.Role- +[collaborate2]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#collaborate-java.lang.String-com.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 passing it to [`updateInfo(BoxCollaboration.Info fieldsToUpdate)`][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-fields] on a collaboration returns a snapshot of the +collaboration's info. + + +```java +BoxCollaboration collaboration = new BoxCollaboration(api, "id"); +BoxCollaboration.Info info = collaboration.getInfo(); +``` + +You can also choose to retrieve only specific fields of the collaboration by calling +[`getInfo(String... fields)`][get-info-fields] with a list of field names. + +```java +BoxCollaboration collaboration = new BoxCollaboration(api, "id"); +BoxCollaboration.Info info = collaboration.getInfo(BoxCollaboration.ALL_FIELDS); +``` + +[get-info-fields]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaboration.html#getInfo-java.lang.String...- + +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 BoxFolder(api, "id"); +Collection collaborations = folder.getCollaborations(); +``` + +[get-collaborations]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getCollaborations-- + +Get the Collaborations on a File +-------------------------------- + +You can get an iterator over all of the collaborations on a file by calling +[`BoxFile#getAllFileCollaborations(String... fields)`][get-collaborations-file] +on the file. + + +```java +BoxFile file = new BoxFile(api, "id"); +Iterable collaborations = file.getAllFileCollaborations(); +``` + +[get-collaborations-file]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getAllFileCollaborations-java.lang.String...- + +Get Pending Collaborations +-------------------------- + +A collection of all the user's pending collaborations can be retrieved with +[`getPendingCollaborations(BoxAPIConnection api)`][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- + +Accept or Decline a Pending Collaboration +----------------------------------------- + +To accept or decline a pending collaboration, update the info of the pending collaboration object +with the desired status. + + +```java +// Accept all pending collaborations +Collection pendingCollaborations = BoxCollaboration.getPendingCollaborations(api); +for (BoxCollaboration.Info collabInfo : pendingCollaborations) { + collabInfo.setStatus(BoxCollaboration.Status.ACCEPTED); + collabInfo.getResource().updateInfo(collabInfo); +} +``` diff --git a/docs/sdk/collections.md b/docs/sdk/collections.md new file mode 100644 index 000000000..3e5304bf4 --- /dev/null +++ b/docs/sdk/collections.md @@ -0,0 +1,104 @@ +Collections +=========== + +Collections contain information about the items contained inside of them, +including files and folders. The only collection available currently is a +“Favorites” collection. The contents of the collection are discovered in a +similar way in which the contents of a folder are discovered. + + + + + +- [Get Collections](#get-collections) +- [Get a Collection's Items](#get-a-collections-items) +- [Add Items to a Collection](#add-items-to-a-collection) +- [Remove Items from a Collection](#remove-items-from-a-collection) + + + +Get Collections +--------------- + +Existing collections can be retrieved by calling the +[`getAllCollections(BoxAPIConnection)`][get-collections] method. Currently only +"Favorites" collection is supported. + + +```java +Iterable collections = BoxCollection.getAllCollections(api); +for (BoxCollection.Info collectionInfo : collections) { + // Do something with the collection. +} +``` + +[get-collections]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollection.html#getAllCollections-com.box.sdk.BoxAPIConnection- + +Get a Collection's Items +------------------------ + +Every `BoxCollection` implements [`Iterable`][iterator] which allows +you to iterate over the collection'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.Info) { + BoxFolder.Info folderInfo = (BoxFolder.Info) itemInfo; + // Do something with the folder. + } +} +``` + +[iterator]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxCollection.html#iterator-- + +Add Items to a Collection +------------------------- + +Add an item to a collection by calling +[`setCollections(BoxCollection... collections)`][set-collections] on any `BoxItem`. Note that this +method will overwrite all collections that the item belongs to. + + +```java +BoxCollection favorites = null; +for (BoxCollection.Info info : BoxCollection.getAllCollections(api)) { + if (info.getCollectionType().equals("favorites")) { + favorites = info.getResource(); + break; + } +} +BoxFile file = new BoxFile(api, "id"); +file.setCollections(favorites); +``` + +Remove Items from a Collection +------------------------------ + +Remove an item from a collection by calling +[`setCollections(BoxCollection... collections)`][set-collections] on any `BoxItem` and exclude the +collection to wish to remove it from. + + +```java +BoxFile file = new BoxFile(api, "id"); +BoxFile.Info info = file.getInfo("collections"); + +ArrayList collections = new ArrayList(); +for (BoxCollection.Info info : info.getCollections(api)) { + // Include every existing collection except for favorites to remove the file + // from the favorites collection. + if (!info.getCollectionType().equals("favorites")) { + collections.add(info.getResource()); + } +} +file.setCollections(collections.toArray()); +``` + +[set-collections]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxItem.html#setCollections-com.box.sdk.BoxCollection...- diff --git a/docs/sdk/comments.md b/docs/sdk/comments.md new file mode 100644 index 000000000..6681330fd --- /dev/null +++ b/docs/sdk/comments.md @@ -0,0 +1,125 @@ +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 message)`][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 message)`][reply] method. + + +```java +BoxComment comment = new BoxComment(api, "id"); +comment.reply("I agree with this!"); +``` + + +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 +BoxComment comment = new BoxComment(api, "id"); +comment.reply("@[1234:user@box.com] I agree with this!"); +``` + +[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 message)`][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/docs/sdk/configuration.md b/docs/sdk/configuration.md new file mode 100644 index 000000000..030b9d171 --- /dev/null +++ b/docs/sdk/configuration.md @@ -0,0 +1,329 @@ +# Configuration + +- [Proxy configuration](#proxy-configuration) + - [Custom proxy authenticator](#custom-proxy-authenticator) + - [Example: NTLM authenticator](#example-ntlm-authenticator) +- [Configure retries of calls and timeouts](#configure-retries-of-calls-and-timeouts) + - [Maximum retries](#maximum-retries) + - [Connection timeout](#connection-timeout) + - [Read timeout](#read-timeout) +- [URLs configuration](#urls-configuration) + - [Base URL](#base-url) + - [Base Upload URL](#base-upload-url) + - [Base App URL](#base-app-url) + - [Token URL](#token-url-deprecated) + - [Revoke URL](#revoke-url-deprecated) +- [SSL configuration](#ssl-configuration) +- [Instrumenation of OpenTelemetry](#instrumenation-of-opentelemetry) + +# Proxy configuration + +To set up proxy +use [BoxApiConnection.setProxy](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html#setProxy-java.net.Proxy-) +to set proxy address +and [BoxApiConnection.setProxyBasicAuthentication][set-basic-proxy-auth] +to set username and password required by proxy: + +```java +BoxAPIConnection api=new BoxAPIConnection("access_token"); +Proxy proxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress("proxy_url",8888)); +// You can use any subclass of BoxAPIConnection +api.setProxy(proxy); +api.setProxyBasicAuthentication("proxyUsername", "proxyPassword"); +``` +Proxy username and password will be used only if provided `SocketAddress` is an instance of +`InetSocketAddress`. If you would like to use a custom `SocketAddress` you can provide your own +`okhttp3.Authenticator` using [BoxApiConnection.setProxyAuthenticator(Authenticator)][set-proxy-authenticator] + + +## Custom proxy authenticator +By using [BoxApiConnection.setProxyBasicAuthentication][set-basic-proxy-auth] you can enable default +proxy authenticator that handles only Basic authentication. But you can provide your own authenticator by using +[BoxApiConnection.setProxyAuthenticator(Authenticator)][set-proxy-authenticator]. + +To do that you will need to add a dependency to your project: +``` +"com.squareup.okhttp3:okhttp:XXX" +``` +Please match the version with what SDK is using by checking `build.gradle` +and looking for entry `implementation "com.squareup.okhttp3:okhttp:"`. + +Now you can add an authenticator. by calling + +```java +BoxAPIConnection api = new BoxAPIConnection("access_token"); +Proxy proxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress("proxy_url",8888)); +api.setProxy(proxy); +api.setProxyAuthenticator((route, response) -> response + .request() + .newBuilder() + .addHeader("Proxy-Authorization", "My custom authenticator") + .build() +); +``` + +### Example: NTLM authenticator + +For example, you can add NTLM authorization. This is example NTLM authenticator that +is using parts from Apache Http Client 5. + +```java +import okhttp3.Authenticator; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.Route; +import org.apache.hc.client5.http.impl.auth.NTLMEngineException; + +public class NTLMAuthenticator implements Authenticator { + final NTLMEngineImpl engine = new NTLMEngineImpl(); + private final String domain; + private final String username; + private final String password; + private final String ntlmMsg1; + + public NTLMAuthenticator(String username, String password, String domain) { + this.domain = domain; + this.username = username; + this.password = password; + String localNtlmMsg1 = null; + try { + localNtlmMsg1 = engine.generateType1Msg(null, null); + } catch (Exception e) { + e.printStackTrace(); + } + ntlmMsg1 = localNtlmMsg1; + } + + @Override + public Request authenticate(Route route, Response response) { + if(response.code() == 407 && "Proxy authorization required".equals(response.message())) { + String ntlmChallenge = response.headers("Proxy-Authenticate") + .stream() + .filter(h -> h.startsWith("NTLM ")) + .findFirst().orElse(""); + if(ntlmChallenge.length() > 5) { + try { + String ntlmMsg3 = engine.generateType3Msg(username, password.toCharArray(), domain, "ok-http-example-ntlm", ntlmChallenge.substring(5)); + return response.request().newBuilder().header("proxy-Authorization", "NTLM " + ntlmMsg3).build(); + } catch (NTLMEngineException e) { + throw new RuntimeException(e); + } + } + return response.request().newBuilder().header("proxy-Authorization", "NTLM " + ntlmMsg1).build(); + } + return response.request(); + } +} +``` + +The `NTLMEngineImpl` could be created by using Apache implementation that can be found +[here](https://github.com/apache/httpcomponents-client/blob/master/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/NTLMEngineImpl.java). +You can add a dependency to `org.apache.httpcomponents.client5:httpclient5:5.1.3`. +Copy the `NTLMEngineImpl` class and add it to your source. + +Now you can use custom NTML Authenticator in your `BoxAPIConnection`: +```java +BoxAPIConnection api = new BoxAPIConnection("access_token"); +Proxy proxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress("proxy_url",8888)); +api.setProxy(proxy); +api.setProxyAuthenticator(new NTLMAuthenticator("some proxy username", "some proxy password", "proxy workgroup")); +``` + +[set-basic-proxy-auth]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html#setProxyBasicAuthentication-java.lang.String-java.lang.String- +[set-proxy-authenticator]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html#setProxyAuthenticator-okhttp3.Authenticator- + +# Configure retries of calls and timeouts +SDK can retry failed calls when: + - failed writting request body + - when recieved HTTP response code: + - 429 - rate limit exceeded + - 5XX - internal server error + - 400 error with error that `exp` claim has expired. This usially means there is a clock skew. + +SDK is using exponnetial strategy to calculate time between retries. + If response contains `Retry-After` header its value will be used as a wait time between calls. +You can check details in `com.box.sdk.BoxAPIRequest.send(com.box.sdk.ProgressListener)` method. + +## Maximum retries + +To configure how many times API will retry calls +use [BoxApiConnection.setMaxRetryAttempts](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html#setMaxRetryAttempts-int-): + +```java +// You can use any subclass of BoxAPIConnection +api.setMaxRetryAttempts(10); +``` + +default value for retry attempts is `5`. + +## Connection timeout + +To set up how log (in milliseconds) API waits to establish connection +use [BoxApiConnection.setConnectTimeout](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html#setConnectTimeout-int-): + +```java +// You can use any subclass of BoxAPIConnection +int connectionTimeout = 100; // timeout in milliseconds +api.setConnectTimeout(connectionTimeout); +``` + +default value is `0` which mean API waits forever to establish connection. + +## Read timeout + +To set up how log (in milliseconds) API waits to read data from connection +use [BoxApiConnection.setReadTimeout](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html#setReadTimeout-int-): + +```java +// You can use any subclass of BoxAPIConnection +int readTimeout = 100; // timeout in milliseconds +api.setReadTimeout(readTimeout); +``` + +default value is `0` which mean API waits forever to read data from connection. + +# URLs configuration + +### Base URL +The default base URL used for making API calls to Box can be changed by calling `BoxAPIConnection#setBaseURL(String)` +method on `BoxApiConnection`. Default value is `https://api.box.com/`. + +```java +BoxAPIConnection api = new BoxAPIConnection("YOUR-DEVELOPER-TOKEN"); + +api.setBaseURL("https://example.com"); +String baseUrl = api.getBaseURL(); // will produce "https://example.com/2.0/" +``` + +Setting Base URL changes the Token and Revoke URL as well: +```java +BoxAPIConnection api = new BoxAPIConnection("YOUR-DEVELOPER-TOKEN"); + +api.setBaseURL("https://example.com"); + +String baseUrl = api.getBaseURL(); // will produce "https://example.com/2.0/" +String tokenUrl = api.getRevokeURL(); // will produce "https://example.com/oauth2/revoke" +String revokeUrl = api.getTokenURL(); // will produce "https://example.com/oauth2/token" +``` + +### Base Upload URL +The default URL used for uploads can be changed by calling `BoxAPIConnection#setBaseUploadURL(String)` method on `BoxApiConnection`. +Default value is `https://upload.box.com/api/`. + +```java +BoxAPIConnection api = new BoxAPIConnection("YOUR-DEVELOPER-TOKEN"); + +api.setBaseUploadURL("https://upload.example.com"); +api.getBaseUploadURL(); // will produce "https://upload.example.com/2.0/" +``` + +### Base App URL +The default base app URL can be changed by calling `BoxAPIConnection#setBaseAppUrl()` method on `BoxApiConnection`. +Default value is https://app.box.com. + +```java +BoxAPIConnection api = new BoxAPIConnection("YOUR-DEVELOPER-TOKEN"); + +api.setBaseAppUrl("https://example.app.com"); +api.getBaseAppUrl(); // will produce "https://app.example.com" +``` + +### Token URL (deprecated) +The default URL used for getting token can be changed by calling `setTokenURL()` method on `BoxApiConnection`. +Default value is https://api.box.com/oauth2/token. This method is deprecated. Use `BoxAPIConnection#setBaseURL(String)` +instead. + +```java +BoxAPIConnection api = new BoxAPIConnection("YOUR-DEVELOPER-TOKEN"); + +api.setTokenURL("https://example.com/token"); +``` + +If you use `setTokenUrl` this URL will be used over the one coming from `setBaseUrl` when doing authentication. + +### Revoke URL (deprecated) +The default URL used for invalidating token can be changed by calling `setRevokeURL()` method on `BoxApiConnection`. +Default value is https://api.box.com/oauth2/revoke. This method is deprecated. Use `BoxAPIConnection#setBaseURL(String)` +instead. + +```java +BoxAPIConnection api = new BoxAPIConnection("YOUR-DEVELOPER-TOKEN"); + +api.setRevokeURL("https://example.com/revoke"); +``` + +If you use `setRevokeUrl` this URL will be used over the one coming from`setBaseUrl` when doing authentication. + +# SSL configuration +You can override default settings used to verify SSL certificates. +This can be used to allow using self-signed certificates. For example: +```java +BoxAPIConnection api = new BoxAPIConnection(...); + +// to allow self-signed certificates +X509TrustManager trustManager = new X509TrustManager() { + @Override + public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) { + } + + @Override + public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) { + } + + @Override + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return new java.security.cert.X509Certificate[]{}; + } +}; + +// to allow self-signed certificates created for localhost +HostnameVerifier hostnameVerifier = (hostname, session) -> true; + +api.configureSslCertificatesValidation(trustManager, hostnameVerifier); +``` + +If you just need to provide trust manager use `BoxAPIConnection.DEFAULT_HOSTNAME_VERIFIER` as a hostname verifier. +The same goes for hostname verifier. If you need just to provide it use +`BoxAPIConnection.DEFAULT_TRUST_MANAGER` as a trust manager. +Example: +```java +BoxAPIConnection api = new BoxAPIConnection(...); +X509TrustManager trustManager = ... +api.configureSslCertificatesValidation(trustManager, BoxAPIConnection.DEFAULT_HOSTNAME_VERIFIER); +``` + +# Instrumenation of OpenTelemetry + +OpenTelemetry is an observability framework and toolkit for creating and managing telemetry data, such as traces, +metrics, and logs. The Box Java SDK can be instrumented with OpenTelemetry to collect telemetry data about the +requests made by the SDK. + +To start, add the [opentelemetry-okhttp-3.0](https://mvnrepository.com/artifact/io.opentelemetry.instrumentation/opentelemetry-okhttp-3.0) dependency to your project. +Next, create a custom class that extends BoxAPIConnection and integrates telemetry in the overridden `createNewCall` method. +Here's an example implementation: +```java +public class BoxAPIConnectionWithTelemetry extends BoxAPIConnection { + + private OkHttpTelemetry telemetry; + + public BoxAPIConnectionWithTelemetry(String accessToken) { + super(accessToken); + } + + /** + * Add required constructors + */ + + public void setTelemetry(OpenTelemetry openTelemetry) { + this.telemetry = OkHttpTelemetry.builder(openTelemetry).build(); + } + + protected Call createNewCall(OkHttpClient httpClient, Request request) { + return this.telemetry.newCallFactory(httpClient).newCall(request); + } +} + +``` + +Please note that you should not modify either `httpClient` or `request` parameters in the createNewCall method. +Altering these parameters can discard the BoxAPIConnection configuration and lead to unexpected behavior. \ No newline at end of file diff --git a/docs/sdk/css/javadoc.css b/docs/sdk/css/javadoc.css new file mode 100644 index 000000000..ad7887e4d --- /dev/null +++ b/docs/sdk/css/javadoc.css @@ -0,0 +1,488 @@ +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/docs/sdk/devices.md b/docs/sdk/devices.md new file mode 100644 index 000000000..9ed133093 --- /dev/null +++ b/docs/sdk/devices.md @@ -0,0 +1,62 @@ +Devices +====== + +Device pinning is a feature that allows enterprise admins to pin their user’s +corporate-managed Box account to a particular mobile device or Box Sync client. + + + + + +- [Get Enterprise Device Pins](#get-enterprise-device-pins) +- [Get Device Pin](#get-device-pin) +- [Delete Device Pin](#delete-device-pin) + + + +Get Enterprise Device Pins +-------------------------- + +Calling the static [`getEnterpriceDevicePins(BoxAPIConnection api, String enterpriseID, String... fields)`][get-enterprise-device-pins] +will return an iterable that will page through all of the device pins belongs to +enterprise with given ID. It is possible to specify maximum number of retrieved +items per single response by passing the maxiumum number of records to retrieve to +[`getEnterpriceDevicePins(BoxAPIConnection api, String enterpriseID, int limit, String... fields)`][get-enterprise-device-pins-with-limit] + + +```java +Iterable enterpriseDevicePins = BoxDevicePin.getEnterpriceDevicePins(api, id); +for (BoxDevicePin.Info devicePin : enterpriseDevicePins) { + // Do something with the device pin. +} +``` + +[get-enterprise-device-pins]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxDevicePin.html#getEnterpriceDevicePins-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String...- +[get-enterprise-device-pins-with-limit]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxDevicePin.html#getEnterpriceDevicePins-com.box.sdk.BoxAPIConnection-java.lang.String-int-java.lang.String...- + +Get Device Pin +-------------- + +Existing collections can be retrieved by calling the [`getInfo(String... fields)`][get-device-pin] method. +Optional parameters can be used to retrieve specific fields of the Device Pin object. + + +```java +BoxDevicePin devicePin = new BoxDevicePin(api, id); +BoxDevicePin.Info devicePinInfo = devicePin.getInfo(); +``` + +[get-device-pin]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxDevicePin.html#getInfo-java.lang.String...- + +Delete Device Pin +-------------- + +A device pin can be deleted by calling the [`delete()`][delete] method. + + +```java +BoxDevicePin devicePin = new BoxDevicePin(api, id); +devicePin.delete(); +``` + +[delete]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxDevicePin.html#delete-- diff --git a/docs/sdk/events.md b/docs/sdk/events.md new file mode 100644 index 000000000..0bf1f8826 --- /dev/null +++ b/docs/sdk/events.md @@ -0,0 +1,244 @@ +# Events + +The Box API provides an events endpoint that utilizes long-polling to send user +events in real-time. The SDK provides an `EventStream` class that automatically +handles long-polling and deduplicating events. + + + + + +- [User Events](#user-events) + - [Deduplicating Events](#deduplicating-events) +- [Enterprise (Admin) Events](#enterprise-admin-events) + - [Historical Querying](#historical-querying) + - [Live Monitoring](#live-monitoring) + + + +## User Events + +Subscribing to user events works by creating an `EventStream` and attaching +listeners for the events that are fetched in near-real time from the API. + +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 as a +[`BoxEvent`][box-event] object. + +To create an `EventStream` starting from the current point in time, use +the [`EventStream(BoxAPIConnection api)`][event-stream] constructor. To +start from a known stream position, pass the stream position to the +[`EventStream(BoxAPIConnection api, long streamPosition)`][event-stream-position] +constructor. + + +```java +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. + +[event-stream]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/EventStream.html#EventStream-com.box.sdk.BoxAPIConnection- +[event-stream-position]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/EventStream.html#EventStream-com.box.sdk.BoxAPIConnection-long- +[box-event]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxEvent.html + +### 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. + +## Enterprise (Admin) Events + +### Historical Querying + +The Box API provides an `EventLog` class and a +`getEnterpriseEvents(BoxAPIConnection api, EnterpriseEventsRequest enterpriseEventsRequest)` method +that reads from the `admin-logs` stream and returns an `Iterable` over +Enterprise [`BoxEvent`][box-event] records. The emphasis for this stream is on completeness over latency, +which means that Box will deliver admin events in chronological order and without duplicates, +but with higher latency. You can specify start and end time/dates. This method +will only work with an API connection for an enterprise admin account or service account with a manage enterprise properties. + + +```java +// get the last two hours of unfiltered enterprise events +Date startDate = new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 2)); +Date endDate = new Date(System.currentTimeMillis()); +EnterpriseEventsRequest request = new EnterpriseEventsRequest() + .after(startDate) + .before(endDate); +EventLog eventLog = EventLog.getEnterpriseEvents(api, request); +for (BoxEvent event : eventLog) { + System.out.println("Enterprise Event Created by User: " + + event.getCreatedBy().getName() + + " Login: " + event.getCreatedBy().getLogin() + + " Event Type: " + event.getEventType() + + " Created at: " + event.getCreatedAt().toString() + ); +}; +``` + +Additionally, you can set a limit of the number of enterprise events to be retrieved per response by specifying the +limit field. + +```java +// get first 20 events +EnterpriseEventsRequest request = new EnterpriseEventsRequest() + .limit(20); +EventLog eventLog = EventLog.getEnterpriseEvents(api, request); +for (BoxEvent event : eventLog) { + System.out.println("Enterprise Event Created by User: " + + event.getCreatedBy().getName() + + " Login: " + event.getCreatedBy().getLogin() + + " Event Type: " + event.getEventType() + + " Created at: " + event.getCreatedAt().toString() + ); +}; +``` + + +You can also filter events by type. +```java +// filter events by type +EnterpriseEventsRequest request = new EnterpriseEventsRequest() + .types(EventType.ITEM_CREATE, EventType.ITEM_OPEN); +EventLog eventLog = EventLog.getEnterpriseEvents(api, request); +for (BoxEvent event : eventLog){ + System.out.println("Enterprise Event Created by User: " + + event.getCreatedBy().getName() + + " Login: " + event.getCreatedBy().getLogin() + + " Event Type: " + event.getEventType() + + " Created at: " + event.getCreatedAt().toString() + ); +}; +``` + +You can also filter events by type name. This is usefull if a new event type is introduced and is not mapped to +`BoxEvent.EventType`. +```java +// filter events by type name +EnterpriseEventsRequest request = new EnterpriseEventsRequest() + .typeNames("ITEM_CREATE", "ITEM_OPEN"); +EventLog eventLog = EventLog.getEnterpriseEvents(api, request); +for (BoxEvent event : eventLog){ + System.out.println("Enterprise Event Created by User: " + + event.getCreatedBy().getName() + + " Login: " + event.getCreatedBy().getLogin() + + " Event Type: " + event.getEventType() + + " Event Type Name: " + event.getTypeName() + + " Created at: " + event.getCreatedAt().toString() + ); +}; +``` + +Bear in mind that if an event type is not mapped to `BoxEvent.EventType` the value of `BoxEvent#getEventType()` will +be `BoxEvent.EventType.UNKNOWN` but `BoxEvent#getTypeName()` will return its name. + +If you want to progress within a stream you can use position parameter: +```java +EnterpriseEventsRequest request1 = new EnterpriseEventsRequest().limit(20); +EventLog eventLog1 = EventLog.getEnterpriseEvents(api, request1); +// process revieved events +EnterpriseEventsRequest request2 = new EnterpriseEventsRequest().limit(20) + .position(eventLog1.getNextStreamPosition()); // get events from the next position +EventLog eventLog2 = EventLog.getEnterpriseEvents(api, request2); +// process revieved events +``` + +### Live Monitoring +To monitor recent events that have been generated within Box across the enterprise use +`EventLog#getEnterpriseEventsStream(BoxAPIConnection api, EnterpriseEventsStreamRequest enterpriseEventsStreamRequest)`, +method that reads from the `admin-logs-streaming` stream and returns an `Iterable` over +Enterprise [`BoxEvent`][box-event] records. +The emphasis for this feed is on low latency rather than chronological accuracy, which means that Box may return +events more than once and out of chronological order. Events are returned via the API around 12 seconds after they +are processed by Box (the 12 seconds buffer ensures that new events are not written after your cursor position). +Only two weeks of events are available via this feed, and you cannot set start and end time/dates. This method +will only work with an API connection for an enterprise admin account or service account with a manage enterprise properties. + + +```java +EnterpriseEventsStreamRequest request = new EnterpriseEventsStreamRequest() +EventLog eventLog = EventLog.getEnterpriseEventsStream(api, request); +for (BoxEvent event : eventLog) { + System.out.println("Enterprise Event Created by User: " + + event.getCreatedBy().getName() + + " Login: " + event.getCreatedBy().getLogin() + + " Event Type: " + event.getEventType() + + " Created at: " + event.getCreatedAt().toString() + ); +}; +``` + +You can limit number of events returned. +```java +// get first 20 events +EnterpriseEventsStreamRequest request = new EnterpriseEventsStreamRequest() + .limit(20) +EventLog eventLog = EventLog.getEnterpriseEventsStream(api, request); +``` + + +You can also filter events by type. +```java +// filter events by type +EnterpriseEventsStreamRequest request = new EnterpriseEventsStreamRequest() + .types(EventType.ITEM_CREATE, EventType.ITEM_OPEN); +EventLog eventLog = EventLog.getEnterpriseEventsStream(api, request); +for (BoxEvent event : eventLog){ + System.out.println("Enterprise Event Created by User: " + + event.getCreatedBy().getName() + + " Login: " + event.getCreatedBy().getLogin() + + " Event Type: " + event.getEventType() + + " Created at: " + event.getCreatedAt().toString() + ); +}; +``` + +You can also filter events by type name. This is usefull if a new event type is introduced and is not mapped to +`BoxEvent.EventType`. +```java +// filter events by type name +EnterpriseEventsRequest request = new EnterpriseEventsStreamRequest() + .typeNames("ITEM_CREATE", "ITEM_OPEN"); +EventLog eventLog = EventLog.getEnterpriseEventsStream(api, request); +for (BoxEvent event : eventLog){ + System.out.println("Enterprise Event Created by User: " + + event.getCreatedBy().getName() + + " Login: " + event.getCreatedBy().getLogin() + + " Event Type: " + event.getEventType() + + " Event Type Name: " + event.getTypeName() + + " Created at: " + event.getCreatedAt().toString() + ); +}; +``` + +Bear in mind that if an event type is not mapped to `BoxEvent.EventType` the value of `BoxEvent#getEventType()` will +be `BoxEvent.EventType.UNKNOWN` but `BoxEvent#getTypeName()` will return its name. + +If you want to progress within a stream you can use position parameter: +```java +EnterpriseEventsStreamRequest request1 = new EnterpriseEventsStreamRequest().limit(20); +EventLog eventLog1 = EventLog.getEnterpriseEventsStream(api, request1); +// process revieved events +EnterpriseEventsStreamRequest request2 = new EnterpriseEventsStreamRequest().limit(20) + .position(eventLog1.getNextStreamPosition()); // get events from the next position +EventLog eventLog2 = EventLog.getEnterpriseEventsStream(api, request2); +// process revieved events +``` + +If you have the next stream position, and make a subsequent call, the API will return immediately +even when there are no events, the next stream position will be returned. +If you have a stream position that is older than two weeks than API will return no events and next +stream position. diff --git a/docs/sdk/file_requests.md b/docs/sdk/file_requests.md new file mode 100644 index 000000000..ca6021f4d --- /dev/null +++ b/docs/sdk/file_requests.md @@ -0,0 +1,77 @@ +File Requests +============= + +File request objects represent a file request associated with a folder. + + + + +- [Get a File Request's Information](#get-a-file-requests-information) +- [Copy a File Request's Information](#copy-a-file-requests-information) +- [Update a File Request's Information](#update-a-file-requests-information) +- [Delete a File Request](#delete-a-file-request) + + + +Get a File Request's Information +------------------------ + +Calling [`getInfo()`][get-info] returns information on a file request. + + +```java +BoxFileRequest fileRequest = new BoxFileRequest(api, "id"); +BoxFileRequest.Info fileRequestInfo = fileRequest.getInfo(); +``` + +[get-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileRequest.html#getInfo + +Copy a File Request's Information +--------------------------- + +Calling [`copyInfo(String folderId)`][copy-info] copies an existing file request that is already present +on one folder, and applies it to another folder. If you want to set certain fields of the newly copied file request when it is created, +set those fields in the `BoxFileRequest.Info` that you pass into this method [`copyInfo(BoxFileRequest.Info info, String folderId)`][copy-info]. + + +```java +BoxFileRequest fileRequest = new BoxFileRequest(api, "id"); +BoxFileRequest.Info fileRequestInfo = fileRequest.new Info(); +fileRequestInfo.setDescription("Following documents are requested for your process"); +fileRequestInfo.setIsDescriptionRequired(true); +fileRequestInfo.setStatus(BoxFileRequest.Status.ACTIVE); +fileRequestInfo = fileRequest.copyInfo(fileRequestInfo, "folderId"); +``` + +[copy-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTask.html#copyInfo + +Update a File Request's Information +--------------------------- + +Calling [`updateInfo(BoxFileRequest.Info info)`][update-info] updates a file request. This can be used to activate +or deactivate a file request. + + +```java +BoxFileRequest fileRequest = new BoxFileRequest(api, "id"); +BoxFileRequest.Info fileRequestInfo = fileRequest.new Info(); +fileRequestInfo.setDescription("Following documents are requested for your process"); +fileRequestInfo.setIsDescriptionRequired(true); +fileRequestInfo.setStatus(BoxFileRequest.Status.ACTIVE); +fileRequestInfo = fileRequest.updateInfo(fileRequestInfo); +``` + +[update-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileRequest.html#updateInfo + +Delete a File Request +------------- + +Calling [`delete()`][delete] deletes a file request permanently. + + +```java +BoxFileRequest fileRequest = new BoxFileRequest(api, "id"); +fileRequest.delete(); +``` + +[delete]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFileRequest.html#delete diff --git a/docs/sdk/files.md b/docs/sdk/files.md new file mode 100644 index 000000000..f275b256c --- /dev/null +++ b/docs/sdk/files.md @@ -0,0 +1,1135 @@ +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) +- [Upload Preflight Check](#upload-preflight-check) +- [Upload a Large File in Chunks](#upload-a-large-file-in-chunks) +- [Upload a Large File in Chunks Including Attributes](#upload-a-large-file-in-chunks-including-attributes) +- [Upload a Large File Version in Chunks](#upload-a-large-file-version-in-chunks) +- [Upload a Large File Version in Chunks Including Attributes](#upload-a-large-file-version-in-chunks-including-attributes) +- [Upload a Large File Or File Version Manually](#upload-a-large-file-or-file-version-manually) +- [Move a File](#move-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) +- [Lock a File](#lock-a-file) +- [Unlock a File](#unlock-a-file) +- [Find File for Shared Link](#find-file-for-shared-link) +- [Download File for Shared Link](#download-file-for-shared-link) +- [Create a Shared Link](#create-a-shared-link) +- [Get a Shared Link](#get-a-shared-link) +- [Update a Shared Link](#update-a-shared-link) +- [Remove a Shared Link](#remove-a-shared-link) +- [Add a Collaborator](#add-a-collaborator) +- [Get an Embed Link](#get-an-embed-link) +- [Create Metadata](#create-metadata) +- [Set Metadata](#set-metadata) +- [Get Metadata](#get-metadata) +- [Update Metadata](#update-metadata) +- [Delete Metadata](#delete-metadata) +- [Get All Metadata on File](#get-all-metadata-on-file) +- [Set Classification on File](#set-classification-on-file) +- [Get Classification on File](#get-classification-on-file) +- [Remove Classification on File](#remove-classification-on-file) +- [Get File Representations](#get-file-representations) +- [Get Representation Content](#get-representation-content) + + + +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... fields)`][get-info] +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-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 fieldsToUpdate)`][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 stream)`][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`][progress] +to [`download(OutputStream stream, ProgressListener progress)`][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-com.box.sdk.ProgressListener- +[progress]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/ProgressListener.html + +Upload a File +------------- + +Files are uploaded to a folder by calling the +[`uploadFile(InputStream fileContents, String fileName)`][upload] method +on the [`BoxFolder`][box-folder] you want to upload the file into. + + +```java +BoxFolder rootFolder = BoxFolder.getRootFolder(api); +FileInputStream stream = new FileInputStream("My File.txt"); +BoxFile.Info newFileInfo = rootFolder.uploadFile(stream, "My File.txt"); +stream.close(); +``` + +Note that using `FileInputStream` allows you to read the content of the file only once. +If the first upload attempt fails, the stream will become exhausted, +and request retry with no content might be performed. To retry an upload, you would have to +create a new `FileInputStream` and call `uploadFile()` method again. + +If you want the SDK to automatically retry the upload in case of any error, you need to provide an +`InputStream` class that supports the `reset()` operation. For example, you can read all bytes from your file into +a `ByteArrayInputStream` and then use it for the upload method. Be aware that this approach will load the whole file +into memory, so it is not recommended for large files, as it can exhaust easily your memory. + +```java +BoxFolder rootFolder = BoxFolder.getRootFolder(api); +InputStream stream = new ByteArrayInputStream(Files.readAllBytes(new File(path).toPath())); +BoxFile.Info newFileInfo = rootFolder.uploadFile(stream, "My File.txt"); +stream.close(); +``` + +Upload progress can be tracked by providing the size of the file and a +[`ProgressListener`][progress] to +[`uploadFile(InputStream fileContents, String fileName, long fileSize, ProgressListener progress)`][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"); +BoxFile.Info newFileInfo = rootFolder.uploadFile(stream, "My File.txt", 1024, new ProgressListener() { + public void onProgressChanged(long numBytes, long totalBytes) { + double percentComplete = numBytes / totalBytes; + } +}); +stream.close(); +``` + +We also support the ability to attach a description of the file upon upload by calling the +[`uploadFile(InputStream fileContents, String fileName, String fileDescription)`][upload3] method. + +```java +BoxFolder rootFolder = BoxFolder.getRootFolder(api); +FileInputStream stream = new FileInputStream("My File.txt"); +BoxFile.Info newFileInfo = rootFolder.uploadFile(stream, "My File.txt", "File Description"); +stream.close(); +``` + +[upload]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#uploadFile-java.io.InputStream-java.lang.String- +[upload2]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#uploadFile-java.io.InputStream-java.lang.String-long-com.box.sdk.ProgressListener- +[upload3]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#uploadFile-java.io.InputStream-java.lang.String-java.lang.String- +[box-folder]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html + +Upload Preflight Check +---------------------- + +You may want to check if a file can be successfully uploaded before beginning +the file transfer, in order to the time and bandwidth of sending the file over +the network if the upload would not have succeeded. Calling the +[`BoxFolder#canUpload(String fileName, long fileSize)`][upload-preflight] method +on the folder you want to upload a new file into will verify that there is no +name conflict and that the account has enough storage space for the file. + + +```java +String fileName = "My Doc.pdf"; +BoxFolder rootFolder = BoxFolder.getRootFolder(api); +try { + folder.canUpload(fileName, 98734576); + + // If the file upload would not have succeeded, it will not be attempted + folder.uploadFile(fileContents, fileName); +} catch (BoxAPIException ex) ( + +) +``` + +[upload-preflight]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#canUpload-java.lang.String-long- + +Upload a Large File in Chunks +----------------------------- + +A large file can be uploaded with the +[`uploadLargeFile(InputStream fileContents, String fileName, long fileSize)`][upload-large-file] +method on the folder to upload the new file into. This will upload the file in +parts with integrity checks on each part, to ensure that network errors +mid-upload do not fail the entire operation. + + +```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()); +``` + +[upload-large-file]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#uploadLargeFile-java.io.InputStream-java.lang.String-long- + +Upload a Large File in Chunks Including Attributes +-------------------------------------------------- + +A large file can be uploaded, including attributes, with the +[`uploadLargeFile(InputStream fileContents, String fileName, long fileSize, Map fileAttributes)`][upload-large-file-including-attributes] +method on the folder to upload the new file into. This will upload the file in +parts with integrity checks on each part, to ensure that network errors +mid-upload do not fail the entire operation. + +```java +File myFile = new File("My Large_File.txt"); +FileInputStream stream = new FileInputStream(myFile); +Map fileAttributes = new HashMap(); +fileAttributes.put("content_modified_at", "2017-04-08T00:58:08Z"); + +BoxFolder rootFolder = BoxFolder.getRootFolder(api); +BoxFile.Info fileInfo = rootFolder.uploadLargeFile(inputStream, "My_Large_File.txt", myFile.length(), fileAttributes); +``` + +[upload-large-file-including-attributes]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#uploadLargeFile-java.io.InputStream-java.lang.String-long-java.util.Map- + +Upload a Large File Version in Chunks +------------------------------------- + +To upload a new file version for a large file, call the +[`uploadLargeFile(InputStream fileContents, long fileSize)`][upload-large-file-version] +method on the file to be updated. This will upload the new version of the file +in parts with integrity checks on each part, to ensure that network errors +mid-upload do not fail the entire operation. + + +```java +File myFile = new File("My Large_File.txt"); +FileInputStream stream = new FileInputStream(myFile); + +String fileID = "12345"; +BoxFile file = new BoxFile(api, fileID); +BoxFile.Info fileInfo = file.uploadLargeFile(inputStream, myFile.length()); +``` + +[upload-large-file-version]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#uploadLargeFile-java.io.InputStream-long- + +Upload a Large File Version in Chunks Including Attributes +---------------------------------------------------------- + +To upload a new file version for a large file, including attributes, call the +[`uploadLargeFile(InputStream fileContents, long fileSize, Map fileAttributes)`][upload-large-file-version-including-attributes] +method on the file to be updated. This will upload the new version of the file +in parts with integrity checks on each part, to ensure that network errors +mid-upload do not fail the entire operation. + +```java +File myFile = new File("My Large_File.txt"); +FileInputStream stream = new FileInputStream(myFile); +Map fileAttributes = new HashMap(); +fileAttributes.put("content_modified_at", "2017-04-08T00:58:08Z"); + +String fileID = "12345"; +BoxFile file = new BoxFile(api, fileID); +BoxFile.Info fileInfo = file.uploadLargeFile(inputStream, myFile.length(), fileAttributes); +``` + +[upload-large-file-version-including-attributes]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#uploadLargeFile-java.io.InputStream-long-java.util.Map- + +Upload a Large File Or File Version Manually +-------------------------------------------- + +To start the process of uploading a large file or file version, first create a +new upload session with +[`BoxFolder#createUploadSession(String fileName, String fileSize)`][create-upload-session] +for a new file, or +[`BoxFile#createUploadSession(long fileSize)`][create-upload-session-version] +for a new file version. Once the upload session is created, all other steps +are identical for both cases. + + +```java +BoxFileUploadSession.Info sessionInfo; +if (/* uploading a new file */) { + // Create the upload session for a new file + BoxFolder rootFolder = BoxFolder.getRootFolder(api); + sessionInfo = rootFolder.createUploadSession("New Large File.pdf", fileSize); +} else if (/* uploading a new version of an exiting file */) { + // Create the uplaod session for a new version of an existing file + String fileID = "93465"; + BoxFile file = new BoxFile(api, fileID); + sessionInfo = file.createUploadSession(fileSize); +} + +//Get the session resource from the session info +BoxFileUploadSession session = sessionInfo.getResource(); + +//Create the Message Digest for the whole file +MessageDigest digest = null; +try { + digest = MessageDigest.getInstance("SHA1"); +} catch (NoSuchAlgorithmException ae) { + throw new BoxAPIException("Digest algorithm not found", ae); +} +``` + +Both of these methods will return a + +Once the upload session is created, the large file can be uploaded in chunks with the +[`uploadPart(InputStream stream, long offset, int partSize, long totalSizeOfFile)`][upload-part] +method of the session instance. If there is a failure in uploading any of the +parts, the failed part can be uploaded again without affecting the other parts. + + +```java +//Reading a large file +FileInputStream fis = new FileInputStream("My_Large_File.txt"); +//Create the digest input stream to calculate the digest for the whole file. +DigestInputStream dis = new DigestInputStream(fis, digest); + +List parts = new ArrayList(); + +//Get the part size. Each uploaded part should match the part size returned as part of the upload session. +//The last part of the file can be less than part size if the remaining bytes of the last part is less than +//the given part size +long partSize = sessionInfo.getPartSize(); +//Start byte of the part +long offset = 0; +//Overall of bytes processed so far +long processed = 0; +while (processed < fileSize) { + long diff = fileSize - processed; + //The size last part of the file can be less than the part size. + if (diff < partSize) { + partSize = diff; + } + + //Upload a part. It can be uploaded asynchorously + BoxFileUploadSessionPart part = session.uploadPart(dis, offset, (int)partSize, fileSize); + parts.add(part); + + //Increase the offset and proceesed bytes to calculate the Content-Range header. + processed += partSize; + offset += partSize; +} +``` + +At any point in time, the list of parts that have been uploaded successfully can be retrieved with the +[`listParts(int offset, int limit)`][list-parts] method of the session instance. + + +```java +//The following snippet retrives first 1000 parts that are uploaded. +BoxFileUploadSessionPartList partList = session.listParts(0, 1000); +List parts = partList.getEntries(); +``` + +Once all the parts are uploaded successfully, the upload session can be committed with the +[`commit(String digest, List parts, Map attributes, String ifMatch, String ifNoneMatch)`][upload-session-commit] method. + + +```java +//Creates the file hash +byte[] digestBytes = digest.digest(); +//Base64 encoding of the hash +String digestStr = Base64.encode(digestBytes); + +//Commit the upload session. If there is a failure, abort the commit. +BoxFile.Info fileInfo = session.commit(digestStr, parts, null, null, null); +``` + +The upload session can be aborted at any time with the +[`abort()`][upload-session-abort] method of the session instance. This will +cancel the upload and any parts that were already uploaded will be lost. + + +```java +session.abort(); +``` + +The upload session status can be retrieved at any time with the [`getStatus()`][upload-session-status] method. +This call will update the parts processed and other information in the session info instance. + + +```java +BoxFileUploadSession.Info updatedSessionInfo = session.getStatus(); +``` + +[create-upload-session]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#createUploadSession-java.lang.String-long- +[create-upload-session-version]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#createUploadSession-long- +[upload-part]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileUploadSession.html#uploadPart-java.io.InputStream-long-int-long- +[list-parts]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileUploadSession.html#listParts-int-int- +[upload-session-commit]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileUploadSession.html#commit-java.lang.String-java.util.List-java.util.Map-java.lang.String-java.lang.String- +[upload-session-abort]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileUploadSession.html#abort-- +[upload-session-status]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileUploadSession.html#getStatus-- + +Move a File +----------- + +To move a file from one folder into another, call +[`move(BoxFolder destination)`][move] on the file to be moved with the +destination folder. + +```java +String fileID = "1234"; +String destinationFolderID = "5678"; +BoxFile file = new BoxFile(api, fileID); +BoxFolder destinationFolder = new BoxFolder(destinationFolderID); +file.move(destinationFolder) +``` + +To avoid name conflicts in the destination folder, you can optionally provide a +new name for the file to [`move(BoxFolder destination, String newName)`][move-rename]. The file +will be placed into the destination folder with the new name. + +```java +String fileID = "1234"; +String destinationFolderID = "5678"; +BoxFile file = new BoxFile(api, fileID); +BoxFolder destinationFolder = new BoxFolder(destinationFolderID); +file.move(destinationFolder, "Vacation Photo (1).jpg"); +``` + +[move]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#move-com.box.sdk.BoxFolder- +[move-rename]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#move-com.box.sdk.BoxFolder-java.lang.String- + +Copy a File +----------- + +A file can be copied to a new folder and optionally be renamed with the +[`copy(BoxFolder destination)`][copy] and +[`copy(BoxFolder destination, String newName)`][copy2] methods. + + +```java +// Copy a file into the user's root folder +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-java.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. By default, it will return up to 1000 file versions with all default fields set. + + +```java +BoxFile file = new BoxFile(api, "id"); +Collection versions = file.getVersions(); +for (BoxFileVersion version : versions) { + System.out.format("SHA1 of \"%s\": %s\n", file.getInfo().getName(), version.getSha1()); +} +``` + +File versions can be retrieved with specified starting position with the +[`getVersionsRange(long offset, long limit)`][get-versions-range] method. +You can use the `limit` and `offset` parameters to page through the all available file versions. + +```java +BoxFile file = new BoxFile(api, "id"); +Collection versions = file.getVersionsRange(1000, 2000); +for (BoxFileVersion version : versions) { + System.out.format("SHA1 of \"%s\": %s\n", file.getInfo().getName(), version.getSha1()); +} +``` + +You can specify selected fields to be returned while getting versions information. +Assume we want to get version SHA1 and version number: +```java +BoxFile file = new BoxFile(api, "id"); +Collection versions = file.getVersions("sha1", "version_number"); +for (BoxFileVersion version : versions) { + System.out.format("SHA1 of \"%d\": %s\n", version.getVersionNumber(), version.getSha1()); +} +``` +You can find a list of available fields at [`BoxFile.ALL_VERSION_FIELDS`][versions-fields]. + +[get-versions]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getVersions-- +[versions-fields]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#ALL_VERSION_FIELDS-- + +Upload a New Version of a File +------------------------------ + +New versions of a file can be uploaded with the +[`uploadNewVersion(InputStream fileContents)`][upload-new-version] +method. + + +```java +BoxFile file = new BoxFile(api, "id"); +FileInputStream stream = new FileInputStream("My File.txt"); +file.uploadNewVersion(stream); +``` + +[upload-new-version]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#uploadNewVersion-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 output)`][download-version]. + + +```java +BoxFile file = new BoxFile(api, "id"); +Collection versions = file.getVersions(); +BoxFileVersion firstVersion = versions.iterator().next(); + +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"); +Collection versions = file.getVersions(); +BoxFileVersion firstVersion = versions.iterator().next(); +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"); +Collection versions = file.getVersions(); +BoxFileVersion firstVersion = versions.iterator().next(); +firstVersion.delete(); +``` + +[delete-version]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileVersion.html#delete-- + +Lock a File +----------- + +A file can be locked indefinitely by calling [`lock()`][lock] on the file to +be locked. A locked file cannot be modified by any other user until it is +unlocked. This is useful if you want to "check out" a file while you're working +on it, to ensure that other collaborators do not make changes while your changes +are in progress. + +```java +BoxFile file = new BoxFile(api, "id"); +file.lock(); +``` + +When locking a file, you can optionally prevent other users from downloading the +file in addition to prevent changes by calling +[`lock(boolean preventDownload)`][lock-download] with `true`. + +```java +// Lock the file and prevent downloading +BoxFile file = new BoxFile(api, "id"); +file.lock(true); +``` + +You can also set a date when the lock will automatically be released by +calling [`lock(Date expirationDate)`][lock-expires] with the date on +which the lock should expire. This is recommended to prevent a file +from accidentally being locked longer than intended. + +```java +final long ONE_WEEK_MILLIS = 1000 * 60 * 60 * 24 * 7; +long expirationTimestamp = System.currentTimeMillis() + ONE_WEEK_MILLIS; +Date expirationTime = new Date(expirationTimestamp); +BoxFile file = new BoxFile(api, "id"); +file.lock(expirationTime); +``` + +Both options can be passed together to +[`lock(boolean preventDownload, Date expireTime)`][lock-both]. + +[lock]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#lock-java.util.Date- +[lock-download]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#lock-boolean- +[lock-expires]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#lock-java.util.Date- +[lock-both]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#lock-java.util.Date-boolean- + +Unlock a File +------------- + +A file can be unlocked by calling [`unlock()`][unlock]. + +```java +BoxFile file = new BoxFile(api, "id"); +file.unlock(); +``` + +[unlock]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#unlock-- + +Find File for Shared Link +------------------------- + +To get the file information for a shared link, you can call +[`BoxItem.getSharedItem(BoxAPIConnection api, String sharedLink)`][get-shared-item] +with the shared link to get information about the file behind it. + +```java +String sharedLink = "https://app.box.com/s/abcdefghijklmnopqrstuvwxyz123456"; +BoxItem.Info itemInfo = BoxItem.getSharedItem(api, sharedLink); +``` + +If the shared link is password-protected, call +[`BoxItem.getSharedItem(BoxAPIConnection api, String sharedLink, String password)`][get-shared-item-password] +with the shared link and password. + + +```java +String sharedLink = "https://app.box.com/s/abcdefghijklmnopqrstuvwxyz123456"; +String password = "letmein"; +BoxItem.Info itemInfo = BoxItem.getSharedItem(api, sharedLink, password); +``` + +[get-shared-item]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxItem.html#getSharedItem-com.box.sdk.BoxAPIConnection-java.lang.String- +[get-shared-item-password]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxItem.html#getSharedItem-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String- + +Download File from Shared Link +--------------- + +A file can be downloaded via a shared link +by calling [`downloadFromSharedLink(BoxAPIConnection api, OutputStream output, String sharedLink)`][download-from-shared-link] +and providing an `OutputStream` where the file's contents will be written and shared link of the file. + +If the shared link is password-protected, call +[`downloadFromSharedLink(BoxAPIConnection api, OutputStream output, String sharedLink, String password)`][download-from-shared-link-password] +method. + +```java +FileOutputStream stream = new FileOutputStream("My File.txt"); +String sharedLink = "https://cloud.box.com/s/12339wbq4c7y2xd3drg4j9j9wer3ptt6n"; +String password = "Secret123@"; +BoxFile.downloadFromSharedLink(api, stream, sharedLink, password); +stream.close(); +``` + +Download progress can be tracked by providing a [`ProgressListener`][progress] +to [` downloadFromSharedLink(BoxAPIConnection api, OutputStream output, String sharedLink, String password, ProgressListener listener)`][download-from-shared-link-password-progress]. +The `ProgressListener` will then receive progress updates as the download +completes. + +```java +FileOutputStream stream = new FileOutputStream("My File.txt"); +// Provide a ProgressListener to monitor the progress of the download. +BoxFile.downloadFromSharedLink(api, stream, sharedLink, password, new ProgressListener() { + public void onProgressChanged(long numBytes, long totalBytes) { + double percentComplete = numBytes / totalBytes; + } +}); +stream.close(); +``` +[download-from-shared-link]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#downloadFromSharedLink-com.box.sdk.BoxAPIConnection-java.io.OutputStream-java.lang.String- +[download-from-shared-link-password]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#downloadFromSharedLink-com.box.sdk.BoxAPIConnection-java.io.OutputStream-java.lang.String-java.lang.String- +[download-from-shared-link-password-progress]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#downloadFromSharedLink-com.box.sdk.BoxAPIConnection-java.io.OutputStream-java.lang.String-java.lang.String-com.box.sdk.ProgressListener- + +Create a Shared Link +-------------------- + +A shared link for a file can be generated by calling +[`createSharedLink(BoxSharedLinkRequest sharedLinkRequest)`][create-shared-link]. + + +```java +// Optionally we can calculate and set the date when shared link will automatically be disabled +final long ONE_WEEK_MILLIS = 1000 * 60 * 60 * 24 * 7; +long unsharedTimestamp = System.currentTimeMillis() + ONE_WEEK_MILLIS; +Date unsharedDate = new Date(unsharedTimestamp); + +BoxFile file = new BoxFile(api, "id"); +BoxSharedLinkRequest sharedLinkRequest = new BoxSharedLinkRequest() + .access(OPEN) + .permissions(true, true) + .unsharedDate(unsharedDate); +BoxSharedLink sharedLink = file.createSharedLink(sharedLinkRequest); +``` + +A set of shared link access level constants are available through the SDK for convenience: +* `BoxSharedLink.Access.OPEN` +* `BoxSharedLink.Access.COLLABORATORS` +* `BoxSharedLink.Access.COMPANY` +* `BoxSharedLink.Access.DEFAULT` + +[create-shared-link]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#createSharedLink-com.box.sdk.sharedlink.BoxSharedLinkRequest- + +Get a Shared Link +----------------- + +Retrieve the shared link for a file by calling +[`getSharedLink()`][get-shared-link]. + + +```java +BoxFile file = new BoxFile(api, "id"); +BoxFile.Info info = file.getInfo(); +BoxSharedLink link = info.getSharedLink(); +String url = link.getUrl(); +``` + +[get-shared-link]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxItem.Info.html#getSharedLink-- + +Update a Shared Link +-------------------- + +A shared link for a file can be updated by calling the same method as used when creating a shared link, +[`createSharedLink(BoxSharedLinkRequest sharedLinkRequest)`][create-shared-link]. + + +```java +BoxFile file = new BoxFile(api, "id"); +BoxSharedLinkRequest sharedLinkRequest = new BoxSharedLinkRequest() + .access(OPEN) + .permissions(true, true); +BoxSharedLink sharedLink = file.createSharedLink(sharedLinkRequest); +``` + +Remove a Shared Link +-------------------- + +A shared link for a file can be removed by calling [`removeSharedLink()`][remove-shared-link]. + + +```java +BoxFile file = new BoxFile(api, "12345"); +BoxFile.Info info = file.getInfo(); +info.removeSharedLink(); +file.updateInfo(info); +``` + +[remove-shared-link]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#removeSharedLink-- + +Add a Collaborator +------------------ + +You can invite another person to collaborate on a file by email with +[`collaborate(String emailAddress, BoxCollaboration.Role role, Boolean notify, Boolean canViewPath, Date expiresAt, Boolean isAccessOnly)`][share-a-file]. + +The `notify` parameter will determine if the user or group will receive an +email notification when being added as a collaborator. This option is only +available to enterprise administrators. + +The `canViewPath` parameter allows the invitee to see the entire list of ancestor +folders of the associated file. The user will not gain privileges in any ancestor +folder, but will be able to see the whole path to that file in the owner's account. + +The `expiresAt` parameter allows the owner to set a date-time in the future when +the collaboration should expire. + +The `isAccessOnly` parameter allows the owner to set the collaboration to be +access only collaboration. + +The `notify`, `canViewPath`, `expiresAt` and `isAccessOnly` parameters can be left as `null`. + +```java +BoxFile file = new BoxFile(api, "id"); +BoxCollaboration.Info collabInfo = file.collaborate("testuser@example.com", BoxCollaboration.Role.EDITOR, true, true); +``` + +Alternatively, if you know the user's ID, you can invite them directly +without needing to know their email address with the +[`collaborate(BoxCollaborator user, BoxCollaboration.Role role, Boolean notify, Boolean canViewPath, Date expiresAt, Boolean isAccessOnly)`][share-a-file-userID] + +```java +BoxUser collaborator = new BoxUser(api, "user-id"); +BoxFile file = new BoxFile(api, "file-id"); +BoxCollaboration.Info collabInfo = file.collaborate(collaborator, BoxCollaboration.Role.EDITOR, true, true); +``` + +[share-a-file]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#collaborate-java.lang.String-com.box.sdk.BoxCollaboration.Role-java.lang.Boolean-java.lang.Boolean-java.lang.String-java.util.Date-java.lang.Boolean- +[share-a-file-userID]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#collaborate-com.box.sdk.BoxCollaborator-com.box.sdk.BoxCollaboration.Role-java.lang.Boolean-java.lang.Boolean-java.lang.String-java.util.Date-java.lang.Boolean- + + +Get an Embed Link +----------------- + +A file embed link can be generated by calling [`getPreviewLink()`][get-preview-link]. + +```java +BoxFile file = new BoxFile(api, "id"); +URL embedLink = file.getPreviewLink(); +``` + +[get-preview-link]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getPreviewLink-- + +Create Metadata +--------------- + +Metadata can be created on a file by calling +[`createMetadata(Metadata metadata)`][create-metadata], +[`createMetadata(String typeName, Metadata metadata)`][create-metadata-2], or +[`createMetadata(String typeName, String scope, Metadata metadata)`][create-metadata-3]. + + +```java +// Add property "foo" with value "bar" to the default metadata properties +BoxFile file = new BoxFile(api, "id"); +file.createMetadata(new Metadata().add("/foo", "bar")); +``` + +Note: This method will only succeed if the provided metadata template is not currently applied to the file, otherwise +it will fail with a Conflict error. To get to know how to edit existing metadata please +go to [set metadata](#set-metadata) and [update metadata](#update-metadata) sections. + +[create-metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#createMetadata-com.box.sdk.Metadata- +[create-metadata-2]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#createMetadata-java.lang.String-com.box.sdk.Metadata- +[create-metadata-3]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#createMetadata-java.lang.String-java.lang.String-com.box.sdk.Metadata- +[update-metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#updateMetadata-com.box.sdk.Metadata- + +Set Metadata +------------ + +To set metadata on a file, call [`setMetadata(String templateName, String scope, Metadata metadata)`][set-metadata]. +This method will try to create provided metadata on a file. However, if metadata has already been applied to this file, +it will overwrite values of metadata keys specified in the `metadata` parameter. The metadata keys not specified in +the `metadata` parameter will remain unchanged. + +```java +BoxFile file = new BoxFile(api, "id"); +file.setMetadata("test_template", "enterprise", new Metadata().add("/foo", "bar")); +``` + +Note: If you want to set new metadata on a file including hard reset of the current metadata +(also removing keys not specified in the `metadata` param): +first delete metadata as specified in [delete metadata](#delete-metadata) section and then set new metadata again. + +[set-metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#setMetadata-java.lang.String-java.lang.String-com.box.sdk.Metadata- + +Get Metadata +------------ + +Retrieve a file's Metadata by calling [`getMetadata()`][get-metadata], +[`getMetadata(String typeName)`][get-metadata-2], or +[`getMetadata(String typeName, String scope)`][get-metadata-3]. +These methods return a [`Metadata`][metadata] object, which allows access to metadata values. + + +```java +// Get the default free-form metadata properties +BoxFile file = new BoxFile(api, "id"); +Metadata metadata = file.getMetadata(); + +// Unknown type metadata field, you can test for type or try to get as any type +JsonValue unknownValue = metadata.getValue("/someField"); + +// String or Enum metadata fields +String stringValue = metadata.getString("/author"); + +// Float metadata fields can be interpreted as any numeric type +float floatValue = metadata.getFloat("/price"); + +// Date metadata fields +Date dateValue = metadata.getDate("/deadline"); + +// Multiselect metadata fields +List multiSelectValues = metadata.getMultiSelect("/categories"); +``` + +[metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/Metadata.html +[get-metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getMetadata-- +[get-metadata-2]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getMetadata-java.lang.String- +[get-metadata-3]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getMetadata-java.lang.String-java.lang.String- + +Update Metadata +--------------- + +Update a file's Metadata by calling [`updateMetadata(Metadata properties)`][update-metadata]. + +Note: This method will only succeed if the provided metadata template has already been applied to the file. If the file +does not have existing metadata, this method will fail with a Not Found error. This is useful in cases where you know +the file will already have metadata applied, since it will save an API call compared to `setMetadata()`. + + +```java +BoxFile file = new BoxFile(api, "id"); +file.updateMetadata(new Metadata("templateScope", "templateKey").add("/foo", "bar")); +``` + +Also, it is possible to add multi-select fields for your file metadata by calling +[`updateMetadata(Metadata properties)`][update-metadata] with a list of values. + +```java +BoxFile file = new BoxFile(api, "id"); +List valueList = new ArrayList(); +valueList.add("bar"); +valueList.add("qux"); +file.updateMetadata(new Metadata("templateScope", "templateKey").add("/foo", valueList)); +``` + +If you wanted to replace all selected fields for a specified key you can use the +[`replace(String path, List values)`][replace-metadata]. + +```java +BoxFile file = new BoxFile(api, "id"); +List valueList = new ArrayList(); +valueList.add("bar"); +valueList.add("qux"); +file.updateMetadata(new Metadata("templateScope", "templateKey").replace("/foo", valueList)); +``` + +If you wanted to remove a metadata value for a specified key you can use the +[`remove(String path)`][remove-metadata]. + +```java +BoxFile file = new BoxFile(api, "id"); +file.updateMetadata(new Metadata("templateScope", "templateKey").remove("/foo")); +``` + +[update-metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#updateMetadata-com.box.sdk.Metadata- +[replace-metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/Metadata.html#replace-java.lang.String-java.util.List- +[remove-metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/Metadata.html#remove-java.lang.String- + +Delete Metadata +--------------- + +A file's Metadata can be deleted by calling +[`deleteMetadata()`][delete-metadata], +[`deleteMetadata(String typeName)`][delete-metadata-2], or +[`deleteMetadata(String typeName, String scope)`][delete-metadata-3]. + + +```java +BoxFile file = new BoxFile(api, "id"); +file.deleteMetadata("myMetadataTemplate"); +``` + +[delete-metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#deleteMetadata-- +[delete-metadata-2]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#deleteMetadata-java.lang.String- +[delete-metadata-3]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#deleteMetadata-java.lang.String-java.lang.String- + +Get All Metadata on File +-------------- + +Calling the [`getAllMetadata()`][get-all-metadata] method on a file will return +an iterable that will page through all of the metadata associated with the file. + + +```java +BoxFile file = new BoxFile(api, "id"); +Iterable metadataList = file.getAllMetadata(); +for (Metadata metadata : metadataList) { + // Do something with the metadata. +} +``` + +[get-all-metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getAllMetadata-java.lang.String...- + +Set Classification on File +-------------------------- + +Calling the [`setClassification(String classificationType)`][set-classification] method on a file will add a +classification template on the file. This method will return the classification type applied on the file. The +classification types include `Public`, `Internal`, and `Confidential`. `Public` being the most available permission, +`Internal` which restricts the specified file to company and collaborators only, and finally, `Confidential`, which is +for collaborators only. + +```java +BoxFile file = new BoxFile(api, "id"); +String classificationType = file.setClassification("Public"); +``` + +It is important to note that this call will attempt to create a classification on the file first, if one already exists +then it will do the update. If you already know that a classification exists on the file and would like to save an API +call, we encourage you to use the [`updateClassification(String classificationType)`][update-classification] method. + +```java +BoxFile file = new BoxFile(api, "id"); +String classificationType = file.updateClassification("Public"); +``` + +[set-classification]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#setClassification-java.lang.String...- +[update-classification]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#updateClassification-java.lang.String...- + +Get Classification on File +-------------------------- + +To retrieve the classification assigned on the file, use the [`getClassification()`][get-classification] method. This +will return the classification type on the file. + +```java +BoxFile file = new BoxFile(api, "id"); +String classificationType = file.getClassification(); +``` + +[get-classification]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getClassification-java.lang.String...- + +Remove Classification on File +----------------------------- + +To remove classification from the file, use the [`deleteClassification()`][delete-classification] method. + +```java +BoxFile file = new BoxFile(api, "id"); +file.deleteClassification(); +``` + +[delete-classification]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#deleteClassification-- + +Get File Representations +------------------------ + +To get the preview representations of a file, call the +[`getInfoWithRepresentations(String representationHints, String... fields)`][get-reps] +method with the [representation hints][rep-hints] to fetch, along with any other +fields on the file object to fetch simultaneously. This method returns a [`BoxFile.Info`][box-file-info] +object that contains the representations as a list of [`Representation`][rep-obj] objects. + +Note that this method only provides information about a set of available representations; your +application will need to handle checking the status of the representations and downlaoding them +via the provided content URL template. + +```java +BoxFile file = new BoxFile(api, "1234"); + +// Get the PDF representation and file name +String repHints = "[pdf]"; +BoxFile.Info fileInfo = file.getInfoWithRepresentations(repHints, "name"); +List representations = fileInfo.getRepresentations(); +String name = fileInfo.getName(); +``` + +[get-reps]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getInfoWithRepresentations-java.lang.String-java.lang.String...- +[rep-hints]: https://developer.box.com/v2.0/reference/#section-x-rep-hints-header +[rep-obj]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/Representation.html + +Get Representation Content +-------------------------- + +To write the contents of a single file representation to an `OutputStream`, call the +[`getRepresentationContent(String representationHint, OutputStream output)`][get-rep-content] +method with an [X-Rep-Hints value][rep-hints] specifying the representation you want. + +> __Note:__ This method only supports getting the contents of a single representation; if your +> X-Rep-Hints value specifies multiple representations, an arbitrary one of them will be fetched. + +```java +// Read the PDF representation of file 12345 into memory +ByteArrayOutputStream output = new ByteArrayOutputStream(); + +BoxFile file = new BoxFile(api, "12345"); +file.getRepresentationContent("[pdf]", output); +``` + +For representations with multiple files, e.g. multi-page images, you will need to pass an `assetPath` +parameter to specify which file you want to fetch. + +```java +// If file 12345 is a document, its PNG representation will consist of one image per page of the document +// Get the image of the first page of the document and write it to a file +FileOutputStream output = new FileOutputStream("/path/to/file.png"); +BoxFile file = new BoxFile(api, "12345"); +file.getRepresentationContent("[png?dimensions=1024x1024]", "1.png", output); +``` + +Generating a representation for the selected file is an asynchronous operation and may take some time. +Therefore, by default, the `getRepresentationContent` method periodically checks the status of the generated file and downloads it when it is ready. +With the `maxRetries` parameter in [`getRepresentationContent(String representationHint, String assetPath, OutputStream output, int maxRetries)`][get-rep-content-overloaded], you can define +the number of status checks for the generated file, which will be performed at intervals of 100 ms. + +If this number is exceeded, a `BoxApiException` will be thrown. + +```java +FileOutputStream output = new FileOutputStream("/path/to/file.png"); +BoxFile file = new BoxFile(api, "12345"); +file.getRepresentationContent("[png?dimensions=1024x1024]", "1.png", output, 10); +``` + + +[get-rep-content]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getRepresentationContent-java.lang.String-java.lang.String-java.io.OutputStream- +[get-rep-content-overloaded]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getRepresentationContent-java.lang.String-java.lang.String-java.io.OutputStream-int- diff --git a/docs/sdk/folders.md b/docs/sdk/folders.md new file mode 100644 index 000000000..e5bb6eb0d --- /dev/null +++ b/docs/sdk/folders.md @@ -0,0 +1,801 @@ +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) + - [SortParameters and Using PagingParameters](#sortparameters-and-using-pagingparameters) +- [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) +- [Find Folder for Shared Link](#find-folder-for-shared-link) +- [Create a Shared Link](#create-a-shared-link) +- [Get a Shared Link](#get-a-shared-link) +- [Update a Shared Link](#update-a-shared-link) +- [Remove a Shared Link](#remove-a-shared-link) +- [Share a Folder](#share-a-folder) +- [Get All Collaborations for a Folder](#get-all-collaborations-for-a-folder) +- [Create Metadata](#create-metadata) +- [Set Metadata](#set-metadata) +- [Get Metadata](#get-metadata) +- [Update Metadata](#update-metadata) +- [Delete Metadata](#delete-metadata) +- [Get All Metadata on Folder](#get-all-metadata-on-folder) +- [Get Metadata for Multiple Files](#get-metadata-for-multiple-files) +- [Set Classification on Folder](#set-classification-on-folder) +- [Get Classification on Folder](#get-classification-on-folder) +- [Remove Classification on Folder](#remove-classification-on-folder) +- [Create Cascade Policy On Folder](#create-cascade-policy-on-folder) +- [Get a Cascade Policy's Information](#get-a-cascade-policys-information) +- [Get All Cascade Policies on Folder](#get-all-cascade-policies-on-folder) +- [Force Apply Cascade Policy on Folder](#force-apply-cascade-policy-on-folder) +- [Delete Cascade Policy](#delete-cascade-policy) +- [Lock a Folder](#lock-a-folder) +- [Get All Locks on a Folder](#get-all-locks-on-a-folder) +- [Delete a Lock on a Folder](#delete-a-lock-on-a-folder) + + + +Get the User's Root Folder +-------------------------- + +The user's root folder can be accessed with the static +[`getRootFolder(BoxAPIConnection api)`][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 API calls to load more data 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.Info) { + 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()); +} +``` + +We also allow users to sort the results of the folder items by `name`, `id`, or `date`. This will maintain the integrity +of the ordering when you retrieve the items for a folder. You can do this by calling the +[`getChildren(String sortField, BoxFolder.SortDirection sortDirection, String... fields)`][get-items-with-sort] method. + +```java +BoxFolder folder = new BoxFolder(this.api, "12345"); +Iterator itemIterator = folder.getChildren("name", BoxFolder.SortDirection.ASC).iterator(); +while (itemIterator.hasNext()) { + BoxItem.Info itemInfo = itemIterator.next(); + // Do something +} +``` + +### SortParameters and Using PagingParameters + +`SortParameters` is an abstraction hiding way that SDK is doing sorting. +`PagingParameters` is an abstraction hiding way that SDK is doing pagination. +If you want to start offset based pagination: + +```java +BoxFolder folder = new BoxFolder(this.api, "12345"); +// setup ascending sorting by name +SortParameters sorting = SortParameters.ascending("name"); +// setup paging with offset 0 and limit 100 +long offset = 0; +long limit = 100; +PagingParameters paging = PagingParameters.offset(offset, limit) +Iterable itemIterator = childFolder.getChildren(sorting, paging); +while (itemIterator.hasNext()) { + BoxItem.Info itemInfo=itemIterator.next(); + // Do something +} +``` + +With offset pagination you cannot set offset larger than 300000. +With marker based pagination you can iterate over folders containing more than 300000 elements. +With marker based pagination you cannot use sorting. Use `SortParameters.none()` to turn off sort. +If you want to use PagingParameters to start marker based pagination do: +```java +BoxFolder folder = new BoxFolder(this.api, "12345"); +// disable sorting +SortParameters sorting = SortParameters.none(); +// setup paging with makred based pagination and limit 100 +long limit = 100; +PagingParameters paging = PagingParameters.marker(limit) +Iterable itemIterator = childFolder.getChildren(sorting, paging); +while (itemIterator.hasNext()) { + BoxItem.Info itemInfo=itemIterator.next(); + // Do something +} +``` + +[iterator]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#iterator-- +[get-items-with-sort]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getChildren-java.lang.String-com.box.sdk.BoxFolder.SortDirection-java.lang.String...- + +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... fields)`][get-info] +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-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 fieldsToUpdate)`][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 folderName)`][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 destination)`][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 destination, String newName)`][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-java.lang.String- + +Move a Folder +------------- + +Call the [`move(BoxFolder destination)`][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 newName)`][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 recursive)`][delete] method. Passing +`true` to this method indicates that the folder and its contents should be +recursively deleted. + + +```java +// Delete the folder and all its contents +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- + +Find Folder for Shared Link +------------------------- + +To get the folder information for a shared link, you can call +[`BoxItem.getSharedItem(BoxAPIConnection api, String sharedLink)`][get-shared-item] +with the shared link to get information about the folder behind it. + +```java +String sharedLink = "https://app.box.com/s/abcdefghijklmnopqrstuvwxyz123456"; +BoxItem.Info itemInfo = BoxItem.getSharedItem(api, sharedLink); +``` + +If the shared link is password-protected, call +[`BoxItem.getSharedItem(BoxAPIConnection api, String sharedLink, String password)`][get-shared-item-password] +with the shared link and password. + + +```java +String sharedLink = "https://app.box.com/s/abcdefghijklmnopqrstuvwxyz123456"; +String password = "letmein"; +BoxItem.Info itemInfo = BoxItem.getSharedItem(api, sharedLink, password); +``` + +[get-shared-item]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxItem.html#getSharedItem-com.box.sdk.BoxAPIConnection-java.lang.String- +[get-shared-item-password]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxItem.html#getSharedItem-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String- + +Create a Shared Link +-------------------- + +A shared link for a folder can be generated by calling +[`createSharedLink(BoxSharedLinkRequest sharedLinkRequest)`][create-shared-link]. + + +```java +// Optionally we can calculate and set the date when shared link will automatically be disabled +final long ONE_WEEK_MILLIS = 1000 * 60 * 60 * 24 * 7; +long unsharedTimestamp = System.currentTimeMillis() + ONE_WEEK_MILLIS; +Date unsharedDate = new Date(unsharedTimestamp); + +BoxFolder folder = new BoxFolder(api, "id"); +BoxSharedLinkRequest sharedLinkRequest = new BoxSharedLinkRequest() + .access(OPEN) + .permissions(true, true) + .unsharedDate(unsharedDate); +BoxSharedLink sharedLink = folder.createSharedLink(sharedLinkRequest); +``` + +A set of shared link access level constants are available through the SDK for convenience: +* `BoxSharedLink.Access.OPEN` +* `BoxSharedLink.Access.COLLABORATORS` +* `BoxSharedLink.Access.COMPANY` +* `BoxSharedLink.Access.DEFAULT` + +[create-shared-link]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#createSharedLink-com.box.sdk.sharedlink.BoxSharedLinkRequest- + +Get a Shared Link +----------------- + +Retrieve the shared link for a folder by calling +[`getSharedLink()`][get-shared-link]. + + +```java +BoxFolder folder = new BoxFolder(api, "id"); +BoxFolder.Info info = folder.getInfo() +BoxSharedLink link = info.getSharedLink() +String url = link.getUrl() +``` + +[get-shared-link]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxItem.Info.html#getSharedLink-- + +Update a Shared Link +-------------------- + +A shared link for a folder can be updated by calling the same method as used when creating a shared link, +[`createSharedLink(BoxSharedLinkRequest sharedLinkRequest)`][create-shared-link]. + + +```java +BoxFolder folder = new BoxFolder(api, "id"); +BoxSharedLinkRequest sharedLinkRequest = new BoxSharedLinkRequest() + .access(OPEN) + .permissions(true, true); + +BoxSharedLink sharedLink = folder.createSharedLink(sharedLinkRequest); +``` + +Remove a Shared Link +-------------------- + +A shared link for a folder can be removed by calling [`removeSharedLink()`][remove-shared-link]. + + +```java +BoxFolder folder = new BoxFolder(api, "12345"); +BoxFolder.Info info = folder.getInfo(); +info.removeSharedLink(); +folder.updateInfo(info); +``` + +[remove-shared-link]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#removeSharedLink-- + +Share a Folder +-------------- + +You can invite another person to collaborate on a folder with the +[`collaborate(String emailAddress, BoxCollaboration.Role 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 user, BoxCollaboration.Role 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); +``` + +You can also create a collaboration with all properties set at once by using the +[`collaborate(BoxCollaborator user, BoxCollaboration.Role role, Boolean notify, Boolean canViewPath, Date expiresAt, Boolean isAccessOnly)`][collaborate3] method. + +The `notify` parameter will determine if the user or group will receive an +email notification when being added as a collaborator. This option is only +available to enterprise administrators. + +The `canViewPath` parameter allows the invitee to see the entire list of ancestor +folders of the associated file. The user will not gain privileges in any ancestor +folder, but will be able to see the whole path to that file in the owner's account. + +The `expiresAt` parameter allows the owner to set a date-time in the future when +the collaboration should expire. + +The `isAccessOnly` parameter allows the owner to set the collaboration to be +access only collaboration. + +The `notify`, `canViewPath`, `expiresAt` and `isAccessOnly` parameters can be left as `null`. + +[collaborate]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#collaborate-java.lang.String-com.box.sdk.BoxCollaboration.Role- +[collaborate2]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#collaborate-com.box.sdk.BoxCollaborator-com.box.sdk.BoxCollaboration.Role- +[collaborate3]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#collaborate-com.box.sdk.BoxCollaborator-com.box.sdk.BoxCollaboration.Role-java.lang.Boolean-java.lang.Boolean-java.util.Date-java.lang.Boolean- + +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-- + +Create Metadata +--------------- + +Metadata can be created on a folder by calling +[`createMetadata(Metadata metadata)`][create-metadata], +[`createMetadata(String templateName, Metadata metadata)`][create-metadata-2], or +[`createMetadata(String templateName, String scope, Metadata metadata)`][create-metadata-3] + + +```java +BoxFolder folder = new BoxFolder(api, "id"); +folder.createMetadata(new Metadata().add("/foo", "bar")); +``` + +Note: This method will only succeed if the provided metadata template is not currently applied to the folder, otherwise +it will fail with a Conflict error. To get to know how to edit existing metadata please +go to [set metadata](#set-metadata) and [update metadata](#update-metadata) sections. + +[create-metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#createMetadata-com.box.sdk.Metadata- +[create-metadata-2]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#createMetadata-java.lang.String-com.box.sdk.Metadata- +[create-metadata-3]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#createMetadata-java.lang.String-java.lang.String-com.box.sdk.Metadata- + +Set Metadata +------------ + +To set metadata on a folder, call [`setMetadata(String templateName, String scope, Metadata metadata)`][set-metadata]. +This method will try to create provided metadata on a folder. However, if metadata has already been applied to this folder, +it will overwrite values of metadata keys specified in the `metadata` parameter. The metadata keys not specified in +the `metadata` parameter will remain unchanged. + +```java +BoxFolder folder = new BoxFolder(api, "id"); +folder.setMetadata("test_template", "enterprise", new Metadata().add("/foo", "bar")); +``` + +Note: If you want to set new metadata on a folder including hard reset of the current metadata +(also removing keys not specified in the `metadata` param): +first delete metadata as specified in [delete metadata](#delete-metadata) section and then set new metadata again. + +[set-metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#setMetadata-java.lang.String-java.lang.String-com.box.sdk.Metadata- + +Get Metadata +------------ + +Retrieve a folder's metadata by calling [`getMetadata()`][get-metadata], +[`getMetadata(String templateName)`][get-metadata-2], or +[`getMetadata(String templateName, String scope)`][get-metadata-3]. +These methods return a [`Metadata`][metadata] object, which allows access to metadata values. + + +```java +BoxFolder folder = new BoxFolder(api, "id"); +Metadata metadata = folder.getMetadata(); + +// Unknown type metadata field, you can test for type or try to get as any type +JsonValue unknownValue = metadata.getValue("/someField"); + +// String or Enum metadata fields +String stringValue = metadata.getString("/author"); + +// Float metadata fields can be interpreted as any numeric type +float floatValue = metadata.getFloat("/price"); + +// Date metadata fields +Date dateValue = metadata.getDate("/deadline"); +``` + +[metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/Metadata.html +[get-metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getMetadata-- +[get-metadata-2]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getMetadata-java.lang.String- +[get-metadata-3]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getMetadata-java.lang.String-java.lang.String- + +Update Metadata +--------------- + +Update a folder's metadata by calling [`updateMetadata(Metadata properties)`][update-metadata]. + +Note: This method will only succeed if the provided metadata template has already been applied to the folder. If the folder +does not have existing metadata, this method will fail with a Not Found error. This is useful in cases where you know +the folder will already have metadata applied, since it will save an API call compared to `setMetadata()`. + + +```java +BoxFolder folder = new BoxFolder(api, "id"); +folder.updateMetadata(new Metadata().add("/foo", "bar")); +``` + +Also, it is possible to add multi-select fields for your folder metadata by calling +[`updateMetadata(Metadata properties)`][update-metadata] with a list of values. + +```java +BoxFolder folder = new BoxFolder(api, "id"); +List valueList = new ArrayList(); +valueList.add("bar"); +valueList.add("qux"); +folder.updateMetadata(new Metadata().add("/foo", valueList)); +``` + +If you wanted to replace all selected fields for a specified key you can use the +[`replace(String key, List values)`][replace-metadata]. + +```java +BoxFolder folder = new BoxFolder(api, "id"); +List valueList = new ArrayList(); +valueList.add("bar"); +valueList.add("qux"); +folder.updateMetadata(new Metadata().replace("/foo", valueList)); +``` + +[update-metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#updateMetadata-com.box.sdk.Metadata- +[replace-metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/Metadata.html#replace-java.lang.String-java.util.List- + +Delete Metadata +--------------- + +A folder's metadata can be deleted by calling +[`deleteMetadata()`][delete-metadata], +[`deleteMetadata(String templateName)`][delete-metadata-2], or +[`deleteMetadata(String templateName, String scope)`][delete-metadata-3]. + + +```java +BoxFolder folder = new BoxFolder(api, "id"); +folder.deleteMetadata("myMetadataTemplate"); +``` + +[delete-metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#deleteMetadata-- +[delete-metadata-2]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#deleteMetadata-java.lang.String- +[delete-metadata-3]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#deleteMetadata-java.lang.String-java.lang.String- + +Get All Metadata on Folder +------------------------- + +[`getAllMetadata()`][get-all-metadata] method will return an iterable that will page through all of the metadata associated with the folder. + + +```java +BoxFolder file = new BoxFolder(api, "id"); +Iterable metadataList = folder.getAllMetadata(); +for (Metadata metadata : metadataList) { + // Do something with the metadata. +} +``` + +[get-all-metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getAllMetadata-java.lang.String...- + +Get Metadata for Multiple Files +------------------------------- + +When fetching a large number of items, for example the items in a folder, it would +often be impractical to fetch the metadata for each of those items individually. +Instead, you can get the metadata for all of the items in a single API call by +requesting the `metadata` field on those items: + +> __Note:__ The field name should have the form `metadata..` + +```java +BoxFolder root = BoxFolder.getRootFolder(); +Iterable itemsInFolder = root.getChildren("metadata.global.properties") +for (BoxItem.Info itemInfo : itemsInFolder) { + if (itemInfo instanceof BoxFile.Info) { + BoxFile.Info fileInfo = (BoxFile.Info) itemInfo; + Metadata itemMetadata = fileInfo.getMetadata("properties", "global"); + } else if (itemInfo instanceof BoxFolder.Info) { + BoxFolder.Info folderInfo = (BoxFolder.Info) itemInfo; + Metadata itemMetadata = folderInfo.getMetadata("properties", "global"); + } +} +``` + +Set Classification on Folder +---------------------------- + +Calling the [`setClassification(String classificationType)`][set-classification] method on a folder will add a +classification template on the folder. This method will return the classification type applied on the folder. The +classification types include `Public`, `Internal`, and `Confidential`. `Public` being the most available permission, +`Internal` which restricts the specified file to company and collaborators only, and finally, `Confidential`, which +is for collaborators only. + +```java +BoxFolder folder = new BoxFolder(api, "id"); +String classificationType = folder.setClassification("Public"); +``` + +It is important to note that this call will attempt to create a classification on the folder first, if one already +exists then it will do the update. If you already know that a classification exists on the folder and would like to save +an API call, we encourage you to use the [`updateClassification(String classificationType)`][update-classification] +method. + +```java +BoxFolder folder = new BoxFolder(api, "id"); +String classificationType = folder.updateClassification("Public"); +``` + +[set-classification]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#setClassification-java.lang.String...- +[update-classification]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#updateClassification-java.lang.String...- + +Get Classification on Folder +---------------------------- + +To retrieve the classification assigned on the folder, use the [`getClassification()`][get-classification] method. This +will return the classification type on the folder. + +```java +BoxFolder folder = new BoxFolder(api, "id"); +String classificationType = folder.getClassification(); +``` + +[get-classification]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getClassification-java.lang.String...- + +Remove Classification on Folder +------------------------------- + +To remove classification from the folder, use the [`deleteClassification()`][delete-classification] method. + +```java +BoxFolder folder = new BoxFolder(api, "id"); +folder.deleteClassification(); +``` + +[delete-classification]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#deleteClassification-- + +Create Cascade Policy On Folder +------------------------------- + +To set a metadata policy, which applies metadata values on a folder to new items in the folder, call +[`BoxFolder.addMetadataCascadePolicy(String scope, String template)`][create-cascade-policy-on-folder]. + +```java +String scope = "global"; +String templateKey = "template"; +String folderId = "12345"; +BoxFolder folder = new BoxFolder(api, folderId); +BoxMetadataCascadePolicy.Info cascadePolicyInfo = folder.addMetadataCascadePolicy(scope, template); +``` + +[create-cascade-policy-on-folder]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#addMetadataCascadePolicy-java.lang.String-java.lang.String- + +Get a Cascade Policy's Information +---------------------------------- + +To retrieve information about a specific metadata cascade policy, call +[`getInfo()`][get-info] + + +```java +String cascadePolicyID = "1234"; +BoxMetadataCascadePolicy metadataCascadePolicy = new BoxMetadataCascadePolicy(api, cascadePolicyID); +BoxMetadataCascadePolicy.Info metadataCascadePolicyInfo = metadataCascadePolicy.getInfo(); +``` + +[get-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxMetadataCascadePolicy.html#getInfo-- + +Get All Cascade Policies on Folder +---------------------------------- + +To get a list of all cascade policies on a folder, which show the metadata templates that are being applied to all +items in the folder, call [`getMetadataCascadePolicies()`][get-all] on that folder. + + +```java +String folderID = "2222"; +BoxFolder folder = new BoxFolder(api, folderID); +Iterable metadataCascadePolicies = folder.getMetadataCascadePolicies(); +for (BoxMetadataCascadePolicy.Info policyInfo : metadataCascadePolicies) { + // take action on policy here +} +``` + +You can also call [`getMetadataCascadePolicies(String enterpriseID, int limit, String... fields)`][get-all-with-limit] +and set the `enterpriseID` option to retrieve metadata cascade policies from another enterprise. + +```java +String folderID = "2222"; +String enterpriseID = "3333"; +int limit = 50; +BoxFolder folder = new BoxFolder(api, folderID); +Iterable metadataCascadePolicies = folder.getMetadataCascadePolicies(enterpriseID, limit); +for (BoxMetadataCascadePolicy.Info policyInfo : metadataCascadePolicies) { + // take action on policy here +} +``` + +[get-all]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getMetadataCascadePolicies-- +[get-all-with-limit]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getMetadataCascadePolicies-java.lang.String-int- + +Force Apply Cascade Policy on Folder +------------------------------------ + +To force apply a metadata template policy and apply metadata values to all existing items in an affected folder, call +[`forceApply(String conflictResolution)`][force-apply] with the conflict resolution method for dealing with items that already have a metadata value that conflicts with the folder. Specifying a resolution value of `none` will preserve the existing values on items, and specifying `overwrite` will overwrite values on items in the folder with the metadata value from the folder. + + +```java +String cascadePolicyID = "e4392a41-7de5-4232-bdf7-15e0d6bba067"; +BoxMetadataCascadePolicy policy = new BoxMetadataCascadePolicy(api, cascadePolicyID); +policy.forceApply("none"); +``` + +[force-apply]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxMetadataCascadePolicy.html#forceApply-java.lang.String- + +Delete Cascade Policy +--------------------- + +To remove a cascade policy and stop applying metadata from a folder to items in the folder, +call [`delete()`][delete-cascade-policy]. + + +```java +String cascadePolicyID = "e4392a41-7de5-4232-bdf7-15e0d6bba067"; +BoxMetadataCascadePolicy policyToDelete = new BoxMetadataCascadePolicy(api, cascadePolicyID); +policyToDelete.delete(); +``` + +[delete-cascade-policy]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxMetadataCascadePolicy.html#delete-- + +Lock a Folder +----------------------------- + +To lock a folder and prevent it from being moved and/or deleted, call [`lock()`][lock] on a folder. + +```java +BoxFolder folder = new BoxFolder(api, "id"); +FolderLock.Info folderLock = folder.lock(); +``` + +[lock]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#lock-- + +Get All Locks on a Folder +----------------------------- + +To get all locks on a folder, call [`getlock()`][get-locks] on folder. + +```java +BoxFolder folder = new BoxFolder(this.api, "id"); +Iterable locks = folder.getLocks(); +for (BoxFolderLock.Info lockInfo : locks) { + // Do something with each lockInfo here +} +``` + +[get-locks]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getLocks-- + +Delete a Lock on a Folder +----------------------------- + +To delete a lock on a folder, call [`delete()`][delete-lock] on a BoxFolderLock object. This cannot be called on a BoxFolder object. + +```java +BoxFolderLock folderLock = new BoxFolderLock(this.api, "folderLockID"); +folderLock.delete(); +``` + +[delete-lock]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolderLock.html#delete-- diff --git a/docs/sdk/groups.md b/docs/sdk/groups.md new file mode 100644 index 000000000..7d5113e20 --- /dev/null +++ b/docs/sdk/groups.md @@ -0,0 +1,218 @@ +Groups +====== + +Groups are sets of users that can be used in collaborations. + + + + + +- [Get All Groups](#get-all-groups) +- [Create a Group](#create-a-group) +- [Get Information About a Group](#get-information-about-a-group) +- [Update a Group](#update-a-group) +- [Delete a Group](#delete-a-group) +- [Get first page of a Group's Collaborations](#get-a-groups-collaborations) +- [Get all of a Group's Collaborations](#get-all-a-groups-collaborations) +- [Create Membership](#create-membership) +- [Get Membership](#get-membership) +- [Update Membership](#update-membership) +- [Delete Membership](#delete-membership) +- [Get Memberships for Group](#get-memberships-for-group) +- [Get Memberships for User](#get-memberships-for-user) + + + +Get All Groups +-------------- + +Calling the static [`getAllGroups(BoxAPIConnection api)`][get-all-groups] will +return an iterable that will page through all of the user's groups. + + +```java +Iterable groups = BoxGroup.getAllGroups(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 api, String name)`][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-java.lang.String- + +Get Information About a Group +----------------------------- + +To look up the information about a group by the group's ID, instantiate the [`BoxGroup`][group-object] +object with the group ID and then call [`getInfo()`][get-info-fields] on the group. You can optionally call +[`getInfo(String... fields)`][get-info-fields] to specify the list of fields to retrieve for the group, +which can result in reduced payload size. + + +```java +String groupID = "92875"; +BoxGroup.Info groupInfo = new BoxGroup(api, groupID).getInfo(); +``` + +[group-object]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroup.html +[get-info-fields]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroup.html#getInfo-java.lang.String...- + +Update a Group +-------------- + +To update a group, call [`updateInfo(BoxGroup.Info fieldsToUpdate)`][update-group] method. + + +```java +BoxGroup group = new BoxGroup(api, id); +BoxGroup.Info groupInfo = group.getInfo(); +groupInfo.setName("New name for My Group"); +group.updateInfo(groupInfo); +``` + +[update-group]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroup.html#updateInfo-com.box.sdk.BoxGroup.Info- + + +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-- + +Get first page of a Group's Collaborations +--------------------------- + +The first page of a group's collaborations can be retrieved by calling the [`getCollaborations()`][get-collaborations] method. + + +```java +BoxGroup group = new BoxGroup(api, "id"); +Collection collaborations = group.getCollaborations(); +``` + +[get-collaborations]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroup.html#getCollaborations-- + +Get all of a Group's Collaborations +--------------------------- + +All of a group's collaborations can be retrieved by calling the [`getAllCollaborations(String... fields)`][get-all-collaborations] method. +An iterable is returned to allow a user to iterate until the last collaboration. + +```java +BoxGroup group = new BoxGroup(api, "id"); +Iterable collaborations = group.getAllCollaborations(); +``` + +[get-all-collaborations]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroup.html#getAllCollaborations-- + +Create Membership +--------------- + +Membership for the group can be created by calling the +[`addMembership(BoxUser user)`][add-membership] and +[`addMembership(BoxUser user, BoxGroupMembership.GroupRole role)`][add-membership2] methods. + + +```java +BoxGroup group = new BoxGroup(api, "groupID"); +BoxUser user = new BoxUser(api, "userID"); +BoxGroupMembership.Info groupMembershipInfo = group.addMembership(user); +``` + +[add-membership]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroup.html#addMembership-com.box.sdk.BoxUser- +[add-membership2]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroup.html#addMembership-com.box.sdk.BoxUser-com.box.sdk.BoxGroupMembership.GroupRole- + +Get Membership +--------------- + +A groups membership can be retrieved by calling the [`BoxGroupMembership.getInfo()`][get-membership] method. + + +```java +BoxGroupMembership membership = new BoxGroupMembership(api, id); +BoxGroupMembership.Info groupMembershipInfo = membership.getInfo(); +``` + +[get-membership]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroupMembership.html#getInfo-- + +Update Membership +--------------- + +A groups membership can be updated by calling the +[`BoxGroupMembership.updateInfo(BoxGroupMembership.Info fieldsToUpdate)`][update-membership] method. + + +```java +BoxGroupMembership membership = new BoxGroupMembership(api, id); +BoxGroupMembership.Info info = membership.new Info(); +info.setGroupRole(BoxGroupMembership.GroupRole.MEMBER); +membership.updateInfo(info); +``` + +[update-membership]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroupMembership.html#updateInfo-com.box.sdk.BoxGroupMembership.Info- + +Delete Membership +--------------- + +A group can be deleted by calling the [`BoxGroupMembership.delete()`][delete-membership] method. + + +```java +BoxGroupMembership membership = new BoxGroupMembership(api, id); +membership.delete(); +``` + +[delete-membership]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroupMembership.html#delete-- + +Get Memberships for Group +--------------- + +Calling the [`getAllMemberships(String... fields)`][get-memberships-for-group] will return an iterable that will page through all of the group's memberships. +Optional parameters can be used to retrieve specific fields of the Group Membership object. + + +```java +BoxGroup group = new BoxGroup(api, id); +Iterable memberships = group.getAllMemberships(); +for (BoxGroupMembership.Info membershipInfo : memberships) { + // Do something with the membership. +} +``` + +[get-memberships-for-group]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroup.html#getAllMemberships-java.lang.String...- + +Get Memberships for User +--------------- + +Calling the [`BoxUser.getAllMemberships(String... fields)`][get-memberships-for-user] will return an iterable that will page through all of the user's memberships. +Optional parameters can be used to retrieve specific fields of the Group Membership object. + + +```java +BoxUser user = new BoxUser(api, id); +Iterable memberships = user.getAllMemberships(); +for (BoxGroupMembership.Info membershipInfo : memberships) { + // Do something with the membership. +} +``` + +[get-memberships-for-user]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getAllMemberships-java.lang.String...- diff --git a/docs/sdk/legal_holds.md b/docs/sdk/legal_holds.md new file mode 100644 index 000000000..189df8981 --- /dev/null +++ b/docs/sdk/legal_holds.md @@ -0,0 +1,206 @@ +Legal Holds Policy +================== + +Legal Hold Policy information describes the basic characteristics of the Policy, +such as name, description, and filter dates. + + + + + +- [Get Legal Hold Policy](#get-legal-hold-policy) +- [Get List of Legal Hold Policies](#get-list-of-legal-hold-policies) +- [Create New Legal Hold Policy](#create-new-legal-hold-policy) +- [Update Existing Legal Hold Policy](#update-existing-legal-hold-policy) +- [Delete Legal Hold Policy](#delete-legal-hold-policy) +- [Get Assignment](#get-assignment) +- [Get List of Assignments](#get-list-of-assignments) +- [Create New Assignment](#create-new-assignment) +- [Delete Assignment](#delete-assignment) +- [Get File Version Legal Hold](#get-file-version-legal-hold) +- [Get List of File Version Legal Holds](#get-list-of-file-version-legal-holds) + + + +Get Legal Hold Policy +--------------------- + +Calling [`getInfo(String...)`][get-info] will return a BoxLegalHoldPolicy.Info object +containing information about the legal hold policy. If necessary to retrieve +limited set of fields, it is possible to specify them using param. + + +```java +BoxLegalHoldPolicy policy = new BoxLegalHoldPolicy(api, id); +BoxLegalHoldPolicy.Info policyInfo = policy.getInfo(); +``` + +[get-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#getInfo-java.lang.String...- + +Get List of Legal Hold Policies +------------------------------- + +Calling the static [`getAll(BoxAPIConnection)`][get-list-of-legal-hold-policies] +will return an iterable that will page through all of the legal hold policies. +It is possible to specify name of legal hold policy, maximum number of items per +response and fields to retrieve by calling the static +[`getAll(BoxAPIConnection, String, int, String...)`][get-list-of-legal-hold-policies-with-fields] method. + + +```java +Iterable policies = BoxLegalHoldPolicy.getAll(api); +for (BoxLegalHoldPolicy.Info policyInfo : policies) { + // Do something with the legal hold policy. +} +``` + +[get-list-of-legal-hold-policies]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#getAll-com.box.sdk.BoxAPIConnection- +[get-list-of-legal-hold-policies-with-fields]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#getAll-com.box.sdk.BoxAPIConnection-java.lang.String-int-java.lang.String...- + +Create New Legal Hold Policy +---------------------------- + +The static [`create(BoxAPIConnection api, String name, String description, Date startDate, Date endDate)`][create-new-legal-hold-policy-with-dates] +method will let you create a new legal hold policy with a specified name, description, start and end dates. + + +```java +BoxLegalHoldPolicy.Info policyInfo = BoxLegalHoldPolicy.create(api, name, description, startedAt, endedAt); +``` + +If you wish to create an ongoing Legal Hold Policy with no end date and a description, call [`createOngoing(BoxAPIConnection api, String name, String description)`][create-ongoing]. + +```java +BoxLegalHoldPolicy.Info policyInfo = BoxLegalHoldPolicy.createOngoing(api, name, description); +``` + +[create-new-legal-hold-policy]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#create-com.box.sdk.BoxAPIConnection-java.lang.String- +[create-new-legal-hold-policy-with-dates]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#create-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String-java.util.Date-java.util.Date- +[create-ongoing]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#createOngoing-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String- + +Update Existing Legal Hold Policy +--------------------------------- + +Updating a legal hold policy's information is done by calling +[`updateInfo(BoxLegalHoldPolicy.Info fieldsToUpdate)`][update-info]. + + +```java +BoxLegalHoldPolicy policy = new BoxLegalHoldPolicy(api, id); +BoxLegalHoldPolicy.Info policyInfo = policy.new Info(); +info.setDescription("new description"); +info.setPolicyName("new policy name"); +policy.updateInfo(info); +``` + +[update-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#updateInfo-com.box.sdk.BoxLegalHoldPolicy.Info- + +Delete Legal Hold Policy +------------------------ + +A legal hold policy can be deleted by calling the [`delete()`][delete] method. + + +```java +BoxLegalHoldPolicy policy = new BoxLegalHoldPolicy(api, id); +policy.delete(); +``` + +[delete]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#delete-- + +Get Assignment +-------------- + +Calling [`getInfo(String... fields)`][get-assignment] will return a BoxLegalHoldAssignment.Info +object containing information about the legal hold policy assignment. + + +```java +BoxLegalHoldAssignment assignment = new BoxLegalHoldAssignment(api, id); +BoxLegalHoldAssignment.Info info = assignment.getInfo("assigned_by"); +``` + +[get-assignment]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldAssignment.html#getInfo-java.lang.String...- + +Get List of Assignments +-------------- + +Calling the static [`getAssignments(String... fields)`][get-list-of-assignments] will return +an iterable that will page through all of the assignments of the legal hold policy. +It is possible to specify filters for type and id, maximum number of items per single +response and fields to retrieve by calling +[`getAssignments(String type, String id, int limit, String... fields)`][get-list-of-assignments-with-params]. + + +```java +BoxLegalHoldPolicy policy = new BoxLegalHoldPolicy(api, id); +Iterable assignments = policy.getAssignments(BoxResource.getResourceType(BoxFolder.class), null, 50, "assigned_at"); +for (BoxLegalHoldAssignment.Info assignmentInfo : assignments) { + // Do something with the legal hold policy assignment. +} +``` + +[get-list-of-assignments]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#getAssignments-java.lang.String...- +[get-list-of-assignments-with-params]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#getAssignments-java.lang.String-java.lang.String-int-java.lang.String...- + +Create New Assignment +--------------------- + +To create new legal hold policy assignment call [`assignTo(BoxResource target)`][create-assignment] method. +Currently only BoxFile, BoxFileVersion, BoxFolder and BoxUser objects are supported as a parameter. + + +```java +BoxLegalHoldPolicy policy = new BoxLegalHoldPolicy(api, policyID); +BoxFolder folder = new BoxFolder(api, folderID); +policy.assignTo(folder); +``` + +[create-assignment]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#assignTo-com.box.sdk.BoxResource- + +Delete Assignment +-------------- + +A legal hold policy assignment can be deleted by calling the [`delete()`][delete-assignment] method +of BoxLegalHoldAssignment object. + + +```java +BoxLegalHoldAssignment assignment = new BoxLegalHoldAssignment(api, id); +assignment.delete(); +``` + +[delete-assignment]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldAssignment.html#delete-- + +Get File Version Legal Hold +-------------- + +Calling [`getInfo(String... fields)`][get-file-version-legal-hold] will return +a BoxFileVersionLegalHold.Info object containing information about the file version legal hold policy. + + +```java +BoxFileVersionLegalHold hold = new BoxFileVersionLegalHold(api, id); +hold.getInfo("file"); +``` + +[get-file-version-legal-hold]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileVersionLegalHold.html#getInfo-java.lang.String...- + +Get List of File Version Legal Holds +-------------- +To get an iterable with all non-deleted file version legal holds for current +legal hold policy, call [`getFileVersionHolds(String... fields)`][get-lest-of-file-version-legal-holds]. +It is possible to specify maximum number of items per single response by calling +[`getFileVersionHolds(int limit, String... fields)`][get-lest-of-file-version-legal-holds-with-limit]. + + +```java +BoxLegalHoldPolicy policy = new BoxLegalHoldPolicy(api, id); +Iterable fileVersionHolds = policy.getFileVersionHolds(); +for (BoxFileVersionLegalHold.Info fileVersionHold : fileVersionHolds) { + // Do something with the file version legal hold. +} +``` + +[get-lest-of-file-version-legal-holds]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#getFileVersionHolds-java.lang.String...- +[get-lest-of-file-version-legal-holds-with-limit]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#getFileVersionHolds-int-java.lang.String...- diff --git a/docs/sdk/logging.md b/docs/sdk/logging.md new file mode 100644 index 000000000..30f39a10f --- /dev/null +++ b/docs/sdk/logging.md @@ -0,0 +1,101 @@ +# Logging in SDK + +We are using `Java Util Logging` within Box Java SDK. You can read about details of this +approach [here](https://docs.oracle.com/javase/8/docs/technotes/guides/logging/overview.html). + +## Logging Levels + +We are using only few of the logging levels: + +- `FINE` - when logging debugging information, like success responses, +- `WARNING` - when API returned 4xx response code, +- `SEVERE` - when API returned 5XX response code. + +By default, the `Java Util Logging` prints to console output only messages that are logged at least at `INFO` level. You +can limit what is being logged by setting desired level on `com.box.sdk` logger like this: + +```java +import com.box.sdk.BoxLogger; + +BoxLogger.defaultLogger().setLevelToError(); +``` + +Example above will limit printed logs to `SEVERE` level only. + +### Getting FINE (ALL) logs printed + +By default `FINE` level logs are not printed to the console. There are several ways to do that. +One way is to define custom handler: + +```java +import java.util.logging.ConsoleHandler; +import java.util.logging.Handler; +import java.util.logging.Level; +import java.util.logging.Logger; + +Logger sdkLogger = BoxLogger.defaultLogger(); +Handler systemOut = new ConsoleHandler(); +// this handler will print any message to System.out +systemOut.setLevel(Level.ALL); +sdkLogger.addHandler(systemOut); +// allow sdk logger to print FINE logs +sdkLogger.setLevelToAll(); +// prevent logs from being processed by default Console handler +sdkLogger.setUseParentHandlers(false); +``` + +you can do this in your aplication initialization. + +### Turn logging off + +To disable logging use `BoxLogger.defaultLogger().turnLoggingOff()`. + +### Reset to default logging level + +To reset to default logging level use `BoxLogger.defaultLogger().resetToDefaultLevel()`. + + +## Putting SDK logs into application logs + +If you are using different logging solution like Log4J2 or Logstash you can use SLF4J and proper bridgge to get your +logs into desired solution. Below is an example of adding SDK logs into Logstash. First you will need to add +SLF4j and Logstash binaries: + +```groovy +implementation 'org.slf4j:jul-to-slf4j:1.7.32' // bridge from Java Util Logging to SLF4J API +implementation 'org.slf4j:slf4j-api:1.7.32' // define SLF4J API +implementation 'ch.qos.logback:logback-core:1.2.7' // use the Logback logging framework +implementation 'ch.qos.logback:logback-classic:1.2.7' // get bindings between SLF4J and Logback +``` + +Now when initializing application you will need to make Java Util Logging to use SLF4J. This sample is based on +description provided [here](http://www.slf4j.org/api/org/slf4j/bridge/SLF4JBridgeHandler.html): + +```java +import org.slf4j.bridge.SLF4JBridgeHandler; + +// Remove existing handlers attached to JUL root logger +SLF4JBridgeHandler.removeHandlersForRootLogger(); +// add SLF4JBridgeHandler to JUL's root logger +SLF4JBridgeHandler.install(); +``` + +Now all logs generated by SDK will be captured by Logback. If you want to see debug logs from SDK you will need to add +this configuration to your logback.xml file: + +```xml + +``` + +Below is a list of log levels used by SDK and coresponding Logback levels: + +| SDK | Logback | +:------:|:-------: +| ALL | ALL | +| OFF | OFF | +| FINE | DEBUG | +| INFO | INFO | +| WARN | WARN | +| SEVERE | ERROR | + +You can read more on java Util Logging to SLF4J bridge [here](http://www.slf4j.org/legacy.html#jul-to-slf4j). diff --git a/docs/sdk/metadata_template.md b/docs/sdk/metadata_template.md new file mode 100644 index 000000000..42d0d49b4 --- /dev/null +++ b/docs/sdk/metadata_template.md @@ -0,0 +1,189 @@ +Metadata Templates +================== + +Metadata that belongs to a file is grouped by templates. Templates allow the metadata service to provide a multitude of services, such as pre-defining sets of key:value pairs or schema enforcement on specific fields. + + + + + +- [Create Metadata Template](#create-metadata-template) +- [Update Metadata Template](#update-metadata-template) +- [Get Metadata Template](#get-metadata-template) + - [Get by scope and template key](#get-by-scope-and-template-key) + - [Get by ID](#get-by-id) +- [Get Enterprise Metadata Templates](#get-enterprise-metadata-templates) +- [Delete a Metadata Template](#delete-a-metadata-template) +- [Execute Metadata Query](#execute-metadata-query) + + + +Create Metadata Template +------------------------ + +The [`createMetadataTemplate(BoxAPIConnection api, String templateScope, String templateKey, String displayName, Boolean hidden, List fields)`][create-metadata-template] +method will create a metadata template schema. + +You can create custom metadata fields that will be associated with the metadata template. + + +```java +MetadataTemplate.Field metadataField = new MetadataTemplate.Field(); +metadataField.setType("string"); +metadataField.setKey("text"); +metadataField.setDisplayName("Text"); + +List fields = new ArrayList(); +fields.add(metadataField); + +MetadataTemplate template = MetadataTemplate.createMetadataTemplate(api, "enterprise", "CustomField", "Custom Field", false, fields); + +final JsonObject jsonObject = new JsonObject(); +jsonObject.add("text", "This is a test text"); + +Metadata metadata = new Metadata(jsonObject); +boxFile.createMetadata("CustomField", metadata); +``` + +[create-metadata-template]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#createMetadataTemplate-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String-java.lang.String-boolean-java.util.List- + +Update Metadata Template +------------------------ + +To update an existing metadata template, call the +[`updateMetadataTemplate(BoxAPIConnection api, String scope, String template, List fieldOperations)`][update-metadata-template] +method with the scope and key of the template, and the list of field operations to perform: + + +```java +List updates = new ArrayList(); + +String addCategoryFieldJSON = "{\"op\":\"addField\","\"data\":{" + + "\"displayName\":\"Category\",\"key\":\"category\",\"hidden\":false,\"type\":\"string\"}}"; +updates.add(new MetadataTemplate.FieldOperation(addCategoryFieldJSON)); + +String changeTemplateNameJSON = "{\"op\":\"editTemplate\",\"data\":{" + + "\"displayName\":\"My Metadata\"}}"; +updates.add(new MetadataTemplate.FieldOperation(changeTemplateNameJSON)); + +MetadataTemplate.updateMetadataTemplate(api, "enterprise", "myData", updates); +``` + +[update-metadata-template]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#updateMetadataTemplate-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String-java.util.List- + +Get Metadata Template +--------------------- + +### Get by scope and template key + +The [`getMetadataTemplate(BoxAPIConnection api)`][get-metadata-template-1] +method will return information about default metadata schema. Also, +[`getMetadataTemplate(BoxAPIConnection api, String templateKey)`][get-metadata-template-2] and +[`getMetadataTemplate(BoxAPIConnection api, String templateKey, String templateScope, String... fields)`][get-metadata-template-3] +can be used to set metadata template name, metadata scope and fields to retrieve. + + +```java +MetadataTemplate template = MetadataTemplate.getMetadataTemplate(api, "templateName"); +``` + +[get-metadata-template-1]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#getMetadataTemplate-com.box.sdk.BoxAPIConnection- +[get-metadata-template-2]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#getMetadataTemplate-com.box.sdk.BoxAPIConnection-java.lang.String- +[get-metadata-template-3]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#getMetadataTemplate-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String-java.lang.String...- + +### Get by ID + +The static [`MetadataTemplate.getMetadataTemplateByID(BoxAPIConnection api, String templateID)`][get-template-by-id] +method will return a specific metadata template. + + +```java +MetadataTemplate template = MetadataTemplate.getMetadataTemplateByID(api, "37c0204b-3fe1-4a32-b9da-f28e88f4c4c6"); +``` + +[get-template-by-id]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#getMetadataTemplateByID-com.box.sdk.BoxAPIConnection-java.lang.String- + +Get Enterprise Metadata Templates +--------------------------------- + +Calling the static +[`getEnterpriseMetadataTemplates(BoxAPIConnection api, String... fields)`][get-enterprise-metadata-1] +will return an iterable that will page through all metadata templates within a user's enterprise. +Also, [`getEnterpriseMetadataTemplates(String templateScope, BoxAPIConnection api, String... fields)`][get-enterprise-metadata-2] and +[`getEnterpriseMetadataTemplates(String templateScope, int limit, BoxAPIConnection api, String... fields)`][get-enterprise-metadata-3] +can be used to set metadata scope, limit of items per single response. + + +```java +Iterable templates = MetadataTemplate.getEnterpriseMetadataTemplates(api); +for (MetadataTemplate templateInfo : templates) { + // Do something with the metadata template. +} +``` + +To return the metadata templates available to all enterprises pass in the +`global` scope. + + +```java +Iterable templates = MetadataTemplate.getEnterpriseMetadataTemplates('global', api); +for (MetadataTemplate templateInfo : templates) { + // Do something with the metadata template. +} +``` + +[get-enterprise-metadata-1]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#getEnterpriseMetadataTemplates-com.box.sdk.BoxAPIConnection-java.lang.String...- +[get-enterprise-metadata-2]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#getEnterpriseMetadataTemplates-java.lang.String-com.box.sdk.BoxAPIConnection-java.lang.String...- +[get-enterprise-metadata-3]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#getEnterpriseMetadataTemplates-java.lang.String-int-com.box.sdk.BoxAPIConnection-java.lang.String...- + +Delete a Metadata Template +-------------------------- + +The [`deleteMetadataTemplate(BoxAPIConnection api, String scope, String template)`][delete-metadata-template] +method will remove a metadata template schema from an enterprise. + + +```java +MetadataTemplate.deleteMetadataTemplate(api, "enterprise", "templateName"); +``` + +[delete-metadata-template]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#deleteMetadataTemplate-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String- + +Execute Metadata Query +-------------------------- + +The [`executeMetadataQuery(BoxAPIConnection api, MetadataQuery queryBody)`][execute-metadata-query] method queries files and folders based on their metadata. + + +```java +String from = "enterprise_341532.test"; +String query = "testfield = :arg"; +String ancestorFolderId = "0"; +MetadataQuery.OrderBy primaryOrderBy = MetadataQuery.OrderBy.ascending("primarySortKey"); +MetadataQuery.OrderBy secondaryOrderBy = MetadataQuery.OrderBy.ascending("secondarySortKey"); + +MetadataQuery mQuery = new MetadataQuery(from); +mQuery.setQuery(query); +mQuery.setAncestorFolderId(ancestorFolderId); +mQuery.setOrderBy(primaryOrderBy, secondaryOrderBy); +mQuery.addParameter("arg", "test"); +mQuery.setFields("metadata.enterprise_341532.test.customField"); +BoxResourceIterable results = MetadataTemplate.executeMetadataQuery(api, mQuery); + +for (BoxItem.Info r: results) { + if (r instanceof BoxFile.Info) { + BoxFile.Info fileInfo = (BoxFile.Info) r; + Metadata fileMetadata = fileInfo.getMetadata("test", "enterprise_341532"); + String customFieldValue = fileMetadata.getString("/customField"); + System.out.println(customFieldValue); + } else if (r instanceof BoxFolder.Info) { + BoxFolder.Info folderInfo = (BoxFolder.Info) r; + Metadata folderMetadata = folderInfo.getMetadata("test", "enterprise_341532"); + String customFieldValue = folderMetadata.getString("/customField"); + System.out.println(customFieldValue); + } +} + +``` + +[execute-metadata-query]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#executeMetadataQuery-com.box.sdk.BoxAPIConnection-com.box.sdk.MetadataQuery- diff --git a/docs/sdk/overview.md b/docs/sdk/overview.md new file mode 100644 index 000000000..50c6e3518 --- /dev/null +++ b/docs/sdk/overview.md @@ -0,0 +1,193 @@ +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) +* [As-User](#as-user) +* [Suppressing Notifications](#suppressing-notifications) + +Authentication +-------------- + +The first step in using the SDK is always authenticating and connecting to the +API. The SDK does this through the [`BoxAPIConnection`][box-api-connection] 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`. + +[box-api-connection]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html + +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 + +As-User +------- + +As-User is used by enterprise administrators to make API calls for their managed +users. It can also be used by a Service Account to make API calls for managed users +or app users. + +As-User state is set on the [`BoxAPIConnection`][box-api-connection] instance with +[`asUser(String userID)`][as-user] and will be used for all requests made from that +API connection going forward, until the state is removed with [`asSelf()`][as-self]. + +```java +String userID = "12345"; +String fileID = "98765"; + +BoxAPIConnection api = new BoxAPIConnection("ACCESS_TOKEN"); + +BoxFile file = new BoxFile(api, fileID); + +// API call made as user associated with access token +BoxFile.Info info = file.getInfo(); + +api.asUser(userID); + +// API call made as user associated with userID +info = file.getInfo(); + +api.asSelf(); + +// API call made as user associated with access token again +BoxFile.Info info = file.getInfo(); +``` + +[as-user]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html#asUser-java.lang.String- +[as-self]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html#asSelf-- + +Suppressing 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. + +To turn on notification suppression for all calls made through a [`BoxAPIConnection`][box-api-connection] +instance, call [`suppressNotifications()`][suppress-notifications]. To re-enable notifications on an API +connection, call [`enableNotifications`][enable-notifications]. + +```java +String userID = "12345"; +String fileID = "98765"; +OutputStream downloadStream; + +BoxAPIConnection api = new BoxAPIConnection("ACCESS_TOKEN"); + +BoxFile file = new BoxFile(api, fileID); + +// Notifications are sent by default +downlaodStream = file.download(); + +api.suppressNotifications(); + +// Notifications are suppressed +downlaodStream = file.download(); + +api.enableNotifications(); + +// Notifications are sent again +downlaodStream = file.download(); +``` + +[suppress-notifications]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html#suppressNotifications-- +[enable-notifications]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html#enableNotifications-- diff --git a/docs/sdk/recent_items.md b/docs/sdk/recent_items.md new file mode 100644 index 000000000..fd13016b8 --- /dev/null +++ b/docs/sdk/recent_items.md @@ -0,0 +1,33 @@ +Recent Items +============ + +Recent Items returns information about files that have been accessed by a user not long ago. It keeps track of items +that were accessed either in the last 90 days or the last 1000 items accessed (both conditions must be met). + + + + + +- [Get a User's Recent Items](#get-a-users-recent-items) + + + + +Get a User's Recent Items +------------------------- + +Get a list of all recent items the user has by calling +[`BoxRecents.getRecentItems(BoxAPIConnection api, int limit, String... fields)`][get-recents]. +This returns an ordered iterable of the [`BoxRecentItem`][recent-item] records, +which describe which item the user interacted with, when they interacted with it, +and what type of interaction it was. Any `fields` specified relate to the items +themselves (e.g. the recent files and folders). + + +```java +// Get the latest 100 items the user has interacted with +Iterable recentItems = BoxRecents.getRecentItems(api, 100); +``` + +[get-recents]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRecents.html#getRecentItems-com.box.sdk.BoxAPIConnection-int-java.lang.String...- +[recent-item]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRecentItem.html diff --git a/docs/sdk/retention_policies.md b/docs/sdk/retention_policies.md new file mode 100644 index 000000000..5c8801e64 --- /dev/null +++ b/docs/sdk/retention_policies.md @@ -0,0 +1,320 @@ +Retention Policies +====== + +A retention policy blocks permanent deletion of content for a specified amount of time. Admins can create retention policies and then later assign them to specific folders or their entire enterprise. + + + + +- [Create Retention Policy](#create-retention-policy) + - [Indefinite Retention Policies](#indefinite-policies) + - [Finite Retention Policies](#finite-policies) + - [Optional parameters](#optional-parameters) +- [Get Retention Policy](#get-retention-policy) +- [Update Retention Policy](#update-retention-policy) +- [Get Retention Policies](#get-retention-policies) +- [Get Retention Policy Assignments](#get-retention-policy-assignments) +- [Create Retention Policy Assignment](#create-retention-policy-assignment) +- [Get Retention Policy Assignment](#get-retention-policy-assignment) +- [Delete Retention Policy Assignment](#delete-retention-policy-assignment) +- [Get File Version Retention](#get-file-version-retention) +- [Get File Version Retentions](#get-file-version-retentions) +- [Get Files Under Retention For Assignment](#get-files-under-retention-for-assignment) +- [Get File Versions Under Retention For Assignment](#get-file-versions-under-retention-for-assignment) +- [Extend retention for a file](#extend-retention-for-a-file) + + + + +## Create Retention Policy + +### Indefinite policies +The static [`createIndefinitePolicy(BoxAPIConnection api, String name)`][create-indefinite-retention-policy] +method will let you create a new indefinite retention policy with a specified name. + + +```java +BoxRetentionPolicy.createIndefinitePolicy(api, name); +``` + +### Finite policies +The static [`BoxRetentionPolicy.createFinitePolicy(com.box.sdk.BoxAPIConnection, java.lang.String, int, com.box.sdk.BoxRetentionPolicy.BoxRetentionPolicyAction)`][create-finite-retention-policy] +method will let you create a new finite retention policy with a specified name, +amount of time to apply the retention policy (in days) and a disposition action. + +```java +BoxRetentionPolicy.createFinitePolicy(api, name, length, PermanentlyDelete); +``` + +### Optional parameters +Both finite and indefinite policies allow you to specify optional parameters using the [`RetentionPolicyParams`][policy-params] +object. + +```java +String notifiedUserID = "12345"; +String description = "Policy to retain all reports"; +RetentionPolicyParams optionalParams = new RetentionPolicyParams(); +optionalParams.setCanOwnerExtendRetention(true); +optionalParams.setAreOwnersNotified(true); +optionalParams.setDescription(description); +optionalParams.addCustomNotificationRecipient(notifiedUserID); + +// Create indefinite policy with optional parameters +BoxRetentionPolicy.createIndefinitePolicy(api, "Retain Stuff Forever", optionalParams); + +// Create finite policy with optional parameters +BoxRetentionPolicy.createFinitePolicy(api, "Keep One Year", 365, BoxRetentionPolicyAction.RemoveRetention, optionalParams); +``` + +[create-indefinite-retention-policy]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#createIndefinitePolicy-com.box.sdk.BoxAPIConnection-java.lang.String- +[create-finite-retention-policy]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#createFinitePolicy-com.box.sdk.BoxAPIConnection-java.lang.String-int-com.box.sdk.BoxRetentionPolicy.BoxRetentionPolicyAction- +[policy-params]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/RetentionPolicyParams.html + +## Get Retention Policy + +Calling [`getInfo(String... fields)`][get-info] will return a +[`BoxRetentionPolicy.Info'][retention-policy-info] object containing information +about the retention policy. If necessary to retrieve limited set of fields, it +is possible to specify them using the `fields` parameter. + + +```java +// Get the policy name and status for a given retention policy +BoxRetentionPolicy policy = new BoxRetentionPolicy(api, id); +policy.getInfo("policy_name", "status"); +``` + +[get-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#getInfo-java.lang.String...- +[retention-policy-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.Info.html + +## Update Retention Policy + +Updating a retention policy's information is done by calling +[`updateInfo(BoxRetentionPolicy.Info fieldsToUpdate)`][update-info]. + + +```java +BoxRetentionPolicy policy = new BoxRetentionPolicy(api, id); +BoxRetentionPolicy.Info policyInfo = policy.new Info(); +policyInfo.setPolicyName("new policy name"); +policy.updateInfo(policyInfo); +``` + +[update-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#updateInfo-com.box.sdk.BoxRetentionPolicy.Info- + +## Get Retention Policies + +Calling the static [`getAll(BoxAPIConnection api, String... fields)`][get-retention-policies] +will return an iterable that will page through all of the retention policies. +It is possible to specify filter for the name of retention policy, filter for +the type of the policy, filter for the id of user, limit of items per single +response and fields to retrieve by calling the static +[`getAll(String name, String type, String userID, int limit, BoxAPIConnection api, String... fields)`][get-retention-policies-with-fields] +method. + + +```java +Iterable policies = BoxRetentionPolicy.getAll(api); +for (BoxRetentionPolicy.Info policyInfo : policies) { + // Do something with the retention policy. +} +``` + +[get-retention-policies]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#getAll-com.box.sdk.BoxAPIConnection-java.lang.String...- +[get-retention-policies-with-fields]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#getAll-java.lang.String-java.lang.String-java.lang.String-int-com.box.sdk.BoxAPIConnection-java.lang.String...- + +## Get Retention Policy Assignments + +Calling [`getAllAssignments(String... fields)`][get-all-assignments] will return +an iterable that will page through all of the assignments of the retention +policy. It is possible to specify maximum number of items per single response +and fields to retrieve by calling +[`getAllAssignments(int limit, String... fields)`][get-all-assignments-with-params]. +If it is necessary to retrieve only assignments of certain type, you can call +[`getFolderAssignments(int limit, String... fields)`][get-folder-assignments] or +[`getEnterpriseAssignments(int limit, String... fields)`][get-enterprise-assignments]. + + +```java +BoxRetentionPolicy policy = new BoxRetentionPolicy(api, id); +Iterable allAssignments = policy.getAllAssignments("assigned_by"); +Iterable folderAssignments = policy.getFolderAssignments(50, "assigned_by"); +Iterable enterpriseAssignments = policy.getEnterpriseAssignments(); +for (BoxRetentionPolicyAssignments.Info assignmentInfo : allAssignments) { + // Do something with the assignment. +} +for (BoxRetentionPolicyAssignments.Info assignmentInfo : folderAssignments) { + // Do something with the assignment. +} +for (BoxRetentionPolicyAssignments.Info assignmentInfo : enterpriseAssignments) { + // Do something with the assignment. +} +``` + +[get-all-assignments]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#getAllAssignments-java.lang.String...- +[get-all-assignments-with-params]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#getAllAssignments-int-java.lang.String...- +[get-folder-assignments]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#getFolderAssignments-int-java.lang.String...- +[get-enterprise-assignments]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#getEnterpriseAssignments-int-java.lang.String...- + +## Create Retention Policy Assignment + +To create new retention policy assignment call [`assignTo(BoxFolder target)`][create-assignment] method to assign the policy +to a specific folder, [`assignToEnterprise()`][create-assignment-to-enterprise] to assign the retention policy to the +entire enterprise, or [`assignToMetadataTemplate(String templateID, String startDateField, MetadataFieldFilter... filterFields)`][assign-to-metadata] +to assign the policy to items with a specific metadata template. + + +```java +// Assign the policy to the entire enterprise +BoxRetentionPolicy policy = new BoxRetentionPolicy(api, policyID); +policy.assignToEnterprise(); + +// Assign the policy to a single folder +BoxFolder folder = new BoxFolder(api, folderID); +policy.assignTo(folderID); + +// Assign the policy to all items with metadata template +String metadataTemplateID = "f0dce190-8106-43ca-9d67-7dce9b10a55e"; +policy.assignToMetadataTemplate(metadataTemplateID); +// You can also pass an optional `startDateField` parameter containing the ID of the metadata template's `date` field +String dateFieldID = "fb523725-04b1-4502-b871-eac305274533"; +policy.assignToMetadataTemplate(metadataTemplateID, dateFieldID); +``` + +[create-assignment]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#assignTo-com.box.sdk.BoxFolder- +[create-assignment-to-enterprise]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#assignToEnterprise-- +[assign-to-metadata]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#assignToMetadataTemplate-java.lang.String-com.box.sdk.MetadataFieldFilter- + +## Get Retention Policy Assignment + +Calling [`getInfo(String... fields)`][get-assignment] will return a +[`BoxRetentionPolicyAssignment.Info`][policy-assignment-info] object containing +information about the retention policy assignment. + + +```java +BoxRetentionPolicyAssignment assignment = new BoxRetentionPolicyAssignment(api, id); +BoxRetentionPolicyAssignment.Info assignmentInfo = assignment.getInfo("assigned_to"); +``` + +[get-assignment]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicyAssignment.html#getInfo-java.lang.String...- +[policy-assignment-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicyAssignment.Info.html + +## Delete Retention Policy Assignment + +To delete Retention Policy Assignment call [`delete()`][delete-assignment] method. + + +```java +BoxRetentionPolicyAssignment assignment = new BoxRetentionPolicyAssignment(api, id); +assignment.delete(); +``` + +[delete-assignment]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicyAssignment.html#delete() + + +## Get File Version Retention + +Calling [`getInfo(String... fields)`][get-file-version-retention] will return a +[`BoxFileVersionRetention.Info`][version-retention-info] object containing +information about the file version retention policy. + + +```java +BoxFileVersionRetention policy = new BoxFileVersionRetention(api, id); +BoxFileVersionRetention.Info policyInfo = policy.getInfo(); +``` + +[get-file-version-retention]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileVersionRetention.html#getInfo-java.lang.String...- +[version-retention-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileVersionRetention.Info.html + +## Get File Version Retentions + +To get an iterable with all file version retentions for the current retention +policy, call the static [`getAll(BoxAPIConnection api, String... fields)`][get-all-file-version-retentions] +method. It is possible to add filters to query passing a +[`BoxFileVersionRetention.QueryFilter`][query-filter] object as a parameter to +[`getRetentions(BoxAPIConnection api, BoxFileVersionRetention.QueryFilter filter, String... fields)`][get-all-file-version-retentions-with-filter]. + + +```java +BoxFileVersionRetention.QueryFilter filter = new BoxFileVersionRetention.QueryFilter() + .addFileID("0") + .addFileVersionID("1") + .addPolicyID("2") + .addDispositionAction(BoxRetentionPolicy.ACTION_PERMANENTLY_DELETE) + .addDispositionBefore(BoxDateFormat.parse("2016-09-15T13:15:35+0000")) + .addDispositionAfter(BoxDateFormat.parse("2014-09-15T13:15:35+0000")); +Iterable retentions + = BoxFileVersionRetention.getRetentions(api, filter, "file", "applied_at"); +for (BoxFileVersionRetention.Info retentionInfo : retentions) { + // Do something with the file version retention. +} +``` + +[get-all-file-version-retentions]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileVersionRetention.html#getAll-com.box.sdk.BoxAPIConnection-java.lang.String...- +[query-filter]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileVersionRetention.QueryFilter.html +[get-all-file-version-retentions-with-filter]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileVersionRetention.html#getRetentions-com.box.sdk.BoxAPIConnection-com.box.sdk.BoxFileVersionRetention.QueryFilter-java.lang.String...- + +## Get Files Under Retention For Assignment + +To get an iterable with all files under retention for assignment +policy, call the [`getFilesUnderRetention(BoxAPIConnection api, int limit, String... fields)`][get-files-under-retention-for-assignment] +method. This will return an interable with [`BoxFile.Info`][file] objects containing information about the files. + + +```java +BoxRetentionPolicyAssignment policyAssignment = new BoxRetentionPolicyAssignment(api, id); +Iterable filesUnderRetention = policyAssignment.getFilesUnderRetention(); +for (BoxFile.Info item : filesUnderRetention){ + // Do something with the files under retention. +} +``` + +[get-files-under-retention-for-assignment]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicyAssignment.html#getFilesUnderRetention-com.box.sdk.BoxAPIConnection-java.lang.String...- +[file]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.Info.html + +Get File Versions Under Retention For Assignment +------------------------------------------------ + +To get an iterable with all file versions under retention for assignment +policy, call the [`getFileVersionsUnderRetention(BoxAPIConnection api, int limit, String... fields)`][get-file-versions-under-retention-for-assignment] +method. This will return an interable with [`BoxFile.Info`][file] objects containing information about the file. +You can get version by calling [`BoxFile.Info#getVersion()`][file-version]. + + +```java +BoxRetentionPolicyAssignment policyAssignment = new BoxRetentionPolicyAssignment(api, id); +Iterable fileVersionsUnderRetention = policyAssignment.getFileVersionsUnderRetention(); +for (BoxFile.Info file : fileVersionsUnderRetention){ + BoxFileVersion version = file.getVersion(); + // Do something with the file version under retention. +} +``` + +[get-file-versions-under-retention-for-assignment]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicyAssignment.html#getFileVersionsUnderRetention-com.box.sdk.BoxAPIConnection-java.lang.String...- +[file-version]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileVersion.html + +## Extend retention for a file + +Once you create retention policy and assign it to a folder all files and subfolders will have same policy applied. +If you need to extend retention for some file you can change it's `dispositionAt` value: + +```java +BoxFile.Info info = someFile.getInfo(); +// to read current disposition date coming from retention policy +BoxFile.Info info = someFile.getInfo("disposition_at"); +Date currentDispositionDate = info.getDispositionAt(); + +// calculate new disposition date +Date dispositionAt = Date.from( + LocalDateTime.ofInstant(currentDispositionDate.toInstant(), ZoneId.of("Z")) + .plusDays(30) + .toInstant(UTC) +); + +// to change disposition date on a file you need to updateInfo +info.setDispositionAt(dispositionAt); +uploadedFile.updateInfo(info); + +``` diff --git a/docs/sdk/search.md b/docs/sdk/search.md new file mode 100644 index 000000000..54bc3abac --- /dev/null +++ b/docs/sdk/search.md @@ -0,0 +1,52 @@ +Search +====== + +Different examples of search which have been implemented in the example [SearchExamplesAsAppUser.java](https://github.com/box/box-java-sdk/blob/main/src/example/java/com/box/sdk/example/SearchExamplesAsAppUser.java) + +For more information refer to the +[Search API documentation](https://developer.box.com/v2.0/reference#searching-for-content). + + + + + +- [Search](#search) + + + +Search +------ + +A search can be performed in your Box instance with specified starting position with +[`searchRange(long offset, long limit, BoxSearchParameters queryParams)`][search] + +You can use the `limit` and `offset` parameters to page through the search results. + + +```java +// Find the first 10 files matching "taxes" +long offsetValue = 0; +long limitValue = 10; +BoxSearch boxSearch = new BoxSearch(api); +BoxSearchParameters searchParams = new BoxSearchParameters(); +searchParams.setQuery("taxes"); +searchParams.setType("file"); +PartialCollection searchResults = boxSearch.searchRange(offsetValue, limitValue, searchParams); +``` + +You can also sort the search results with the `sort` and `direction` flags passed into BoxSearch. This allows for the +order of items returned to be maintained. The `sort` field can only be set to `modified_at` currently. For direction you +can specify either `DESC` for descending order or `ASC` for ascending order to sort the results. + +```java +long offsetValue = 0; +long limitValue = 10; +BoxSearch boxSearch = new BoxSearch(api); +BoxSearchParameters searchParams = new BoxSearchParameters(); +searchParams.setQuery("taxes"); +searchParams.setSort("modified_at"); +searchParams.setDirection("DESC"); +PartialCollection searchResults = boxSearch.searchRange(offsetValue, limitValue, searchParams); +``` + +[search]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSearch.html#searchRange-long-long-com.box.sdk.BoxSearchParameters- diff --git a/docs/sdk/shared-items.md b/docs/sdk/shared-items.md new file mode 100644 index 000000000..33c580ac9 --- /dev/null +++ b/docs/sdk/shared-items.md @@ -0,0 +1,32 @@ +Shared Items +============ + +Shared Items represent files and folders on Box accessed via a shared link. + +* [Get a Shared Item](#get-a-shared-item) + +Get a Shared Item +----------------- + +To get the file or folder information for a shared link, you can call +[`BoxItem.getSharedItem(BoxAPIConnection api, String sharedLink)`][get-shared-item] +with the shared link to get information about the item behind it. + +```java +String sharedLink = "https://app.box.com/s/abcdefghijklmnopqrstuvwxyz123456"; +BoxItem.Info itemInfo = BoxItem.getSharedItem(api, sharedLink); +``` + +If the shared link is password-protected, call +[`BoxItem.getSharedItem(BoxAPIConnection api, String sharedLink, String password)`][get-shared-item-password] +with the shared link and password. + + +```java +String sharedLink = "https://app.box.com/s/abcdefghijklmnopqrstuvwxyz123456"; +String password = "foo"; +BoxItem.Info itemInfo = BoxItem.getSharedItem(api, sharedLink, password); +``` + +[get-shared-item]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxItem.html#getSharedItem-com.box.sdk.BoxAPIConnection-java.lang.String- +[get-shared-item-password]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxItem.html#getSharedItem-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String- diff --git a/docs/sdk/sign_requests.md b/docs/sdk/sign_requests.md new file mode 100644 index 000000000..1469867d5 --- /dev/null +++ b/docs/sdk/sign_requests.md @@ -0,0 +1,152 @@ +Sign Requests +================== + +Sign Requests are used to request e-signatures on documents from signers. +A Sign Request can refer to one or more Box Files and can be sent to one or more Box Sign Request Signers. + + + + +- [Create Sign Request](#create-sign-request) +- [Get all Sign Requests](#get-all-sign-requests) +- [Get Sign Request by ID](#get-sign-request-by-id) +- [Cancel Sign Request](#cancel-sign-request) +- [Resend Sign Request](#resend-sign-request) + + + +Create Sign Request +------------------------ + +The [`createSignRequest(BoxAPIConnection api, List signers, List files, String parentFolderId)`][create-sign-request] +method will create a Sign Request. + +You need to provide 1 to 10 files (from which the signing document will be created) and at least one signer to receive the Sign Request. You can use [`BoxSignRequestFile`][box-sign-request-file] +and [`BoxSignRequestSigner`][box-sign-request-signer] classes to provide the necessary data. + + +```java +List files = new ArrayList(); +BoxSignRequestFile file = new BoxSignRequestFile("12345"); +files.add(file); + +// you can also use specific version of the file +BoxFile file = new BoxFile(api, "12345"); +List versions = file.getVersions(); +BoxFileVersion firstVersion = versions.get(0); +BoxSignRequestFile file = new BoxSignRequestFile(firstVersion.getFileID(), firstVersion.getVersionID()); + +List signers = new ArrayList(); +BoxSignRequestSigner newSigner = new BoxSignRequestSigner("signer@mail.com"); +signers.add(newSigner); + +String destinationParentFolderId = "55555"; + +BoxSignRequest.Info signRequestInfo = BoxSignRequest.createSignRequest(api, files, + signers, destinationParentFolderId); +``` + +[`createSignRequest`][create-sign-request] allows you to specify optional parameters using the [`BoxSignRequestCreateParams`][sign-request-create-params] +object. + +```java +List files = new ArrayList(); + BoxSignRequestFile file = new BoxSignRequestFile("12345"); + files.add(file); + +List signers = new ArrayList(); +BoxSignRequestSigner newSigner = new BoxSignRequestSigner("signer@mail.com"); +signers.add(newSigner); + +String destinationParentFolderId = "55555"; + +BoxSignRequestCreateParams createParams = new BoxSignRequestCreateParams() + .setIsDocumentPreparationNeeded(true); + +BoxSignRequest.Info signRequestInfo = BoxSignRequest.createSignRequest(api, files, + signers, destinationParentFolderId, createParams); +``` + +If you set ```isDocumentPreparationNeeded``` flag to true, you need to visit ```prepareUrl``` before the Sign Request will be sent. +For more information on ```isDocumentPreparationNeeded``` and the other ```BoxSignRequestCreateParams``` available, please refer to the [developer documentation](https://developer.box.com/guides/box-sign/). + +[sign-request-create-params]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignRequestCreateParams.html +[create-sign-request]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignRequest.html#createSignRequest-com.box.sdk.BoxAPIConnection-java.util.List-java.util.List-java.lang.String- +[box-sign-request-signer]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignRequestSigner.html +[box-sign-request-file]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignRequestFile.html + +Get All Sign Requests +------------------------ + +Calling the static [`getAll(BoxAPIConnection api, String... fields)`][get-all-sign-requests] +will return an iterable that will page through all the Sign Requests. + +The static +[`getAll(int limit, BoxAPIConnection api, String... fields)`][get-all-sign-requests-with-fields] +method offers `limit` and `fields` parameters. The `limit` parameter specifies the maximum number of items to be returned in a single response. The `fields` parameter is used to specify what additional properties should be returned on the `BoxSignRequest.Info` objects. For more information on what `fields` are available, please refer to the [developer documentation](https://developer.box.com/guides/box-sign/). + + +```java +Iterable signRequests = BoxSignRequest.getAll(api); +for (BoxSignRequest.Info signRequestInfo : signRequests) { + // Do something with each `signRequestInfo`. +} +``` + +[get-all-sign-requests]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignRequest.html#getAll-com.box.sdk.BoxAPIConnection-java.lang.String...- +[get-all-sign-requests-with-fields]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignRequest.html#getAll-int-com.box.sdk.BoxAPIConnection-java.lang.String...- + +Get Sign Request by ID +------------------------ + +Calling [`getInfo(String fields ...)`][get-sign-request-by-id] will return a [`BoxSignRequest.Info`][box-sign-request-info] object +containing information about the Sign Request. +The `fields` parameter is used to specify what additional properties should be returned on the `BoxSignRequest.Info` objects. + + +```java +BoxSignRequest signRequest = new BoxSignRequest(api, id); +BoxSignRequest.Info signRequestInfo = signRequest.getInfo(); + +//using `fields` parameter +BoxSignRequest.Info signRequestInfoWithFields = signRequest.getInfo("status") + +``` + +[get-sign-request-by-id]:http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignRequest.html#getInfo-java.lang.String...- +[box-sign-request-info]:http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignRequest.Info.html + + +Cancel Sign Request +------------------------ + +Calling [`cancel()`][cancel-sign-request] will cancel a created Sign Request. + + +```java +BoxSignRequest signRequest = new BoxSignRequest(api, id); +BoxSignRequest.Info signRequestInfo = signRequest.getInfo(); + +signRequestInfo.cancel(); +``` + +[cancel-sign-request]:http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignRequest.html#cancel-- + + +Resend Sign Request +------------------------ + +Calling [`resend()`][resend-sign-request] will resend a Sign Request to all signers that have not signed it yet. +There is an 10-minute cooling-off period between re-sending reminder emails. If this method is called during the +cooling-off period, a [`BoxAPIException`][box-api-exception] will be thrown. + + +```java +BoxSignRequest signRequest = new BoxSignRequest(api, id); +BoxSignRequest.Info signRequestInfo = signRequest.getInfo(); + +signRequestInfo.resend(); +``` + +[resend-sign-request]:http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignRequest.html#resend-- +[box-api-exception]:http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIException.html diff --git a/docs/sdk/sign_templates.md b/docs/sdk/sign_templates.md new file mode 100644 index 000000000..9f2e5d192 --- /dev/null +++ b/docs/sdk/sign_templates.md @@ -0,0 +1,51 @@ +Sign Templates +================== + +Box Sign enables you to create templates so you can automatically add the same fields and formatting to requests for signature. With templates, you don't need to repetitively add the same fields to each request every time you send a new document for signature. + +Making and testing a template takes a few minutes, but when done it makes working with Box Sign easier and faster. + + + + +- [Get all Sign Templates](#get-all-sign-templates) +- [Get Sign Template by ID](#get-sign-template-by-id) + + + +Get All Sign Templates +------------------------ + +Calling the static [`getAll(BoxAPIConnection api)`][get-all-sign-templates] +will return an iterable that will page through all the Sign Templates. + +The static +[`getAll(BoxAPIConnection api, int limit)`][get-all-sign-templates-with-limit] +method offers `limit` parameter. The `limit` parameter specifies the maximum number of items to be returned in a single response. + + +```java +Iterable signTemplates = BoxSignTemplate.getAll(api); +for (BoxSignTemplate.Info signTemplateInfo : signTemplates) { + // Do something with each `signTemplateInfo`. +} +``` + +[get-all-sign-templates]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignTemplate.html#getAll-com.box.sdk.BoxAPIConnection- +[get-all-sign-templates-with-limit]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignTemplate.html#getAll-com.box.sdk.BoxAPIConnection-int- + +Get Sign Template by ID +------------------------ + +Calling [`getInfo()`][get-sign-template-by-id] will return a [`BoxSignTemplate.Info`][box-sign-template-info] object +containing information about the Sign Template. + + + +```java +BoxSignTemplate signTemplate = new BoxSignTemplate(api, id); +BoxSignTemplate.Info signTemplateInfo = signTemplate.getInfo(); +``` + +[get-sign-template-by-id]:http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignTemplate.html#getInfo- +[box-sign-template-info]:http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignTemplate.Info.html diff --git a/docs/sdk/storage_policy.md b/docs/sdk/storage_policy.md new file mode 100644 index 000000000..1da7c9baf --- /dev/null +++ b/docs/sdk/storage_policy.md @@ -0,0 +1,132 @@ +Storage Policy +============== + +Allows the enterprise admin to manage the Storage Policies for users in their +enterprise. Used for an enterprise to decide storage location for users based on +where they work/reside. + +* [Get Storage Policy](#get-storage-policy) +* [Get List of Storage Policies](#get-list-of-storage-policies) +* [Create New Assignment](#create-new-assignment) +* [Get Assignment](#get-assignment) +* [Get Assignment For Target](#get-assignment-for-target) +* [Update Existing Assignment](#update-existing-assignment) +* [Assign Storage Policy](#assign-storage-policy) +* [Delete Assignment](#delete-assignment) + +Get Storage Policy +------------------ + +Calling [`getInfo(String fields ...)`][get-info] will return BoxStoragePolicy.Info object +containing information about the storage policy. If necessary to retrieve +limited set of fields. It is possible to specify them using param. + + +```java +BoxStoragePolicy storagePolicy = new BoxStoragePolicy(api, id); +BoxStoragePolicy.Info storagePolicyInfo = storagePolicy.getInfo(); +``` + +[get-info]:http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxStoragePolicy.html#getInfo-- + +Get List of Storage Policies +---------------------------- + +Calling the static [`getAll(BoxAPIConnection api)`][get-list-of-storage-policies] +will return an iterable that will page through all of the storage policies. +It is possible to specify maximum number of items per response and fields to retrieve by +calling the static [`getAll(BoxAPIConnection api, int limit, String fields ...)`][get-list-of-storage-policies-with-fields] method. + + +```java +Iterable storagePolicies = BoxStoragePolicy.getAll(api); +for (BoxStoragePolicy.Info storagePolicyInfo : storagePolicies) { + //Do something with the storage policy. +} +``` + +[get-list-of-storage-policies]:http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxStoragePolicy.html#getAll-- +[get-list-of-storage-policies-with-fields]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxStoragePolicy.html#getAll-java.lang.String...- + +Create New Assignment +--------------------- + +To create new storage policy assignment call [`create(BoxAPIConnection api, String policyID, String userID)`][create] method. + + +```java +BoxStoragePolicyAssignment.Info assignmentInfo = BoxStoragePolicyAssignment.create(api, policyID, userID); +``` + +[create]:http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxStoragePolicyAssignment.html#create-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String- + +Update Existing Assignment +-------------------------- + +Updating a storage policy assignment information is done by calling +[`updateInfo(BoxStoragePolicyAssignment.Info updatedInfo)`][update-info]. + + +```java +BoxStoragePolicyAssignment storagePolicyAssignment = new BoxStoragePolicyAssignment(api, "ASSIGNMENT_ID"); +BoxStoragePolicyAssignment.Info assignmentInfo = storagePolicyAssignment.new Info(); +assignmentInfo.setStoragePolicyID("NEW_STORAGE_POLICY_ID"); +storagePolicyAssignment.updateInfo(assignmentInfo); +``` + +[update-info]:http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxStoragePolicyAssignment.html#updateInfo-com.box.sdk.BoxStoragePolicyAssignment.Info- + +Get Assignment +-------------- + +Calling [`getInfo(String fields ...)`][get-assignment] will return a BoxStoragePolicyAssignment.Info object containing information +about the storage policy assignment. + + +```java +BoxStoragePolicyAssignment storagePolicyAssignment = new BoxStoragePolicyAssignment(api, id); +BoxStoragePolicyAssignment.Info assignmentInfo = storagePolicyAssignment.getInfo(); +``` + +[get-assignment]:http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxStoragePolicyAssignment.html#getInfo-- + +Get Assignment for Target +------------------------- + +Calling [`getAssignmentForTarget(BoxAPIConnection api, String resolvedForType, String resolvedForID)`][get-assignment-for-target] will return a BoxStorageAssignment.Info +object containing information about the storage policy assignment. + + +```java +BoxStoragePolicyAssignment.Info assignmentInfo = BoxStoragePolicyAssignment.getAssignmentForTarget(api, "user", "1234") +``` + +[get-assignment-for-target]:http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxStoragePolicyAssignment.html#getAssignmentForTarget-com.box.BoxAPIConnection-java.lang.String-java.lang.String- + +Assign Storage Policy +--------------------- + +Calling [`assign(BoxAPIConnection api, String storagePolicyID, String userID)`][assign] will check if this user already has storage policy assigned to them. If not then a new +this user will be assigned the specified storage policy. + + +```java +BoxStoragePolicyAssignment.Info assignmentInfo = BoxStoragePolicyAssignment.assign(api, "1234", "5678"); +``` + +[assign]:http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxStoragePolicyAssigbment.html#assign-com.box.BoxAPIConnection-java.lang.String-java.lang.String- + +Delete Assignment +----------------- + +Calling [`delete()`][delete] will remove the storage policy assignment from the user. + + +```java +BoxStoragePolicyAssignment assignment = new BoxStoragePolicyAssignment(api, "dXNlcl8xMjM0"); +assignment.delete(); +``` + +[delete]:http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxStoragePolicyAssignment.html#delete-- + + diff --git a/docs/sdk/tasks.md b/docs/sdk/tasks.md new file mode 100644 index 000000000..de1927f14 --- /dev/null +++ b/docs/sdk/tasks.md @@ -0,0 +1,182 @@ +Tasks +===== + +Task objects represent a user-created task on a file. + + + + + +- [Get a Task's Information](#get-a-tasks-information) +- [Get the Tasks on a File](#get-the-tasks-on-a-file) +- [Add a Task to a File](#add-a-task-to-a-file) +- [Update a Task's Information](#update-a-tasks-information) +- [Delete a Task](#delete-a-task) +- [Get a Task's Assignments](#get-a-tasks-assignments) +- [Get Information About a Task Assignment](#get-information-about-a-task-assignment) +- [Add a Task Assignment](#add-a-task-assignment) +- [Delete a Task Assignment](#delete-a-task-assignment) +- [Update a Task Assignment](#update-a-task-assignment) + + + +Get a Task's Information +------------------------ + +Calling [`getInfo()`][get-info] on a task returns a snapshot of the task's +info. + + +```java +BoxTask task = new BoxTask(api, "id"); +BoxTask.Info info = task.getInfo(); +``` + +[get-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTask.html#getInfo-- + +Get the Tasks on a File +----------------------- + +You can get all of the tasks on a file by calling the +[`getTasks()`][get-tasks] method. + + +```java +BoxFile file = new BoxFile(api, "id"); +List tasks = file.getTasks(); +``` + +[get-tasks]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getTasks-- + +Add a Task to a File +-------------------- + +A task can be added to a file with the +[`addTask(BoxTask.Action action, String message, Date dueAt)`][add-task] method. + + +```java +BoxFile file = new BoxFile(api, "id"); +Date dueAt = new Date(); +file.addTask(BoxTask.Action.REVIEW, "Please review this file.", dueAt); +``` + +[add-task]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#addTask-com.box.sdk.BoxTask.Action-java.lang.String-java.util.Date- + +Update a Task's Information +--------------------------- + +The message of a task can be changed with the +[`updateInfo(BoxTask.Info fieldsToUpdate)`][update-info] method. + + +```java +BoxTask task = new BoxTask(api, "id"); +BoxTask.Info info = task.new Info(); +info.setMessage("An edited message."); +task.updateInfo(info); +``` + +[update-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTask.html#updateInfo-com.box.sdk.BoxTask.Info- + +Delete a Task +------------- + +A task can be deleted with the [`delete()`][delete] method. + + +```java +BoxTask task = new BoxTask(api, "id"); +task.delete(); +``` + +[delete]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxTask.html#delete-- + +Get a Task's Assignments +------------------------ + +Retreive a tasks assignments with the [`getAssignments()`][get-assignments] method. + + +```java +BoxTask task = new BoxTask(api, "id"); +task.getAssignments(); +``` + +[get-assignments]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxTask.html#getAssignments-- + +Get Information About a Task Assignment +--------------------------------------- + +To look up information about a task assignment by its ID, instantiate the +[`BoxTaskAssignment`][task-assignment-object] object with the ID, and call [`getInfo()`][get-assignment-info] +on the assignment. To retrieve only specific fields on the task assignment, call +[`getInfo(String... fields)`][get-assignment-fields] with the fields to retrieve. + + +```java +String assignmentID = "4256974"; +BoxTaskAssignment.Info assignmentInfo = new BoxTaskAssignment(api, assignmentID).getInfo(); +``` + +[task-assignment-object]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTaskAssignment.html +[get-assignment-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTaskAssignment.html#getInfo-- +[get-assignment-fields]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTaskAssignment.html#getInfo-java.lang.String...- + +Add a Task Assignment +--------------------- + +An assignment can be added to a task with the +[`addAssignment(BoxUser assignee)`][add-assignment] method. + + +```java +BoxUser user = new BoxUser(api, "user-id") +BoxTask task = new BoxTask(api, "id"); +task.addAssignment(user); +``` + +[add-assignment]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTask.html#addAssignment-com.box.sdk.BoxUser- + +Delete a Task Assignment +------------------------ + +An assignment can be deleted from a task with the +[`delete()`][delete-assignment] method on a [`BoxTaskAssignment`][task-assignment-object] +instance. + + +```java +BoxTaskAssignment taskAssignment = new BoxTaskAssignment(api, "id"); +taskAssignment.delete(); +``` + +[delete-assignment]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTaskAssignment.html#delete-- + +Update a Task Assignment +------------------------ + +A task assignment can be updated with the +[`updateInfo(BoxTask.Info fieldsToUpdate)`][update-assignment] method. + +Updating the resolution state: + +```java +String assignmentID = "12345"; +BoxTaskAssignment taskAssignment = new BoxTaskAssignment(api, assignmentID); +BoxTaskAssignment.Info info = taskAssignment.getInfo(); +info.setResolutionState(BoxTaskAssignment.ResolutionState.APPROVED); +taskAssignment.updateInfo(info); +``` + +Updating the message: + +```java +String assignmentID = "12345"; +BoxTaskAssignment taskAssignment = new BoxTaskAssignment(api, assignmentID); +BoxTaskAssignment.Info info = taskAssignment.getInfo(); +info.setMessage("Please review the meeting notes"); +taskAssignment.updateInfo(info); +``` + +[update-assignment]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTaskAssignment.html#updateInfo-com.box.sdk.BoxTaskAssignment.Info- diff --git a/docs/sdk/terms_of_service.md b/docs/sdk/terms_of_service.md new file mode 100644 index 000000000..6ec68cc66 --- /dev/null +++ b/docs/sdk/terms_of_service.md @@ -0,0 +1,154 @@ +Terms of Service +================ + +Terms of Service allows Box Admins to configure a custom Terms of Service for end users to +accept/re-accept/decline for platform applications + + + + + +- [Terms of Service](#terms-of-service) + - [Create a Terms of Service](#create-a-terms-of-service) + - [Edit a Terms of Service](#edit-a-terms-of-service) + - [Get a Terms of Service](#get-a-terms-of-service) + - [Get All Terms of Services](#get-all-terms-of-services) + - [Accept or Decline a Terms of Service for New User](#accept-or-decline-a-terms-of-service-for-new-user) + - [Accept or Decline a Terms of Service for Existing User](#accept-or-decline-a-terms-of-service-for-existing-user) + - [Get User Status on a Terms of Service](#get-user-status-on-a-terms-of-service) + + + +Create a Terms of Service +------------------------- + +A terms of service can be created in an enterprise. Please note that only two can be created. One external +and one managed. If a terms of service already exists please use the update call to change the current +terms of service. + +You can create a custom terms of service by calling +[`create(BoxAPIConnection api, BoxTermsOfService.TermsOfServiceStatus status, BoxTermsOfService.TermsOfServiceType type, String text)`][createTermsOfService]. + + +```java +BoxTermsOfService.Info newTOS = BoxTermsOfService.create( + api, + BoxTermsOfService.TermsOfServiceStatus.ENABLED, + BoxTermsOfService.TermsOfServiceType.EXTERNAL, + "Terms of Service..." +); +``` + +[createTermsOfService]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTermsOfService.html#create-com.box.sdk.BoxAPIConnection-com.box.sdk.BoxTermsOfService.TermsOfServiceStatus-com.box.sdk.BoxTermsOfService.TermsOfServiceType-java.lang.String- + +Edit a Terms of Service +----------------------- + +You can update a terms of service status and text after you have created them by calling +[`updateInfo(BoxTermsOfService.Info fieldsToUpdate)`][update-terms-of-service] + + +```java +BoxTermsOfService termsOfService = new BoxTermsOfService(api, "tos-id"); +BoxTermsOfService.Info termsOfServiceInfo = termsOfService.new Info(); +termsOfServiceInfo.setStatus(BoxTermsOfService.TermsOfServiceStatus.DISABLED); +termsOfServiceInfo.setText("New Terms of Service Text"); +termsOfService.updateInfo(termsOfService); +``` + +[update-terms-of-service]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTermsOfService.html#updateInfo-com.box.sdk.BoxTermsOfService.Info- + +Get a Terms of Service +---------------------- + +You can retrieve a terms of service by providing the ID and calling +[`getInfo()`][getTermsOfServiceInfo]. + + +```java +BoxTermsOfService termsOfService = new BoxTermsOfService(api, "tos-id"); +BoxTermsOfService.Info tosInfo = termsOfService.getInfo(); +``` + +[getTermsOfServiceInfo]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTermsOfService.html#getInfo-- + +Get All Terms of Services +------------------------- + +You can also retrieve all terms of service in your enterprise by calling +[`getAllTermsOfServices(BoxAPIConnection api)`][get-all-terms-of-services1]. +This will return an iterable that will page through all of the enterprises terms of services. + + +```java +List termsOfServices = BoxTermsOfService.getAllTermsOfServices(api); +for(BoxTermsOfService.Info termsOfServiceInfo : termsOfServices){ + // Do something with the terms of service. +} +``` + +You can also filter by managed or external terms of service by calling +[`getAllTermsOfServices(BoxAPIConnection api, BoxTermsOfService.TermsOfServiceType type)`][get-all-terms-of-services2]. + +[get-all-terms-of-services1]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTermsOfService.html#getAllTermsOfServices-com.box.sdk.BoxAPIConnection- +[get-all-terms-of-services2]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTermsOfService.html#getAllTermsOfServices-com.box.sdk.BoxAPIConnection-com.box.sdk.BoxTermsOfService.TermsOfServiceType- + + +Accept or Decline a Terms of Service for New User +------------------------------------------------- + +For new users you can accept or decline a terms of service by calling +[`create(BoxAPIConnection api, String tosID, Boolean accepted, String userID)`][create-user-status] + + +```java +BoxTermsOfService.Info newUserStatus = BoxTermsOfServiceUserStatus.create(api, "tos-id", true, "user-id"); +``` + +You can only create a new user status on a terms of service if the user has never accepted/declined a terms of service. +If they have then you will need to make the update call. + +[create-user-status]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTermsOfServiceUserStatus.html#create-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.Boolean-java.lang.String- + +Accept or Decline a Terms of Service for Existing User +------------------------------------------------------ + +For an existing user you can accept or decline a terms of service by calling +[`updateInfo(BoxTermsOfService.Info fieldsToUpdate)`][update-user-status]. + + +```java +BoxTermsOfServiceUserStatus tosUserStatus = new BoxTermsOfServiceUserStatus(api, "tos-user-status-id"); +BoxTermOfServiceUserStatus.Info tosUserStatusInfo = tosUserStatus.new Info(); +tosUserStatusInfo.setStatus(newStatus); +tosUserStatus.updateInfo(tosUSerStatusInfo); +``` + +[update-user-status]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTermsOfServiceUserStatus.html#updateInfo-com.box.sdk.BoxTermsOfServiceUserStatus.Info- + +Get User Status on a Terms of Service +------------------------------------- + +You can retrieve the terms of service status for a user by calling +[`getInfo(BoxAPIConnection api, String tosID, String userID)`][get-user-status1] + + +```java +List tosUserStatusInfo = BoxTermsOfServiceUserStatus.getInfo(api, "tos-id", "user-id"); +for(BoxTermsOfServiceUserStatus.Info info : toUserStatusInfo){ + // Do something with the user status on terms of service. +} +``` + +Alternatively you can get the user status by the ID of the terms of service by +calling [`getInfo(BoxAPIConnection api, String tosID)`][get-user-status2]. + +```java +List tosUserStatusInfo = BoxTermsOfServiceUserStatus.getInfo(api, "tos-id"); +for(BoxTermsOfServiceUserStatus.Info info : toUserStatusInfo){ + // Do something with the user status on terms of service. +} +``` + +[get-user-status1]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTermsOfServiceUserStatus.html#getInfo-com.box.sdk.BoxAPIConnection-java.lang.String- +[get-user-status2]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTermsOfServiceUserStatus.html#getInfo-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String- diff --git a/docs/sdk/trash.md b/docs/sdk/trash.md new file mode 100644 index 000000000..ea4f83044 --- /dev/null +++ b/docs/sdk/trash.md @@ -0,0 +1,189 @@ +Trash +===== + +Under normal circumstances, when an item in Box is deleted, it is not actually erased immediately. Instead, it is +moved to the Trash. The Trash allows you to recover files and folders that have been deleted. By default, items in +the Trash will be purged after 30 days. + + + + + +- [Get Trashed Items](#get-trashed-items) +- [Get Trashed File Information](#get-trashed-file-information) +- [Get Trashed Folder Information](#get-trashed-folder-information) +- [Permanently Delete File From Trash](#permanently-delete-file-from-trash) +- [Permanently Delete Folder From Trash](#permanently-delete-folder-from-trash) +- [Restore a File from the Trash](#restore-a-file-from-the-trash) +- [Restore a Folder from the Trash](#restore-a-folder-from-the-trash) + + + +Get Trashed Items +----------------- + +The [`BoxTrash`][trash-object] implements `Iterable`, so to get +the collection of items currently in the trash, simply iterate over it. + + +```java +BoxTrash trash = new BoxTrash(api); +for (BoxItem.Info itemInfo : trash) { + // Process the item +} +``` + +Alternatively you can specify sort order, limit, use marker based pagination or specify which fields you want to extract with +[`BoxTrash#items`][trash-items]. + +To use sorting you have to use offset based pagination: +```java +BoxTrash trash = new BoxTrash(api); +Iterable trashEntries = trash.items( + SortParameters.ascending("name"), + PagingParameters.offset(0, 500) +); +for (BoxItem.Info trashEntry : trashEntries) { + // Process the item +} +``` +If you have a lot of items in trash and offset value is in tens of thousands it is better to use marker based pagination. +However, marker based pagination cannot be used with sorting. To disable sorting use `SortParameters.none()`: +```java +BoxTrash trash = new BoxTrash(api); +Iterable trashEntries = trash.items( + SortParameters.none(), + PagingParameters.marker(500) +); +for (BoxItem.Info trashEntry : trashEntries) { + // Process the item +} +``` + +[trash-object]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTrash.html +[trash-items]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTrash.html#items-com.box.sdk.SortParameters-com.box.sdk.PagingParameters-java.lang.String...- + +Get Trashed File Information +---------------------------- + +Ordinarily, trying to call [`getInfo()`][file-get-info] on a file that is in +the trash will return a 404 error. To get the information of a file in the +trash, you must instead call +[`BoxTrash#getFileInfo(String fileID)`][get-trashed-file] with the ID of the trashed file. You can optionally +pass a specific list of fields to retrieve to [`getFileInfo(String fileID, String... fields)`][get-trashed-file-fields], +which will return only the specified fields to reduce payload size. + + +```java +String fileID = "9873459"; +BoxTrash trash = new BoxTrash(api); +BoxFile.Info fileInfo = trash.getFileInfo(fileID); +``` +[file-get-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getInfo-java.lang.String...- +[get-trashed-file]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTrash.html#getFileInfo-java.lang.String- +[get-trashed-file-fields]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTrash.html#getFileInfo-java.lang.String-java.lang.String...- + +Get Trashed Folder Information +------------------------------ + +Ordinarily, trying to call [`getInfo()`][folder-get-info] on a folder that is in the trash will return a 404 error. +To get the information of a folder in the trash, you must instead call +[`BoxTrash#getFolderInfo(String fileID)`][get-trashed-folder] with the ID of the trashed folder. You can optionally +pass a specific list of fields to retrieve to +[`getFileInfo(String folderID, String... fields)`][get-trashed-folder-fields], which will return only the specified +fields to reduce payload size. + + +```java +String folderID = "2345343"; +BoxTrash trash = new BoxTrash(api); +BoxFolder.Info folderInfo = trash.getFolderInfo(folderInfo); +``` +[folders-get-info]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getInfo-java.lang.String...- +[get-trashed-folder]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTrash.html#getFolderInfo-java.lang.String- +[get-trashed-folder-fields]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTrash.html#getFolderInfo-java.lang.String-java.lang.String...- + + +Permanently Delete File From Trash +---------------------------------- + +To delete a file from the trash, call [`BoxTrash#deleteFile(String fileID)`][delete-file] with the ID of the file to +delete. + +> __Note:__ This will permanently delete the file, and cannot be undone. + + +```java +String fileID = "87398"; +BoxTrash trash = new BoxTrash(api); +trash.deleteFile(fileID); +``` + +[delete-file]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTrash.html#deleteFile-java.lang.String- + + +Permanently Delete Folder From Trash +---------------------------------- + +To delete a folder from the trash, call [`BoxTrash#deleteFolder(String fileID)`][delete-folder] with the ID of the +folder to delete. + +> __Note:__ This will permanently delete the folder, and cannot be undone. + + +```java +String folder = "123456"; +BoxTrash trash = new BoxTrash(api); +trash.deleteFolder(folderID); +``` + +[delete-folder]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTrash.html#deleteFolder-java.lang.String- + +Restore a File from the Trash +----------------------------- + +To restore a file from the trash, effectively undeleting it, call [`BoxTrash#restoreFile(String fileID)`][restore-file] +with the ID of the file. To avoid scenarios where the parent folder that previously contained the file is no longer available, +the user does not have permission to create items in that folder, or that folder has an item with the same name as the one +being restored; you can pass a new parent folder ID and/or file name to +[`BoxTrash#restoreFile(String fileID, String newName, String newParentID)`][restore-file-safe]. The new name +and parent will only be used if a conflict is encountered while trying to restore the file to its original location. + + +```java +String fileID = "125367"; +String newName = "Presentation 2018 ORIGINAL.pptx"; +String newParentID = "98765"; + +BoxTrash trash = new BoxTrash(api); +// Avoid conflicts at the original location +trash.restoreFile(fileID, newName, newParentID); +``` + +[restore-file]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTrash.html#restoreFile-java.lang.String- +[restore-file-safe]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTrash.html#restoreFile-java.lang.String-java.lang.String-java.lang.String- + +Restore a Folder from the Trash +------------------------------- + +To restore a folder from the trash, effectively undeleting it, call +[`BoxTrash#restoreFolder(String folderID)`][restore-folder] with the ID of the folder. To avoid scenarios where the +parent folder that previously contained the folder to be restored is no longer available, the user +does not have permission to create items in that folder, or that folder has an item with the same name as the one +being restored; you can pass a new parent folder ID and/or folder name to +[`BoxTrash#restoreFolder(String folderID, String newName, String newParentID)`][restore-folder-safe]. The new name +and parent will only be used if a conflict is encountered while trying to restore the folder to its original location. + + +```java +String folderID = "125367"; +String newName = "My Documents ORIGINAL"; +String newParentID = "98765"; + +BoxTrash trash = new BoxTrash(api); +// Avoid conflicts at the original location +trash.restoreFolder(folderID, newName, newParentID); +``` + +[restore-folder]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTrash.html#restoreFolder-java.lang.String- +[restore-folder-safe]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTrash.html#restoreFolder-java.lang.String-java.lang.String-java.lang.String- diff --git a/docs/sdk/upgrading.md b/docs/sdk/upgrading.md new file mode 100644 index 000000000..ed966930f --- /dev/null +++ b/docs/sdk/upgrading.md @@ -0,0 +1,116 @@ +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") +BoxJSONRequest request = new BoxJSONRequest(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/docs/sdk/users.md b/docs/sdk/users.md new file mode 100644 index 000000000..047dd478c --- /dev/null +++ b/docs/sdk/users.md @@ -0,0 +1,321 @@ +# Users + +Users represent an individual's account on Box. + + + + + +- [Get the Current User's Information](#get-the-current-users-information) +- [Get User Information](#get-user-information) +- [Get Avatar for a User](#get-avatar-for-a-user) +- [Add or update user avatar](#add-or-update-user-avatar) +- [Delete user avatar](#delete-user-avatar) +- [Create An Enterprise User](#create-an-enterprise-user) +- [Create An App User](#create-an-app-user) +- [Update User](#update-user) +- [Delete User](#delete-user) +- [Invite User](#invite-user) +- [Get Email Aliases](#get-email-aliases) +- [Add Email Alias](#add-email-alias) +- [Delete Email Alias](#delete-email-alias) +- [Get Enterprise Users](#get-enterprise-users) +- [Get Enterprise Users (Marker Pagination)](#get-enterprise-users-marker-pagination) +- [Get App Users By External App User ID](#get-app-users-by-external-app-user-id) +- [Get App Users By External App User ID (Marker Pagination)](#get-app-users-by-external-app-user-id-marker-pagination) +- [Move User's Folder](#move-users-folder) + + + +## Get the Current User's Information + +To get the current user, call the static +[`getCurrentUser(BoxAPIConnection api)`][get-current-user] method. +Then use [`getInfo(String... fields)`][get-info] to get information about the user. + + +```java +BoxUser user = BoxUser.getCurrentUser(api); +BoxUser.Info info = user.getInfo(); +``` + +[get-current-user]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getCurrentUser-com.box.sdk.BoxAPIConnection- +[get-info]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getInfo-java.lang.String...- + +## Get User Information + +To get information about a user, call the [`getInfo()`][get-info] method on the user object. + + +```java +String userID = "33333"; +BoxUser user = new BoxUser(api, userID); +BoxUser.Info userInfo = user.getInfo(); +``` + +## Get Avatar for a User + +To retrieve the avatar for a User, call the [`downloadAvatar(OutputStream stream)`][download-avatar] method on the user object. + + +```java +String userID = "33333"; +// some stream do download avatar +try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()){ + BoxUser user=new BoxUser(api,userID); + user.downloadAvatar(outputStream); +} catch (IOException e) { + throw new RuntimeException(e); +} +``` + +## Add or update user avatar + +To add or update the avatar for a User, call the [`uploadAvatar(File)`][upload-avatar-1] method on the user object. + + +```java +String userID = "33333"; +BoxUser user = new BoxUser(api, userID); +AvatarUploadResponse response = user.uploadAvatar(new File("path_to_avatar_file")); +``` +In return, you will get an object with links to several representations of an avatar within Box account. +Your image file should have correct extension, it is used to determine image type used in upload. +Supported formats are JPG and PNG. The image size cannot exceed 1024 * 1024 pixels or 1MB. + +You can upload avatart using `InputStream` with [`uploadAvatar(InputStream, String)`][upload-avatar-2]: + +```java +String userID = "33333"; +BoxUser user = new BoxUser(api, userID); +AvatarUploadResponse response = user.uploadAvatar(Files.newInputStream(Paths.get("path_to_avatar_file")), "file_name.jpeg"); +``` + +Both upload methods supports [`ProgressListener`][progress-listener]. + +## Delete user avatar + +To delete User avatar image use [`deleteAvatar()`][delete-avatar] method on the user object: + + +```java +String userID = "33333"; +BoxUser user = new BoxUser(api, userID); +user.deleteAvatar(); +``` + +[download-avatar]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#downloadAvatar-java.io.OutputStream- +[upload-avatar-1]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#uploadAvatar-java.io.File- +[upload-avatar-2]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#uploadAvatar-java.io.InputStream-java.lang.String- +[delete-avatar]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#deleteAvatar-- +[progress-listener]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/ProgressListener.html + +## Create An Enterprise User + +To create an enterprise user, call the +[`createEnterpriseUser(BoxAPIConnection api, String loginEmail, String userName, String... fields)`][create-enterprise-user]. +To pass additional optional parameters, use the +[`createEnterpriseUser(BoxAPIConnection api, String loginEmail, String userName, CreateUserParams options, String... fields)`][create-enterprise-user-2] +method. + + +```java +BoxUser.Info createdUserInfo = BoxUser.createEnterpriseUser(api, "user@example.com", "A User"); +``` + +[create-enterprise-user]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#createEnterpriseUser-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String-java.lang.String...- +[create-enterprise-user-2]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#createAppUser-com.box.sdk.BoxAPIConnection-java.lang.String-com.box.sdk.CreateUserParams-java.lang.String...- + +## Create An App User + +To create an app user, call the +[`createAppUser(BoxAPIConnection api, String userName, String... fields)`][create-app-user] method. +To pass additional optional parameters, use the +[`createAppUser(BoxAPIConnection api, String userName, CreateUserParams options, String... fields)`][create-app-user-2] method. + + +```java +BoxUser.Info createdUserInfo = BoxUser.createAppUser(api, "A User"); +``` + +```java +CreateUserParams params = new CreateUserParams(); +params.setExternalAppUserId("An Identifier Like Login"); +BoxUser.Info createdUserInfo = BoxUser.createAppUser(api, "A User", params); +``` + +[create-app-user]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#createAppUser-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String...- +[create-app-user-2]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#createAppUser-com.box.sdk.BoxAPIConnection-java.lang.String-com.box.sdk.CreateUserParams-java.lang.String...- + + +## Update User + +To update a user call the [`updateInfo(BoxUser.Info fieldsToUpdate, String... fields)`][update-info] method. + + +```java +BoxUser user = new BoxUser(api, "0"); +BoxUser.Info info = user.new Info(); +info.setName(name); +user.updateInfo(info); +``` + +[update-info]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#updateInfo-com.box.sdk.BoxUser.Info-java.lang.String...- + +## Delete User + +To delete a user call the [`delete(boolean notifyUser, boolean force)`][deleteWithParams] method or one that +uses API default parameters [`delete()][delete] + +The `notifyUser` determines whether the user should receive an email about the deletion, +and the `force` parameter will cause the user to be deleted even if they still have files +in their account. + + +```java +BoxUser user = new BoxUser(api, "0"); +user.delete(false, false); +``` + +[deleteWithParams]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#delete-boolean-boolean- +[delete]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#delete-- + +## Invite User + +To invite an existing user to join an Enterprise call the +[`inviteUser(String enterpriseID, String userEmail)`][invite] method. + + +```java +BoxUser user = new BoxUser(api, "0"); +user.invite("Enterprise ID", "Invited User Login"); +``` + +[invite]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#inviteUser-java.lang.String-java.lang.String- + +## Get Email Aliases + +To get a user's email aliases call the [`getEmailAliases()`][get-email-aliases] method. + + +```java +BoxUser user = new BoxUser(api, "0"); +Collection emailAliases = user.getEmailAliases(); +``` + +[get-email-aliases]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getEmailAliases-- + +## Add Email Alias + +To add an email alias for a user, call the +[`addEmailAlias(String emailAddress)`][add-email-alias] method. + + +```java +BoxUser user = new BoxUser(api, "0"); +user.addEmailAlias("user+alias@example.com"); +``` + +Enterprise admins can automatically confirm the new email alias by calling the +[`addEmailAlias(String emailAddress, boolean confirm)`][add-email-alias2] method: + +```java +BoxUser user = new BoxUser(api, "0"); +user.addEmailAlias("user+alias@eexample.com", true); +``` + +[add-email-alias]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#addEmailAlias-java.lang.String- +[add-email-alias2]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#addEmailAlias-java.lang.String-boolean- + +## Delete Email Alias + +To delete a users email alias call the +[`deleteEmailAlias(String emailAliasID)`][delete-email-alias] method. + + +```java +BoxUser user = new BoxUser(api, "0"); +user.deleteEmailAlias("123"); +``` + +[delete-email-alias]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#deleteEmailAlias-java.lang.String- + +## Get Enterprise Users + +To get an enterprise's users call the +[`getAllEnterpriseUsers(BoxAPIConnection api)`][get-all-enterprise-users], +[`getAllEnterpriseUsers(BoxAPIConnection api, String filterTerm, String... fields)`][get-all-enterprise-users-2], or +[`getAllEnterpriseOrExternalUsers(BoxAPIConnection api, String filterTerm, String... fields)`][get-all-enterprise-users-3] method. + + +```java +Iterable users = BoxUser.getAllEnterpriseUsers(api); +``` + +[get-all-enterprise-users]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getAllEnterpriseUsers-com.box.sdk.BoxAPIConnection- +[get-all-enterprise-users-2]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getAllEnterpriseUsers-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String...- +[get-all-enterprise-users-3]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getAllEnterpriseOrExternalUsers-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String...- + +## Get Enterprise Users (Marker Pagination) + +To get a list of all users in an enterprise, call the +[`getAllEnterpriseUsers(BoxAPIConnection api, boolean usemarker, String marker)`][get-all-enterprise-users], +[`getAllEnterpriseUsers(BoxAPIConnection api, String filterTerm, boolean usemarker, String marker, String... fields)`][get-all-enterprise-users-2], or +[`getAllEnterpriseOrExternalUsers(BoxAPIConnection api, String filterTerm, boolean usemarker, String marker, String... fields)`][get-all-enterprise-users-3] method. +To get a list of users starting from the first page of results, set the `usemarker` parameter as `true` and the `marker` parameter as `null`. If you would like to get the marker for the next page of results from the page the iterator is currently on, you must cast the iterable to `BoxResourseIterable` and call `getNextMarker()` on that iterable. For more information on marker pagination, look here: https://developer.box.com/en/guides/api-calls/pagination/marker-based/. + + +```java +Iterable users = BoxUser.getAllEnterpriseUsers(api, true, null); + +// Get marker +String marker = ((BoxResourceIterable) users).getNextMarker(); +``` + +[get-all-enterprise-users]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getAllEnterpriseUsers-com.box.sdk.BoxAPIConnection- +[get-all-enterprise-users-2]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getAllEnterpriseUsers-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String...- +[get-all-enterprise-users-3]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getAllEnterpriseOrExternalUsers-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String...- + +## Get App Users By External App User ID + +To get app user using external app user ID, call the +[`getAppUsersByExternalAppUserID(BoxAPIConnection api, String externalID, String... fields)`][get-app-users-by-external-app-user-id]. +This method allows you to easily associate Box app users with your application's +identifiers for those users. + +```java +Iterable users = BoxUser.getAppUsersByExternalAppUserID(api, "external_app_user_id"); +``` + +[get-app-users-by-external-app-user-id]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getAppUsersByExternalAppUserID-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String...- + +## Get App Users By External App User ID (Marker Pagination) + +To get app user using external app user ID, call the +[`getAppUsersByExternalAppUserID(BoxAPIConnection api, String externalID, boolean usemarker, String marker, String... fields)`][get-app-users-by-external-app-user-id]. +This method allows you to easily associate Box app users with your application's +identifiers for those users. To get a list of users starting from the first page of results, set the `usemarker` parameter as `true` and the `marker` parameter as `null`. If you would like to get the marker for the next page of results from the page the iterator is currently on, you must cast the iterable to `BoxResourseIterable` and call `getNextMarker()` on that iterable. For more information on marker pagination, look here: https://developer.box.com/en/guides/api-calls/pagination/marker-based/. + +```java +Iterable users = BoxUser.getAppUsersByExternalAppUserID(api, "external_app_user_id"); + +// Get marker +String marker = ((BoxResourceIterable) users).getNextMarker(); +``` + +[get-app-users-by-external-app-user-id]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getAppUsersByExternalAppUserID-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String...- + +## Move User's Folder + +To move all of a user's content to another user, call the +[`transferContent(String destinationUserID)`][transfer-folder-to-new-user] method. + + +```java +String sourceUserID = "11111"; +String destinationUserID = "22222"; +BoxUser sourceUser = new BoxUser(api, sourceUserID); +BoxFolder.Info transferredFolderInfo = sourceUser.transferContent(destinationUserID); +``` + +[transfer-folder-to-new-user]: https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#transferContent-java.lang.String- diff --git a/docs/sdk/watermarking.md b/docs/sdk/watermarking.md new file mode 100644 index 000000000..65d28f86d --- /dev/null +++ b/docs/sdk/watermarking.md @@ -0,0 +1,99 @@ +Watermarking +====== + +The ability to watermark files and folders is represented as a sub-resource on the Files and Folders resources, respectively. You can think of the sub-resource as a "label" marking whether the file or folder is watermarked or not. If you apply a watermark label to a folder, then all files inside of it will be protected by the watermark (e.g. previews will be watermarked). However, those files' watermark sub-resource is independent from the folder that got watermarked. This allows you to watermark files and folders independently. + + + + + +- [Get Watermark on File](#get-watermark-on-file) +- [Apply Watermark on File](#apply-watermark-on-file) +- [Remove Watermark on File](#remove-watermark-on-file) +- [Get Watermark on Folder](#get-watermark-on-folder) +- [Apply Watermark on Folder](#apply-watermark-on-folder) +- [Remove Watermark on Folder](#remove-watermark-on-folder) + + + +Get Watermark on File +-------------- + +Calling [`getWatermark(String... fields)`][get-watermark-on-file] will return a BoxWatermark object containing information about the watermark associated for this file. If the file does not have a watermark applied on it, a 404 Not Found will be returned. + + +```java +BoxFile file = new BoxFile(api, id); +BoxWatermark watermark = file.getWatermark(); +``` + +[get-watermark-on-file]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getWatermark-java.lang.String...- + +Apply Watermark on File +-------------- + +To apply watermark on file, call [`applyWatermark()`][apply-watermark-on-file] method. While the endpoint accepts a JSON body describing the watermark to apply, custom watermarks are not supported yet. +The method will return a BoxWatermark object containing information about the watermark applied on this file. + + +```java +BoxFile file = new BoxFile(api, id); +file.applyWatermark(); +``` + +[apply-watermark-on-file]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#applyWatermark-- + +Remove Watermark on File +-------------- + +A watermark can be removed by calling the [`removeWatermark()`][remove-watermark-on-file] method. +If the file did not have a watermark applied on it, a 404 Not Found will be returned by API. + + +```java +BoxFile file = new BoxFile(api, id); +file.removeWatermark(); +``` + +[remove-watermark-on-file]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#removeWatermark-- + +Get Watermark on Folder +-------------- + +Calling [`getWatermark(String... fields)`][get-watermark-on-folder] will return a BoxWatermark object containing information about the watermark associated for this folder. If the folder does not have a watermark applied on it, a 404 Not Found will be returned. + + +```java +BoxFolder folder = new BoxFolder(api, id); +BoxWatermark watermark = folder.getWatermark(); +``` + +[get-watermark-on-folder]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getWatermark-java.lang.String...- + +Apply Watermark on Folder +-------------- + +To apply watermark on folder, call [`applyWatermark()`][apply-watermark-on-folder] method. +The method will return a BoxWatermark object containing information about the watermark applied on this folder. + + +```java +BoxFolder folder = new BoxFolder(api, id); +fodler.applyWatermark(); +``` + +[apply-watermark-on-folder]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#applyWatermark-- + +Remove Watermark on Folder +-------------- + +A watermark can be removed by calling the [`removeWatermark()`][remove-watermark-on-folder] method. +If the folder did not have a watermark applied on it, a 404 Not Found will be returned by API. + + +```java +BoxFolder folder = new BoxFolder(api, id); +folder.removeWatermark(); +``` + +[remove-watermark-on-folder]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#removeWatermark-- diff --git a/docs/sdk/webhooks.md b/docs/sdk/webhooks.md new file mode 100644 index 000000000..1597e4f6a --- /dev/null +++ b/docs/sdk/webhooks.md @@ -0,0 +1,156 @@ +Webhooks +====== + +Webhooks enable you to attach event triggers to Box files and folders. Event triggers monitor events on Box objects and notify your application when they occur. A webhook notifies your application by sending HTTP requests to a URL of your choosing. + + + + + +- [Get a Webhook](#get-a-webhook) +- [Get All Webhooks](#get-all-webhooks) +- [Create a Webhook](#create-a-webhook) +- [Delete a Webhook](#delete-a-webhook) +- [Update a Webhook](#update-a-webhook) +- [Verify a Webhook Message](#verify-a-webhook-message) + + + +Get a Webhook +------------- + +A webhook infocan be retrieved by calling the [`getInfo(String... fields)`][get-info] method. + + +```java +BoxWebHook webhook = new BoxWebHook(api, id); +BoxWebHook.Info info = webhook.getInfo(); +``` + +[get-info]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxWebHook.html#getInfo-java.lang.String...- + +Get All Webhooks +---------------- + +Calling the static [`all(BoxAPIConnection api, String... fields)`][all] will +return an iterable that will page through all defined webhooks for the +requesting application and user. + + +```java +Iterable webhooks = BoxWebHook.all(api); +for (BoxWebHook.Info webhookInfo: webhooks) { + // Do something with the webhook. +} +``` + +[all]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxWebHook.html#all-com.box.sdk.BoxAPIConnection-java.lang.String...- + +Create a Webhook +---------------- + +The static [`create(BoxResource targetItem, URL callbackURL, BoxWebHook.Trigger... triggerEvents)`][create-webhook] +method will let you create a new webhook for a specified target object. + + +```java +// Listen for preview events for a file +BoxFile file = new BoxFile(api, id); +BoxWebHook.Info webhookInfo = BoxWebHook.create(file, url, BoxWebHook.Trigger.FILE.PREVIEWED); +``` + + +```java +// Listen for file upload events in the specified folder +BoxFolder folder = new BoxFolder(api, id); +BoxWebHook.Info webhookInfo = BoxWebHook.create(folder, url, BoxWebHook.Trigger.FILE_UPLOADED); +``` + +[create-webhook]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxWebHook.html#create-com.box.sdk.BoxResource-java.net.URL-com.box.sdk.BoxWebHook.Trigger...- + +Delete a Webhook +---------------- + +A webhook can be deleted by calling the [`delete()`][delete] method. + + +```java +BoxWebHook webhook = new BoxWebHook(api, id); +webhook.delete(); +``` + +[delete]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxWebHook.html#delete-- + +Update a Webhook +---------------- + +A webhook can be updated by calling the [`update(BoxWebHook.Info fieldsToUpdate)`][update] method. + + +```java +BoxWebHook webhook = new BoxWebHook(api, id); +BoxWebHook.Info info = webhook.new Info(); +info.setAddress(url); +webhook.update(info); +``` + +[update]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxWebHook.html#updateInfo-com.box.sdk.BoxWebHook.Info- + +Verify a Webhook Message +------------------------ + +When you receive a webhook message from Box, you should validate that it actually came from Box by calling +[`BoxWebHookSignatureVerifier#verify(String sigVersion, String sigAlgorithm, String primarySignature, String secondarySignature, String payload, String deliveryTimestamp)`][verify] + +> __Note:__ It is recommended to ensure that your application and verifier use both a primary and secondary key +> to ensure that these keys can be safely rotated. + + +```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") +); + +if (isValidMessage) { + // Message is valid, handle it +} else { + // Message is invalid, reject it +} +``` + +[verify]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxWebHookSignatureVerifier.html#verify-java.lang.String-java.lang.String-java.lang.String-java.lang.String-java.lang.String-java.lang.String- diff --git a/docs/sdk/weblinks.md b/docs/sdk/weblinks.md new file mode 100644 index 000000000..8fa09b4de --- /dev/null +++ b/docs/sdk/weblinks.md @@ -0,0 +1,126 @@ +Web Links +====== + +Web links are objects that point to URLs. These objects are also known as +bookmarks within the Box web application. Web link objects are treated +similarly to file objects. + + + + + +- [Create Web Link](#create-web-link) +- [Get Web Link](#get-web-link) +- [Update Web Link](#update-web-link) +- [Delete Web Link](#delete-web-link) +- [Create Shared Link](#create-shared-link) +- [Remove Shared Link](#remove-shared-link) + + + +Create Web Link +--------------- + +Calling [`BoxFolder.createWebLink(String name, URL url, String description)`][create-web-link] will let you create a new web link with a specified name and description. + + +```java +BoxFolder folder = new BoxFolder(api, id); +URL url = new URL("https://www.example.com"); +folder.createWebLink("Link to Example", url, "This goes to an example page"); +``` + +Name and description params are optional, so it is possible to create web link +with only one of them or with URL only: +[`BoxFolder.createWebLink(URL url)`][create-web-link2] + +```java +BoxFolder folder = new BoxFolder(api, id); +URL url = new URL("https://www.example.com"); +BoxWebLink.Info webLinkInfo = folder.createWebLink(url); +``` + +[create-web-link]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#createWebLink-java.lang.String-java.net.URL-java.lang.String- +[create-web-link2]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#createWebLink-java.net.URL- + +Get Web Link +------------ + +A web link info can be retrieved by calling the [`getInfo(String... fields)`][get-web-link] method. +Optional parameters can be used to retrieve specific fields of the Device Pin object. + + +```java +BoxWebLink webLink = new BoxWebLink(api, id); +BoxWebLink.Info webLinkInfo = webLink.getInfo(); +``` + +[get-web-link]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxWebLink.html#getInfo-java.lang.String...- + +Update Web Link +--------------- + +A web link can be updated by calling the +[`updateInfo(BoxWebLink.Info fieldsToUpdate)`][update-web-link] method. + + +```java +BoxWebLink webLink = new BoxWebLink(api, id); +BoxWebLink.Info webLinkInfo = webLink.new Info(); +webLinkInfo.setName("new name for weblink"); +webLink.updateInfo(webLinkInfo); +``` + +[update-web-link]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxWebLink.html#updateInfo-com.box.sdk.BoxWebLink.Info- + +Delete Web Link +--------------- + +A web link can be deleted by calling the [`delete()`][delete] method. + + +```java +BoxWebLink webLink = new BoxWebLink(api, id); +webLink.delete(); +``` + +[delete]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxWebLink.html#delete-- + +Create Shared Link +-------------------- + +You can create a shared link for a web link by calling the +[`createSharedLink(BoxSharedLinkWithoutPermissionsRequest sharedLinkRequest)`][create-shared-link] +method. + + +```java +// Optionally we can calculate and set the date when shared link will automatically be disabled +final long ONE_WEEK_MILLIS = 1000 * 60 * 60 * 24 * 7; +long unsharedTimestamp = System.currentTimeMillis() + ONE_WEEK_MILLIS; +Date unsharedDate = new Date(unsharedTimestamp); + +BoxWebLink webLink = new BoxWebLink(api, "id"); +BoxSharedLinkWithoutPermissionsRequest sharedLinkRequest = new BoxSharedLinkWithoutPermissionsRequest() + .access(OPEN) + .unsharedDate(unsharedDate); +BoxSharedLink sharedLink = webLink.createSharedLink(sharedLinkRequest); +``` + +[create-shared-link]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxWebLink.html#createSharedLink-com.box.sdk.sharedlink.BoxSharedLinkWithoutPermissionsRequest- + +Remove Shared Link +-------------------- + +You can remove a shared link for a web link by calling the [`removeSharedLink`](remove-shared-link) method. + + +```java +BoxWebLink webLink = new BoxWebLink(api, "12345"); +BoxWebLink.Info webLinkInfo = webLink.getInfo(); +info.removeSharedLink() +webLink.updateInfo(info) +``` + +[remove-shared-link]: https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxWebLink.html#removeSharedLink-- + diff --git a/docs/sdk/zip_download.md b/docs/sdk/zip_download.md new file mode 100644 index 000000000..32262f155 --- /dev/null +++ b/docs/sdk/zip_download.md @@ -0,0 +1,58 @@ +Zip Download +====== + +Allows you to create a temporary zip file of Box files and folders and download them. + + + + + +- [Create a Zip File](#create-a-zip-file) +- [Download a Zip File](#download-a-zip-file) + + + +Create a Zip File +--------------- + +Calling [`BoxZip.create(String name, List items)`][create-a-zip-file] will let you create a new zip file with the specified name and +with the specified items and will return a `BoxZipInfo` object with the download link. This file does not show up in your Box account, but will be temporarily +available for download. + + +```java +ArrayList items = new ArrayList(); +BoxZipItem file = new BoxZipItem("file", "12345"); +BoxZipItem folder = new BoxZipItem("folder", "156472"); +items.add(file); +items.add(folder); +BoxZip zip = new BoxZip(api); +BoxZipInfo zipInfo = zip.create("Awesome Zip File", items); +``` + +[create-a-zip-file]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxZip.html + +Download a Zip File +------------ + +Calling [`BoxZip.download(String name, List items, OutputStream output)`][download-a-zip-file] will let you create a new zip file +with the specified name and with the specified items and download it to the stream that is passed in. The return object is a `BoxZipDownloadStatus` +object that contains information about the download, including whether it was successful. The created zip file does not show up in your Box account. + + +```java +ArrayList items = new ArrayList(); +BoxZipItem file = new BoxZipItem("file", "12345"); +BoxZipItem folder = new BoxZipItem("folder", "156472"); +items.add(file); +items.add(folder); +BoxZip zip = new BoxZip(api); +FileOutputStream stream = new FileOutputStream(); +BoxZipDownloadStatus zipDownloadStatus = zip.download("Another Awesome Zip File", items, stream); +stream.close(); +if (zipDownloadStatus.getState() == BoxZipDownloadStatus.State.SUCCEEDED) { + System.out.println("Zip downloaded successfully"); +} +``` + +[download-a-zip-file]: http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxZip.html From d0fb8503243e29d7440732c4425010b6ab6f403d Mon Sep 17 00:00:00 2001 From: lsocha Date: Fri, 26 Sep 2025 17:32:23 +0200 Subject: [PATCH 05/19] change order --- build.gradle | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/build.gradle b/build.gradle index a29542935..4289ba86b 100644 --- a/build.gradle +++ b/build.gradle @@ -201,18 +201,6 @@ tasks.register('integrationTestsAll') { group = "Verification" } -jacoco { - toolVersion = "0.8.10" - reportsDirectory = file("$buildDir/reports/jacoco") -} - -jacocoTestReport { - reports { - xml.required = true // coveralls plugin depends on xml format report - html.required = true - } -} - tasks.withType(JavaCompile) { options.compilerArgs << "-Xlint:all" @@ -342,3 +330,16 @@ idea { testSourceDirs += file("src/intTest/java") } } + +jacoco { + toolVersion = "0.8.10" + reportsDirectory = file("$buildDir/reports/jacoco") +} + +jacocoTestReport { + dependsOn test + reports { + xml.required = true // coveralls plugin depends on xml format report + html.required = true + } +} From 8039726a6790b4f901e61125a847f6659f0055a3 Mon Sep 17 00:00:00 2001 From: lsocha Date: Fri, 26 Sep 2025 17:39:35 +0200 Subject: [PATCH 06/19] add coverallsJacoco --- build.gradle | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/build.gradle b/build.gradle index 4289ba86b..55e924a0a 100644 --- a/build.gradle +++ b/build.gradle @@ -343,3 +343,7 @@ jacocoTestReport { html.required = true } } + +coverallsJacoco { + dependsOn jacocoTestReport +} From 5209fb733f231d850c9784b113c2228ae94398e0 Mon Sep 17 00:00:00 2001 From: lsocha Date: Fri, 26 Sep 2025 17:43:49 +0200 Subject: [PATCH 07/19] add coverallsJacoco --- build.gradle | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/build.gradle b/build.gradle index 55e924a0a..de5e926d8 100644 --- a/build.gradle +++ b/build.gradle @@ -344,6 +344,4 @@ jacocoTestReport { } } -coverallsJacoco { - dependsOn jacocoTestReport -} +coverallsJacoco.dependsOn jacocoTestReport From 84cf0f61a921696eec0c87d8b983b73acb1c97ea Mon Sep 17 00:00:00 2001 From: lsocha Date: Fri, 26 Sep 2025 17:45:33 +0200 Subject: [PATCH 08/19] add coverallsJacoco --- build.gradle | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index de5e926d8..411d71d32 100644 --- a/build.gradle +++ b/build.gradle @@ -344,4 +344,7 @@ jacocoTestReport { } } -coverallsJacoco.dependsOn jacocoTestReport +coverallsJacoco { + sourceDirs = files("src/main/java") + jacocoReportPath = file("${buildDir}/reports/jacoco/test/jacocoTestReport.xml") +} From c047bef768da2c9636230719e144575342903cd2 Mon Sep 17 00:00:00 2001 From: lsocha Date: Fri, 26 Sep 2025 18:06:52 +0200 Subject: [PATCH 09/19] fixes --- build.gradle | 24 +++--------------------- 1 file changed, 3 insertions(+), 21 deletions(-) diff --git a/build.gradle b/build.gradle index 411d71d32..3f52ec574 100644 --- a/build.gradle +++ b/build.gradle @@ -211,7 +211,8 @@ tasks.withType(JavaCompile) { } } -tasks.withType(Test) { +test { + useJUnitPlatform() testLogging { exceptionFormat = "full" } @@ -223,21 +224,11 @@ tasks.withType(Test) { outputs.upToDateWhen { false } } + tasks.withType(GenerateModuleMetadata) { enabled = false } -jacoco { - reportsDirectory = file("$buildDir/reports/jacoco") -} - -jacocoTestReport { - reports { - xml.required = true // coveralls plugin depends on xml format report - html.required = true - } -} - artifacts { archives sourcesJar, javadocJar } @@ -249,10 +240,6 @@ spotless { } } -test { - useJUnitPlatform() -} - publishing { publications { boxJavaSdk(MavenPublication) { @@ -343,8 +330,3 @@ jacocoTestReport { html.required = true } } - -coverallsJacoco { - sourceDirs = files("src/main/java") - jacocoReportPath = file("${buildDir}/reports/jacoco/test/jacocoTestReport.xml") -} From a3bc394f15f265f74cb5dddff93cdf2641cb39da Mon Sep 17 00:00:00 2001 From: lsocha Date: Fri, 26 Sep 2025 18:12:28 +0200 Subject: [PATCH 10/19] fixes --- build.gradle | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/build.gradle b/build.gradle index 3f52ec574..a1205ba97 100644 --- a/build.gradle +++ b/build.gradle @@ -193,6 +193,18 @@ tasks.register('smokeTestGen', Test) { } } +tasks.withType(Test) { + testLogging { + exceptionFormat = "full" + } + + jacoco { + destinationFile = file("$buildDir/jacoco/test.exec") + } + + outputs.upToDateWhen { false } +} + // Combined task to run both sets tasks.register('integrationTestsAll') { @@ -212,16 +224,7 @@ tasks.withType(JavaCompile) { } test { - useJUnitPlatform() - testLogging { - exceptionFormat = "full" - } - - jacoco { - destinationFile = file("$buildDir/jacoco/test.exec") - } - - outputs.upToDateWhen { false } + useJUnit() } From 6e834da94518edd47205cf18987ecf72cc96fe3e Mon Sep 17 00:00:00 2001 From: lsocha Date: Fri, 26 Sep 2025 18:16:20 +0200 Subject: [PATCH 11/19] fix --- build.gradle | 1 - 1 file changed, 1 deletion(-) diff --git a/build.gradle b/build.gradle index a1205ba97..b11f8183a 100644 --- a/build.gradle +++ b/build.gradle @@ -322,7 +322,6 @@ idea { } jacoco { - toolVersion = "0.8.10" reportsDirectory = file("$buildDir/reports/jacoco") } From 2dc89deb3984583f0c7ea157756664096c1362a9 Mon Sep 17 00:00:00 2001 From: lsocha Date: Fri, 26 Sep 2025 18:17:42 +0200 Subject: [PATCH 12/19] reorder --- build.gradle | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/build.gradle b/build.gradle index b11f8183a..2667b7530 100644 --- a/build.gradle +++ b/build.gradle @@ -213,6 +213,19 @@ tasks.register('integrationTestsAll') { group = "Verification" } +jacoco { + reportsDirectory = file("$buildDir/reports/jacoco") +} + +jacocoTestReport { + dependsOn test + reports { + xml.required = true // coveralls plugin depends on xml format report + html.required = true + } +} + + tasks.withType(JavaCompile) { options.compilerArgs << "-Xlint:all" @@ -320,15 +333,3 @@ idea { testSourceDirs += file("src/intTest/java") } } - -jacoco { - reportsDirectory = file("$buildDir/reports/jacoco") -} - -jacocoTestReport { - dependsOn test - reports { - xml.required = true // coveralls plugin depends on xml format report - html.required = true - } -} From e7a745820c02e4e1bb5067d3d175db8f66d8f823 Mon Sep 17 00:00:00 2001 From: lsocha Date: Fri, 26 Sep 2025 19:11:50 +0200 Subject: [PATCH 13/19] check --- .github/workflows/unit-tests.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml index 76aa983d4..9b6b47ba5 100644 --- a/.github/workflows/unit-tests.yml +++ b/.github/workflows/unit-tests.yml @@ -23,8 +23,8 @@ jobs: java-version: ${{ matrix.java }} cache: 'gradle' - name: Build and test - run: ./gradlew check --stacktrace + run: ./gradlew clean test --stacktrace - name: Coverage env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: ./gradlew jacocoTestReport coverallsJacoco + run: ./gradlew jacocoTestReport coverallsJacoco --stacktrace From b75a4e9989d89ed064a11e8d6c7f16a7bd0e59a4 Mon Sep 17 00:00:00 2001 From: lsocha Date: Fri, 26 Sep 2025 19:16:26 +0200 Subject: [PATCH 14/19] check2 --- .github/workflows/unit-tests.yml | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml index 9b6b47ba5..48669b935 100644 --- a/.github/workflows/unit-tests.yml +++ b/.github/workflows/unit-tests.yml @@ -23,8 +23,10 @@ jobs: java-version: ${{ matrix.java }} cache: 'gradle' - name: Build and test - run: ./gradlew clean test --stacktrace - - name: Coverage + run: ./gradlew check --stacktrace + - name: Generate JaCoCo report + run: ./gradlew jacocoTestReport --stacktrace + - name: Upload coverage to Coveralls env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: ./gradlew jacocoTestReport coverallsJacoco --stacktrace + run: ./gradlew coverallsJacoco --stacktrace From 53aafa1e22b40a5229e210b70340899e0424d97c Mon Sep 17 00:00:00 2001 From: lsocha Date: Fri, 26 Sep 2025 19:20:08 +0200 Subject: [PATCH 15/19] check3 --- .github/workflows/unit-tests.yml | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml index 48669b935..105f9e6d6 100644 --- a/.github/workflows/unit-tests.yml +++ b/.github/workflows/unit-tests.yml @@ -24,9 +24,7 @@ jobs: cache: 'gradle' - name: Build and test run: ./gradlew check --stacktrace - - name: Generate JaCoCo report - run: ./gradlew jacocoTestReport --stacktrace - - name: Upload coverage to Coveralls + - name: Coverage env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: ./gradlew coverallsJacoco --stacktrace + run: ./gradlew cjacocoTestReport overallsJacoco --stacktrace From 362b32f89a2cddbd7b8cd6d8c96ee0f4a72b6c30 Mon Sep 17 00:00:00 2001 From: lsocha Date: Fri, 26 Sep 2025 19:22:17 +0200 Subject: [PATCH 16/19] fix --- .github/workflows/unit-tests.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml index 105f9e6d6..e9265038f 100644 --- a/.github/workflows/unit-tests.yml +++ b/.github/workflows/unit-tests.yml @@ -24,7 +24,9 @@ jobs: cache: 'gradle' - name: Build and test run: ./gradlew check --stacktrace - - name: Coverage + - name: Generate JaCoCo report + run: ./gradlew jacocoTestReport --stacktrace + - name: Upload coverage to Coveralls env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: ./gradlew cjacocoTestReport overallsJacoco --stacktrace From fa8db00e2cd675e1261c27a850d3e81bc83b9756 Mon Sep 17 00:00:00 2001 From: lsocha Date: Fri, 26 Sep 2025 19:22:32 +0200 Subject: [PATCH 17/19] fix1 --- .github/workflows/unit-tests.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml index e9265038f..e253be254 100644 --- a/.github/workflows/unit-tests.yml +++ b/.github/workflows/unit-tests.yml @@ -29,4 +29,4 @@ jobs: - name: Upload coverage to Coveralls env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: ./gradlew cjacocoTestReport overallsJacoco --stacktrace + run: ./gradlew jacocoTestReport overallsJacoco --stacktrace From 3dd9b4cdb5c1b273fb0d694e151ef02e96c83fb0 Mon Sep 17 00:00:00 2001 From: lsocha Date: Fri, 26 Sep 2025 19:25:49 +0200 Subject: [PATCH 18/19] working --- .github/workflows/spell-check-lint.yml | 4 ++-- .github/workflows/unit-tests.yml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/spell-check-lint.yml b/.github/workflows/spell-check-lint.yml index cff82f58d..d7526ef62 100644 --- a/.github/workflows/spell-check-lint.yml +++ b/.github/workflows/spell-check-lint.yml @@ -9,9 +9,9 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout current repository - uses: actions/checkout@v2 + uses: actions/checkout@v4 - name: Checkout spellchecker - uses: actions/checkout@v2 + uses: actions/checkout@v4 with: ref: refs/heads/main repository: box/box-sdk-spellchecker diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml index e253be254..48669b935 100644 --- a/.github/workflows/unit-tests.yml +++ b/.github/workflows/unit-tests.yml @@ -29,4 +29,4 @@ jobs: - name: Upload coverage to Coveralls env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: ./gradlew jacocoTestReport overallsJacoco --stacktrace + run: ./gradlew coverallsJacoco --stacktrace From c0ebe1450c185a19b4d6a0be5bb3f8f886353f3d Mon Sep 17 00:00:00 2001 From: lsocha Date: Fri, 26 Sep 2025 19:40:47 +0200 Subject: [PATCH 19/19] fixes --- build.gradle | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/build.gradle b/build.gradle index 2667b7530..1b4923f7f 100644 --- a/build.gradle +++ b/build.gradle @@ -263,7 +263,7 @@ publishing { pom { artifactId = project.getArchivesBaseName() name = "Box Java SDK" - description = "The Box SDK for Java." + description = "Official Box Java SDK." url = "https://opensource.box.com/box-java-sdk/" packaging = "jar" licenses { @@ -275,7 +275,7 @@ publishing { developers { developer { id = "box" - name = "Box" + name = "box" email = "sdks@box.com" } } @@ -299,12 +299,12 @@ 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 comaptible with Gradle implementation + // not compatible with Gradle implementation useGpgCmd() sign publishing.publications.boxJavaSdk } -def centralUsername = project.findProperty("centralUsername") +def centralUsername = project.findProperty("centralUsername") def centralPassword = project.findProperty("centralPassword") jreleaser { signing { @@ -314,9 +314,9 @@ jreleaser { maven { mavenCentral { sonatype { + active = "ALWAYS" + url = "https://central.sonatype.com/api/v1/publisher" sign = false - active = 'RELEASE' - url = 'https://central.sonatype.com/api/v1/publisher' stagingRepository('build/staging-deploy') username = centralUsername password = centralPassword