com.dropbox.core.DbxRequestConfig Java Examples

The following examples show how to use com.dropbox.core.DbxRequestConfig. 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: AuthActivity.java    From dropbox-sdk-java with MIT License 6 votes vote down vote up
/**
 * Set static authentication parameters. If both host and webHost are provided, we take use
 * host as source of truth.
 */
static void setAuthParams(String appKey, String desiredUid,
                          String[] alreadyAuthedUids, String sessionId, String webHost,
                          String apiType, TokenAccessType tokenAccessType,
                          DbxRequestConfig requestConfig, DbxHost host, String scope,
                          IncludeGrantedScopes includeGrantedScopes) {
    sAppKey = appKey;
    sDesiredUid = desiredUid;
    sAlreadyAuthedUids = (alreadyAuthedUids != null) ? alreadyAuthedUids : new String[0];
    sSessionId = sessionId;
    sApiType = apiType;
    sTokenAccessType = tokenAccessType;
    sRequestConfig = requestConfig;
    if (host != null) {
        sHost = host;
    } else if (webHost != null) {
        sHost = new DbxHost(
            DbxHost.DEFAULT.getApi(), DbxHost.DEFAULT.getContent(), webHost,
            DbxHost.DEFAULT.getNotify()
        );
    } else {
        sHost = DbxHost.DEFAULT;
    }
    sScope = scope;
    sIncludeGrantedScopes = includeGrantedScopes;
}
 
Example #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
Source File: DbxTeamClientV2.java    From dropbox-sdk-java with MIT License 6 votes vote down vote up
private DbxTeamRawClientV2(
    DbxRequestConfig requestConfig,
    DbxCredential credential,
    DbxHost host,
    String userId,
    String memberId,
    String adminId,
    PathRoot pathRoot) {
    super(requestConfig, host, userId, pathRoot);

    if (credential == null) throw new NullPointerException("credential");

    this.credential = credential;
    this.memberId = memberId;
    this.adminId = adminId;
}
 
Example #9
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 #10
Source File: DbxClientV2Test.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
@Test
public void testDontRefreshBeforeCallIfNotExpired() throws Exception {
    HttpRequestor mockRequestor = mock(HttpRequestor.class);
    DbxRequestConfig config = createRequestConfig()
        .withHttpRequestor(mockRequestor)
        .build();

    long now = System.currentTimeMillis();

    DbxCredential credential = new DbxCredential("accesstoken", now + 2*DbxCredential
        .EXPIRE_MARGIN,
        "refresh_token",
        "appkey", "app_secret");

    DbxClientV2 client = new DbxClientV2(config, credential);
    FileMetadata expected = constructFileMetadate();

    HttpRequestor.Uploader mockUploader = mockUploader();
    when(mockUploader.finish()).thenReturn(createSuccessResponse(serialize(expected)));

    when(mockRequestor.startPost(anyString(), anyHeaders()))
        .thenReturn(mockUploader);

    Metadata actual = client.files().getMetadata(expected.getId());

    verify(mockRequestor, times(1)).startPost(anyString(), anyHeaders());
    assertEquals(credential.getAccessToken(), "accesstoken");

    assertEquals(actual.getName(), expected.getName());
    assertTrue(actual instanceof FileMetadata, actual.getClass().toString());
    assertEquals(((FileMetadata) actual).getId(), expected.getId());
}
 
Example #11
Source File: Main.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
private static DbxClientV2 createClient(String authFile) {
    DbxAuthInfo authInfo;
    try {
        authInfo = DbxAuthInfo.Reader.readFromFile(authFile);
    } catch (JsonReader.FileLoadException ex) {
        System.err.println("Error loading <auth-file>: " + ex.getMessage());
        System.exit(1);
        return null;
    }

    DbxRequestConfig requestConfig = new DbxRequestConfig("examples-proguard");
    return new DbxClientV2(requestConfig, authInfo.getAccessToken(), authInfo.getHost());
}
 
Example #12
Source File: DbxClientV2Test.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
@Test
public void testRefreshAndRetryAfterTokenExpired() throws Exception {
    HttpRequestor mockRequestor = mock(HttpRequestor.class);
    DbxRequestConfig config = createRequestConfig()
        .withHttpRequestor(mockRequestor)
        .build();

    long now = System.currentTimeMillis();

    DbxCredential credential = new DbxCredential("accesstoken", now + 2*DbxCredential
        .EXPIRE_MARGIN,
        "refresh_token",
        "appkey", "app_secret");

    DbxClientV2 client = new DbxClientV2(config, credential);
    FileMetadata expected = constructFileMetadate();

    HttpRequestor.Uploader mockUploader = mockUploader();
    when(mockUploader.finish())
        .thenReturn(createTokenExpiredResponse())
        .thenReturn(createSuccessRefreshResponse("new_token", 14400L))
        .thenReturn(createSuccessResponse(serialize(expected)));

    when(mockRequestor.startPost(anyString(), anyHeaders()))
        .thenReturn(mockUploader);

    Metadata actual = client.files().getMetadata(expected.getId());

    verify(mockRequestor, times(3)).startPost(anyString(), anyHeaders());
    assertEquals(credential.getAccessToken(), "new_token");

    assertEquals(actual.getName(), expected.getName());
    assertTrue(actual instanceof FileMetadata, actual.getClass().toString());
    assertEquals(((FileMetadata) actual).getId(), expected.getId());
}
 
Example #13
Source File: DbxRefershTest.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
@Test
public void testGrantRevoked() throws Exception{
    ByteArrayInputStream responseStream = new ByteArrayInputStream(
        (
            "{" +
                "\"error_description\":\"refresh token is invalid or revoked\"" +
                ",\"error\":\"invalid_grant\"" +
                "}"
        ).getBytes("UTF-8")
    );
    HttpRequestor.Response finishResponse = new HttpRequestor.Response(
        400, responseStream, new HashMap<String, List<String>>());

    // Mock requester and uploader
    HttpRequestor.Uploader mockUploader = mock(HttpRequestor.Uploader.class);
    DbxRequestConfig mockConfig = setupMockRequestConfig(finishResponse, mockUploader);

    // Execute Refresh
    DbxCredential credential = new DbxCredential(EXPIRED_TOKEN, 100L, REFRESH_TOKEN,
        APP.getKey(), APP.getSecret());
    DbxClientV2 client = new DbxClientV2(mockConfig, credential);

    try {
        client.refreshAccessToken();
    } catch (DbxOAuthException e) {
        assertEquals(e.getDbxOAuthError().getError(), "invalid_grant");
        return;
    }

    fail("Should not reach here.");
}
 
Example #14
Source File: DbxClientV2.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
DbxUserRawClientV2(DbxRequestConfig requestConfig, DbxCredential credential, DbxHost host,
                   String userId, PathRoot pathRoot) {
    super(requestConfig, host, userId, pathRoot);

    if (credential == null) throw new NullPointerException("credential");
    this.credential = credential;
}
 
Example #15
Source File: ShortLiveTokenAuthorize.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
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;
    }
}
 
Example #16
Source File: PkceAuthorize.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
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 {
        // You must use the same DbxPKCEWebAuth to generate authorizationUrl and to handle code
        // exchange.
        return pkceWebAuth.finishFromCode(code);
    } catch (DbxException ex) {
        System.err.println("Error in DbxWebAuth.authorize: " + ex.getMessage());
        System.exit(1); return null;
    }
}
 
Example #17
Source File: DbxRefershTest.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
@Test
public void testDownScoping() throws Exception {
    ByteArrayInputStream responseStream = new ByteArrayInputStream(
        (
            "{" +
                "\"token_type\":\"Bearer\"" +
                ",\"access_token\":\"" + NEW_TOKEN + "\"" +
                ",\"expires_in\":" + EXPIRES_IN +
                ",\"scope\":" + "\"myscope1\"" +
            "}"
        ).getBytes("UTF-8")
    );
    HttpRequestor.Response finishResponse = new HttpRequestor.Response(
        200, responseStream, new HashMap<String, List<String>>());
    long currentMilllis = System.currentTimeMillis();

    // Mock requester and uploader
    HttpRequestor.Uploader mockUploader = mock(HttpRequestor.Uploader.class);
    DbxRequestConfig mockConfig = setupMockRequestConfig(finishResponse, mockUploader);

    // Execute Refreshing
    DbxCredential credential = new DbxCredential(EXPIRED_TOKEN, EXPIRES_IN, REFRESH_TOKEN,
        APP.getKey());
    DbxRefreshResult refreshResult = credential.refresh(mockConfig, Arrays.asList("myscope1", "myscope2"));

    // Get URL Param
    ArgumentCaptor<byte[]> paramCaptor = ArgumentCaptor.forClass(byte[].class);
    verify(mockUploader).upload(paramCaptor.capture());
    Map<String, List<String>> refreshParams = toParamsMap(new String(paramCaptor.getValue(), "UTF-8"));

    // Verification
    assertEquals(refreshParams.get("grant_type").get(0), "refresh_token");
    assertEquals(refreshParams.get("refresh_token").get(0), REFRESH_TOKEN);
    assertEquals(refreshParams.get("client_id").get(0), APP.getKey());
    assertEquals(refreshParams.get("scope").get(0), "myscope1 myscope2");
    assertEquals(credential.getAccessToken(), NEW_TOKEN);
    assertTrue(currentMilllis + EXPIRES_IN < credential.getExpiresAt());
    assertEquals(refreshResult.getScope(), "myscope1");
}
 
Example #18
Source File: DropboxStorageProvider.java    From sling-whiteboard with Apache License 2.0 5 votes vote down vote up
@Activate
private void activate(DropboxStorageProviderConfiguration configuration) {
    if (StringUtils.isNotEmpty(configuration.accessToken())) {
        DbxRequestConfig requestConfig = DbxRequestConfig.newBuilder(this.getClass().getName()).build();
        client = new DbxClientV2(requestConfig, configuration.accessToken());
        StandardHttpRequestor.Config longpollConfig = StandardHttpRequestor.Config.DEFAULT_INSTANCE.copy().withReadTimeout(5,
                TimeUnit.MINUTES).build();
        DbxRequestConfig pollingRequestConfig = DbxRequestConfig.newBuilder(this.getClass().getName() + "-longpoll")
                .withHttpRequestor(new StandardHttpRequestor(longpollConfig))
                .build();
        longPollClient = new DbxClientV2(pollingRequestConfig, configuration.accessToken());
        try {
            FullAccount account = client.users().getCurrentAccount();
            LOGGER.info("Initialised Dropbox provider for {}.", account.getName().getDisplayName());
            dropboxRootPath = configuration.remote_storage_provider_root();
            if (dropboxRootPath.isEmpty()) {
                dropboxRootPath = "/";
            }
            slingMountPoint = new Path(configuration.resource_provider_root());
            cursor = client.files()
                    .listFolderGetLatestCursorBuilder("/".equals(dropboxRootPath) ? "" : dropboxRootPath)
                    .withIncludeDeleted(true)
                    .withIncludeMediaInfo(false)
                    .withRecursive(true)
                    .start().getCursor();
        } catch (Exception e) {
            LOGGER.error("Unable to initialise a Dropbox Storage Provider for configuration {}.", configuration);
            throw new IllegalStateException(e);
        }
    } else {
        throw new IllegalStateException("The access token cannot be empty.");
    }
}
 
Example #19
Source File: DbxRefershTest.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
@Test
public void testMissingScope() throws Exception {
    Long now = System.currentTimeMillis();
    ByteArrayInputStream responseStream = new ByteArrayInputStream(
        (
            "{" +
                "\"error_summary\":\"missing_scope/.\" ,\"error\":{\".tag\": \"missing_scope\", \"required_scope\": \"account.info.read\"}" +
                "}"
        ).getBytes("UTF-8")
    );
    HttpRequestor.Response finishResponse = new HttpRequestor.Response(
        401, responseStream, new HashMap<String, List<String>>());

    // Mock requester and uploader
    HttpRequestor.Uploader mockUploader = mock(HttpRequestor.Uploader.class);
    DbxRequestConfig mockConfig = setupMockRequestConfig(finishResponse, mockUploader);

    DbxCredential credential = new DbxCredential(NEW_TOKEN, now +2 * DbxCredential.EXPIRE_MARGIN,
        REFRESH_TOKEN,
        APP.getKey(), APP.getSecret());
    DbxClientV2 client = new DbxClientV2(mockConfig, credential);

    try {
        client.users().getCurrentAccount();
        fail("Should raise exception before reaching here");
    } catch (InvalidAccessTokenException ex) {
        assertTrue(ex.getAuthError().isMissingScope());
        String missingScope = ex.getAuthError().getMissingScopeValue().getRequiredScope();
        assertEquals("account.info.read", missingScope, "expect account.info.read, get " + missingScope);
    }
}
 
Example #20
Source File: DbxRawClientV2.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
/**
 * @param requestConfig Configuration controlling How requests should be issued to Dropbox
 * servers.
 * @param host Dropbox server hostnames (primarily for internal use)
 * @param userId The user ID of the current Dropbox account. Used for multi-Dropbox account use-case.
 * @param pathRoot We will send this value in Dropbox-API-Path-Root header if it presents.
 */
protected DbxRawClientV2(DbxRequestConfig requestConfig, DbxHost host, String userId, PathRoot pathRoot) {
    if (requestConfig == null) throw new NullPointerException("requestConfig");
    if (host == null) throw new NullPointerException("host");

    this.requestConfig = requestConfig;
    this.host = host;
    this.userId = userId;
    this.pathRoot = pathRoot;
}
 
Example #21
Source File: DbxClientV2Test.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
@Test
public void testRefreshBeforeCall() throws Exception {
    HttpRequestor mockRequestor = mock(HttpRequestor.class);
    DbxRequestConfig config = createRequestConfig()
        .withHttpRequestor(mockRequestor)
        .build();

    DbxCredential credential = new DbxCredential("accesstoken", 10L, "refresh_token",
        "appkey", "app_secret");

    DbxClientV2 client = new DbxClientV2(config, credential);
    FileMetadata expected = constructFileMetadate();

    HttpRequestor.Uploader mockUploader = mockUploader();
    when(mockUploader.finish())
        .thenReturn(createSuccessRefreshResponse("newToken", 10L))
        .thenReturn(createSuccessResponse(serialize(expected)));

    when(mockRequestor.startPost(anyString(), anyHeaders()))
        .thenReturn(mockUploader);

    long now = System.currentTimeMillis();

    Metadata actual = client.files().getMetadata(expected.getId());

    verify(mockRequestor, times(2)).startPost(anyString(), anyHeaders());

    assertEquals(credential.getAccessToken(), "newToken");
    assertTrue(credential.getExpiresAt() > now);

    assertEquals(actual.getName(), expected.getName());
    assertTrue(actual instanceof FileMetadata, actual.getClass().toString());
    assertEquals(((FileMetadata) actual).getId(), expected.getId());
}
 
Example #22
Source File: DbxClientV2Test.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
@Test
public void testRetrySuccessWithBackoff() throws Exception {
    HttpRequestor mockRequestor = mock(HttpRequestor.class);
    DbxRequestConfig config = createRequestConfig()
        .withAutoRetryEnabled(3)
        .withHttpRequestor(mockRequestor)
        .build();

    DbxClientV2 client = new DbxClientV2(config, "fakeAccessToken");
    FileMetadata expected = constructFileMetadate();

    // 503 twice, then return result
    HttpRequestor.Uploader mockUploader = mockUploader();
    when(mockUploader.finish())
        .thenReturn(createEmptyResponse(503))   // no backoff
        .thenReturn(createRateLimitResponse(1)) // backoff 1 sec
        .thenReturn(createRateLimitResponse(2)) // backoff 2 sec
        .thenReturn(createSuccessResponse(serialize(expected)));

    when(mockRequestor.startPost(anyString(), anyHeaders()))
        .thenReturn(mockUploader);

    long start = System.currentTimeMillis();
    Metadata actual = client.files().getMetadata(expected.getId());
    long end = System.currentTimeMillis();

    // no way easy way to properly test this, but request should
    // have taken AT LEAST 3 seconds due to backoff.
    assertTrue((end - start) >= 3000L, "duration: " + (end - start) + " millis");

    // should have been called 4 times: initial call + 3 retries
    verify(mockRequestor, times(4)).startPost(anyString(), anyHeaders());

    assertEquals(actual.getName(), expected.getName());
    assertTrue(actual instanceof FileMetadata, actual.getClass().toString());
}
 
Example #23
Source File: DbxClientV2Test.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
@Test
public void testRetryDownload() throws Exception {
    HttpRequestor mockRequestor = mock(HttpRequestor.class);
    DbxRequestConfig config = createRequestConfig()
        .withAutoRetryEnabled(3)
        .withHttpRequestor(mockRequestor)
        .build();

    DbxClientV2 client = new DbxClientV2(config, "fakeAccessToken");
    FileMetadata expectedMetadata = constructFileMetadate();
    byte [] expectedBytes = new byte [] { 1, 2, 3, 4 };

    // 503 once, then return 200
    HttpRequestor.Uploader mockUploader = mockUploader();
    when(mockUploader.finish())
        .thenReturn(createEmptyResponse(503))
        .thenReturn(createDownloaderResponse(expectedBytes, serialize(expectedMetadata)));
    when(mockRequestor.startPost(anyString(), anyHeaders()))
        .thenReturn(mockUploader);

    DbxDownloader<FileMetadata> downloader = client.files().download(expectedMetadata.getId());

    // should have been attempted twice
    verify(mockRequestor, times(2)).startPost(anyString(), anyHeaders());

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    FileMetadata actualMetadata = downloader.download(bout);
    byte [] actualBytes = bout.toByteArray();

    assertEquals(actualBytes, expectedBytes);
    assertEquals(actualMetadata, expectedMetadata);
}
 
Example #24
Source File: DbxClientV2Test.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
@Test
public void testRetrySuccess() throws Exception {
    HttpRequestor mockRequestor = mock(HttpRequestor.class);
    DbxRequestConfig config = createRequestConfig()
        .withAutoRetryEnabled(3)
        .withHttpRequestor(mockRequestor)
        .build();

    DbxClientV2 client = new DbxClientV2(config, "fakeAccessToken");
    FileMetadata expected = constructFileMetadate();

    // 503 twice, then return result
    HttpRequestor.Uploader mockUploader = mockUploader();
    when(mockUploader.finish())
        .thenReturn(createEmptyResponse(503))
        .thenReturn(createEmptyResponse(503))
        .thenReturn(createSuccessResponse(serialize(expected)));

    when(mockRequestor.startPost(anyString(), anyHeaders()))
        .thenReturn(mockUploader);

    Metadata actual = client.files().getMetadata(expected.getId());

    // should have only been called 3 times: initial call + 2 retries
    verify(mockRequestor, times(3)).startPost(anyString(), anyHeaders());

    assertEquals(actual.getName(), expected.getName());
    assertTrue(actual instanceof FileMetadata, actual.getClass().toString());
    assertEquals(((FileMetadata) actual).getId(), expected.getId());
}
 
Example #25
Source File: DbxClientV1Test.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
@Test
public void testRetryDownload() throws DbxException, IOException {
    HttpRequestor mockRequestor = mock(HttpRequestor.class);
    DbxRequestConfig config = createRequestConfig()
        .withAutoRetryEnabled(3)
        .withHttpRequestor(mockRequestor)
        .build();

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

    // load File metadata json
    InputStream in = getClass().getResourceAsStream("/file-with-photo-info.json");
    assertNotNull(in);
    String metadataJson = IOUtil.toUtf8String(in);

    byte [] expected = new byte [] { 1, 2, 3, 4 };

    // 503 once, then return 200
    when(mockRequestor.doGet(anyString(), anyHeaders()))
        .thenReturn(createEmptyResponse(503))
        .thenReturn(createDownloaderResponse(expected, "X-Dropbox-Metadata", metadataJson));

    Downloader downloader = client.startGetThumbnail(
        DbxThumbnailSize.w64h64,
        DbxThumbnailFormat.JPEG,
        "/foo/bar.jpg",
        null
    );

    // should have been attempted twice
    verify(mockRequestor, times(2)).doGet(anyString(), anyHeaders());

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    IOUtil.copyStreamToStream(downloader.body, bout);
    byte [] actual = bout.toByteArray();

    assertEquals(actual, expected);
    assertEquals(downloader.metadata.path, "/Photos/Sample Album/Boston City Flow.jpg");
}
 
Example #26
Source File: DbxClientV1Test.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
@Test
public void testRetrySuccess() throws DbxException, IOException {
    HttpRequestor mockRequestor = mock(HttpRequestor.class);
    DbxRequestConfig config = createRequestConfig()
        .withAutoRetryEnabled(3)
        .withHttpRequestor(mockRequestor)
        .build();

    DbxClientV1 client = new DbxClientV1(config, "fakeAccessToken");
    String json = "{\"reset\":true,\"entries\":[],\"cursor\":\"fakeCursor\",\"has_more\":true}";


    // 503 twice, then return result
    HttpRequestor.Uploader mockUploader = mockUploader();
    when(mockUploader.finish())
        .thenReturn(createEmptyResponse(503))   // no backoff
        .thenReturn(createRateLimitResponse(1)) // backoff 1 sec
        .thenReturn(createRateLimitResponse(2)) // backoff 2 sec
        .thenReturn(createSuccessResponse(json));

    when(mockRequestor.startPost(anyString(), anyHeaders()))
        .thenReturn(mockUploader);

    long start = System.currentTimeMillis();
    DbxDelta<DbxEntry> actual = client.getDelta(null);
    long end = System.currentTimeMillis();

    // no way easy way to properly test this, but request should
    // have taken AT LEAST 3 seconds due to backoff.
    assertTrue((end - start) >= 3000L, "duration: " + (end - start) + " millis");

    // should have been called 4 times: initial call + 3 retries
    verify(mockRequestor, times(4)).startPost(anyString(), anyHeaders());

    assertEquals(actual.reset, true);
    assertEquals(actual.cursor, "fakeCursor");
}
 
Example #27
Source File: Auth.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
public static void startOAuth2PKCE(Context context, String appKey, DbxRequestConfig
    requestConfig, DbxHost host, Collection<String> scope) {
    if (requestConfig == null) {
        throw new IllegalArgumentException("Invalid Dbx requestConfig for PKCE flow.");
    }
    startOAuth2Authentication(context, appKey, null, null, null, null, TokenAccessType
        .OFFLINE, requestConfig, host, scope, null);
}
 
Example #28
Source File: Auth.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
private static void startOAuth2Authentication(Context context,
                                              String appKey,
                                              String desiredUid,
                                              String[] alreadyAuthedUids,
                                              String sessionId,
                                              String webHost,
                                              TokenAccessType tokenAccessType,
                                              DbxRequestConfig requestConfig,
                                              DbxHost host) {
    startOAuth2Authentication(context, appKey, desiredUid, alreadyAuthedUids, sessionId,
        webHost, tokenAccessType, requestConfig, host, null, null);
}
 
Example #29
Source File: Auth.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
private static void startOAuth2Authentication(Context context,
                                              String appKey,
                                              String desiredUid,
                                              String[] alreadyAuthedUids,
                                              String sessionId,
                                              String webHost,
                                              TokenAccessType tokenAccessType,
                                              DbxRequestConfig requestConfig,
                                              DbxHost host,
                                              Collection<String>  scope,
                                              IncludeGrantedScopes includeGrantedScopes) {
    if (!AuthActivity.checkAppBeforeAuth(context, appKey, true /*alertUser*/)) {
        return;
    }

    if (alreadyAuthedUids != null && Arrays.asList(alreadyAuthedUids).contains(desiredUid)) {
        throw new IllegalArgumentException("desiredUid cannot be present in alreadyAuthedUids");
    }

    String scopeString = null;
    if (scope != null) {
        scopeString = StringUtil.join(scope, " ");
    }

    // Start Dropbox auth activity.
    String apiType = "1";
    Intent intent =  AuthActivity.makeIntent(
        context, appKey, desiredUid, alreadyAuthedUids, sessionId, webHost, apiType,
        tokenAccessType, requestConfig, host, scopeString, includeGrantedScopes
    );
    if (!(context instanceof Activity)) {
        // If starting the intent outside of an Activity, must include
        // this. See startActivity(). Otherwise, we prefer to stay in
        // the same task.
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    }
    context.startActivity(intent);
}
 
Example #30
Source File: AuthActivity.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
/**
 * If both host and webHost are provided, we take use host as source of truth.
 */
static Intent makeIntent(
    Context context, String appKey, String desiredUid, String[] alreadyAuthedUids,
    String sessionId, String webHost, String apiType, TokenAccessType tokenAccessType,
    DbxRequestConfig requestConfig, DbxHost host, String scope, IncludeGrantedScopes includeGrantedScopes
) {
    if (appKey == null) throw new IllegalArgumentException("'appKey' can't be null");
    setAuthParams(
        appKey, desiredUid, alreadyAuthedUids, sessionId, webHost, apiType, tokenAccessType,
        requestConfig, host, scope, includeGrantedScopes
    );
    return new Intent(context, AuthActivity.class);
}