Search in sources :

Example 6 with DbxClientV2

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

the class Main method longpoll.

/**
 * Will perform longpoll request for changes in the user's Dropbox
 * account and display those changes. This is more efficient that
 * periodic polling the endpoint.
 */
public static void longpoll(DbxAuthInfo auth, String path) throws IOException {
    long longpollTimeoutSecs = TimeUnit.MINUTES.toSeconds(2);
    // need 2 Dropbox clients for making calls:
    // 
    // (1) One for longpoll requests, with its read timeout set longer than our polling timeout
    // (2) One for all other requests, with its read timeout set to the default, shorter timeout
    // 
    StandardHttpRequestor.Config config = StandardHttpRequestor.Config.DEFAULT_INSTANCE;
    StandardHttpRequestor.Config longpollConfig = config.copy().withReadTimeout(5, TimeUnit.MINUTES).build();
    DbxClientV2 dbxClient = createClient(auth, config);
    DbxClientV2 dbxLongpollClient = createClient(auth, longpollConfig);
    try {
        // We only care about file changes, not existing files, so grab latest cursor for this
        // path and then longpoll for changes.
        String cursor = getLatestCursor(dbxClient, path);
        System.out.println("Longpolling for changes... press CTRL-C to exit.");
        while (true) {
            // will block for longpollTimeoutSecs or until a change is made in the folder
            ListFolderLongpollResult result = dbxLongpollClient.files().listFolderLongpoll(cursor, longpollTimeoutSecs);
            // we have changes, list them
            if (result.getChanges()) {
                cursor = printChanges(dbxClient, cursor);
            }
            // we were asked to back off from our polling, wait the requested amount of seconds
            // before issuing another longpoll request.
            Long backoff = result.getBackoff();
            if (backoff != null) {
                try {
                    System.out.printf("backing off for %d secs...\n", backoff.longValue());
                    Thread.sleep(TimeUnit.SECONDS.toMillis(backoff));
                } catch (InterruptedException ex) {
                    System.exit(0);
                }
            }
        }
    } catch (DbxApiException ex) {
        // if a user message is available, try using that instead
        String message = ex.getUserMessage() != null ? ex.getUserMessage().getText() : ex.getMessage();
        System.err.println("Error making API call: " + message);
        System.exit(1);
    } catch (NetworkIOException ex) {
        System.err.println("Error making API call: " + ex.getMessage());
        if (ex.getCause() instanceof SocketTimeoutException) {
            System.err.println("Consider increasing socket read timeout or decreasing longpoll timeout.");
        }
        System.exit(1);
    } catch (DbxException ex) {
        System.err.println("Error making API call: " + ex.getMessage());
        System.exit(1);
    }
}
Also used : StandardHttpRequestor(com.dropbox.core.http.StandardHttpRequestor) DbxClientV2(com.dropbox.core.v2.DbxClientV2) SocketTimeoutException(java.net.SocketTimeoutException) DbxApiException(com.dropbox.core.DbxApiException) ListFolderLongpollResult(com.dropbox.core.v2.files.ListFolderLongpollResult) DbxException(com.dropbox.core.DbxException) NetworkIOException(com.dropbox.core.NetworkIOException)

Example 7 with DbxClientV2

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

the class DropboxBrowse method doUpload.

// -------------------------------------------------------------------------------------------
// POST /upload
// -------------------------------------------------------------------------------------------
public void doUpload(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    MultipartConfigElement multipartConfigElement = new MultipartConfigElement("/tmp");
    request.setAttribute("org.eclipse.multipartConfig", multipartConfigElement);
    if (!common.checkPost(request, response))
        return;
    User user = common.requireLoggedInUser(request, response);
    if (user == null)
        return;
    DbxClientV2 dbxClient = requireDbxClient(request, response, user);
    if (dbxClient == null)
        return;
    try {
        // Just call getParts() to trigger the too-large exception.
        request.getParts();
    } catch (IllegalStateException ex) {
        response.sendError(400, "Request too large");
        return;
    }
    String targetFolder = slurpUtf8Part(request, response, "targetFolder", 1024);
    if (targetFolder == null)
        return;
    Part filePart = request.getPart("file");
    if (filePart == null) {
        response.sendError(400, "Field \"file\" is missing.");
        return;
    }
    String fileName = filePart.getName();
    if (fileName == null) {
        response.sendError(400, "Field \"file\" has no name.");
        return;
    }
    // Upload file to Dropbox
    String fullTargetPath = targetFolder + "/" + fileName;
    FileMetadata metadata;
    try {
        metadata = dbxClient.files().upload(fullTargetPath).uploadAndFinish(filePart.getInputStream());
    } catch (DbxException ex) {
        common.handleDbxException(response, user, ex, "upload(" + jq(fullTargetPath) + ", ...)");
        return;
    } catch (IOException ex) {
        response.sendError(400, "Error getting file data from you.");
        return;
    }
    // Display uploaded file metadata.
    response.setContentType("text/html");
    response.setCharacterEncoding("utf-8");
    PrintWriter out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));
    out.println("<html>");
    out.println("<head><title>File uploaded: " + escapeHtml4(metadata.getPathLower()) + "</title></head>");
    out.println("<body>");
    out.println("<h2>File uploaded: " + escapeHtml4(metadata.getPathLower()) + "</h2>");
    out.println("<pre>");
    out.print(escapeHtml4(metadata.toStringMultiline()));
    out.println("</pre>");
    out.println("</body>");
    out.println("</html>");
    out.flush();
}
Also used : DbxClientV2(com.dropbox.core.v2.DbxClientV2) MultipartConfigElement(javax.servlet.MultipartConfigElement) Part(javax.servlet.http.Part) FileMetadata(com.dropbox.core.v2.files.FileMetadata) OutputStreamWriter(java.io.OutputStreamWriter) IOException(java.io.IOException) DbxException(com.dropbox.core.DbxException) PrintWriter(java.io.PrintWriter)

Example 8 with DbxClientV2

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

the class Main method testEnumeratedSubtypeSerialization.

private static void testEnumeratedSubtypeSerialization(DbxClientV2 client) throws DbxException, IOException {
    String rootPath = "/test/proguard-tests";
    try {
        FolderMetadata root = client.files().createFolderV2(rootPath).getMetadata();
        assertNotNull(root);
        assertEquals(root.getPathLower(), rootPath);
        assertEquals(root.getPathDisplay(), rootPath);
    } catch (CreateFolderErrorException ex) {
        if (ex.errorValue.isPath() && ex.errorValue.getPathValue().isConflict() && ex.errorValue.getPathValue().getConflictValue() == WriteConflictError.FOLDER) {
        // ignore duplicate folder exception
        } else {
            throw ex;
        }
    }
    Map<String, byte[]> files = new LinkedHashMap<String, byte[]>();
    files.put(rootPath + "/foo.blob", bytes(1024));
    files.put(rootPath + "/bar.blob", bytes(512));
    files.put(rootPath + "/sub/a.dat", bytes(4096));
    files.put(rootPath + "/sub/b/c.dat", bytes(64));
    files.put(rootPath + "/pics/cat.rawb", bytes(8196));
    try {
        for (Map.Entry<String, byte[]> entry : files.entrySet()) {
            String path = entry.getKey();
            byte[] data = entry.getValue();
            FileMetadata file = client.files().uploadBuilder(path).withMode(WriteMode.OVERWRITE).withAutorename(false).withMute(true).uploadAndFinish(new ByteArrayInputStream(data));
            assertNotNull(file);
            assertEquals(file.getPathLower(), path);
            assertEquals(file.getSize(), data.length);
            Metadata metadata = client.files().getMetadata(path);
            assertEquals(metadata, file);
        }
        for (String path : files.keySet()) {
            Metadata file = client.files().deleteV2(path).getMetadata();
            assertNotNull(file);
            assertEquals(file.getPathLower(), path);
            assertTrue(file instanceof FileMetadata);
            Metadata deleted = client.files().getMetadataBuilder(path).withIncludeDeleted(true).start();
            assertNotNull(deleted);
            assertTrue(deleted instanceof DeletedMetadata, deleted.getClass().toString());
            assertEquals(deleted.getPathLower(), path);
        }
    } finally {
        client.files().deleteV2(rootPath);
    }
}
Also used : CreateFolderErrorException(com.dropbox.core.v2.files.CreateFolderErrorException) ByteArrayInputStream(java.io.ByteArrayInputStream) FileMetadata(com.dropbox.core.v2.files.FileMetadata) FolderMetadata(com.dropbox.core.v2.files.FolderMetadata) DeletedMetadata(com.dropbox.core.v2.files.DeletedMetadata) FileMetadata(com.dropbox.core.v2.files.FileMetadata) Metadata(com.dropbox.core.v2.files.Metadata) FolderMetadata(com.dropbox.core.v2.files.FolderMetadata) DeletedMetadata(com.dropbox.core.v2.files.DeletedMetadata) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap)

Example 9 with DbxClientV2

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

the class Main method testBasicSerialization.

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());
}
Also used : BasicAccount(com.dropbox.core.v2.users.BasicAccount) FullAccount(com.dropbox.core.v2.users.FullAccount)

Example 10 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 DbxException, IOException {
    // Create Dropbox client
    DbxRequestConfig config = new DbxRequestConfig("dropbox/java-tutorial");
    DbxClientV2 client = new DbxClientV2(config, ACCESS_TOKEN);
    // Instantiate factory and set shared factory
    DbxRequestUtil.sharedCallbackFactory = new DbxExampleGlobalCallbackFactory();
    try {
        // Get files and folder metadata from Dropbox root directory
        client.files().listFolder("/does/not/exist/folder/");
    } catch (ListFolderErrorException ex) {
        System.err.println("STANDARD ROUTE ERROR HANDLER: " + ex.errorValue + "\n");
    } catch (DbxException ex) {
        System.err.println("STANDARD NETWORK ERROR HANDLER: " + ex + "\n");
    }
    try {
        // Get files and folder metadata from Dropbox root directory
        client.auth().tokenRevoke();
        client.files().listFolder("/does/not/exist");
    } catch (ListFolderErrorException ex) {
        System.err.println("STANDARD ROUTE ERROR HANDLER2: " + ex.errorValue + "\n");
    } catch (DbxException ex) {
        System.err.println("STANDARD NETWORK ERROR HANDLER2: " + ex + "\n");
    }
}
Also used : DbxClientV2(com.dropbox.core.v2.DbxClientV2) DbxRequestConfig(com.dropbox.core.DbxRequestConfig) ListFolderErrorException(com.dropbox.core.v2.files.ListFolderErrorException) DbxException(com.dropbox.core.DbxException)

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