Search in sources :

Example 36 with DbxClientV2

use of com.dropbox.core.v2.DbxClientV2 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 != 3) {
        System.out.println("");
        System.out.println("Usage: COMMAND <auth-file> <local-path> <dropbox-path>");
        System.out.println("");
        System.out.println(" <auth-file>: An \"auth file\" that contains the information necessary to make");
        System.out.println("    an authorized Dropbox API request.  Generate this file using the \"authorize\"");
        System.out.println("    example program.");
        System.out.println("");
        System.out.println(" <local-path>: The path to a local file whose contents you want to upload.");
        System.out.println("");
        System.out.println(" <dropbox-path>: The path on Dropbox to save the file to.");
        System.out.println("");
        System.exit(1);
        return;
    }
    String argAuthFile = args[0];
    String localPath = args[1];
    String dropboxPath = args[2];
    // Read auth info file.
    DbxAuthInfo authInfo;
    try {
        authInfo = DbxAuthInfo.Reader.readFromFile(argAuthFile);
    } catch (JsonReader.FileLoadException ex) {
        System.err.println("Error loading <auth-file>: " + ex.getMessage());
        System.exit(1);
        return;
    }
    String pathError = DbxPathV2.findError(dropboxPath);
    if (pathError != null) {
        System.err.println("Invalid <dropbox-path>: " + pathError);
        System.exit(1);
        return;
    }
    File localFile = new File(localPath);
    if (!localFile.exists()) {
        System.err.println("Invalid <local-path>: file does not exist.");
        System.exit(1);
        return;
    }
    if (!localFile.isFile()) {
        System.err.println("Invalid <local-path>: not a file.");
        System.exit(1);
        return;
    }
    // Create a DbxClientV2, which is what you use to make API calls.
    DbxRequestConfig requestConfig = new DbxRequestConfig("examples-upload-file");
    DbxClientV2 dbxClient = new DbxClientV2(requestConfig, authInfo.getAccessToken(), authInfo.getHost());
    // deciding factor. This should really depend on your network.
    if (localFile.length() <= (2 * CHUNKED_UPLOAD_CHUNK_SIZE)) {
        uploadFile(dbxClient, localFile, dropboxPath);
    } else {
        chunkedUploadFile(dbxClient, localFile, dropboxPath);
    }
    System.exit(0);
}
Also used : DbxClientV2(com.dropbox.core.v2.DbxClientV2) DbxRequestConfig(com.dropbox.core.DbxRequestConfig) DbxAuthInfo(com.dropbox.core.DbxAuthInfo) JsonReader(com.dropbox.core.json.JsonReader) File(java.io.File)

Example 37 with DbxClientV2

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

the class DbxRefreshTest method testRefreshUserClient.

@Test
public void testRefreshUserClient() throws Exception {
    ByteArrayInputStream responseStream = new ByteArrayInputStream(("{" + "\"token_type\":\"Bearer\"" + ",\"access_token\":\"" + NEW_TOKEN + "\"" + ",\"expires_in\":" + EXPIRES_IN_SECONDS + "}").getBytes("UTF-8"));
    HttpRequestor.Response finishResponse = new HttpRequestor.Response(200, responseStream, new HashMap<String, List<String>>());
    long currentMillis = System.currentTimeMillis();
    // Mock requester and uploader
    HttpRequestor.Uploader mockUploader = mock(HttpRequestor.Uploader.class);
    DbxRequestConfig mockConfig = setupMockRequestConfig(finishResponse, mockUploader);
    // Execute Refreshing
    long expiresAtMs = currentMillis + EXPIRES_IN_SECONDS * 1000;
    DbxCredential credential = new DbxCredential(EXPIRED_TOKEN, expiresAtMs, REFRESH_TOKEN, APP.getKey(), APP.getSecret());
    DbxClientV2 client = new DbxClientV2(mockConfig, credential);
    DbxRefreshResult token = client.refreshAccessToken();
    // 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
    assertThat(refreshParams.get("grant_type").get(0)).isEqualTo("refresh_token");
    assertThat(refreshParams.get("refresh_token").get(0)).isEqualTo(REFRESH_TOKEN);
    assertThat(refreshParams.containsKey("client_id")).isFalse();
    assertThat(credential.getAccessToken()).isEqualTo(NEW_TOKEN);
    assertThat(credential.getExpiresAt()).isLessThan(expiresAtMs + OFFSET_BETWEEN_CALLS_IN_MS);
    assertThat(token.getExpiresAt()).isLessThan(expiresAtMs + OFFSET_BETWEEN_CALLS_IN_MS);
}
Also used : HttpRequestor(com.dropbox.core.http.HttpRequestor) Matchers.anyString(org.mockito.Matchers.anyString) DbxClientV2(com.dropbox.core.v2.DbxClientV2) DbxRequestConfig(com.dropbox.core.DbxRequestConfig) ByteArrayInputStream(java.io.ByteArrayInputStream) List(java.util.List) Test(org.testng.annotations.Test)

Example 38 with DbxClientV2

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

the class DbxRefreshTest method testGrantRevoked.

@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) {
        assertThat(e.getDbxOAuthError().getError()).isEqualTo("invalid_grant");
        return;
    }
    fail("Should not reach here.");
}
Also used : DbxClientV2(com.dropbox.core.v2.DbxClientV2) HttpRequestor(com.dropbox.core.http.HttpRequestor) DbxRequestConfig(com.dropbox.core.DbxRequestConfig) ByteArrayInputStream(java.io.ByteArrayInputStream) List(java.util.List) Matchers.anyString(org.mockito.Matchers.anyString) Test(org.testng.annotations.Test)

Example 39 with DbxClientV2

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

the class DbxRefreshTest method testMissingScope.

@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) {
        assertThat(ex.getAuthError().isMissingScope()).isTrue();
        String missingScope = ex.getAuthError().getMissingScopeValue().getRequiredScope();
        assertWithMessage("expect account.info.read, get " + missingScope).that("account.info.read").isEqualTo(missingScope);
    }
}
Also used : HttpRequestor(com.dropbox.core.http.HttpRequestor) Matchers.anyString(org.mockito.Matchers.anyString) DbxClientV2(com.dropbox.core.v2.DbxClientV2) InvalidAccessTokenException(com.dropbox.core.InvalidAccessTokenException) DbxRequestConfig(com.dropbox.core.DbxRequestConfig) ByteArrayInputStream(java.io.ByteArrayInputStream) List(java.util.List) Test(org.testng.annotations.Test)

Example 40 with DbxClientV2

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

the class DbxClientV2Test method testOnlineBadTokenResponse.

@Test
public void testOnlineBadTokenResponse() throws Exception {
    HttpRequestor mockRequestor = mock(HttpRequestor.class);
    DbxRequestConfig config = createRequestConfig().withHttpRequestor(mockRequestor).build();
    DbxCredential credential = new DbxCredential("accesstoken");
    DbxClientV2 client = new DbxClientV2(config, credential);
    FileMetadata expected = constructFileMetadate();
    HttpRequestor.Uploader mockUploader = mockUploader();
    when(mockUploader.finish()).thenReturn(createBadTokenResponse());
    when(mockRequestor.startPost(anyString(), anyHeaders())).thenReturn(mockUploader);
    try {
        client.files().getMetadata(expected.getId());
    } catch (BadResponseException ex) {
        verify(mockRequestor, times(1)).startPost(anyString(), anyHeaders());
        assertThat(credential.getAccessToken()).isEqualTo("accesstoken");
        assertThat(ex.getMessage()).startsWith("Bad JSON:");
        return;
    }
    fail("API v2 call should throw exception");
}
Also used : HttpRequestor(com.dropbox.core.http.HttpRequestor) FileMetadata(com.dropbox.core.v2.files.FileMetadata) DbxCredential(com.dropbox.core.oauth.DbxCredential) Test(org.testng.annotations.Test)

Aggregations

DbxClientV2 (com.dropbox.core.v2.DbxClientV2)25 FileMetadata (com.dropbox.core.v2.files.FileMetadata)24 Test (org.testng.annotations.Test)19 DbxRequestConfig (com.dropbox.core.DbxRequestConfig)18 HttpRequestor (com.dropbox.core.http.HttpRequestor)15 Metadata (com.dropbox.core.v2.files.Metadata)15 DbxException (com.dropbox.core.DbxException)10 DbxCredential (com.dropbox.core.oauth.DbxCredential)10 ByteArrayInputStream (java.io.ByteArrayInputStream)9 JsonReader (com.dropbox.core.json.JsonReader)5 ListFolderResult (com.dropbox.core.v2.files.ListFolderResult)5 FullAccount (com.dropbox.core.v2.users.FullAccount)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)5 DbxAuthInfo (com.dropbox.core.DbxAuthInfo)4 DeletedMetadata (com.dropbox.core.v2.files.DeletedMetadata)4 FolderMetadata (com.dropbox.core.v2.files.FolderMetadata)4 IOException (java.io.IOException)4 Date (java.util.Date)4 NetworkIOException (com.dropbox.core.NetworkIOException)3 ProgressListener (com.dropbox.core.util.IOUtil.ProgressListener)3