com.dropbox.core.v2.DbxClientV2 Java Examples

The following examples show how to use com.dropbox.core.v2.DbxClientV2. 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: Main.java    From dropbox-sdk-java with MIT License 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    // Only display important log messages.
    Logger.getLogger("").setLevel(Level.WARNING);

    if (args.length != 1) {
        System.out.println("");
        System.out.println("Usage: COMMAND <auth-file>");
        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.exit(1);
        return;
    }

    DbxClientV2 client = createClient(args[0]);

    runTest(client, Main::testBasicSerialization, "testBasicSerialization");
    runTest(client, Main::testEnumeratedSubtypeSerialization, "testEnumeratedSubtypeSerialization");
    runTest(client, Main::testErrorSerialization, "testErrorSerialization");
}
 
Example #2
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 #3
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 #4
Source File: ITUtil.java    From dropbox-sdk-java with MIT License 6 votes vote down vote up
@BeforeSuite
@AfterSuite(alwaysRun=true)
public static void deleteRoot() throws Exception {
    // always use standard HTTP requestor for delete root
    DbxClientV2 client = newClientV2(
        newRequestConfig()
            .withHttpRequestor(newStandardHttpRequestor())
    );
    try {
        client.files().delete(RootContainer.ROOT);
    } catch (DeleteErrorException ex) {
        if (ex.errorValue.isPathLookup() &&
            ex.errorValue.getPathLookupValue().isNotFound()) {
            // ignore
        } else {
            throw ex;
        }
    }
}
 
Example #5
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 #6
Source File: DropboxFilePickerActivity.java    From NoNonsense-FilePicker with Mozilla Public License 2.0 6 votes vote down vote up
@Override
protected AbstractFilePickerFragment<Metadata> getFragment(@Nullable final String startPath,
                                                           final int mode, final boolean allowMultiple,
                                                           final boolean allowCreateDir, final boolean allowExistingFile,
                                                           final boolean singleClick) {
    DropboxFilePickerFragment fragment = null;

    if (!dropboxHelper.authenticationFailed(this)) {
        DbxClientV2 dropboxClient = dropboxHelper.getClient(this);

        if (dropboxClient != null) {
            fragment = new DropboxFilePickerFragment(dropboxClient);
            fragment.setArgs(startPath, mode, allowMultiple, allowCreateDir, allowExistingFile, singleClick);
        }
    }

    return fragment;
}
 
Example #7
Source File: Main.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
/**
 * Returns latest cursor for listing changes to a directory in
 * Dropbox with the given path.
 *
 * @param dbxClient Dropbox client to use for fetching the latest cursor
 * @param path path to directory in Dropbox
 *
 * @return cursor for listing changes to the given Dropbox directory
 */
private static String getLatestCursor(DbxClientV2 dbxClient, String path)
    throws DbxApiException, DbxException {
    ListFolderGetLatestCursorResult result = dbxClient.files()
        .listFolderGetLatestCursorBuilder(path)
        .withIncludeDeleted(true)
        .withIncludeMediaInfo(false)
        .withRecursive(true)
        .start();
    return result.getCursor();
}
 
Example #8
Source File: Main.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
/**
 * Create a new Dropbox client using the given authentication
 * information and HTTP client config.
 *
 * @param auth Authentication information
 * @param config HTTP request configuration
 *
 * @return new Dropbox V2 client
 */
private static DbxClientV2 createClient(DbxAuthInfo auth, StandardHttpRequestor.Config config) {
    String clientUserAgentId = "examples-longpoll";
    StandardHttpRequestor requestor = new StandardHttpRequestor(config);
    DbxRequestConfig requestConfig = DbxRequestConfig.newBuilder(clientUserAgentId)
        .withHttpRequestor(requestor)
        .build();

    return new DbxClientV2(requestConfig, auth.getAccessToken(), auth.getHost());
}
 
Example #9
Source File: PicassoClient.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
public static void init(Context context, DbxClientV2 dbxClient) {

        // Configure picasso to know about special thumbnail requests
        sPicasso = new Picasso.Builder(context)
                .downloader(new OkHttp3Downloader(context))
                .addRequestHandler(new FileThumbnailRequestHandler(dbxClient))
                .build();
    }
 
Example #10
Source File: ITUtil.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
public static DbxClientV2 newClientV2(DbxRequestConfig config) {
    DbxAuthInfo auth = getAuth();
    return new DbxClientV2(
        config,
        auth.getAccessToken(),
        auth.getHost()
    );
}
 
Example #11
Source File: DbxRefershTest.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
@Test
public void testRefreshUserClient() throws Exception {
    ByteArrayInputStream responseStream = new ByteArrayInputStream(
        (
            "{" +
                "\"token_type\":\"Bearer\"" +
                ",\"access_token\":\"" + NEW_TOKEN + "\"" +
                ",\"expires_in\":" + EXPIRES_IN +
            "}"
        ).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(), APP.getSecret());
    DbxClientV2 client = new DbxClientV2(mockConfig, credential);
    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
    assertEquals(refreshParams.get("grant_type").get(0), "refresh_token");
    assertEquals(refreshParams.get("refresh_token").get(0), REFRESH_TOKEN);
    assertFalse(refreshParams.containsKey("client_id"));
    assertEquals(credential.getAccessToken(), NEW_TOKEN);
    assertTrue(currentMilllis + EXPIRES_IN < credential.getExpiresAt());
}
 
Example #12
Source File: DropboxBrowse.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
private DbxClientV2 requireDbxClient(HttpServletRequest request, HttpServletResponse response, User user)
        throws IOException, ServletException
{
    if (user.dropboxAccessToken == null) {
        common.pageSoftError(response, "This page requires a user whose has linked to their Dropbox account.  Current user hasn't linked us to their Dropbox account.");
        return null;
    }

    return new DbxClientV2(common.getRequestConfig(request),
                           user.dropboxAccessToken,
                           common.dbxAppInfo.getHost());
}
 
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: DropboxFilePickerFragment.java    From NoNonsense-FilePicker with Mozilla Public License 2.0 5 votes vote down vote up
@SuppressLint("ValidFragment")
public DropboxFilePickerFragment(final DbxClientV2 api) {
    super();
    if (api == null) {
        throw new IllegalArgumentException("Must be authenticated with Dropbox");
    }

    this.dropboxClient = api;
}
 
Example #15
Source File: DbxUtil.java    From Open-LaTeX-Studio with MIT License 5 votes vote down vote up
public static DbxClientV2 getDbxClient() {
    String accessToken = (String) ApplicationSettings.Setting.DROPBOX_TOKEN.getValue();
    if (accessToken == null) {
        JOptionPane.showMessageDialog(null, 
            "The authentication token has not been set.\n"
                    + "Please connect the application to your Dropbox account first!", 
            "Dropbox authentication token not found", JOptionPane.ERROR_MESSAGE
        );
        return null;
    }
    return new DbxClientV2(getDbxConfig(), accessToken); 
}
 
Example #16
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 #17
Source File: DbxFileActions.java    From Open-LaTeX-Studio with MIT License 5 votes vote down vote up
/**
 * @return List with user's files or empty List if error occurs
 */
public List<DbxEntryDto> getDbxTexEntries(DbxClientV2 client) {
    List<DbxEntryDto> dbxEntries = new ArrayList<>();

    if (client == null) {
        return dbxEntries;
    }

    try {
        ListFolderResult result = client.files().listFolderBuilder("").withRecursive(true).start();
        while (true) {
            for (Metadata metadata : result.getEntries()) {
                if (metadata instanceof FileMetadata) {
                    String name = metadata.getName();
                    if (name.endsWith(TEX_EXTENSION)) {
                        dbxEntries.add(new DbxEntryDto((FileMetadata) metadata));
                    }
                }
            }

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

            result = client.files().listFolderContinue(result.getCursor());
        }
    } catch (DbxException ex) {
        DbxUtil.showDbxAccessDeniedPrompt();
        dbxEntries = new ArrayList<>(); //Empty list
    } finally {
        return dbxEntries;
    }
}
 
Example #18
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 #19
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 #20
Source File: Main.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
private static void testBasicSerialization(DbxClientV2 client) throws DbxException, IOException {
    // Make the /account/info API call.
    FullAccount expected = client.users().getCurrentAccount();
    assertNotNull(expected);

    String accountId = expected.getAccountId();
    assertNotNull(accountId);
    assertNotNull(expected.getName());

    BasicAccount actual = client.users().getAccount(accountId);
    assertNotNull(actual);
    assertEquals(actual.getAccountId(), expected.getAccountId());
    assertEquals(actual.getEmail(), expected.getEmail());
}
 
Example #21
Source File: DropBoxStorageImageUtil.java    From microservices-sample-project with Apache License 2.0 5 votes vote down vote up
@Override
public ResponseEntity<StreamingResponseBody> readFile(String fileLocation, String imageDir, String id,
		String fileName) {
	
       StreamingResponseBody streamingResponseBody = new StreamingResponseBody() {

		@Override
		public void writeTo(OutputStream outputStream) {
			try {

				String fileStr = SEPARATOR + imageDir + SEPARATOR + id + SEPARATOR + fileName;

				DbxRequestConfig config = new DbxRequestConfig(APP_IDENTIFIER);
		        DbxClientV2 client = new DbxClientV2(config, ACCESS_TOKEN);
		        client.files().download(fileStr).download(outputStream);

			} catch (Exception e) {
				logger.error(e.getMessage());
				throw new ResourceNotFoundException("Image Not Found : " + id + "/" + fileName);
			}
		}
	};

	HttpHeaders headers = new HttpHeaders();
	headers.add(HttpHeaders.CONTENT_TYPE, "image/*");
	return new ResponseEntity<StreamingResponseBody>(streamingResponseBody, headers, HttpStatus.OK);
}
 
Example #22
Source File: DropboxAuth.java    From jbpm-work-items with Apache License 2.0 5 votes vote down vote up
public DbxClientV2 authorize(String clientIdentifier,
                             String accessToken) throws IllegalArgumentException {
    try {
        DbxRequestConfig config = new DbxRequestConfig(clientIdentifier);
        DbxClientV2 client = new DbxClientV2(config,
                                             accessToken);
        return client;
    } catch (Exception e) {
        throw new IllegalArgumentException(e.getMessage());
    }
}
 
Example #23
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 #24
Source File: ITUtil.java    From dropbox-sdk-java with MIT License 4 votes vote down vote up
public static DbxClientV2 newClientV2(DbxRequestConfig.Builder config) {
    return newClientV2(config.build());
}
 
Example #25
Source File: ITUtil.java    From dropbox-sdk-java with MIT License 4 votes vote down vote up
public static DbxClientV2 newClientV2() {
    return newClientV2(newRequestConfig());
}
 
Example #26
Source File: UploadTask.java    From fingen with Apache License 2.0 4 votes vote down vote up
public UploadTask(DbxClientV2 dbxClient, File file, IOnComplete onComplete) {
    this.dbxClient = dbxClient;
    this.file = file;
    mOnComplete = onComplete;
}
 
Example #27
Source File: DropboxClientFactory.java    From dropbox-sdk-java with MIT License 4 votes vote down vote up
public static DbxClientV2 getClient() {
    if (sDbxClient == null) {
        throw new IllegalStateException("Client not initialized.");
    }
    return sDbxClient;
}
 
Example #28
Source File: DownloadFileTask.java    From dropbox-sdk-java with MIT License 4 votes vote down vote up
DownloadFileTask(Context context, DbxClientV2 dbxClient, Callback callback) {
    mContext = context;
    mDbxClient = dbxClient;
    mCallback = callback;
}
 
Example #29
Source File: FileThumbnailRequestHandler.java    From dropbox-sdk-java with MIT License 4 votes vote down vote up
public FileThumbnailRequestHandler(DbxClientV2 dbxClient) {
    mDbxClient = dbxClient;
}
 
Example #30
Source File: UploadFileTask.java    From dropbox-sdk-java with MIT License 4 votes vote down vote up
UploadFileTask(Context context, DbxClientV2 dbxClient, Callback callback) {
    mContext = context;
    mDbxClient = dbxClient;
    mCallback = callback;
}