Dropbox Java SDK

repository·main·Indexed 20 days ago

https://github.com/dropbox/dropbox-sdk-java

A Java library for accessing Dropbox's HTTP-based Core API v2, providing a high-level interface for managing files, folders, and user accounts. It supports Java 21+ (v8.0.0+) and Java 8-20 (v7.x), as well as Android 8+ (SDK 26+). The SDK includes features for OAuth2 authentication, global error handling via callback factories, and support for various requestors including OkHttp3.

Tokens
4.3K
Snippets
14
Records
18
Agent score
71%

What's inside dropbox-sdk-java

  1. Implement global error handling with callback factories

    main

    The Dropbox Java SDK allows you to move away from request-by-request error handling by supplying a callback factory to the client. This enables consistent, global handling of two types of errors:

    1. General Network Errors: Implement getNetworkErrorCallback to handle errors that occur at the networking layer, such as authentication errors.
    2. Route-Specific Errors: Implement one of the getRouteErrorCallback methods to handle errors specific to certain API endpoints or routes.

    This pattern is useful for centralizing error logic (like logging or re-authentication flows) that should apply to all requests regardless of the specific endpoint being called.

  2. Setup the Dropbox SDK for Android

    main

    To use the Dropbox SDK in an Android project, add the core and Android-specific dependencies to your build.gradle file.

    Note on Kotlin: The Android SDK is written in Kotlin. If your project does not already include Kotlin, you must add the Kotlin standard library as a dependency to avoid runtime exceptions.

    Jettifier Workaround: If you encounter transformation errors with jackson-core or fastdoubleparser while using Jettifier, add the following to your gradle.properties: android.jetifier.ignorelist = jackson-core,fastdoubleparser

    dependencies {
        // ...
        implementation 'com.dropbox.core:dropbox-core-sdk:8.0.2'
        implementation 'com.dropbox.core:dropbox-android-sdk:8.0.2'
        // Required if your project doesn't have Kotlin
        implementation "org.jetbrains.kotlin:kotlin-stdlib:2.4.0"
    }
  3. Run the Dropbox Java SDK Tutorial Example

    main

    The tutorial example demonstrates basic usage of the Dropbox Java SDK. To run the provided example code, you must provide a valid Dropbox access token.

    1. Locate Main.java in the example source.
    2. Replace the placeholder "<ACCESS TOKEN>" with your actual Dropbox access token.
    3. Refer to the official Dropbox online tutorial for instructions on how to generate an access token and complete the setup.
    // In Main.java, replace the placeholder with your token:
    String accessToken = "<ACCESS TOKEN>";
  4. Use the published Dropbox SDK in an Android project

    main

    The provided Android example uses the local source version of the SDK. To use the published version of the SDK in your own Android project instead of the local source, modify your build.gradle file to replace the project dependency with the remote Maven dependency.

    Replace: implementation(project(":core"))

    With: implementation("com.dropbox.core:dropbox-core-sdk:LATEST_VERSION_GOES_HERE")

    // Replace this:
    implementation(project(":core"))
    
    // With this:
    implementation("com.dropbox.core:dropbox-core-sdk:LATEST_VERSION_GOES_HERE")
  5. Initialize a Dropbox client

    main

    To interact with the Dropbox API, you must instantiate a DbxClientV2. This requires a DbxRequestConfig (which includes a client name for identification) and an access token obtained from the Dropbox App Console.

    import com.dropbox.core.DbxException;
    import com.dropbox.core.DbxRequestConfig;
    import com.dropbox.core.v2.DbxClientV2;
    
    public class Main {
        private static final String ACCESS_TOKEN = "<ACCESS TOKEN>";
    
        public static void main(String args[]) throws DbxException {
            // Create Dropbox client
            DbxRequestConfig config = DbxRequestConfig.newBuilder("dropbox/java-tutorial").build();
            DbxClientV2 client = new DbxClientV2(config, ACCESS_TOKEN);
        }
    }
  6. Install the Dropbox Java SDK

    main

    You can add the Dropbox Java SDK to your project using Maven or Gradle.

    Note on Java Versions:

    • v8.0.0+: Requires Java 21+.
    • v7.x: Supports Java 8 through Java 20.

    Note on Android:

    • Supports Android 8+ (SDK 26+).
    ### Maven
    
    ```xml
    <dependency>
        <groupId>com.dropbox.core</groupId>
        <artifactId>dropbox-core-sdk</artifactId>
        <version>8.0.2</version>
    </dependency>

    Gradle

    dependencies {
        // ...
        implementation 'com.dropbox.core:dropbox-core-sdk:8.0.2'
    }
  7. Build and run Dropbox SDK examples from source

    main

    To run the provided examples in the repository, follow these steps:

    1. Build the SDK:
      git clone https://github.com/dropbox/dropbox-sdk-java.git
      cd dropbox-sdk-java
      ./update-submodules
      ./gradlew build
    2. Configure Credentials: Create a JSON file (e.g., test.app) containing your key and secret from the Dropbox App Console.
    3. Run Examples: Use the ./run script in the examples directory.

    Common Example Commands:

    • OAuth Authorization: ./run authorize test.app test.auth (generates test.auth containing the access token).
    • Account Info: ./run account-info test.auth.
    • Longpoll (Watch changes): ./run longpoll test.auth "/path/to/watch".
    • Upload File: ./run upload-file test.auth local-path/file.txt /dropbox-path/file.txt.
    # Build from source
    ```shell
    git clone https://github.com/dropbox/dropbox-sdk-java.git
    cd dropbox-sdk-java
    ./update-submodules    # also do this after every "git checkout"
    ./gradlew build # requires `python` command to use Python 3.9, pip dropbox

    Running the examples

    cd examples ./run authorize test.app test.auth ./run account-info test.auth ./run longpoll test.auth "/path/to/watch" ./run upload-file test.auth local-path/file.txt /dropbox-path/file.txt

  8. Implement certificate pinning

    main

    As of version 7.0.0, the SDK no longer provides certificate pinning by default and SSLConfig is no longer available. You must provide your own SSLSocketFactory or CertificatePinner using the available requestors.

    // Using StandardHttpRequestor
    StandardHttpRequestor.Config customConfig = StandardHttpRequestor.Config.DEFAULT_INSTANCE.copy()
            .withSslSocketFactory(mySslSocketFactory)
            .build();
    StandardHttpRequestor requestor = new StandardHttpRequestor(customConfig);
    
    // Using OkHttp3Requestor
    okhttp3.OkHttpClient httpClient = OkHttp3Requestor.defaultOkHttpClientBuilder()
            .certificatePinner(myCertificatePinner)
            .build();
    
    // Using OkHttpRequestor
    OkHttpClient httpClient = OkHttpRequestor.defaultOkHttpClient().clone()
            .setCertificatePinner(myCertificatePinner)
            .build();
  9. Set up the Dropbox Android Example project

    main

    To run the Android example application, you must provide your Dropbox App/API Key. This is done by creating a local.properties file within the Android example directory (examples/android/local.properties).

    Note: Creating this file is not required to build the app, but it is mandatory if you want to test the authentication flow.

    Steps:

    1. Ensure your build environment supports at least Android SDK version 21 (Android 5.0 Lollipop).
    2. Create examples/android/local.properties with the following content: DROPBOX_APP_KEY=YOUR_KEY_HERE (replace YOUR_KEY_HERE with your actual Dropbox App/API Key).

    You can automate this via the terminal from the root of the dropbox-sdk-java repository:

    echo "DROPBOX_APP_KEY=YOUR_KEY_HERE" > examples/android/local.properties
  10. Configure AndroidManifest.xml for Dropbox Authentication

    main

    To enable Dropbox authentication on Android, you must configure your AndroidManifest.xml with two specific components:

    1. AuthActivity: Register the com.dropbox.core.android.AuthActivity with an intent-filter using your specific Dropbox App Key in the scheme (db-${dropboxKey}).

      • The activity starting the authorization flow must have android:launchMode="singleTask".
      • If your activity uses android:taskAffinity, ensure AuthActivity uses the same affinity.
      • A second intent-filter is included as a workaround for apps targeting targetSdk=33.
    2. Queries: Add the Dropbox package name to your <queries> block to allow the SDK to verify the official Dropbox app during the app-to-app authentication flow.

    <manifest>
        ...
        <application>
            <activity
                android:name="com.dropbox.core.android.AuthActivity"
                android:exported="true"
                android:configChanges="orientation|keyboard"
                android:launchMode="singleTask">
                <intent-filter>
                    <data android:scheme="db-${dropboxKey}" />
            
                    <action android:name="android.intent.action.VIEW" />
            
                    <category android:name="android.intent.category.BROWSABLE" />
                    <category android:name="android.intent.category.DEFAULT" />
                </intent-filter>
                
                <!-- Workaround for targetSdk=33 -->
                <intent-filter>
                    <action android:name="android.intent.action.VIEW" />
                    <category android:name="android.intent.category.DEFAULT" />
                </intent-filter>
            </activity>
        </application>
    
        <queries>
            <package android:name="com.dropbox.android" />
        </queries>
        ...
    </manifest>
  11. Configure the Stone Gradle Plugin

    main

    The Stone Gradle Plugin automates the generation of Stone Java source files. When applied, it automatically creates generation tasks for every available SourceSet in your project and ensures that JavaCompile and KotlinCompile tasks depend on these generation tasks so that code is generated before compilation begins.

    Generated Tasks

    For each source set, a task is registered with the following naming convention:

    • main source set: generateStone
    • Other source sets (e.g., test): generateTestStone

    Configuration Properties

    You can configure the plugin via Gradle project properties using the following naming patterns:

    Property NameDescription
    com.dropbox.api.${sourceSet.name}.routeWhitelistFilterPath to a file containing the route whitelist filter.
    com.dropbox.api.${sourceSet.name}.specDirThe directory containing Stone specifications. Defaults to src/${sourceSet.name}/stone.

    Default Behavior

    • Generator File: Uses ${projectDirectory}/generator/java/java.stoneg.py.
    • Stone Directory: Defaults to stone.
    • Python Command: Defaults to python.
    • Output Directory: Generated files are placed in build/generated/source/stone/${sourceSet.name}/src and are automatically added to the corresponding source set's Java source directories.