com.dropbox.core.DbxException Java Examples

The following examples show how to use com.dropbox.core.DbxException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DropboxPublicShareUrlProvider.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Override
public DescriptiveUrl toDownloadUrl(final Path file, final Void options, final PasswordCallback callback) throws BackgroundException {
    try {
        final SharedLinkMetadata share = new DbxUserSharingRequests(session.getClient(file)).createSharedLinkWithSettings(containerService.getKey(file),
            SharedLinkSettings.newBuilder().withRequestedVisibility(RequestedVisibility.PUBLIC).build());
        if(log.isDebugEnabled()) {
            log.debug(String.format("Created shared link %s", share));
        }
        return new DescriptiveUrl(URI.create(share.getUrl()), DescriptiveUrl.Type.signed,
            MessageFormat.format(LocaleFactory.localizedString("{0} URL"),
                LocaleFactory.localizedString("Public Share", "Dropbox"))
        );
    }
    catch(DbxException e) {
        throw new DropboxExceptionMappingService().map(e);
    }
}
 
Example #2
Source File: DropboxWriteFeature.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Override
public HttpResponseOutputStream<String> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
    try {
        final DbxUserFilesRequests files = new DbxUserFilesRequests(session.getClient(file));
        final UploadSessionStartUploader start = files.uploadSessionStart();
        new DefaultStreamCloser().close(start.getOutputStream());
        final String sessionId = start.finish().getSessionId();
        if(log.isDebugEnabled()) {
            log.debug(String.format("Obtained session id %s for upload %s", sessionId, file));
        }
        final UploadSessionAppendV2Uploader uploader = open(files, sessionId, 0L);
        return new SegmentingUploadProxyOutputStream(file, status, files, uploader, sessionId);
    }
    catch(DbxException ex) {
        throw new DropboxExceptionMappingService().map("Upload failed.", ex, file);
    }
}
 
Example #3
Source File: DbxRawClientV2.java    From dropbox-sdk-java with MIT License 6 votes vote down vote up
public <ArgT> HttpRequestor.Uploader uploadStyle(String host,
                                                 String path,
                                                 ArgT arg,
                                                 boolean noAuth,
                                                 StoneSerializer<ArgT> argSerializer)
    throws DbxException {

    String uri = DbxRequestUtil.buildUri(host, path);
    List<HttpRequestor.Header> headers = new ArrayList<HttpRequestor.Header>();
    if (!noAuth) {
        refreshAccessTokenIfNeeded();
        addAuthHeaders(headers);
    }
    addUserLocaleHeader(headers, requestConfig);
    addPathRootHeader(headers, this.pathRoot);
    headers.add(new HttpRequestor.Header("Content-Type", "application/octet-stream"));
    headers = DbxRequestUtil.addUserAgentHeader(headers, requestConfig, USER_AGENT_ID);
    headers.add(new HttpRequestor.Header("Dropbox-API-Arg", headerSafeJson(argSerializer, arg)));
    try {
        return requestConfig.getHttpRequestor().startPostInStreamingMode(uri, headers);
    }
    catch (IOException ex) {
        throw new NetworkIOException(ex);
    }
}
 
Example #4
Source File: EditorTopComponent.java    From Open-LaTeX-Studio with MIT License 6 votes vote down vote up
private void displayCloudStatus() {
    String message = "Working locally.";
    String displayName;

    // Check Dropbox connection
    DbxClientV2 client = DbxUtil.getDbxClient();
    if (client != null) {  
        try {
            displayName = client.users().getCurrentAccount().getName().getDisplayName();
            message = "Connected to Dropbox account as " + displayName + ".";
            Cloud.getInstance().setStatus(Cloud.Status.DBX_CONNECTED, " (" + displayName + ")");
        } catch (DbxException ex) {
            // simply stay working locally.
            Cloud.getInstance().setStatus(Cloud.Status.DISCONNECTED);
        }
    }
    
    LOGGER.log(message);
}
 
Example #5
Source File: DbxRawClientV2.java    From dropbox-sdk-java with MIT License 6 votes vote down vote up
/**
 * Retries the execution at most a maximum number of times.
 *
 * <p> This method is an alternative implementation to {@code DbxRequestUtil.runAndRetry(..)}
 * that does <b>not</b> retry 500 errors ({@link com.dropbox.core.ServerException}). To maintain
 * behavior backwards compatibility in v1, we leave the old implementation in {@code
 * DbxRequestUtil} unchanged.
 */
private static <T> T executeRetriable(int maxRetries, RetriableExecution<T> execution) throws DbxWrappedException, DbxException {
    if (maxRetries == 0) {
        return execution.execute();
    }

    int retries = 0;
    while (true) {
        try {
            return execution.execute();
        } catch (RetryException ex) {
            if (retries < maxRetries) {
                ++retries;
                sleepQuietlyWithJitter(ex.getBackoffMillis());
            } else {
                throw ex;
            }
        }
    }
}
 
Example #6
Source File: DbxRawClientV2.java    From dropbox-sdk-java with MIT License 6 votes vote down vote up
private <T> T executeRetriableWithRefresh(int maxRetries, RetriableExecution<T>
    execution) throws DbxWrappedException, DbxException {
    try {
        return executeRetriable(maxRetries, execution);
    } catch (InvalidAccessTokenException ex) {
        if (ex.getMessage() == null) {
            // Java built-in URLConnection would terminate 401 response before receiving body
            // in streaming mode. Give up.
            throw ex;
        }

        AuthError authError = ex.getAuthError();

        if (AuthError.EXPIRED_ACCESS_TOKEN.equals(authError) && canRefreshAccessToken()) {
            // retry with new access token.
            refreshAccessToken();
            return executeRetriable(maxRetries, execution);
        } else {
            // Doesn't need refresh.
            throw ex;
        }
    }

}
 
Example #7
Source File: DropBoxVerifierExtension.java    From syndesis with Apache License 2.0 6 votes vote down vote up
private static void verifyCredentials(ResultBuilder builder, Map<String, Object> parameters) {

        String token = ConnectorOptions.extractOption(parameters, "accessToken");
        String clientId = ConnectorOptions.extractOption(parameters, "clientIdentifier");

        try {
            // Create Dropbox client
            DbxRequestConfig config = new DbxRequestConfig(clientId, Locale.getDefault().toString());
            DbxClientV2 client = new DbxClientV2(config, token);
            client.users().getCurrentAccount();
        } catch (DbxException e) {
            builder.error(ResultErrorBuilder
                    .withCodeAndDescription(VerificationError.StandardCode.AUTHENTICATION,
                            "Invalid client identifier and/or access token")
                    .parameterKey("accessToken").parameterKey("clientIdentifier").build());
        }

    }
 
Example #8
Source File: DbxClientV1Test.java    From dropbox-sdk-java with MIT License 6 votes vote down vote up
@Test(expectedExceptions = RetryException.class)
public void testRetryDisabled() throws DbxException, IOException {
    HttpRequestor mockRequestor = mock(HttpRequestor.class);
    DbxRequestConfig config = createRequestConfig()
        .withAutoRetryDisabled()
        .withHttpRequestor(mockRequestor)
        .build();

    DbxClientV1 client = new DbxClientV1(config, "fakeAccessToken");

    // 503 every time
    when(mockRequestor.doGet(anyString(), anyHeaders()))
        .thenReturn(createEmptyResponse(503));

    try {
        client.getAccountInfo();
    } finally {
        // should only have been called once since we disabled retry
        verify(mockRequestor, times(1)).doGet(anyString(), anyHeaders());
    }
}
 
Example #9
Source File: DbxClientV1Test.java    From dropbox-sdk-java with MIT License 6 votes vote down vote up
@Test(expectedExceptions = RetryException.class)
public void testRetryRetriesExceeded() throws DbxException, IOException {
    HttpRequestor mockRequestor = mock(HttpRequestor.class);
    DbxRequestConfig config = createRequestConfig()
        .withAutoRetryEnabled(3)
        .withHttpRequestor(mockRequestor)
        .build();

    DbxClientV1 client = new DbxClientV1(config, "fakeAccessToken");

    // 503 always and forever
    when(mockRequestor.doGet(anyString(), anyHeaders()))
        .thenReturn(createEmptyResponse(503));

    try {
        client.getAccountInfo();
    } finally {
        // should only have been called 4: initial call + max number of retries (3)
        verify(mockRequestor, times(4)).doGet(anyString(), anyHeaders());
    }
}
 
Example #10
Source File: DbxClientV1Test.java    From dropbox-sdk-java with MIT License 6 votes vote down vote up
@Test(expectedExceptions = BadRequestException.class)
public void testRetryOtherFailure() throws DbxException, IOException {
    HttpRequestor mockRequestor = mock(HttpRequestor.class);
    DbxRequestConfig config = createRequestConfig()
        .withAutoRetryEnabled(3)
        .withHttpRequestor(mockRequestor)
        .build();

    DbxClientV1 client = new DbxClientV1(config, "fakeAccessToken");

    // 503 once, then return 400
    when(mockRequestor.doGet(anyString(), anyHeaders()))
        .thenReturn(createEmptyResponse(503))
        .thenReturn(createEmptyResponse(400));

    try {
        client.getAccountInfo();
    } finally {
        // should only have been called 2 times: initial call + one retry
        verify(mockRequestor, times(2)).doGet(anyString(), anyHeaders());
    }
}
 
Example #11
Source File: DbxClientV2Test.java    From dropbox-sdk-java with MIT License 6 votes vote down vote up
@Test(expectedExceptions = RetryException.class)
public void testRetryDisabled() throws DbxException, IOException {
    HttpRequestor mockRequestor = mock(HttpRequestor.class);
    DbxRequestConfig config = createRequestConfig()
        .withAutoRetryDisabled()
        .withHttpRequestor(mockRequestor)
        .build();

    DbxClientV2 client = new DbxClientV2(config, "fakeAccessToken");

    // 503 every time
    HttpRequestor.Uploader mockUploader = mockUploader();
    when(mockUploader.finish())
        .thenReturn(createEmptyResponse(503));
    when(mockRequestor.startPost(anyString(), anyHeaders()))
        .thenReturn(mockUploader);

    try {
        client.users().getCurrentAccount();
    } finally {
        // should only have been called once since we disabled retry
        verify(mockRequestor, times(1)).startPost(anyString(), anyHeaders());
    }
}
 
Example #12
Source File: Main.java    From dropbox-sdk-java with MIT License 6 votes vote down vote up
/**
 * Prints changes made to a folder in Dropbox since the given
 * cursor was retrieved.
 *
 * @param dbxClient Dropbox client to use for fetching folder changes
 * @param cursor lastest cursor received since last set of changes
 *
 * @return latest cursor after changes
 */
private static String printChanges(DbxClientV2 client, String cursor)
    throws DbxApiException, DbxException {

    while (true) {
        ListFolderResult result = client.files()
            .listFolderContinue(cursor);
        for (Metadata metadata : result.getEntries()) {
            String type;
            String details;
            if (metadata instanceof FileMetadata) {
                FileMetadata fileMetadata = (FileMetadata) metadata;
                type = "file";
                details = "(rev=" + fileMetadata.getRev() + ")";
            } else if (metadata instanceof FolderMetadata) {
                FolderMetadata folderMetadata = (FolderMetadata) metadata;
                type = "folder";
                details = folderMetadata.getSharingInfo() != null ? "(shared)" : "";
            } else if (metadata instanceof DeletedMetadata) {
                type = "deleted";
                details = "";
            } else {
                throw new IllegalStateException("Unrecognized metadata type: " + metadata.getClass());
            }

            System.out.printf("\t%10s %24s \"%s\"\n", type, details, metadata.getPathLower());
        }
        // update cursor to fetch remaining results
        cursor = result.getCursor();

        if (!result.getHasMore()) {
            break;
        }
    }

    return cursor;
}
 
Example #13
Source File: DropboxPasswordShareUrlProvider.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Override
public DescriptiveUrl toDownloadUrl(final Path file, final Void options, final PasswordCallback callback) throws BackgroundException {
    try {
        final SharedLinkMetadata share = new DbxUserSharingRequests(session.getClient(file)).createSharedLinkWithSettings(containerService.getKey(file),
            SharedLinkSettings.newBuilder().withRequestedVisibility(RequestedVisibility.PASSWORD).withLinkPassword(callback.prompt(
                session.getHost(), LocaleFactory.localizedString("Passphrase", "Cryptomator"),
                LocaleFactory.localizedString("Provide additional login credentials", "Credentials"), new LoginOptions().icon(session.getHost().getProtocol().disk())
            ).getPassword()).build());
        if(log.isDebugEnabled()) {
            log.debug(String.format("Created shared link %s", share));
        }
        return new DescriptiveUrl(URI.create(share.getUrl()), DescriptiveUrl.Type.signed,
            MessageFormat.format(LocaleFactory.localizedString("{0} URL"),
                LocaleFactory.localizedString("Password Share", "Dropbox"))
        );
    }
    catch(DbxException e) {
        throw new DropboxExceptionMappingService().map(e);
    }
}
 
Example #14
Source File: DropboxDeleteFeature.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException {
    for(Path file : files.keySet()) {
        try {
            callback.delete(file);
            // Delete the file or folder at a given path. If the path is a folder, all its contents will be deleted too.
            if(containerService.isContainer(file)) {
                new DbxUserFilesRequests(session.getClient(file.getParent())).deleteV2(file.getAbsolute());
            }
            else {
                new DbxUserFilesRequests(session.getClient(file)).deleteV2(containerService.getKey(file));
            }
        }
        catch(DbxException e) {
            throw new DropboxExceptionMappingService().map("Cannot delete {0}", e, file);
        }
    }
}
 
Example #15
Source File: DropboxSearchFeature.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Override
public AttributedList<Path> search(final Path workdir, final Filter<Path> regex, final ListProgressListener listener) throws BackgroundException {
    try {
        final AttributedList<Path> list = new AttributedList<>();
        long start = 0;
        SearchV2Result result = new DbxUserFilesRequests(session.getClient(workdir)).searchV2Builder(regex.toPattern().pattern())
            .withOptions(SearchOptions.newBuilder().withPath(containerService.getKey(workdir)).build()).start();
        this.parse(workdir, listener, list, result);
        while(result.getHasMore()) {
            this.parse(workdir, listener, list, result = new DbxUserFilesRequests(session.getClient(workdir)).searchContinueV2(result.getCursor()));
            if(this.parse(workdir, listener, list, result)) {
                return null;
            }
        }
        return list;
    }
    catch(DbxException e) {
        throw new DropboxExceptionMappingService().map("Failure to read attributes of {0}", e, workdir);
    }
}
 
Example #16
Source File: DropboxDirectory.java    From sling-whiteboard with Apache License 2.0 6 votes vote down vote up
@Override
public @NotNull List<RemoteResourceReference> getChildren() {
    ArrayList<RemoteResourceReference> children = new ArrayList<>();
    ListFolderResult result;
    try {
        result = client.files().listFolder(metadata.getPathLower());
        boolean hasMoreResults = true;
        while (hasMoreResults) {
            for (Metadata entry : result.getEntries()) {
                if (!(entry instanceof DeletedMetadata)) {
                    children.add(new DropboxResourceReference(dropboxStorageProvider, entry));
                }
            }
            result = client.files().listFolderContinue(result.getCursor());
            hasMoreResults = result.getHasMore();
        }
    } catch (ListFolderContinueErrorException e) {
        LOGGER.error(String.format("Cannot read all children of folder %s.", metadata.getPathLower()), e);
    } catch (
            DbxException ex) {
        LOGGER.error(String.format("Cannot access path %s on Dropbox.", metadata.getPathLower()), ex);
    }
    return children;
}
 
Example #17
Source File: DropboxSession.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void login(final Proxy proxy, final LoginCallback prompt, final CancelCallback cancel) throws BackgroundException {
    authorizationService.setTokens(authorizationService.authorize(host, prompt, cancel));
    try {
        final Credentials credentials = host.getCredentials();
        final FullAccount account = new DbxUserUsersRequests(client).getCurrentAccount();
        if(log.isDebugEnabled()) {
            log.debug(String.format("Authenticated as user %s", account));
        }
        credentials.setUsername(account.getEmail());
        switch(account.getAccountType()) {
            case BUSINESS:
                locking = new DropboxLockFeature(this);
        }
    }
    catch(DbxException e) {
        throw new DropboxExceptionMappingService().map(e);
    }
}
 
Example #18
Source File: DropboxQuotaFeature.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Space get() throws BackgroundException {
    try {
        final SpaceUsage usage = new DbxUserUsersRequests(session.getClient()).getSpaceUsage();
        final SpaceAllocation allocation = usage.getAllocation();
        if(allocation.isIndividual()) {
            return new Space(usage.getUsed(), allocation.getIndividualValue().getAllocated());
        }
        else if(allocation.isTeam()) {
            return new Space(usage.getUsed(), allocation.getTeamValue().getAllocated());
        }
        return new Space(0L, Long.MAX_VALUE);
    }
    catch(DbxException e) {
        throw new DropboxExceptionMappingService().map("Failure to read attributes of {0}", e,
                new Path(String.valueOf(Path.DELIMITER), EnumSet.of(Path.Type.volume, Path.Type.directory)));
    }
}
 
Example #19
Source File: DropboxRootListService.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
    try {
        if(directory.isRoot()) {
            final FullAccount account = new DbxUserUsersRequests(session.getClient()).getCurrentAccount();
            switch(account.getAccountType()) {
                case BUSINESS:
                    return new DropboxListService(session).list(
                        directory.withAttributes(new PathAttributes().withVersionId(account.getRootInfo().getRootNamespaceId())),
                        new HomeNamespaceListProgressListener(listener, account));
            }
        }
        return new DropboxListService(session).list(directory, listener);
    }
    catch(DbxException e) {
        throw new DropboxExceptionMappingService().map("Listing directory {0} failed", e, directory);
    }
}
 
Example #20
Source File: DropboxListService.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
    try {
        final AttributedList<Path> children = new AttributedList<>();
        ListFolderResult result;
        final DbxRawClientV2 client;
        this.parse(directory, listener, children, result = new DbxUserFilesRequests(session.getClient(directory)).listFolder(containerService.getKey(directory)));
        // If true, then there are more entries available. Pass the cursor to list_folder/continue to retrieve the rest.
        while(result.getHasMore()) {
            this.parse(directory, listener, children, result = new DbxUserFilesRequests(session.getClient(directory)).listFolderContinue(result.getCursor()));
        }
        return children;
    }
    catch(DbxException e) {
        throw new DropboxExceptionMappingService().map("Listing directory {0} failed", e, directory);
    }
}
 
Example #21
Source File: DropboxLockFeature.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Override
public String lock(final Path file) throws BackgroundException {
    if(!containerService.getContainer(file).getType().contains(Path.Type.shared)) {
        log.warn(String.format("Skip attempting to lock file %s not in shared folder", file));
        throw new UnsupportedException();
    }
    try {
        for(LockFileResultEntry result : new DbxUserFilesRequests(session.getClient(file)).lockFileBatch(Collections.singletonList(
            new LockFileArg(containerService.getKey(file)))).getEntries()) {
            if(result.isFailure()) {
                throw this.failure(result);
            }
            if(result.isSuccess()) {
                if(log.isDebugEnabled()) {
                    log.debug(String.format("Locked file %s with result %s", file, result.getSuccessValue()));
                }
                return String.valueOf(true);
            }
        }
        return null;
    }
    catch(DbxException e) {
        throw new DropboxExceptionMappingService().map("Failure to write attributes of {0}", e, file);
    }
}
 
Example #22
Source File: DropboxLockFeature.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void unlock(final Path file, final String token) throws BackgroundException {
    try {
        for(LockFileResultEntry result : new DbxUserFilesRequests(session.getClient(file)).unlockFileBatch(Collections.singletonList(
            new UnlockFileArg(containerService.getKey(file)))).getEntries()) {
            if(result.isFailure()) {
                throw failure(result);
            }
            if(log.isDebugEnabled()) {
                log.debug(String.format("Unlocked file %s with result %s", file, result.getSuccessValue()));
            }
        }
    }
    catch(DbxException e) {
        throw new DropboxExceptionMappingService().map("Failure to write attributes of {0}", e, file);
    }
}
 
Example #23
Source File: DropboxSharedFoldersListService.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
    try {
        final AttributedList<Path> children = new AttributedList<>();
        ListFoldersResult listFoldersResult;
        this.parse(directory, listener, children, listFoldersResult = new DbxUserSharingRequests(session.getClient()).listFolders());
        while(listFoldersResult.getCursor() != null) {
            this.parse(directory, listener, children, listFoldersResult = new DbxUserSharingRequests(session.getClient())
                .listMountableFoldersContinue(listFoldersResult.getCursor()));
        }
        return children;
    }
    catch(DbxException e) {
        throw new DropboxExceptionMappingService().map("Listing directory {0} failed", e, directory);
    }
}
 
Example #24
Source File: DropboxHomeFinderFeature.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Path find() throws BackgroundException {
    final Path directory = super.find();
    if(directory.isRoot()) {
        try {
            // Retrieve he namespace ID for a users home folder and team root folder
            final FullAccount account = new DbxUserUsersRequests(session.getClient()).getCurrentAccount();
            switch(account.getAccountType()) {
                case BUSINESS:
                    if(log.isDebugEnabled()) {
                        log.debug(String.format("Set root namespace %s", account.getRootInfo().getRootNamespaceId()));
                    }
                    return directory.withAttributes(new PathAttributes().withVersionId(account.getRootInfo().getRootNamespaceId()));
            }
        }
        catch(DbxException e) {
            throw new DropboxExceptionMappingService().map(e);
        }
    }
    return directory;
}
 
Example #25
Source File: DropboxTemporaryUrlProvider.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Override
public DescriptiveUrl toDownloadUrl(final Path file, final Void options, final PasswordCallback callback) throws BackgroundException {
    try {
        if(log.isDebugEnabled()) {
            log.debug(String.format("Create temporary link for %s", file));
        }
        // This link will expire in four hours and afterwards you will get 410 Gone.
        final String link = new DbxUserFilesRequests(session.getClient(file)).getTemporaryLink(containerService.getKey(file)).getLink();
        // Determine expiry time for URL
        final Calendar expiry = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
        expiry.add(Calendar.HOUR, 4);
        return new DescriptiveUrl(URI.create(link), DescriptiveUrl.Type.signed,
            MessageFormat.format(LocaleFactory.localizedString("{0} URL"), LocaleFactory.localizedString("Temporary", "S3"))
                + " (" + MessageFormat.format(LocaleFactory.localizedString("Expires {0}", "S3") + ")",
                UserDateFormatterFactory.get().getMediumFormat(expiry.getTimeInMillis()))
        );
    }
    catch(DbxException e) {
        throw new DropboxExceptionMappingService().map(e);
    }
}
 
Example #26
Source File: DbxClientV2Test.java    From dropbox-sdk-java with MIT License 6 votes vote down vote up
@Test(expectedExceptions = BadRequestException.class)
public void testRetryOtherFailure() throws DbxException, IOException {
    HttpRequestor mockRequestor = mock(HttpRequestor.class);
    DbxRequestConfig config = createRequestConfig()
        .withAutoRetryEnabled(3)
        .withHttpRequestor(mockRequestor)
        .build();

    DbxClientV2 client = new DbxClientV2(config, "fakeAccessToken");

    // 503 once, then return 400
    HttpRequestor.Uploader mockUploader = mockUploader();
    when(mockUploader.finish())
        .thenReturn(createEmptyResponse(503))
        .thenReturn(createEmptyResponse(400));
    when(mockRequestor.startPost(anyString(), anyHeaders()))
        .thenReturn(mockUploader);

    try {
        client.users().getCurrentAccount();
    } finally {
        // should only have been called 2 times: initial call + retry
        verify(mockRequestor, times(2)).startPost(anyString(), anyHeaders());
    }
}
 
Example #27
Source File: UploadFileTask.java    From dropbox-sdk-java with MIT License 6 votes vote down vote up
@Override
protected FileMetadata doInBackground(String... params) {
    String localUri = params[0];
    File localFile = UriHelpers.getFileForUri(mContext, Uri.parse(localUri));

    if (localFile != null) {
        String remoteFolderPath = params[1];

        // Note - this is not ensuring the name is a valid dropbox file name
        String remoteFileName = localFile.getName();

        try (InputStream inputStream = new FileInputStream(localFile)) {
            return mDbxClient.files().uploadBuilder(remoteFolderPath + "/" + remoteFileName)
                    .withMode(WriteMode.OVERWRITE)
                    .uploadAndFinish(inputStream);
        } catch (DbxException | IOException e) {
            mException = e;
        }
    }

    return null;
}
 
Example #28
Source File: DbxClientV2Test.java    From dropbox-sdk-java with MIT License 6 votes vote down vote up
@Test(expectedExceptions = RetryException.class)
public void testRetryRetriesExceeded() throws DbxException, IOException {
    HttpRequestor mockRequestor = mock(HttpRequestor.class);
    DbxRequestConfig config = createRequestConfig()
        .withAutoRetryEnabled(3)
        .withHttpRequestor(mockRequestor)
        .build();

    DbxClientV2 client = new DbxClientV2(config, "fakeAccessToken");

    // 503 always and forever
    HttpRequestor.Uploader mockUploader = mockUploader();
    when(mockUploader.finish())
        .thenReturn(createEmptyResponse(503));
    when(mockRequestor.startPost(anyString(), anyHeaders()))
        .thenReturn(mockUploader);

    try {
        client.users().getCurrentAccount();
    } finally {
        // should only have been called 4 times: initial call plus our maximum retry limit
        verify(mockRequestor, times(1 + 3)).startPost(anyString(), anyHeaders());
    }
}
 
Example #29
Source File: DisconnectDropbox.java    From Open-LaTeX-Studio with MIT License 5 votes vote down vote up
@Override
public void actionPerformed(ActionEvent e) {
    Cloud.Status currentCloudStatus = Cloud.getInstance().getStatus();
    Cloud.getInstance().setStatus(Cloud.Status.CONNECTING);

    DbxClientV2 client = DbxUtil.getDbxClient();

    if (client == null) {
        LOGGER.log("Dropbox account already disconnected.");
        Cloud.getInstance().setStatus(Cloud.Status.DISCONNECTED);
        return;
    }
    
    try {
        client.auth().tokenRevoke();

        drtc.updateRevisionsList(null);
        drtc.close();
        revtc.close();

        ApplicationSettings.Setting.DROPBOX_TOKEN.setValue("");
        ApplicationSettings.INSTANCE.save();
        LOGGER.log("Successfully disconnected from Dropbox account.");
        Cloud.getInstance().setStatus(Cloud.Status.DISCONNECTED);

    } catch (DbxException ex) {
        DbxUtil.showDbxAccessDeniedPrompt();
        Cloud.getInstance().setStatus(currentCloudStatus);
    }
}
 
Example #30
Source File: GetCurrentAccountTask.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
@Override
protected FullAccount doInBackground(Void... params) {

    try {
        return mDbxClient.users().getCurrentAccount();

    } catch (DbxException e) {
        mException = e;
    }

    return null;
}