Example usage for org.apache.http.client.entity EntityBuilder setContentEncoding

List of usage examples for org.apache.http.client.entity EntityBuilder setContentEncoding

Introduction

In this page you can find the example usage for org.apache.http.client.entity EntityBuilder setContentEncoding.

Prototype

public EntityBuilder setContentEncoding(final String contentEncoding) 

Source Link

Document

Sets content encoding of the entity.

Usage

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.
 * //from  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 av a 2s  .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.
 * /*from w w w .  j a  v  a2s.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.nextdoor.bender.ipc.http.HttpTransportTest.java

private HttpClient getMockClientWithResponse(byte[] respPayload, ContentType contentType, int status,
        boolean compressed) throws IOException {
    HttpClient mockClient = mock(HttpClient.class);
    HttpResponse mockResponse = mock(HttpResponse.class);

    StatusLine mockStatusLine = mock(StatusLine.class);
    doReturn("expected failure").when(mockStatusLine).getReasonPhrase();
    doReturn(status).when(mockStatusLine).getStatusCode();
    doReturn(mockStatusLine).when(mockResponse).getStatusLine();
    EntityBuilder eb = EntityBuilder.create().setBinary(respPayload).setContentType(contentType);

    HttpEntity he;//from w ww  .j av  a  2s . c o m
    if (compressed) {
        eb.setContentEncoding("gzip");
        he = new GzipDecompressingEntity(eb.build());
    } else {
        he = eb.build();
    }

    doReturn(he).when(mockResponse).getEntity();

    doReturn(mockResponse).when(mockClient).execute(any(HttpPost.class));
    return mockClient;
}

From source file:com.brienwheeler.svc.authorize_net.impl.CIMClientService.java

@Override
@MonitoredWork//from  w w  w .  j  a  v  a  2  s.  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);
    }
}