下面列出了org.testng.annotations.AfterSuite#com.dropbox.core.v2.DbxClientV2 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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());
}
}
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);
}
@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;
}
@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;
}
}
}
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");
}
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());
}
}
@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);
}
@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.");
}
}
/**
* @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;
}
}
@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);
}
}
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);
}
@SuppressLint("ValidFragment")
public DropboxFilePickerFragment(final DbxClientV2 api) {
super();
if (api == null) {
throw new IllegalArgumentException("Must be authenticated with Dropbox");
}
this.dropboxClient = api;
}
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());
}
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();
}
/**
* 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());
}
/**
* 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();
}
/**
* 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;
}
public static DbxClientV2 newClientV2(DbxRequestConfig config) {
DbxAuthInfo auth = getAuth();
return new DbxClientV2(
config,
auth.getAccessToken(),
auth.getHost()
);
}
@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());
}
@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.");
}
@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);
}
}
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());
}
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());
}
public static DbxClientV2 getClient(String ACCESS_TOKEN) {
// Create Dropbox client
DbxRequestConfig config = new DbxRequestConfig("dropbox/sample-app");
return new DbxClientV2(config, ACCESS_TOKEN);
}
public UploadTask(DbxClientV2 dbxClient, File file, IOnComplete onComplete) {
this.dbxClient = dbxClient;
this.file = file;
mOnComplete = onComplete;
}
public UserAccountTask(DbxClientV2 dbxClient, TaskDelegate delegate){
this.dbxClient =dbxClient;
this.delegate = delegate;
}
private FileMetadata dropBoxSave(String uploadPath, InputStream inputStream)throws Exception{
DbxRequestConfig config = new DbxRequestConfig(APP_IDENTIFIER);
DbxClientV2 client = new DbxClientV2(config, ACCESS_TOKEN);
return client.files().uploadBuilder(uploadPath).uploadAndFinish(inputStream);
}
DbxClientV2 getClient() {
return client;
}
public static void main(String[] args) throws IOException {
// Only display important log messages.
Logger.getLogger("").setLevel(Level.WARNING);
if (args.length != 3) {
System.out.println("");
System.out.println("Usage: COMMAND <auth-file> <local-path> <dropbox-path>");
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.out.println(" <local-path>: The path to a local file whose contents you want to upload.");
System.out.println("");
System.out.println(" <dropbox-path>: The path on Dropbox to save the file to.");
System.out.println("");
System.exit(1);
return;
}
String argAuthFile = args[0];
String localPath = args[1];
String dropboxPath = args[2];
// 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;
}
String pathError = DbxPathV2.findError(dropboxPath);
if (pathError != null) {
System.err.println("Invalid <dropbox-path>: " + pathError);
System.exit(1);
return;
}
File localFile = new File(localPath);
if (!localFile.exists()) {
System.err.println("Invalid <local-path>: file does not exist.");
System.exit(1);
return;
}
if (!localFile.isFile()) {
System.err.println("Invalid <local-path>: not a file.");
System.exit(1);
return;
}
// Create a DbxClientV2, which is what you use to make API calls.
DbxRequestConfig requestConfig = new DbxRequestConfig("examples-upload-file");
DbxClientV2 dbxClient = new DbxClientV2(requestConfig, authInfo.getAccessToken(), authInfo.getHost());
// upload the file with simple upload API if it is small enough, otherwise use chunked
// upload API for better performance. Arbitrarily chose 2 times our chunk size as the
// deciding factor. This should really depend on your network.
if (localFile.length() <= (2 * CHUNKED_UPLOAD_CHUNK_SIZE)) {
uploadFile(dbxClient, localFile, dropboxPath);
} else {
chunkedUploadFile(dbxClient, localFile, dropboxPath);
}
System.exit(0);
}
GetCurrentAccountTask(DbxClientV2 dbxClient, Callback callback) {
mDbxClient = dbxClient;
mCallback = callback;
}