com.dropbox.core.v2.files.FileMetadata Java Examples

The following examples show how to use com.dropbox.core.v2.files.FileMetadata. 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: ActivityBackup.java    From fingen with Apache License 2.0 6 votes vote down vote up
@NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
void restoreDBFromDropbox() {
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            SharedPreferences dropboxPrefs = getApplicationContext().getSharedPreferences("com.yoshione.fingen.dropbox", Context.MODE_PRIVATE);
            String token = dropboxPrefs.getString("dropbox-token", null);
            List<Metadata> metadataList;
            List<MetadataItem> items = new ArrayList<>();
            try {
                metadataList = DropboxClient.getListFiles(DropboxClient.getClient(token));
                for (int i = metadataList.size() - 1; i >= 0; i--) {
                    if (metadataList.get(i).getName().toLowerCase().contains(".zip")) {
                        items.add(new MetadataItem((FileMetadata) metadataList.get(i)));
                    }
                }
            } catch (Exception e) {
                Log.d(TAG, "Error read list of files from Dropbox");
            }
            mHandler.sendMessage(mHandler.obtainMessage(MSG_SHOW_DIALOG, items));
        }
    });
    t.start();
}
 
Example #2
Source File: DbxClientV2Test.java    From dropbox-sdk-java with MIT License 6 votes vote down vote up
private FileMetadata constructFileMetadate() throws Exception {
    Class builderClass = FileMetadata.Builder.class;
    Constructor constructor = builderClass.getDeclaredConstructors()[0];
    constructor.setAccessible(true);

    List<Object> arguments = new ArrayList<Object>(Arrays.asList(
            "bar.txt",
            "id:1HkLjqifwMAAAAAAAAAAAQ",
            new Date(1456169040985L),
            new Date(1456169040985L),
            "2e0c38735597",
            2091603
    ));

    // hack for internal version of SDK
    if (constructor.getParameterTypes().length > 6) {
        arguments.addAll(Arrays.asList("20MB", "text.png", "text/plain"));
    }

    FileMetadata.Builder builder = (FileMetadata.Builder) constructor.newInstance(arguments.toArray());
    return builder.build();
}
 
Example #3
Source File: DbxClientV2IT.java    From dropbox-sdk-java with MIT License 6 votes vote down vote up
@Test
public void testRangeDownload() throws Exception {
    DbxClientV2 client = ITUtil.newClientV2();

    byte [] contents = ITUtil.randomBytes(500);
    String path = ITUtil.path(getClass(), "/testRangeDownload.dat");

    FileMetadata metadata = client.files().uploadBuilder(path)
        .withAutorename(false)
        .withMode(WriteMode.OVERWRITE)
        .withMute(true)
        .uploadAndFinish(new ByteArrayInputStream(contents));

    assertEquals(metadata.getSize(), contents.length);

    assertRangeDownload(client, path, contents, 0, contents.length);
    assertRangeDownload(client, path, contents, 0, 200);
    assertRangeDownload(client, path, contents, 300, 200);
    assertRangeDownload(client, path, contents, 499, 1);
    assertRangeDownload(client, path, contents, 0, 600);
    assertRangeDownload(client, path, contents, 250, null);
}
 
Example #4
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 #5
Source File: UploadFileTask.java    From dropbox-sdk-java with MIT License 6 votes vote down vote up
@Override
protected FileMetadata doInBackground(String... params) {
    String localUri = params[0];
    File localFile = UriHelpers.getFileForUri(mContext, Uri.parse(localUri));

    if (localFile != null) {
        String remoteFolderPath = params[1];

        // Note - this is not ensuring the name is a valid dropbox file name
        String remoteFileName = localFile.getName();

        try (InputStream inputStream = new FileInputStream(localFile)) {
            return mDbxClient.files().uploadBuilder(remoteFolderPath + "/" + remoteFileName)
                    .withMode(WriteMode.OVERWRITE)
                    .uploadAndFinish(inputStream);
        } catch (DbxException | IOException e) {
            mException = e;
        }
    }

    return null;
}
 
Example #6
Source File: DropboxBrowse.java    From dropbox-sdk-java with MIT License 6 votes vote down vote up
private void renderFile(HttpServletResponse response, String path, FileMetadata f)
    throws IOException
{
    FormProtection fp = FormProtection.start(response);

    response.setContentType("text/html");
    response.setCharacterEncoding("utf-8");
    PrintWriter out = new PrintWriter(IOUtil.utf8Writer(response.getOutputStream()));

    out.println("<html>");
    out.println("<head><title>" + escapeHtml4(path) + "- Web File Browser</title></head>");
    out.println("<body>");
    fp.insertAntiRedressHtml(out);

    out.println("<h2>Path: " + escapeHtml4(path) + "</h2>");

    out.println("<pre>");
    out.print(escapeHtml4(f.toStringMultiline()));
    out.println("</pre>");

    out.println("</body>");
    out.println("</html>");

    out.flush();
}
 
Example #7
Source File: DropboxAttributesFinderFeature.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
protected PathAttributes toAttributes(final Metadata metadata) {
    final PathAttributes attributes = new PathAttributes();
    if(metadata instanceof FileMetadata) {
        final FileMetadata file = (FileMetadata) metadata;
        attributes.setSize(file.getSize());
        attributes.setModificationDate(file.getClientModified().getTime());
        if(file.getFileLockInfo() != null) {
            attributes.setLockId(String.valueOf(file.getFileLockInfo().getIsLockholder()));
        }
    }
    if(metadata instanceof FolderMetadata) {
        final FolderMetadata folder = (FolderMetadata) metadata;
        // All shared folders have a shared_folder_id. This value is identical to the namespace ID for that shared folder
        attributes.setVersionId(folder.getSharedFolderId());
    }
    return attributes;
}
 
Example #8
Source File: DropboxListService.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
protected Path parse(final Path directory, final Metadata metadata) {
    final EnumSet<Path.Type> type;
    if(metadata instanceof FileMetadata) {
        type = EnumSet.of(Path.Type.file);
    }
    else if(metadata instanceof FolderMetadata) {
        type = EnumSet.of(Path.Type.directory);
        if(StringUtils.isNotBlank(((FolderMetadata) metadata).getSharedFolderId())) {
            type.add(Path.Type.volume);
            type.add(Path.Type.shared);
        }
        else if(directory.isRoot()) {
            // Home folder
            type.add(Path.Type.volume);
        }
    }
    else {
        log.warn(String.format("Skip file %s", metadata));
        return null;
    }
    return new Path(directory, PathNormalizer.name(metadata.getName()), type, attributes.toAttributes(metadata));
}
 
Example #9
Source File: DropboxSearchFeature.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
protected boolean parse(final Path workdir, final ListProgressListener listener, final AttributedList<Path> list, final SearchV2Result result) throws ConnectionCanceledException {
    final List<SearchMatchV2> matches = result.getMatches();
    for(SearchMatchV2 match : matches) {
        final Metadata metadata = match.getMetadata().getMetadataValue();
        final EnumSet<Path.Type> type;
        if(metadata instanceof FileMetadata) {
            type = EnumSet.of(Path.Type.file);
        }
        else if(metadata instanceof FolderMetadata) {
            type = EnumSet.of(Path.Type.directory);
        }
        else {
            log.warn(String.format("Skip file %s", metadata));
            return true;
        }
        list.add(new Path(metadata.getPathDisplay(), type, attributes.toAttributes(metadata)));
        listener.chunk(workdir, list);
    }
    return false;
}
 
Example #10
Source File: Dropbox.java    From financisto with GNU General Public License v2.0 6 votes vote down vote up
public FileMetadata uploadFile(File file) throws Exception {
    if (authSession()) {
        try {
            InputStream is = new FileInputStream(file);
            try {
                FileMetadata fileMetadata = dropboxClient.files().uploadBuilder("/" + file.getName()).withMode(WriteMode.ADD).uploadAndFinish(is);
                Log.i("Financisto", "Dropbox: The uploaded file's rev is: " + fileMetadata.getRev());
                return fileMetadata;
            } finally {
                IOUtil.closeInput(is);
            }
        } catch (Exception e) {
            Log.e("Financisto", "Dropbox: Something wrong", e);
            throw new ImportExportException(R.string.dropbox_error, e);
        }
    } else {
        throw new ImportExportException(R.string.dropbox_auth_error);
    }
}
 
Example #11
Source File: DbxClientV2Test.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
@Test
public void testRefreshBeforeCall() throws Exception {
    HttpRequestor mockRequestor = mock(HttpRequestor.class);
    DbxRequestConfig config = createRequestConfig()
        .withHttpRequestor(mockRequestor)
        .build();

    DbxCredential credential = new DbxCredential("accesstoken", 10L, "refresh_token",
        "appkey", "app_secret");

    DbxClientV2 client = new DbxClientV2(config, credential);
    FileMetadata expected = constructFileMetadate();

    HttpRequestor.Uploader mockUploader = mockUploader();
    when(mockUploader.finish())
        .thenReturn(createSuccessRefreshResponse("newToken", 10L))
        .thenReturn(createSuccessResponse(serialize(expected)));

    when(mockRequestor.startPost(anyString(), anyHeaders()))
        .thenReturn(mockUploader);

    long now = System.currentTimeMillis();

    Metadata actual = client.files().getMetadata(expected.getId());

    verify(mockRequestor, times(2)).startPost(anyString(), anyHeaders());

    assertEquals(credential.getAccessToken(), "newToken");
    assertTrue(credential.getExpiresAt() > now);

    assertEquals(actual.getName(), expected.getName());
    assertTrue(actual instanceof FileMetadata, actual.getClass().toString());
    assertEquals(((FileMetadata) actual).getId(), expected.getId());
}
 
Example #12
Source File: Dropbox.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
public List<FileMetadata> listFilesInTree(String basePath) throws DbxException {
	List<FileMetadata> files = new ArrayList<FileMetadata>();
	if (basePath.endsWith("/"))
		basePath.substring(0, basePath.length() - 1);
	if (!basePath.startsWith("/"))
		basePath = "/" + basePath;
	if (basePath.equals("/"))
		basePath = "";
	treeList(basePath, files);
	return files;
}
 
Example #13
Source File: UploadFileTask.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
@Override
protected void onPostExecute(FileMetadata result) {
    super.onPostExecute(result);
    if (mException != null) {
        mCallback.onError(mException);
    } else if (result == null) {
        mCallback.onError(null);
    } else {
        mCallback.onUploadComplete(result);
    }
}
 
Example #14
Source File: Dropbox.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void treeList(String parentPath, List<FileMetadata> files) throws DbxException {
	List<Metadata> list = list(parentPath);
	for (Metadata entry : list) {
		if (entry instanceof FolderMetadata)
			treeList(entry.getPathDisplay(), files);
		else
			files.add((FileMetadata) entry);
	}
}
 
Example #15
Source File: FileThumbnailRequestHandler.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
/**
 * Builds a {@link Uri} for a Dropbox file thumbnail suitable for handling by this handler
 */
public static Uri buildPicassoUri(FileMetadata file) {
    return new Uri.Builder()
            .scheme(SCHEME)
            .authority(HOST)
            .path(file.getPathLower()).build();
}
 
Example #16
Source File: FileThumbnailRequestHandler.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
@Override
public Result load(Request request, int networkPolicy) throws IOException {

    try {
        DbxDownloader<FileMetadata> downloader =
                mDbxClient.files().getThumbnailBuilder(request.uri.getPath())
                        .withFormat(ThumbnailFormat.JPEG)
                        .withSize(ThumbnailSize.W1024H768)
                        .start();

        return new Result(Okio.source(downloader.getInputStream()), Picasso.LoadedFrom.NETWORK);
    } catch (DbxException e) {
        throw new IOException(e);
    }
}
 
Example #17
Source File: DownloadFileTask.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
@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;
}
 
Example #18
Source File: DbxClientV2Test.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
@Test
public void testRetrySuccessWithBackoff() throws Exception {
    HttpRequestor mockRequestor = mock(HttpRequestor.class);
    DbxRequestConfig config = createRequestConfig()
        .withAutoRetryEnabled(3)
        .withHttpRequestor(mockRequestor)
        .build();

    DbxClientV2 client = new DbxClientV2(config, "fakeAccessToken");
    FileMetadata expected = constructFileMetadate();

    // 503 twice, then return result
    HttpRequestor.Uploader mockUploader = mockUploader();
    when(mockUploader.finish())
        .thenReturn(createEmptyResponse(503))   // no backoff
        .thenReturn(createRateLimitResponse(1)) // backoff 1 sec
        .thenReturn(createRateLimitResponse(2)) // backoff 2 sec
        .thenReturn(createSuccessResponse(serialize(expected)));

    when(mockRequestor.startPost(anyString(), anyHeaders()))
        .thenReturn(mockUploader);

    long start = System.currentTimeMillis();
    Metadata actual = client.files().getMetadata(expected.getId());
    long end = System.currentTimeMillis();

    // no way easy way to properly test this, but request should
    // have taken AT LEAST 3 seconds due to backoff.
    assertTrue((end - start) >= 3000L, "duration: " + (end - start) + " millis");

    // should have been called 4 times: initial call + 3 retries
    verify(mockRequestor, times(4)).startPost(anyString(), anyHeaders());

    assertEquals(actual.getName(), expected.getName());
    assertTrue(actual instanceof FileMetadata, actual.getClass().toString());
}
 
Example #19
Source File: FilesAdapter.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
@Override
public void onClick(View v) {

    if (mItem instanceof FolderMetadata) {
        mCallback.onFolderClicked((FolderMetadata) mItem);
    }  else if (mItem instanceof FileMetadata) {
        mCallback.onFileClicked((FileMetadata)mItem);
    }
}
 
Example #20
Source File: FilesAdapter.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
public void bind(Metadata item) {
    mItem = item;
    mTextView.setText(mItem.getName());

    // Load based on file path
    // Prepending a magic scheme to get it to
    // be picked up by DropboxPicassoRequestHandler

    if (item instanceof FileMetadata) {
        MimeTypeMap mime = MimeTypeMap.getSingleton();
        String ext = item.getName().substring(item.getName().indexOf(".") + 1);
        String type = mime.getMimeTypeFromExtension(ext);
        if (type != null && type.startsWith("image/")) {
            mPicasso.load(FileThumbnailRequestHandler.buildPicassoUri((FileMetadata)item))
                    .placeholder(R.drawable.ic_photo_grey_600_36dp)
                    .error(R.drawable.ic_photo_grey_600_36dp)
                    .into(mImageView);
        } else {
            mPicasso.load(R.drawable.ic_insert_drive_file_blue_36dp)
                    .noFade()
                    .into(mImageView);
        }
    } else if (item instanceof FolderMetadata) {
        mPicasso.load(R.drawable.ic_folder_blue_36dp)
                .noFade()
                .into(mImageView);
    }
}
 
Example #21
Source File: FilesActivity.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    String path = getIntent().getStringExtra(EXTRA_PATH);
    mPath = path == null ? "" : path;

    setContentView(R.layout.activity_files);

    Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            performWithPermissions(FileAction.UPLOAD);
        }
    });
    //init picaso client
    PicassoClient.init(this,DropboxClientFactory.getClient());
    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.files_list);
    mFilesAdapter = new FilesAdapter(PicassoClient.getPicasso(), new FilesAdapter.Callback() {
        @Override
        public void onFolderClicked(FolderMetadata folder) {
            startActivity(FilesActivity.getIntent(FilesActivity.this, folder.getPathLower()));
        }

        @Override
        public void onFileClicked(final FileMetadata file) {
            mSelectedFile = file;
            performWithPermissions(FileAction.DOWNLOAD);
        }
    });
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.setAdapter(mFilesAdapter);

    mSelectedFile = null;
}
 
Example #22
Source File: FilesActivity.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
private void downloadFile(FileMetadata file) {
    final ProgressDialog dialog = new ProgressDialog(this);
    dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    dialog.setCancelable(false);
    dialog.setMessage("Downloading");
    dialog.show();

    new DownloadFileTask(FilesActivity.this, DropboxClientFactory.getClient(), new DownloadFileTask.Callback() {
        @Override
        public void onDownloadComplete(File result) {
            dialog.dismiss();

            if (result != null) {
                viewFileInExternalApp(result);
            }
        }

        @Override
        public void onError(Exception e) {
            dialog.dismiss();

            Log.e(TAG, "Failed to download file.", e);
            Toast.makeText(FilesActivity.this,
                    "An error has occurred",
                    Toast.LENGTH_SHORT)
                    .show();
        }
    }).execute(file);

}
 
Example #23
Source File: FilesActivity.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
private void uploadFile(String fileUri) {
    final ProgressDialog dialog = new ProgressDialog(this);
    dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    dialog.setCancelable(false);
    dialog.setMessage("Uploading");
    dialog.show();

    new UploadFileTask(this, DropboxClientFactory.getClient(), new UploadFileTask.Callback() {
        @Override
        public void onUploadComplete(FileMetadata result) {
            dialog.dismiss();

            String message = result.getName() + " size " + result.getSize() + " modified " +
                    DateFormat.getDateTimeInstance().format(result.getClientModified());
            Toast.makeText(FilesActivity.this, message, Toast.LENGTH_SHORT)
                    .show();

            // Reload the folder
            loadData();
        }

        @Override
        public void onError(Exception e) {
            dialog.dismiss();

            Log.e(TAG, "Failed to upload file.", e);
            Toast.makeText(FilesActivity.this,
                    "An error has occurred",
                    Toast.LENGTH_SHORT)
                    .show();
        }
    }).execute(fileUri, mPath);
}
 
Example #24
Source File: DbxClientV2Test.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
@Test
public void testRefreshAndRetryWith503Retry() throws Exception {
    HttpRequestor mockRequestor = mock(HttpRequestor.class);
    DbxRequestConfig config = createRequestConfig()
        .withAutoRetryEnabled()
        .withHttpRequestor(mockRequestor)
        .build();

    long now = System.currentTimeMillis();

    DbxCredential credential = new DbxCredential("accesstoken", now + 2*DbxCredential
        .EXPIRE_MARGIN,
        "refresh_token",
        "appkey", "app_secret");

    DbxClientV2 client = new DbxClientV2(config, credential);
    FileMetadata expected = constructFileMetadate();

    HttpRequestor.Uploader mockUploader = mockUploader();
    when(mockUploader.finish())
        .thenReturn(createTokenExpiredResponse())
        .thenReturn(createSuccessRefreshResponse("new_token", 14400L))
        .thenReturn(createEmptyResponse(503))
        .thenReturn(createSuccessResponse(serialize(expected)));

    when(mockRequestor.startPost(anyString(), anyHeaders()))
        .thenReturn(mockUploader);

    Metadata actual = client.files().getMetadata(expected.getId());

    verify(mockRequestor, times(4)).startPost(anyString(), anyHeaders());
    assertEquals(credential.getAccessToken(), "new_token");

    assertEquals(actual.getName(), expected.getName());
    assertTrue(actual instanceof FileMetadata, actual.getClass().toString());
    assertEquals(((FileMetadata) actual).getId(), expected.getId());
}
 
Example #25
Source File: DbxClientV2Test.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
@Test
public void testRetryDownload() throws Exception {
    HttpRequestor mockRequestor = mock(HttpRequestor.class);
    DbxRequestConfig config = createRequestConfig()
        .withAutoRetryEnabled(3)
        .withHttpRequestor(mockRequestor)
        .build();

    DbxClientV2 client = new DbxClientV2(config, "fakeAccessToken");
    FileMetadata expectedMetadata = constructFileMetadate();
    byte [] expectedBytes = new byte [] { 1, 2, 3, 4 };

    // 503 once, then return 200
    HttpRequestor.Uploader mockUploader = mockUploader();
    when(mockUploader.finish())
        .thenReturn(createEmptyResponse(503))
        .thenReturn(createDownloaderResponse(expectedBytes, serialize(expectedMetadata)));
    when(mockRequestor.startPost(anyString(), anyHeaders()))
        .thenReturn(mockUploader);

    DbxDownloader<FileMetadata> downloader = client.files().download(expectedMetadata.getId());

    // should have been attempted twice
    verify(mockRequestor, times(2)).startPost(anyString(), anyHeaders());

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    FileMetadata actualMetadata = downloader.download(bout);
    byte [] actualBytes = bout.toByteArray();

    assertEquals(actualBytes, expectedBytes);
    assertEquals(actualMetadata, expectedMetadata);
}
 
Example #26
Source File: DbxClientV2Test.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
@Test
public void testOnlineWontRefresh() 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(createTokenExpiredResponse());

    when(mockRequestor.startPost(anyString(), anyHeaders()))
        .thenReturn(mockUploader);

    try {
        client.files().getMetadata(expected.getId());
    } catch (InvalidAccessTokenException ex) {
        verify(mockRequestor, times(1)).startPost(anyString(), anyHeaders());
        assertEquals(credential.getAccessToken(), "accesstoken");

        AuthError authError = DbxRequestUtil.readJsonFromErrorMessage(AuthError.Serializer
            .INSTANCE, ex.getMessage(), ex.getRequestId());
        assertEquals(authError, AuthError.EXPIRED_ACCESS_TOKEN);
        return;
    }

    fail("API v2 call should throw exception");
}
 
Example #27
Source File: DbxClientV2Test.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
@Test
public void testRetrySuccess() throws Exception {
    HttpRequestor mockRequestor = mock(HttpRequestor.class);
    DbxRequestConfig config = createRequestConfig()
        .withAutoRetryEnabled(3)
        .withHttpRequestor(mockRequestor)
        .build();

    DbxClientV2 client = new DbxClientV2(config, "fakeAccessToken");
    FileMetadata expected = constructFileMetadate();

    // 503 twice, then return result
    HttpRequestor.Uploader mockUploader = mockUploader();
    when(mockUploader.finish())
        .thenReturn(createEmptyResponse(503))
        .thenReturn(createEmptyResponse(503))
        .thenReturn(createSuccessResponse(serialize(expected)));

    when(mockRequestor.startPost(anyString(), anyHeaders()))
        .thenReturn(mockUploader);

    Metadata actual = client.files().getMetadata(expected.getId());

    // should have only been called 3 times: initial call + 2 retries
    verify(mockRequestor, times(3)).startPost(anyString(), anyHeaders());

    assertEquals(actual.getName(), expected.getName());
    assertTrue(actual instanceof FileMetadata, actual.getClass().toString());
    assertEquals(((FileMetadata) actual).getId(), expected.getId());
}
 
Example #28
Source File: DbxEntryDto.java    From Open-LaTeX-Studio with MIT License 5 votes vote down vote up
public DbxEntryDto(FileMetadata metadata) {
    name = metadata.getName();
    path = metadata.getPathDisplay();
    humanSize = FileUtils.byteCountToDisplaySize(metadata.getSize());
    lastModified = metadata.getServerModified();
    revision = metadata.getRev();
}
 
Example #29
Source File: Dropbox.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
public boolean uploadFile(File inputFile, String path) throws IOException {
	FileInputStream inputStream = new FileInputStream(inputFile);
	try {
		if (!path.startsWith("/"))
			path = "/" + path;
		FileMetadata uploadedFile = client.files().upload(path).uploadAndFinish(inputStream);
		return uploadedFile != null;
	} catch (DbxException e) {
		log.error(e.getMessage(), e);
	} finally {
		inputStream.close();
	}
	return false;
}
 
Example #30
Source File: Dropbox.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
public List<FileMetadata> find(String basePath, String query) throws DbxException {
	List<FileMetadata> list = new ArrayList<FileMetadata>();
	SearchResult result = client.files().search(basePath, query);
	List<SearchMatch> matches = result.getMatches();
	for (SearchMatch searchMatch : matches) {
		Metadata metadata = searchMatch.getMetadata();
		if (metadata instanceof FileMetadata)
			list.add((FileMetadata) metadata);
	}
	return list;
}