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);
}
}
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();
}
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);
}
}
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());
}
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");
}
}
Aggregations