Search in sources :

Example 11 with DbxException

use of com.dropbox.core.DbxException in project dropbox-sdk-java by dropbox.

the class Main method uploadFile.

/**
 * Uploads a file in a single request. This approach is preferred for small files since it
 * eliminates unnecessary round-trips to the servers.
 *
 * @param dbxClient Dropbox user authenticated client
 * @param localFIle local file to upload
 * @param dropboxPath Where to upload the file to within Dropbox
 */
private static void uploadFile(DbxClientV2 dbxClient, File localFile, String dropboxPath) {
    try (InputStream in = new FileInputStream(localFile)) {
        ProgressListener progressListener = l -> printProgress(l, localFile.length());
        FileMetadata metadata = dbxClient.files().uploadBuilder(dropboxPath).withMode(WriteMode.ADD).withClientModified(new Date(localFile.lastModified())).uploadAndFinish(in, progressListener);
        System.out.println(metadata.toStringMultiline());
    } catch (UploadErrorException ex) {
        System.err.println("Error uploading to Dropbox: " + ex.getMessage());
        System.exit(1);
    } catch (DbxException ex) {
        System.err.println("Error uploading to Dropbox: " + ex.getMessage());
        System.exit(1);
    } catch (IOException ex) {
        System.err.println("Error reading from file \"" + localFile + "\": " + ex.getMessage());
        System.exit(1);
    }
}
Also used : NetworkIOException(com.dropbox.core.NetworkIOException) RetryException(com.dropbox.core.RetryException) DbxWebAuth(com.dropbox.core.DbxWebAuth) UploadSessionFinishErrorException(com.dropbox.core.v2.files.UploadSessionFinishErrorException) DbxClientV2(com.dropbox.core.v2.DbxClientV2) UploadSessionCursor(com.dropbox.core.v2.files.UploadSessionCursor) Date(java.util.Date) ProgressListener(com.dropbox.core.util.IOUtil.ProgressListener) WriteMode(com.dropbox.core.v2.files.WriteMode) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) JsonReader(com.dropbox.core.json.JsonReader) Logger(java.util.logging.Logger) File(java.io.File) Level(java.util.logging.Level) FileMetadata(com.dropbox.core.v2.files.FileMetadata) DbxException(com.dropbox.core.DbxException) CommitInfo(com.dropbox.core.v2.files.CommitInfo) DbxRequestConfig(com.dropbox.core.DbxRequestConfig) UploadSessionLookupErrorException(com.dropbox.core.v2.files.UploadSessionLookupErrorException) DbxAuthInfo(com.dropbox.core.DbxAuthInfo) UploadErrorException(com.dropbox.core.v2.files.UploadErrorException) DbxPathV2(com.dropbox.core.v2.DbxPathV2) InputStream(java.io.InputStream) ProgressListener(com.dropbox.core.util.IOUtil.ProgressListener) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) UploadErrorException(com.dropbox.core.v2.files.UploadErrorException) FileMetadata(com.dropbox.core.v2.files.FileMetadata) NetworkIOException(com.dropbox.core.NetworkIOException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) Date(java.util.Date) DbxException(com.dropbox.core.DbxException)

Example 12 with DbxException

use of com.dropbox.core.DbxException in project dropbox-sdk-java by dropbox.

the class Main method chunkedUploadFile.

/**
 * Uploads a file in chunks using multiple requests. This approach is preferred for larger files
 * since it allows for more efficient processing of the file contents on the server side and
 * also allows partial uploads to be retried (e.g. network connection problem will not cause you
 * to re-upload all the bytes).
 *
 * @param dbxClient Dropbox user authenticated client
 * @param localFIle local file to upload
 * @param dropboxPath Where to upload the file to within Dropbox
 */
private static void chunkedUploadFile(DbxClientV2 dbxClient, File localFile, String dropboxPath) {
    long size = localFile.length();
    // below to simplify the logic.
    if (size < CHUNKED_UPLOAD_CHUNK_SIZE) {
        System.err.println("File too small, use upload() instead.");
        System.exit(1);
        return;
    }
    long uploaded = 0L;
    DbxException thrown = null;
    ProgressListener progressListener = new ProgressListener() {

        long uploadedBytes = 0;

        @Override
        public void onProgress(long l) {
            printProgress(l + uploadedBytes, size);
            if (l == CHUNKED_UPLOAD_CHUNK_SIZE)
                uploadedBytes += CHUNKED_UPLOAD_CHUNK_SIZE;
        }
    };
    // Chunked uploads have 3 phases, each of which can accept uploaded bytes:
    // 
    // (1)  Start: initiate the upload and get an upload session ID
    // (2) Append: upload chunks of the file to append to our session
    // (3) Finish: commit the upload and close the session
    // 
    // We track how many bytes we uploaded to determine which phase we should be in.
    String sessionId = null;
    for (int i = 0; i < CHUNKED_UPLOAD_MAX_ATTEMPTS; ++i) {
        if (i > 0) {
            System.out.printf("Retrying chunked upload (%d / %d attempts)\n", i + 1, CHUNKED_UPLOAD_MAX_ATTEMPTS);
        }
        try (InputStream in = new FileInputStream(localFile)) {
            // if this is a retry, make sure seek to the correct offset
            in.skip(uploaded);
            // (1) Start
            if (sessionId == null) {
                sessionId = dbxClient.files().uploadSessionStart().uploadAndFinish(in, CHUNKED_UPLOAD_CHUNK_SIZE, progressListener).getSessionId();
                uploaded += CHUNKED_UPLOAD_CHUNK_SIZE;
                printProgress(uploaded, size);
            }
            UploadSessionCursor cursor = new UploadSessionCursor(sessionId, uploaded);
            // (2) Append
            while ((size - uploaded) > CHUNKED_UPLOAD_CHUNK_SIZE) {
                dbxClient.files().uploadSessionAppendV2(cursor).uploadAndFinish(in, CHUNKED_UPLOAD_CHUNK_SIZE, progressListener);
                uploaded += CHUNKED_UPLOAD_CHUNK_SIZE;
                printProgress(uploaded, size);
                cursor = new UploadSessionCursor(sessionId, uploaded);
            }
            // (3) Finish
            long remaining = size - uploaded;
            CommitInfo commitInfo = CommitInfo.newBuilder(dropboxPath).withMode(WriteMode.ADD).withClientModified(new Date(localFile.lastModified())).build();
            FileMetadata metadata = dbxClient.files().uploadSessionFinish(cursor, commitInfo).uploadAndFinish(in, remaining, progressListener);
            System.out.println(metadata.toStringMultiline());
            return;
        } catch (RetryException ex) {
            thrown = ex;
            // RetryExceptions are never automatically retried by the client for uploads. Must
            // catch this exception even if DbxRequestConfig.getMaxRetries() > 0.
            sleepQuietly(ex.getBackoffMillis());
            continue;
        } catch (NetworkIOException ex) {
            thrown = ex;
            // network issue with Dropbox (maybe a timeout?) try again
            continue;
        } catch (UploadSessionLookupErrorException ex) {
            if (ex.errorValue.isIncorrectOffset()) {
                thrown = ex;
                // server offset into the stream doesn't match our offset (uploaded). Seek to
                // the expected offset according to the server and try again.
                uploaded = ex.errorValue.getIncorrectOffsetValue().getCorrectOffset();
                continue;
            } else {
                // Some other error occurred, give up.
                System.err.println("Error uploading to Dropbox: " + ex.getMessage());
                System.exit(1);
                return;
            }
        } catch (UploadSessionFinishErrorException ex) {
            if (ex.errorValue.isLookupFailed() && ex.errorValue.getLookupFailedValue().isIncorrectOffset()) {
                thrown = ex;
                // server offset into the stream doesn't match our offset (uploaded). Seek to
                // the expected offset according to the server and try again.
                uploaded = ex.errorValue.getLookupFailedValue().getIncorrectOffsetValue().getCorrectOffset();
                continue;
            } else {
                // some other error occurred, give up.
                System.err.println("Error uploading to Dropbox: " + ex.getMessage());
                System.exit(1);
                return;
            }
        } catch (DbxException ex) {
            System.err.println("Error uploading to Dropbox: " + ex.getMessage());
            System.exit(1);
            return;
        } catch (IOException ex) {
            System.err.println("Error reading from file \"" + localFile + "\": " + ex.getMessage());
            System.exit(1);
            return;
        }
    }
    // if we made it here, then we must have run out of attempts
    System.err.println("Maxed out upload attempts to Dropbox. Most recent error: " + thrown.getMessage());
    System.exit(1);
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) FileMetadata(com.dropbox.core.v2.files.FileMetadata) NetworkIOException(com.dropbox.core.NetworkIOException) IOException(java.io.IOException) RetryException(com.dropbox.core.RetryException) FileInputStream(java.io.FileInputStream) Date(java.util.Date) NetworkIOException(com.dropbox.core.NetworkIOException) UploadSessionLookupErrorException(com.dropbox.core.v2.files.UploadSessionLookupErrorException) ProgressListener(com.dropbox.core.util.IOUtil.ProgressListener) UploadSessionFinishErrorException(com.dropbox.core.v2.files.UploadSessionFinishErrorException) UploadSessionCursor(com.dropbox.core.v2.files.UploadSessionCursor) CommitInfo(com.dropbox.core.v2.files.CommitInfo) DbxException(com.dropbox.core.DbxException)

Example 13 with DbxException

use of com.dropbox.core.DbxException in project dropbox-sdk-java by dropbox.

the class Main method main.

public static void main(String[] args) throws IOException {
    // Only display important log messages.
    Logger.getLogger("").setLevel(Level.WARNING);
    if (args.length != 2) {
        System.out.println("Usage: COMMAND <app-info-file> <auth-file-output>");
        System.out.println("");
        System.out.println("<app-info-file>: a JSON file with information about your API app.  Example:");
        System.out.println("");
        System.out.println("  {");
        System.out.println("    \"key\": \"Your Dropbox API app key...\",");
        System.out.println("    \"secret\": \"Your Dropbox API app secret...\"");
        System.out.println("  }");
        System.out.println("");
        System.out.println("  Get an API app key by registering with Dropbox:");
        System.out.println("    https://dropbox.com/developers/apps");
        System.out.println("");
        System.out.println("<auth-file-output>: If authorization is successful, the resulting API");
        System.out.println("  access token will be saved to this file, which can then be used with");
        System.out.println("  other example programs, such as the one in \"examples/account-info\".");
        System.out.println("");
        System.exit(1);
        return;
    }
    String argAppInfoFile = args[0];
    String argAuthFileOutput = args[1];
    // Read app info file (contains app key and app secret)
    DbxAppInfo appInfo;
    try {
        appInfo = DbxAppInfo.Reader.readFromFile(argAppInfoFile);
    } catch (JsonReader.FileLoadException ex) {
        System.err.println("Error reading <app-info-file>: " + ex.getMessage());
        System.exit(1);
        return;
    }
    // Run through Dropbox API authorization process
    DbxRequestConfig requestConfig = new DbxRequestConfig("examples-authorize");
    DbxWebAuth webAuth = new DbxWebAuth(requestConfig, appInfo);
    DbxWebAuth.Request webAuthRequest = DbxWebAuth.newRequestBuilder().withNoRedirect().build();
    String authorizeUrl = webAuth.authorize(webAuthRequest);
    System.out.println("1. Go to " + authorizeUrl);
    System.out.println("2. Click \"Allow\" (you might have to log in first).");
    System.out.println("3. Copy the authorization code.");
    System.out.print("Enter the authorization code here: ");
    String code = new BufferedReader(new InputStreamReader(System.in)).readLine();
    if (code == null) {
        System.exit(1);
        return;
    }
    code = code.trim();
    DbxAuthFinish authFinish;
    try {
        authFinish = webAuth.finishFromCode(code);
    } catch (DbxException ex) {
        System.err.println("Error in DbxWebAuth.authorize: " + ex.getMessage());
        System.exit(1);
        return;
    }
    System.out.println("Authorization complete.");
    System.out.println("- User ID: " + authFinish.getUserId());
    System.out.println("- Account ID: " + authFinish.getAccountId());
    System.out.println("- Access Token: " + authFinish.getAccessToken());
    // Save auth information to output file.
    DbxAuthInfo authInfo = new DbxAuthInfo(authFinish.getAccessToken(), appInfo.getHost());
    File output = new File(argAuthFileOutput);
    try {
        DbxAuthInfo.Writer.writeToFile(authInfo, output);
        System.out.println("Saved authorization information to \"" + output.getCanonicalPath() + "\".");
    } catch (IOException ex) {
        System.err.println("Error saving to <auth-file-out>: " + ex.getMessage());
        System.err.println("Dumping to stderr instead:");
        DbxAuthInfo.Writer.writeToStream(authInfo, System.err);
        System.exit(1);
        return;
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) IOException(java.io.IOException) DbxRequestConfig(com.dropbox.core.DbxRequestConfig) DbxAuthInfo(com.dropbox.core.DbxAuthInfo) DbxAppInfo(com.dropbox.core.DbxAppInfo) BufferedReader(java.io.BufferedReader) JsonReader(com.dropbox.core.json.JsonReader) DbxAuthFinish(com.dropbox.core.DbxAuthFinish) File(java.io.File) DbxException(com.dropbox.core.DbxException) DbxWebAuth(com.dropbox.core.DbxWebAuth)

Example 14 with DbxException

use of com.dropbox.core.DbxException in project dropbox-sdk-java by dropbox.

the class PkceAuthorize method authorize.

public DbxAuthFinish authorize(DbxAppInfo appInfo) throws IOException {
    // Run through Dropbox API authorization process without client secret
    DbxRequestConfig requestConfig = new DbxRequestConfig("examples-authorize");
    DbxAppInfo appInfoWithoutSecret = new DbxAppInfo(appInfo.getKey());
    DbxPKCEWebAuth pkceWebAuth = new DbxPKCEWebAuth(requestConfig, appInfoWithoutSecret);
    DbxWebAuth.Request webAuthRequest = DbxWebAuth.newRequestBuilder().withNoRedirect().withTokenAccessType(TokenAccessType.OFFLINE).build();
    String authorizeUrl = pkceWebAuth.authorize(webAuthRequest);
    System.out.println("1. Go to " + authorizeUrl);
    System.out.println("2. Click \"Allow\" (you might have to log in first).");
    System.out.println("3. Copy the authorization code.");
    System.out.print("Enter the authorization code here: ");
    String code = new BufferedReader(new InputStreamReader(System.in)).readLine();
    if (code == null) {
        System.exit(1);
    }
    code = code.trim();
    try {
        // exchange.
        return pkceWebAuth.finishFromCode(code);
    } catch (DbxException ex) {
        System.err.println("Error in DbxWebAuth.authorize: " + ex.getMessage());
        System.exit(1);
        return null;
    }
}
Also used : DbxRequestConfig(com.dropbox.core.DbxRequestConfig) InputStreamReader(java.io.InputStreamReader) DbxAppInfo(com.dropbox.core.DbxAppInfo) BufferedReader(java.io.BufferedReader) DbxPKCEWebAuth(com.dropbox.core.DbxPKCEWebAuth) DbxException(com.dropbox.core.DbxException) DbxWebAuth(com.dropbox.core.DbxWebAuth)

Example 15 with DbxException

use of com.dropbox.core.DbxException in project dropbox-sdk-java by dropbox.

the class ShortLiveTokenAuthorize method authorize.

public DbxAuthFinish authorize(DbxAppInfo appInfo) throws IOException {
    // Run through Dropbox API authorization process
    DbxRequestConfig requestConfig = new DbxRequestConfig("examples-authorize");
    DbxWebAuth webAuth = new DbxWebAuth(requestConfig, appInfo);
    // TokenAccessType.OFFLINE means refresh_token + access_token. ONLINE means access_token only.
    DbxWebAuth.Request webAuthRequest = DbxWebAuth.newRequestBuilder().withNoRedirect().withTokenAccessType(TokenAccessType.OFFLINE).build();
    String authorizeUrl = webAuth.authorize(webAuthRequest);
    System.out.println("1. Go to " + authorizeUrl);
    System.out.println("2. Click \"Allow\" (you might have to log in first).");
    System.out.println("3. Copy the authorization code.");
    System.out.print("Enter the authorization code here: ");
    String code = new BufferedReader(new InputStreamReader(System.in)).readLine();
    if (code == null) {
        System.exit(1);
    }
    code = code.trim();
    try {
        return webAuth.finishFromCode(code);
    } catch (DbxException ex) {
        System.err.println("Error in DbxWebAuth.authorize: " + ex.getMessage());
        System.exit(1);
        return null;
    }
}
Also used : DbxRequestConfig(com.dropbox.core.DbxRequestConfig) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) DbxException(com.dropbox.core.DbxException) DbxWebAuth(com.dropbox.core.DbxWebAuth)

Aggregations

DbxException (com.dropbox.core.DbxException)31 FileMetadata (com.dropbox.core.v2.files.FileMetadata)14 IOException (java.io.IOException)14 DbxRequestConfig (com.dropbox.core.DbxRequestConfig)10 Metadata (com.dropbox.core.v2.files.Metadata)9 DbxClientV2 (com.dropbox.core.v2.DbxClientV2)8 FolderMetadata (com.dropbox.core.v2.files.FolderMetadata)8 DbxWebAuth (com.dropbox.core.DbxWebAuth)7 File (java.io.File)6 JsonReader (com.dropbox.core.json.JsonReader)5 DeletedMetadata (com.dropbox.core.v2.files.DeletedMetadata)5 ListFolderResult (com.dropbox.core.v2.files.ListFolderResult)5 FileInputStream (java.io.FileInputStream)5 InputStream (java.io.InputStream)5 DbxAuthInfo (com.dropbox.core.DbxAuthInfo)4 BufferedReader (java.io.BufferedReader)4 FileOutputStream (java.io.FileOutputStream)4 InputStreamReader (java.io.InputStreamReader)4 Uri (android.net.Uri)3 DbxAppInfo (com.dropbox.core.DbxAppInfo)3