Search in sources :

Example 26 with DbxException

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

the class DownloadFileTask method doInBackground.

@Override
protected File doInBackground(FileMetadata... params) {
    FileMetadata metadata = params[0];
    try {
        File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        File file = new File(path, metadata.getName());
        // Make sure the Downloads directory exists.
        if (!path.exists()) {
            if (!path.mkdirs()) {
                mException = new RuntimeException("Unable to create directory: " + path);
            }
        } else if (!path.isDirectory()) {
            mException = new IllegalStateException("Download path is not a directory: " + path);
            return null;
        }
        // Download the file.
        try (OutputStream outputStream = new FileOutputStream(file)) {
            mDbxClient.files().download(metadata.getPathLower(), metadata.getRev()).download(outputStream);
        }
        // Tell android about the file
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intent.setData(Uri.fromFile(file));
        mContext.sendBroadcast(intent);
        return file;
    } catch (DbxException | IOException e) {
        mException = e;
    }
    return null;
}
Also used : OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileOutputStream(java.io.FileOutputStream) FileMetadata(com.dropbox.core.v2.files.FileMetadata) Intent(android.content.Intent) IOException(java.io.IOException) File(java.io.File) DbxException(com.dropbox.core.DbxException)

Example 27 with DbxException

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

the class Main method main.

public static void main(String[] args) throws DbxException, IOException {
    // Create Dropbox client
    DbxRequestConfig config = new DbxRequestConfig("dropbox/java-tutorial");
    DbxClientV2 client = new DbxClientV2(config, ACCESS_TOKEN);
    // Get current account info
    FullAccount account = client.users().getCurrentAccount();
    System.out.println(account.getName().getDisplayName());
    // Get files and folder metadata from Dropbox root directory
    ListFolderResult result = client.files().listFolder("");
    while (true) {
        for (Metadata metadata : result.getEntries()) {
            System.out.println(metadata.getPathLower());
        }
        if (!result.getHasMore()) {
            break;
        }
        result = client.files().listFolderContinue(result.getCursor());
    }
    // Upload "test.txt" to Dropbox
    try (InputStream in = new FileInputStream("test.txt")) {
        FileMetadata metadata = client.files().uploadBuilder("/test.txt").uploadAndFinish(in);
    }
    DbxDownloader<FileMetadata> downloader = client.files().download("/test.txt");
    try {
        FileOutputStream out = new FileOutputStream("test.txt");
        downloader.download(out);
        out.close();
    } catch (DbxException ex) {
        System.out.println(ex.getMessage());
    }
}
Also used : DbxClientV2(com.dropbox.core.v2.DbxClientV2) DbxRequestConfig(com.dropbox.core.DbxRequestConfig) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) FileOutputStream(java.io.FileOutputStream) FileMetadata(com.dropbox.core.v2.files.FileMetadata) Metadata(com.dropbox.core.v2.files.Metadata) FileMetadata(com.dropbox.core.v2.files.FileMetadata) ListFolderResult(com.dropbox.core.v2.files.ListFolderResult) FullAccount(com.dropbox.core.v2.users.FullAccount) FileInputStream(java.io.FileInputStream) DbxException(com.dropbox.core.DbxException)

Example 28 with DbxException

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

the class DropboxAuth method doFinish.

// -------------------------------------------------------------------------------------------
// GET /dropbox-auth-finish
// -------------------------------------------------------------------------------------------
// The Dropbox API authorization page will redirect the user's browser to this page.
// 
// This is a GET (even though it modifies state) because we get here via a browser
// redirect (Dropbox redirects the user here).  You can't do a browser redirect to
// an HTTP POST.
public void doFinish(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    if (!common.checkGet(request, response))
        return;
    User user = common.requireLoggedInUser(request, response);
    if (user == null) {
        common.pageSoftError(response, "Can't do /dropbox-auth-finish.  Nobody is logged in.");
        return;
    }
    DbxAuthFinish authFinish;
    try {
        authFinish = getWebAuth(request).finishFromRedirect(getRedirectUri(request), getSessionStore(request), request.getParameterMap());
    } catch (DbxWebAuth.BadRequestException e) {
        common.log.println("On /dropbox-auth-finish: Bad request: " + e.getMessage());
        response.sendError(400);
        return;
    } catch (DbxWebAuth.BadStateException e) {
        // Send them back to the start of the auth flow.
        response.sendRedirect(common.getUrl(request, "/dropbox-auth-start"));
        return;
    } catch (DbxWebAuth.CsrfException e) {
        common.log.println("On /dropbox-auth-finish: CSRF mismatch: " + e.getMessage());
        response.sendError(403);
        return;
    } catch (DbxWebAuth.NotApprovedException e) {
        common.page(response, 200, "Not approved?", "Why not, bro?");
        return;
    } catch (DbxWebAuth.ProviderException e) {
        common.log.println("On /dropbox-auth-finish: Auth failed: " + e.getMessage());
        response.sendError(503, "Error communicating with Dropbox.");
        return;
    } catch (DbxException e) {
        common.log.println("On /dropbox-auth-finish: Error getting token: " + e);
        response.sendError(503, "Error communicating with Dropbox.");
        return;
    }
    // We have an Dropbox API access token now.  This is what will let us make Dropbox API
    // calls.  Save it in the database entry for the current user.
    user.dropboxAccessToken = authFinish.getAccessToken();
    common.saveUserDb();
    response.sendRedirect("/");
}
Also used : DbxAuthFinish(com.dropbox.core.DbxAuthFinish) DbxException(com.dropbox.core.DbxException) DbxWebAuth(com.dropbox.core.DbxWebAuth)

Example 29 with DbxException

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

the class ScopeAuthorize method authorize.

public DbxAuthFinish authorize(DbxAppInfo appInfo) throws IOException {
    // Run through Dropbox API authorization process
    DbxRequestConfig requestConfig = new DbxRequestConfig("examples-authorize");
    DbxWebAuth webAuth = new DbxWebAuth(requestConfig, appInfo);
    // OAuth2 flow 1: Ask for account_info.read scope. Get a token with account_info.read
    DbxWebAuth.Request webAuthRequest = DbxWebAuth.newRequestBuilder().withNoRedirect().withTokenAccessType(TokenAccessType.OFFLINE).withScope(Collections.singletonList("account_info.read")).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 {
        DbxAuthFinish authFinish = webAuth.finishFromCode(code);
        assert authFinish.getScope().contains("account_info.read");
        if (!authFinish.getScope().contains("account_info.read")) {
            System.err.println("You app doesn't have account_info.read scope. Can't finish " + "this example.");
            System.exit(1);
            return null;
        }
        System.out.println("Successfully requested scope " + authFinish.getScope());
    } catch (DbxException ex) {
        System.err.println("Error in DbxWebAuth.authorize: " + ex.getMessage());
        System.exit(1);
        return null;
    }
    // OAuth2 flow 2: Ask for files.metadata.write only. Get a token with files.metadata
    // .write and its dependency files.metadata.read.
    webAuthRequest = DbxWebAuth.newRequestBuilder().withNoRedirect().withTokenAccessType(TokenAccessType.OFFLINE).withScope(Collections.singletonList("files.metadata.write")).build();
    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: ");
    code = new BufferedReader(new InputStreamReader(System.in)).readLine();
    if (code == null) {
        System.exit(1);
    }
    code = code.trim();
    try {
        DbxAuthFinish authFinish = webAuth.finishFromCode(code);
        if (!authFinish.getScope().contains("files.metadata.write")) {
            System.err.println("You app doesn't have files.metadata.write scope. Can't finish " + "this example.");
            System.exit(1);
            return null;
        }
        assert !authFinish.getScope().contains("account_info.read");
        System.out.println("Successfully requested scope " + authFinish.getScope());
    } catch (DbxException ex) {
        System.err.println("Error in DbxWebAuth.authorize: " + ex.getMessage());
        System.exit(1);
        return null;
    }
    // Oauth2 flow 3: Ask for "files.content.read", "files.content.write" and "sharing.read",
    // along with all previously granted scopes.
    webAuthRequest = DbxWebAuth.newRequestBuilder().withNoRedirect().withTokenAccessType(TokenAccessType.OFFLINE).withScope(Arrays.asList("files.content.read", "files.content.write", "sharing.read")).withIncludeGrantedScopes(IncludeGrantedScopes.USER).build();
    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: ");
    code = new BufferedReader(new InputStreamReader(System.in)).readLine();
    if (code == null) {
        System.exit(1);
    }
    code = code.trim();
    try {
        DbxAuthFinish authFinish = webAuth.finishFromCode(code);
        if (!authFinish.getScope().contains("files.content.read")) {
            System.err.println("You app doesn't have files.content.read scope. Can't finish " + "this example.");
            System.exit(1);
            return null;
        }
        if (!authFinish.getScope().contains("files.content.write")) {
            System.err.println("You app doesn't have files.content.write scope. Can't finish" + " " + "this example.");
            System.exit(1);
            return null;
        }
        if (!authFinish.getScope().contains("sharing.read")) {
            System.err.println("You app doesn't have sharing.read scope. Can't finish" + " " + "this example.");
            System.exit(1);
            return null;
        }
        assert authFinish.getScope().contains("account_info.read");
        assert authFinish.getScope().contains("files.metadata.write");
        assert authFinish.getScope().contains("sharing.read");
        System.out.println("Successfully requested scope " + authFinish.getScope());
        return authFinish;
    } catch (DbxException ex) {
        System.err.println("Error in DbxWebAuth.authorize: " + ex.getMessage());
        System.exit(1);
        return null;
    }
}
Also used : DbxRequestConfig(com.dropbox.core.DbxRequestConfig) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) DbxAuthFinish(com.dropbox.core.DbxAuthFinish) DbxException(com.dropbox.core.DbxException) DbxWebAuth(com.dropbox.core.DbxWebAuth)

Example 30 with DbxException

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

the class Main method main.

public static void main(String[] args) throws IOException {
    // Only display important log messages.
    Logger.getLogger("").setLevel(Level.WARNING);
    if (args.length != 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;
    }
    String argAuthFile = args[0];
    // 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;
    }
    // Create a DbxClientV2, which is what you use to make API calls.
    DbxRequestConfig requestConfig = new DbxRequestConfig("examples-account-info");
    DbxClientV2 dbxClient = new DbxClientV2(requestConfig, authInfo.getAccessToken(), authInfo.getHost());
    StoneDeserializerLogger.LoggerCallback callback = (o, s) -> {
        System.out.println("This is from StoneDeserializerLogger: ");
        System.out.println(s);
    };
    StoneDeserializerLogger.registerCallback(Name.class, callback);
    // Make the /account/info API call.
    FullAccount dbxAccountInfo;
    try {
        dbxAccountInfo = dbxClient.users().getCurrentAccount();
    } catch (DbxException ex) {
        System.err.println("Error making API call: " + ex.getMessage());
        System.exit(1);
        return;
    }
    System.out.println("This is from main: ");
    System.out.print(dbxAccountInfo.toStringMultiline());
}
Also used : DbxWebAuth(com.dropbox.core.DbxWebAuth) DbxException(com.dropbox.core.DbxException) Name(com.dropbox.core.v2.users.Name) DbxClientV2(com.dropbox.core.v2.DbxClientV2) DbxRequestConfig(com.dropbox.core.DbxRequestConfig) FullAccount(com.dropbox.core.v2.users.FullAccount) DbxAuthInfo(com.dropbox.core.DbxAuthInfo) IOException(java.io.IOException) JsonReader(com.dropbox.core.json.JsonReader) Logger(java.util.logging.Logger) StoneDeserializerLogger(com.dropbox.core.stone.StoneDeserializerLogger) Level(java.util.logging.Level) DbxClientV2(com.dropbox.core.v2.DbxClientV2) DbxRequestConfig(com.dropbox.core.DbxRequestConfig) DbxAuthInfo(com.dropbox.core.DbxAuthInfo) JsonReader(com.dropbox.core.json.JsonReader) StoneDeserializerLogger(com.dropbox.core.stone.StoneDeserializerLogger) FullAccount(com.dropbox.core.v2.users.FullAccount) DbxException(com.dropbox.core.DbxException)

Aggregations

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