List of usage examples for org.apache.http.client.entity EntityBuilder setContentType
public EntityBuilder setContentType(final ContentType contentType)
From source file:com.jaspersoft.studio.community.RESTCommunityHelper.java
/** * Uploads the specified file to the community site. The return identifier * can be used later when composing other requests. * /* w w w .j a v a 2s. c om*/ * @param httpclient * the http client * @param attachment * the file to attach * @param authCookie * the session cookie to use for authentication purpose * @return the identifier of the file uploaded, <code>null</code> otherwise * @throws CommunityAPIException */ public static String uploadFile(CloseableHttpClient httpclient, File attachment, Cookie authCookie) throws CommunityAPIException { FileInputStream fin = null; try { fin = new FileInputStream(attachment); byte fileContent[] = new byte[(int) attachment.length()]; fin.read(fileContent); byte[] encodedFileContent = Base64.encodeBase64(fileContent); FileUploadRequest uploadReq = new FileUploadRequest(attachment.getName(), encodedFileContent); HttpPost fileuploadPOST = new HttpPost(CommunityConstants.FILE_UPLOAD_URL); EntityBuilder fileUploadEntity = EntityBuilder.create(); fileUploadEntity.setText(uploadReq.getAsJSON()); fileUploadEntity.setContentType(ContentType.create(CommunityConstants.JSON_CONTENT_TYPE)); fileUploadEntity.setContentEncoding(CommunityConstants.REQUEST_CHARSET); fileuploadPOST.setEntity(fileUploadEntity.build()); CloseableHttpResponse resp = httpclient.execute(fileuploadPOST); int httpRetCode = resp.getStatusLine().getStatusCode(); String responseBodyAsString = EntityUtils.toString(resp.getEntity()); if (HttpStatus.SC_OK == httpRetCode) { ObjectMapper mapper = new ObjectMapper(); mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true); JsonNode jsonRoot = mapper.readTree(responseBodyAsString); String fid = jsonRoot.get("fid").asText(); //$NON-NLS-1$ return fid; } else { CommunityAPIException ex = new CommunityAPIException(Messages.RESTCommunityHelper_FileUploadError); ex.setHttpStatusCode(httpRetCode); ex.setResponseBodyAsString(responseBodyAsString); throw ex; } } catch (FileNotFoundException e) { JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_FileNotFoundError, e); throw new CommunityAPIException(Messages.RESTCommunityHelper_FileUploadError, e); } catch (UnsupportedEncodingException e) { JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_EncodingNotValidError, e); throw new CommunityAPIException(Messages.RESTCommunityHelper_FileUploadError, e); } catch (IOException e) { JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_PostMethodIOError, e); throw new CommunityAPIException(Messages.RESTCommunityHelper_FileUploadError, e); } finally { IOUtils.closeQuietly(fin); } }
From source file:com.jaspersoft.studio.community.RESTCommunityHelper.java
/** * Creates a new issue in the community tracker. * //w w w .j a v a 2 s. c o m * @param httpclient * the http client * @param newIssue * the new issue to create on the community tracker * @param attachmentsIds * the list of file identifiers that will be attached to the * final issue * @param authCookie * the session cookie to use for authentication purpose * @return the tracker URL of the newly created issue * @throws CommunityAPIException */ public static String createNewIssue(CloseableHttpClient httpclient, IssueRequest newIssue, List<String> attachmentsIds, Cookie authCookie) throws CommunityAPIException { try { // Add attachments if any if (!attachmentsIds.isEmpty()) { IssueField attachmentsField = new IssueField() { @Override protected String getValueAttributeName() { return "fid"; //$NON-NLS-1$ } @Override public boolean isArray() { return true; } }; attachmentsField.setName("field_bug_attachments"); //$NON-NLS-1$ attachmentsField.setValues(attachmentsIds); newIssue.setAttachments(attachmentsField); } HttpPost issueCreationPOST = new HttpPost(CommunityConstants.ISSUE_CREATION_URL); EntityBuilder newIssueEntity = EntityBuilder.create(); newIssueEntity.setText(newIssue.getAsJSON()); newIssueEntity.setContentType(ContentType.create(CommunityConstants.JSON_CONTENT_TYPE)); newIssueEntity.setContentEncoding(CommunityConstants.REQUEST_CHARSET); issueCreationPOST.setEntity(newIssueEntity.build()); HttpResponse httpResponse = httpclient.execute(issueCreationPOST); int httpRetCode = httpResponse.getStatusLine().getStatusCode(); String responseBodyAsString = EntityUtils.toString(httpResponse.getEntity()); if (HttpStatus.SC_OK != httpRetCode) { CommunityAPIException ex = new CommunityAPIException( Messages.RESTCommunityHelper_IssueCreationError); ex.setHttpStatusCode(httpRetCode); ex.setResponseBodyAsString(responseBodyAsString); throw ex; } else { // extract the node ID information in order // to retrieve the issue URL available on the tracker ObjectMapper mapper = new ObjectMapper(); mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true); JsonNode jsonRoot = mapper.readTree(responseBodyAsString); String nodeID = jsonRoot.get("nid").asText(); //$NON-NLS-1$ JsonNode jsonNodeContent = retrieveNodeContentAsJSON(httpclient, nodeID, authCookie); return jsonNodeContent.get("path").asText(); //$NON-NLS-1$ } } catch (UnsupportedEncodingException e) { JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_EncodingNotValidError, e); throw new CommunityAPIException(Messages.RESTCommunityHelper_IssueCreationError, e); } catch (IOException e) { JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_PostMethodIOError, e); throw new CommunityAPIException(Messages.RESTCommunityHelper_IssueCreationError, e); } }
From source file:com.jaspersoft.studio.community.RESTCommunityHelper.java
/** * Executes the authentication to the Jaspersoft community in order to * retrieve the session cookie to use later for all other operations. * /*w w w . ja v a2 s. c o m*/ * @param httpclient * the http client * * @param cookieStore * the Cookie Store instance * @param username * the community user name (or email) * @param password * the community user password * @return the authentication cookie if able to retrieve it, * <code>null</code> otherwise * @throws CommunityAPIException */ public static Cookie getAuthenticationCookie(CloseableHttpClient httpclient, CookieStore cookieStore, String username, String password) throws CommunityAPIException { try { HttpPost loginPOST = new HttpPost(CommunityConstants.LOGIN_URL); EntityBuilder loginEntity = EntityBuilder.create(); loginEntity.setText("{ \"username\": \"" + username + "\", \"password\":\"" + password + "\" }"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ loginEntity.setContentType(ContentType.create(CommunityConstants.JSON_CONTENT_TYPE)); loginEntity.setContentEncoding(CommunityConstants.REQUEST_CHARSET); loginPOST.setEntity(loginEntity.build()); CloseableHttpResponse resp = httpclient.execute(loginPOST); int httpRetCode = resp.getStatusLine().getStatusCode(); String responseBodyAsString = EntityUtils.toString(resp.getEntity()); if (HttpStatus.SC_OK == httpRetCode) { // Can proceed List<Cookie> cookies = cookieStore.getCookies(); Cookie authCookie = null; for (Cookie cookie : cookies) { if (cookie.getName().startsWith("SESS")) { //$NON-NLS-1$ authCookie = cookie; break; } } return authCookie; } else if (HttpStatus.SC_UNAUTHORIZED == httpRetCode) { // Unauthorized... wrong username or password CommunityAPIException unauthorizedEx = new CommunityAPIException( Messages.RESTCommunityHelper_WrongUsernamePasswordError); unauthorizedEx.setHttpStatusCode(httpRetCode); unauthorizedEx.setResponseBodyAsString(responseBodyAsString); throw unauthorizedEx; } else { // Some other problem occurred CommunityAPIException generalEx = new CommunityAPIException( Messages.RESTCommunityHelper_AuthInfoProblemsError); generalEx.setHttpStatusCode(httpRetCode); generalEx.setResponseBodyAsString(responseBodyAsString); throw generalEx; } } catch (UnsupportedEncodingException e) { JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_EncodingNotValidError, e); throw new CommunityAPIException(Messages.RESTCommunityHelper_AuthenticationError, e); } catch (IOException e) { JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_PostMethodIOError, e); throw new CommunityAPIException(Messages.RESTCommunityHelper_AuthenticationError, e); } }
From source file:com.jkoolcloud.tnt4j.streams.inputs.HttpStreamTest.java
@Test public void httpFilePostTest() throws Exception { HttpClientBuilder builder = HttpClientBuilder.create(); HttpClient client = builder.build(); URI url = makeURI();// ww w.j a va 2s. com HttpPost post = new HttpPost(url); File file = new File(samplesDir, "/http-file/log.txt"); EntityBuilder entityBuilder = EntityBuilder.create(); entityBuilder.setFile(file); entityBuilder.setContentType(ContentType.TEXT_PLAIN); MultipartEntityBuilder builder2 = MultipartEntityBuilder.create(); builder2.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM, "file.ext"); // NON-NLS HttpEntity multipart = builder2.build(); post.setEntity(multipart); final HttpResponse returned = client.execute(post); assertNotNull(returned); }
From source file:com.brienwheeler.svc.authorize_net.impl.CIMClientService.java
@Override @MonitoredWork//from w ww. ja v a 2s. c om @GracefulShutdown @Transactional //(readOnly=true, propagation=Propagation.SUPPORTS) public String getHostedProfilePageToken(DbId<User> userId, String returnUrl) { // More than two years later this still isn't in their Java SDK. Oh well, let's just do it // the stupid way... String customerProfileId = userAttributeService.getAttribute(userId, ATTR_PROFILE_ID); if (customerProfileId == null) customerProfileId = createCustomerProfile(userId); StringBuffer buffer = new StringBuffer(4096); buffer.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"); buffer.append("<getHostedProfilePageRequest xmlns=\"AnetApi/xml/v1/schema/AnetApiSchema.xsd\">\n"); buffer.append(" <merchantAuthentication>\n"); buffer.append(" <name>" + apiLoginID + "</name>"); buffer.append(" <transactionKey>" + transactionKey + "</transactionKey>\n"); buffer.append(" </merchantAuthentication>\n"); buffer.append(" <customerProfileId>" + customerProfileId + "</customerProfileId> \n"); buffer.append(" <hostedProfileSettings>\n"); buffer.append(" <setting>\n"); buffer.append(" <settingName>hostedProfileReturnUrl</settingName>\n"); buffer.append(" <settingValue>" + returnUrl + "</settingValue>\n"); buffer.append(" </setting>\n"); buffer.append(" </hostedProfileSettings>\n"); buffer.append("</getHostedProfilePageRequest>\n"); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(merchant.isSandboxEnvironment() ? TEST_URL : PRODUCTION_URL); EntityBuilder entityBuilder = EntityBuilder.create(); entityBuilder.setContentType(ContentType.TEXT_XML); entityBuilder.setContentEncoding("utf-8"); entityBuilder.setText(buffer.toString()); httpPost.setEntity(entityBuilder.build()); try { CloseableHttpResponse httpResponse = httpClient.execute(httpPost); String response = EntityUtils.toString(httpResponse.getEntity()); int start = response.indexOf(ELEMENT_TOKEN_OPEN); if (start == -1) throw new AuthorizeNetException( "error fetching hosted profile page token for " + userId + ", response: " + response); int end = response.indexOf(ELEMENT_TOKEN_CLOSE); if (end == -1) throw new AuthorizeNetException( "error fetching hosted profile page token for " + userId + ", response: " + response); return response.substring(start + ELEMENT_TOKEN_OPEN.length(), end); } catch (ClientProtocolException e) { throw new AuthorizeNetException(e.getMessage(), e); } catch (IOException e) { throw new AuthorizeNetException(e.getMessage(), e); } }
From source file:org.identityconnectors.office365.Office365Connection.java
public boolean patchObject(String path, JSONObject body) { log.info("patchRequest(" + path + ")"); // http://msdn.microsoft.com/en-us/library/windowsazure/dn151671.aspx HttpPatch httpPatch = new HttpPatch(getAPIEndPoint(path)); httpPatch.addHeader("Authorization", this.getToken()); // patch.addHeader("Content-Type", "application/json;odata=verbose"); httpPatch.addHeader("DataServiceVersion", "3.0;NetFx"); httpPatch.addHeader("MaxDataServiceVersion", "3.0;NetFx"); httpPatch.addHeader("Accept", "application/atom+xml"); EntityBuilder eb = EntityBuilder.create(); eb.setText(body.toString());//from www . j a v a 2 s . co m eb.setContentType(ContentType.create("application/json")); httpPatch.setEntity(eb.build()); HttpClient httpClient = HttpClientBuilder.create().build(); try { HttpResponse response = httpClient.execute(httpPatch); HttpEntity entity = response.getEntity(); if (response.getStatusLine().getStatusCode() != 204) { log.error("An error occured when modify an object in Office 365"); this.invalidateToken(); StringBuffer sb = new StringBuffer(); if (entity != null && entity.getContent() != null) { BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent())); String s = null; log.info("Response :{0}", response.getStatusLine().toString()); while ((s = in.readLine()) != null) { sb.append(s); log.info(s); } } throw new ConnectorException("Modify Object failed to " + path + " and body of " + body.toString() + ". Error code was " + response.getStatusLine().getStatusCode() + ". Received the following response " + sb.toString()); } else { return true; } } catch (ClientProtocolException cpe) { log.error(cpe, "Error doing patchRequest to path {0}", path); throw new ConnectorException("Exception whilst doing PATCH to " + path); } catch (IOException ioe) { log.error(ioe, "IOE Error doing patchRequest to path {0}", path); throw new ConnectorException("Exception whilst doing PATCH to " + path); } }
From source file:org.identityconnectors.office365.Office365Connection.java
public Uid postRequest(String path, JSONObject body) { log.info("postRequest(" + path + ")"); HttpPost post = new HttpPost(getAPIEndPoint(path)); post.addHeader("Authorization", this.getToken()); // patch.addHeader("Content-Type", "application/json;odata=verbose"); post.addHeader("DataServiceVersion", "3.0;NetFx"); post.addHeader("MaxDataServiceVersion", "3.0;NetFx"); post.addHeader("Accept", "application/atom+xml"); EntityBuilder eb = EntityBuilder.create(); eb.setText(body.toString());/*from w w w. j av a 2 s .c o m*/ eb.setContentType(ContentType.create("application/json")); post.setEntity(eb.build()); HttpClient httpClient = HttpClientBuilder.create().build(); try { HttpResponse response = httpClient.execute(post); HttpEntity entity = response.getEntity(); log.info("Status code from postRequest is {0}", response.getStatusLine().getStatusCode()); // assignLicense returns 200 if ((response.getStatusLine().getStatusCode() != 201 && !path.contains("/assignLicense?")) || response.getStatusLine().getStatusCode() == 400) { log.error("An error occured when creating object in Office 365, path was {0}", path); this.invalidateToken(); StringBuffer sb = new StringBuffer(); if (entity != null && entity.getContent() != null) { BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent())); String s = null; log.info("Response :{0}", response.getStatusLine().toString()); while ((s = in.readLine()) != null) { sb.append(s); log.info(s); } } throw new ConnectorException("Error on post to " + path + " and body of " + body.toString() + ". Error code: " + response.getStatusLine().getStatusCode() + " Received the following response " + sb.toString()); } else if (path.contains("/assignLicense?") && response.getStatusLine().getStatusCode() == 200) { return SUCCESS_UID; } else { Header[] location = response.getHeaders("Location"); // Location: https://directory.windows.net/contoso.onmicrosoft.com/directoryObjects/4e971521-101a-4311-94f4-0917d7218b4e/Microsoft.WindowsAzure.ActiveDirectory.User Matcher m = directoryObjectGUIDPattern.matcher(location[0].getValue()); boolean b = m.matches(); if (b) { String guid = m.group(1); log.info("Object has GUID of {0}", guid); return new Uid(guid); } else { log.error("No GUID found on path {0}", path); throw new ConnectorException("No GUID found for " + path + " and body of " + body.toString()); } } } catch (ClientProtocolException cpe) { log.error(cpe, "Error doing postRequest to path {0}", path); throw new ConnectorException("Exception whilst doing POST to " + path); } catch (IOException ioe) { log.error(ioe, "IOE Error doing postRequest to path {0}", path); throw new ConnectorException("Exception whilst doing POST to " + path); } }