use of com.box.sdk.BoxAPIException in project camel by apache.
the class BoxUsersManager method deleteUserEmailAlias.
/**
* Delete an email alias from user's account.
*
* @param userId
* - the id of user.
* @param emailAliasId
* - the id of the email alias to delete.
*/
public void deleteUserEmailAlias(String userId, String emailAliasId) {
try {
LOG.debug("Deleting email_alias(" + emailAliasId + ") for user(id=" + userId + ")");
if (userId == null) {
throw new IllegalArgumentException("Parameter 'userId' can not be null");
}
if (emailAliasId == null) {
throw new IllegalArgumentException("Parameter 'emailAliasId' can not be null");
}
BoxUser user = new BoxUser(boxConnection, userId);
user.deleteEmailAlias(emailAliasId);
} catch (BoxAPIException e) {
throw new RuntimeException(String.format("Box API returned the error code %d\n\n%s", e.getResponseCode(), e.getResponse()), e);
}
}
use of com.box.sdk.BoxAPIException in project camel by apache.
the class BoxConnectionHelper method createStandardAuthenticatedConnection.
public static BoxAPIConnection createStandardAuthenticatedConnection(BoxConfiguration configuration) {
// Create web client for first leg of OAuth2
//
final WebClient webClient = new WebClient();
final WebClientOptions options = webClient.getOptions();
options.setRedirectEnabled(true);
options.setJavaScriptEnabled(false);
options.setThrowExceptionOnFailingStatusCode(true);
options.setThrowExceptionOnScriptError(true);
options.setPrintContentOnFailingStatusCode(LOG.isDebugEnabled());
try {
// use default SSP to create supported non-SSL protocols list
final SSLContext sslContext = new SSLContextParameters().createSSLContext(null);
options.setSSLClientProtocols(sslContext.createSSLEngine().getEnabledProtocols());
} catch (GeneralSecurityException e) {
throw ObjectHelper.wrapRuntimeCamelException(e);
} catch (IOException e) {
throw ObjectHelper.wrapRuntimeCamelException(e);
} finally {
if (webClient != null) {
webClient.close();
}
}
// disable default gzip compression, as htmlunit does not negotiate
// pages sent with no compression
new WebConnectionWrapper(webClient) {
@Override
public WebResponse getResponse(WebRequest request) throws IOException {
request.setAdditionalHeader(HttpHeaders.ACCEPT_ENCODING, "identity");
return super.getResponse(request);
}
};
// add HTTP proxy if set
final Map<String, Object> httpParams = configuration.getHttpParams();
if (httpParams != null && httpParams.get("http.route.default-proxy") != null) {
final HttpHost proxyHost = (HttpHost) httpParams.get("http.route.default-proxy");
final Boolean socksProxy = (Boolean) httpParams.get("http.route.socks-proxy");
final ProxyConfig proxyConfig = new ProxyConfig(proxyHost.getHostName(), proxyHost.getPort(), socksProxy != null ? socksProxy : false);
options.setProxyConfig(proxyConfig);
}
// authorize application on user's behalf
try {
// generate anti-forgery token to prevent/detect CSRF attack
final String csrfToken = String.valueOf(new SecureRandom().nextLong());
final HtmlPage authPage = webClient.getPage(authorizationUrl(configuration.getClientId(), csrfToken));
// look for <div role="error_message">
final HtmlDivision div = authPage.getFirstByXPath("//div[contains(concat(' ', @class, ' '), ' error_message ')]");
if (div != null) {
final String errorMessage = div.getTextContent().replaceAll("\\s+", " ").replaceAll(" Show Error Details", ":").trim();
throw new IllegalArgumentException("Error authorizing application: " + errorMessage);
}
// submit login credentials
final HtmlForm loginForm = authPage.getFormByName("login_form");
final HtmlTextInput login = loginForm.getInputByName("login");
login.setText(configuration.getUserName());
final HtmlPasswordInput password = loginForm.getInputByName("password");
password.setText(configuration.getUserPassword());
final HtmlSubmitInput submitInput = loginForm.getInputByName("login_submit");
// submit consent
final HtmlPage consentPage = submitInput.click();
final HtmlForm consentForm = consentPage.getFormByName("consent_form");
final HtmlButton consentAccept = consentForm.getButtonByName("consent_accept");
// disable redirect to avoid loading redirect URL
webClient.getOptions().setRedirectEnabled(false);
// validate CSRF and get authorization code
String redirectQuery;
try {
final Page redirectPage = consentAccept.click();
redirectQuery = redirectPage.getUrl().getQuery();
} catch (FailingHttpStatusCodeException e) {
// escalate non redirect errors
if (e.getStatusCode() != HttpStatus.SC_MOVED_TEMPORARILY) {
throw e;
}
final String location = e.getResponse().getResponseHeaderValue("Location");
redirectQuery = new URL(location).getQuery();
}
final Map<String, String> params = new HashMap<String, String>();
final Matcher matcher = QUERY_PARAM_PATTERN.matcher(redirectQuery);
while (matcher.find()) {
params.put(matcher.group(1), matcher.group(2));
}
final String state = params.get("state");
if (!csrfToken.equals(state)) {
throw new SecurityException("Invalid CSRF code!");
} else {
// get authorization code
final String authorizationCode = params.get("code");
return new BoxAPIConnection(configuration.getClientId(), configuration.getClientSecret(), authorizationCode);
}
} catch (BoxAPIException e) {
throw new RuntimeCamelException(String.format("Box API connection failed: API returned the error code %d\n\n%s", e.getResponseCode(), e.getResponse()), e);
} catch (Exception e) {
throw new RuntimeCamelException(String.format("Box API connection failed: %s", e.getMessage()), e);
}
}
use of com.box.sdk.BoxAPIException in project camel by apache.
the class BoxCollaborationsManagerIntegrationTest method testAddFolderCollaboration.
@Test
public void testAddFolderCollaboration() throws Exception {
// delete collaborator created by setupTest
deleteTestCollaborator();
BoxUser user = null;
try {
// create test collaborator
CreateUserParams params = new CreateUserParams();
// 1 GB
params.setSpaceAmount(1073741824);
user = BoxUser.createAppUser(getConnection(), CAMEL_TEST_COLLABORATOR_NAME, params).getResource();
final Map<String, Object> headers = new HashMap<String, Object>();
// parameter type is String
headers.put("CamelBox.folderId", testFolder.getID());
// parameter type is String
headers.put("CamelBox.collaborator", user);
// parameter type is com.box.sdk.BoxCollaboration.Role
headers.put("CamelBox.role", BoxCollaboration.Role.EDITOR);
final com.box.sdk.BoxCollaboration result = requestBodyAndHeaders("direct://ADDFOLDERCOLLABORATION", testFolder.getID(), headers);
assertNotNull("addFolderCollaboration result", result);
LOG.debug("addFolderCollaboration: " + result);
} catch (BoxAPIException e) {
throw new RuntimeException(String.format("Box API returned the error code %d\n\n%s", e.getResponseCode(), e.getResponse()), e);
} finally {
if (user != null) {
user.delete(false, true);
}
}
}
use of com.box.sdk.BoxAPIException in project camel by apache.
the class BoxFoldersManager method renameFolder.
/**
* Rename folder giving it the name <code>newName</code>
*
* @param folderId
* - the id of folder to rename.
* @param newFolderName
* - the new name of folder.
* @return The renamed folder.
*/
public BoxFolder renameFolder(String folderId, String newFolderName) {
try {
LOG.debug("Renaming folder(id=" + folderId + ") to '" + newFolderName + "'");
if (folderId == null) {
throw new IllegalArgumentException("Parameter 'folderId' can not be null");
}
if (newFolderName == null) {
throw new IllegalArgumentException("Parameter 'newFolderName' can not be null");
}
BoxFolder folderToRename = new BoxFolder(boxConnection, folderId);
folderToRename.rename(newFolderName);
return folderToRename;
} catch (BoxAPIException e) {
throw new RuntimeException(String.format("Box API returned the error code %d\n\n%s", e.getResponseCode(), e.getResponse()), e);
}
}
use of com.box.sdk.BoxAPIException in project camel by apache.
the class BoxFoldersManager method getFolderItems.
/**
* Returns a specific range of child items in folder and specifies which
* fields of each item to retrieve.
*
* @param folderId
* - the id of folder.
* @param offset
* - the index of first child item to retrieve; if
* <code>null</code> all child items are retrieved.
* @param limit
* - the maximum number of children to retrieve after the offset;
* if <code>null</code> all child items are retrieved.
* @param fields
* - the item fields to retrieve for each child item; if
* <code>null</code> all item fields are retrieved.
* @return The Items in folder
*/
public Collection<BoxItem.Info> getFolderItems(String folderId, Long offset, Long limit, String... fields) {
try {
LOG.debug("Getting folder items in folder(id=" + folderId + ") at offset=" + offset + " and limit=" + limit + " with fields=" + Arrays.toString(fields));
if (folderId == null) {
throw new IllegalArgumentException("Parameter 'folderId' can not be null");
}
BoxFolder folder = new BoxFolder(boxConnection, folderId);
if (fields == null) {
fields = new String[0];
}
if (offset != null && limit != null) {
return folder.getChildrenRange(offset, limit, fields);
} else {
Collection<BoxItem.Info> folderItems = new ArrayList<BoxItem.Info>();
Iterable<BoxItem.Info> iterable;
if (fields.length > 0) {
iterable = folder.getChildren(fields);
} else {
iterable = folder.getChildren();
}
for (BoxItem.Info itemInfo : iterable) {
folderItems.add(itemInfo);
}
return folderItems;
}
} catch (BoxAPIException e) {
throw new RuntimeException(String.format("Box API returned the error code %d\n\n%s", e.getResponseCode(), e.getResponse()), e);
}
}
Aggregations