I am building a app that allows interaction with Dropbox. I have successfully authenticated to, and Dropbox is returning a key and template using it's default login page. However, when I try to use the login with Google option for Dropbox upon authenticating Dropbox returns a user key, however it doesn't return a template id, but instead a too many templates error.
Any help would be appreciated.
Here is my code
public void authUrl(HttpServletRequest request)
{
DbxWebAuth webAuth = new DbxWebAuth(requestConfig, appInfo);
HttpSession session = request.getSession(true);
String sessionKey = "dropbox-auth-csrf-token";
DbxSessionStore csrfTokenStore = new DbxStandardSessionStore(session, sessionKey);
DbxWebAuth.Request authRequest = DbxWebAuth.newRequestBuilder()
.withRedirectUri(redirectUri, csrfTokenStore)
.build();
String authorizeUrl = webAuth.authorize(authRequest);
url =authorizeUrl;
}
public String getTemplate()
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost("https://api.dropboxapi.com/2/file_properties/templates/add_for_user");
post.addHeader("Authorization","Bearer "+code);
post.addHeader("Content-Type", "application/json");
try {
HttpEntity entity = new StringEntity(json);
post.setEntity(entity);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
HttpResponse response = httpclient.execute(post);
HttpEntity entity = response.getEntity();
System.out.println(response.getStatusLine().getStatusCode());
if (entity != null) {
InputStream instream = entity.getContent();
try {
Scanner s = new Scanner(instream).useDelimiter("\\A");
String result = s.hasNext() ? s.next() : "";
System.out.println(result);
System.err.println(result);
return result;
} finally {
instream.close();
}
}
}catch(Exception e)
{
e.printStackTrace();
}
return null;
}
public String authcode(HttpServletRequest request)
{
DbxWebAuth auth = new DbxWebAuth(requestConfig, appInfo);
String sessionKey = "dropbox-auth-csrf-token";
HttpSession session = request.getSession(true);
DbxSessionStore csrfTokenStore = new DbxStandardSessionStore(session, sessionKey);
DbxAuthFinish authFinish;
try {
authFinish = auth.finishFromRedirect(redirectUri, csrfTokenStore, request.getParameterMap());
} catch (DbxWebAuth.BadRequestException ex) {
System.out.println("On /dropbox-auth-finish: Bad request: " + ex.getMessage());
return "failed";
} catch (DbxWebAuth.BadStateException ex) {
System.out.println(ex.getMessage());
// Send them back to the start of the auth flow.
return "failed";
} catch (DbxWebAuth.CsrfException ex) {
System.out.println("On /dropbox-auth-finish: CSRF mismatch: " + ex.getMessage());
//response.sendError(403, "Forbidden.");
return "failed";
} catch (DbxWebAuth.NotApprovedException ex) {
// When Dropbox asked "Do you want to allow this app to access your
// Dropbox account?", the user clicked "No".
//...
return "failed";
} catch (DbxWebAuth.ProviderException ex) {
System.out.println("On /dropbox-auth-finish: Auth failed: " + ex.getMessage());
//response.sendError(503, "Error communicating with Dropbox.");
return "failed";
} catch (DbxException ex) {
System.out.println("On /dropbox-auth-finish: Error getting token: " + ex.getMessage());
//response.sendError(503, "Error communicating with Dropbox.");
return "failed";
}
String accessToken = authFinish.getAccessToken();
code =accessToken;
return accessToken;
}
Notes
I am using a java, running on a google app engine server to complete this authentication.
The exact error text in the logs is
{"error_summary": "too_many_templates/...", "error": {".tag":
"too_many_templates"}}
Along with a error 409.
If you need any more information feel free to ask
Related
I want to access REST server to activate my software. For this, I provide an URL, request body, and some credentials. When I use port 3000 (URL http://localhost:3000/activation), I got java.net.ConnectException. But it be normal when use port 80 or 443.
FYI, my simulator already run and I can access it by Postman.
How can I access port 3000 or other port using HttpClient?
This is my code in Java 1.8
private static ResponseEntityCustom sendRequestHttp(String method, String url, Map<String, List<String>> parameters, Headers requestHeaders, String body, int timeout) throws HttpRequestException {
Builder builder = HttpRequest.newBuilder();
URI uri = null;
try {
uri = new URI(url);
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("uri.getPort(); = "+uri.getPort());
builder.uri(uri);
builder.timeout(Duration.ofMillis(timeout));
System.out.println("URL : "+url);
System.out.println("Method : "+method);
if(method.equalsIgnoreCase(HttpMethod.POST) ||
method.equalsIgnoreCase(HttpMethod.PUT) ||
method.equalsIgnoreCase(HttpMethod.PATCH)
)
{
if(body == null && parameters != null)
{
body = Utility.buildQuery(parameters);
}
if(body != null)
{
builder.method(method, BodyPublishers.ofByteArray(body.getBytes()));
}
}
else if(method.equalsIgnoreCase(HttpMethod.DELETE))
{
builder.DELETE();
}
else if(method.equalsIgnoreCase(HttpMethod.GET))
{
builder.GET();
}
for(Map.Entry<String, List<String>> entry : requestHeaders.entrySet()) {
String key = entry.getKey();
for (String value : entry.getValue())
{
builder.header(key, value);
}
}
HttpRequest request = builder.build();
HttpClient client = HttpClient.newBuilder()
.version(Version.HTTP_1_1)
.followRedirects(Redirect.NORMAL)
.connectTimeout(Duration.ofMillis(timeout))
.build();
HttpResponse<String> response;
ResponseEntityCustom responseEntity = new ResponseEntityCustom();
try {
response = client.send(request, BodyHandlers.ofString());
System.out.println("response = "+response.toString());
responseEntity = new ResponseEntityCustom(response.body(), response.statusCode(), response.headers());
}
catch (InterruptedException e)
{
e.printStackTrace();
throw new HttpRequestException(e.getMessage());
}
catch(ConnectException e)
{
e.printStackTrace();
throw new HttpRequestException(e.getMessage());
}
catch(IOException e)
{
e.printStackTrace();
throw new HttpRequestException(e.getMessage());
}
return responseEntity;
}
I'm attempted to make a request to the ROBLOX API to rank a user, however after about 15 minutes or so I get the error "attempted to read from closed stream. After researching this error, I close the client after each request, and release the connection from the request. However I still get the error. Any help would be greatly appreciated.
public void rankUser(String username, long rank, SlashCommandEvent exceptionCatcher) throws IOException {
try {
URL url = new URL(apiUrl + "v1/groups/" + group + "/users/" + getUserIdFromUsername(username, exceptionCatcher));
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPatch request = new HttpPatch(url.toString());
try {
request.addHeader("Cookie", ".ROBLOSECURITY=" + token);
request.addHeader("X-CSRF-Token", xcsrfToken);
request.addHeader("Content-Type", "application/json");
StringEntity params = new StringEntity("{\"roleId\":" + rank + "}");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
if(response.getHeaders("x-csrf-token") != null && xcsrfToken.equalsIgnoreCase("")) {
xcsrfToken = response.getHeaders("x-csrf-token")[0].getValue();
rankUser(username, rank, exceptionCatcher);
return;
}
request.releaseConnection();
statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
String responseAsString = getResponseAsString(response);
JsonParser parser = new JsonParser();
JsonObject jsonObject = (JsonObject) parser.parse(responseAsString);
} else if(statusCode == 429) {
exceptionCatcher.reply("You are being rate limited. Please try again in a few minutes.").setEphemeral(true).queue();
return;
} else {
System.out.println(getResponseAsString(response));
exceptionCatcher.reply("Could not rank user. Response: " + getResponseAsString(response)).setEphemeral(true).queue();
return;
}
httpClient.close();
} catch (Exception e) {
exceptionCatcher.reply("Could not rank. Ensure that the user is in the group. Error: " + e.getMessage()).setEphemeral(true).queue();
httpClient.close();
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
I'm trying to upload an Excel file in SharePoint using java, but I'm getting as response code: 301. How do I fix it?
Generated the client id, Secret, Tenant id, Access token. Bearer= tenant id, access Token = "your generated access token".
This is the code
public class fileUpload
{
private static void executeRequest(HttpPost httpPost)
{
try
{
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);
System.out.println("Response Code: " + response.getStatusLine().getStatusCode());
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IllegalStateException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void executeMultiPartRequest(String urlString, File file) throws IOException
{
HttpPost postRequest = new HttpPost(urlString);
postRequest = addHeader(postRequest,"Access Token");
try
{
postRequest.setEntity(new FileEntity(file));
}
catch (Exception ex)
{
ex.printStackTrace();
}
executeRequest(postRequest);
}
private static HttpPost addHeader(HttpPost httpPost, String accessToken)
{
httpPost.addHeader("Accept", "application/json;odata=verbose");
httpPost.setHeader("Authorization", "Bearer " + accessToken);
httpPost.addHeader("Content-type", "multipart/form-data");
return httpPost;
}
public static void main(String args[]) throws IOException
{
BasicConfigurator.configure();
fileUpload fileUpload = new fileUpload();
File file = new File("C:\\Users\\Desktop\\Proto.xlsx");
fileUpload.executeMultiPartRequest(
"https://<organization name>.sharepoint.com/:f:/r/sites/Shared%20Documents/General/L1L2%20FORM?csf=1&web=1&e=MI5gZf", file);
}
}
String jsonBody = "<Json input>";
HttpResponse<String> response = null;
RequestBodyEntity res=null;
String url = "<some url>";
try {
response = Unirest.post(url).header("content-type", "application/json").body(jsonBody).asString();
System.out.println("Response: " + response.getBody());
} catch (UnirestException e) {
Reporter.reportStatus("Fail", "Failure in Unirest call", "path is "+url);
}
File file = new File("<Location of the file>");
InputStream input = response.getRawBody();
try {
FileOutputStream report = convertInputStreamToFile(input, file);
} catch (Exception e) {
e.printStackTrace();
}
I want to get some response to this post call that will be stored in "response".
I want to download the response, preferably to an excelsheet.
How do I go about it?
Am trying to create user into my salesforce account through REST api using java.But its returning 400 status code.Can you please guide me?
Here is the code am trying:
public static void createUsers() {
System.out.println("\n_______________ USER INSERT _______________");
String uri = baseUri + "/sobjects/User/";
System.out.println(uri);
try {
//create the JSON object containing the new lead details.
JSONObject lead = new JSONObject();
lead.put("FirstName", "Jake");
lead.put("LastName", "sully");
lead.put("Alias", "Jake");
lead.put("Email", "Jake#gmail.com");
lead.put("Username", "Jake#gmail.com");
lead.put("Name", "jake");
lead.put("UserRoleId","00E28000000oD8EEAU");
lead.put("Id", "10028000000GLSIAA4");
lead.put("EmailEncodingKey", "ISO-8859-1");
lead.put("TimeZoneSidKey", "Asia/Kolkata");
lead.put("LocaleSidKey", "en_US");
lead.put("ProfileId", "00e280000027hnGAAQ");
lead.put("LanguageLocaleKey", "en_US");
//Construct the objects needed for the request
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(uri);
httpPost.addHeader(oauthHeader);
httpPost.addHeader(prettyPrintHeader);
// The message we are going to post
StringEntity body = new StringEntity(lead.toString(1));
body.setContentType("application/json");
httpPost.setEntity(body);
//Make the request
HttpResponse response = httpClient.execute(httpPost);
//Process the results
System.out.println(response.toString());
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 201) {
String response_string = EntityUtils.toString(response.getEntity());
JSONObject json = new JSONObject(response_string);
// Store the retrieved lead id to use when we update the lead.
leadId = json.getString("id");
} else {
System.out.println("Insertion unsuccessful. Status code returned is " + statusCode);
}
} catch (JSONException e) {
System.out.println("Issue creating JSON or processing results");
e.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (NullPointerException npe) {
npe.printStackTrace();
}
}