Example usage for org.apache.http.client.methods CloseableHttpResponse getFirstHeader

List of usage examples for org.apache.http.client.methods CloseableHttpResponse getFirstHeader

Introduction

In this page you can find the example usage for org.apache.http.client.methods CloseableHttpResponse getFirstHeader.

Prototype

Header getFirstHeader(String str);

Source Link

Usage

From source file:org.mobicents.servlet.restcomm.http.client.Downloader.java

public HttpResponseDescriptor fetch(final HttpRequestDescriptor descriptor)
        throws IllegalArgumentException, IOException, URISyntaxException, XMLStreamException {
    int code = -1;
    HttpRequest request = null;// ww  w.  j  a v  a 2 s .  com
    CloseableHttpResponse response = null;
    HttpRequestDescriptor temp = descriptor;
    CloseableHttpClient client = null;
    HttpResponseDescriptor responseDescriptor = null;
    try {
        do {
            client = (CloseableHttpClient) CustomHttpClientBuilder
                    .build(RestcommConfiguration.getInstance().getMain());
            //            client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
            //            client.getParams().setParameter("http.protocol.content-charset", "UTF-8");
            request = request(temp);
            request.setHeader("http.protocol.content-charset", "UTF-8");

            response = client.execute((HttpUriRequest) request);
            code = response.getStatusLine().getStatusCode();
            if (isRedirect(code)) {
                final Header header = response.getFirstHeader(HttpHeaders.LOCATION);
                if (header != null) {
                    final String location = header.getValue();
                    final URI uri = URI.create(location);
                    temp = new HttpRequestDescriptor(uri, temp.getMethod(), temp.getParameters());
                    continue;
                } else {
                    break;
                }
            }
            //                HttpResponseDescriptor httpResponseDescriptor = response(request, response);
            responseDescriptor = validateXML(response(request, response));
        } while (isRedirect(code));
        if (isHttpError(code)) {
            String requestUrl = request.getRequestLine().getUri();
            String errorReason = response.getStatusLine().getReasonPhrase();
            String httpErrorMessage = String.format(
                    "Error while fetching http resource: %s \n Http error code: %d \n Http error message: %s",
                    requestUrl, code, errorReason);
            logger.warning(httpErrorMessage);
        }
    } catch (IllegalArgumentException | URISyntaxException | IOException e) {
        logger.error("Exception during HTTP request execution: " + e.getCause());
        HttpClientUtils.closeQuietly(client);
        client = null;
    } finally {
        response.close();
        HttpClientUtils.closeQuietly(client);
        client = null;
    }
    return responseDescriptor;
}

From source file:org.apache.sling.discovery.base.connectors.ping.TopologyConnectorClient.java

/** ping the server and pass the announcements between the two **/
void ping(final boolean force) {
    if (autoStopped) {
        // then we suppress any further pings!
        logger.debug("ping: autoStopped=true, hence suppressing any further pings.");
        return;//from w ww  .  j  a  v a 2  s .  c om
    }
    if (force) {
        backoffPeriodEnd = -1;
    } else if (backoffPeriodEnd > 0) {
        if (System.currentTimeMillis() < backoffPeriodEnd) {
            logger.debug("ping: not issueing a heartbeat due to backoff instruction from peer.");
            return;
        } else {
            logger.debug("ping: backoff period ended, issuing another ping now.");
        }
    }
    final String uri = connectorUrl.toString() + "." + clusterViewService.getSlingId() + ".json";
    if (logger.isDebugEnabled()) {
        logger.debug("ping: connectorUrl=" + connectorUrl + ", complete uri=" + uri);
    }
    final HttpClientContext clientContext = HttpClientContext.create();
    final CloseableHttpClient httpClient = createHttpClient();
    final HttpPut putRequest = new HttpPut(uri);

    // setting the connection timeout (idle connection, configured in seconds)
    putRequest.setConfig(
            RequestConfig.custom().setConnectTimeout(1000 * config.getSocketConnectTimeout()).build());

    Announcement resultingAnnouncement = null;
    try {
        String userInfo = connectorUrl.getUserInfo();
        if (userInfo != null) {
            Credentials c = new UsernamePasswordCredentials(userInfo);
            clientContext.getCredentialsProvider().setCredentials(
                    new AuthScope(putRequest.getURI().getHost(), putRequest.getURI().getPort()), c);
        }

        Announcement topologyAnnouncement = new Announcement(clusterViewService.getSlingId());
        topologyAnnouncement.setServerInfo(serverInfo);
        final ClusterView clusterView;
        try {
            clusterView = clusterViewService.getLocalClusterView();
        } catch (UndefinedClusterViewException e) {
            // SLING-5030 : then we cannot ping
            logger.warn("ping: no clusterView available at the moment, cannot ping others now: " + e);
            return;
        }
        topologyAnnouncement.setLocalCluster(clusterView);
        if (force) {
            logger.debug("ping: sending a resetBackoff");
            topologyAnnouncement.setResetBackoff(true);
        }
        announcementRegistry.addAllExcept(topologyAnnouncement, clusterView, new AnnouncementFilter() {

            public boolean accept(final String receivingSlingId, final Announcement announcement) {
                // filter out announcements that are of old cluster instances
                // which I dont really have in my cluster view at the moment
                final Iterator<InstanceDescription> it = clusterView.getInstances().iterator();
                while (it.hasNext()) {
                    final InstanceDescription instance = it.next();
                    if (instance.getSlingId().equals(receivingSlingId)) {
                        // then I have the receiving instance in my cluster view
                        // all fine then
                        return true;
                    }
                }
                // looks like I dont have the receiving instance in my cluster view
                // then I should also not propagate that announcement anywhere
                return false;
            }
        });
        final String p = requestValidator.encodeMessage(topologyAnnouncement.asJSON());

        if (logger.isDebugEnabled()) {
            logger.debug("ping: topologyAnnouncement json is: " + p);
        }
        requestValidator.trustMessage(putRequest, p);
        if (config.isGzipConnectorRequestsEnabled()) {
            // tell the server that the content is gzipped:
            putRequest.addHeader("Content-Encoding", "gzip");
            // and gzip the body:
            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            final GZIPOutputStream gzipOut = new GZIPOutputStream(baos);
            gzipOut.write(p.getBytes("UTF-8"));
            gzipOut.close();
            final byte[] gzippedEncodedJson = baos.toByteArray();
            putRequest.setEntity(new ByteArrayEntity(gzippedEncodedJson, ContentType.APPLICATION_JSON));
            lastRequestEncoding = "gzip";
        } else {
            // otherwise plaintext:
            final StringEntity plaintext = new StringEntity(p, "UTF-8");
            plaintext.setContentType(ContentType.APPLICATION_JSON.getMimeType());
            putRequest.setEntity(plaintext);
            lastRequestEncoding = "plaintext";
        }
        // independent of request-gzipping, we do accept the response to be gzipped,
        // so indicate this to the server:
        putRequest.addHeader("Accept-Encoding", "gzip");
        final CloseableHttpResponse response = httpClient.execute(putRequest, clientContext);
        if (logger.isDebugEnabled()) {
            logger.debug("ping: done. code=" + response.getStatusLine().getStatusCode() + " - "
                    + response.getStatusLine().getReasonPhrase());
        }
        lastStatusCode = response.getStatusLine().getStatusCode();
        lastResponseEncoding = null;
        if (response.getStatusLine().getStatusCode() == HttpServletResponse.SC_OK) {
            final Header contentEncoding = response.getFirstHeader("Content-Encoding");
            if (contentEncoding != null && contentEncoding.getValue() != null
                    && contentEncoding.getValue().contains("gzip")) {
                lastResponseEncoding = "gzip";
            } else {
                lastResponseEncoding = "plaintext";
            }
            final String responseBody = requestValidator.decodeMessage(putRequest.getURI().getPath(), response); // limiting to 16MB, should be way enough
            if (logger.isDebugEnabled()) {
                logger.debug("ping: response body=" + responseBody);
            }
            if (responseBody != null && responseBody.length() > 0) {
                Announcement inheritedAnnouncement = Announcement.fromJSON(responseBody);
                final long backoffInterval = inheritedAnnouncement.getBackoffInterval();
                if (backoffInterval > 0) {
                    // then reset the backoffPeriodEnd:

                    /* minus 1 sec to avoid slipping the interval by a few millis */
                    this.backoffPeriodEnd = System.currentTimeMillis() + (1000 * backoffInterval) - 1000;
                    logger.debug("ping: servlet instructed to backoff: backoffInterval=" + backoffInterval
                            + ", resulting in period end of " + new Date(backoffPeriodEnd));
                } else {
                    logger.debug("ping: servlet did not instruct any backoff-ing at this stage");
                    this.backoffPeriodEnd = -1;
                }
                if (inheritedAnnouncement.isLoop()) {
                    if (logger.isDebugEnabled()) {
                        logger.debug(
                                "ping: connector response indicated a loop detected. not registering this announcement from "
                                        + inheritedAnnouncement.getOwnerId());
                    }
                    if (inheritedAnnouncement.getOwnerId().equals(clusterViewService.getSlingId())) {
                        // SLING-3316 : local-loop detected. Check config to see if we should stop this connector

                        if (config.isAutoStopLocalLoopEnabled()) {
                            inheritedAnnouncement = null; // results in connected -> false and representsloop -> true
                            autoStopped = true; // results in isAutoStopped -> true
                        }
                    }
                } else {
                    inheritedAnnouncement.setInherited(true);
                    if (announcementRegistry.registerAnnouncement(inheritedAnnouncement) == -1) {
                        if (logger.isDebugEnabled()) {
                            logger.debug(
                                    "ping: connector response is from an instance which I already see in my topology"
                                            + inheritedAnnouncement);
                        }
                        statusDetails = "receiving side is seeing me via another path (connector or cluster) already (loop)";
                        return;
                    }
                }
                resultingAnnouncement = inheritedAnnouncement;
                statusDetails = null;
            } else {
                statusDetails = "no response body received";
            }
        } else {
            statusDetails = "got HTTP Status-Code: " + lastStatusCode;
        }
        // SLING-2882 : reset suppressPingWarnings_ flag in success case
        suppressPingWarnings_ = false;
    } catch (IOException e) {
        // SLING-2882 : set/check the suppressPingWarnings_ flag
        if (suppressPingWarnings_) {
            if (logger.isDebugEnabled()) {
                logger.debug("ping: got IOException: " + e + ", uri=" + uri);
            }
        } else {
            suppressPingWarnings_ = true;
            logger.warn("ping: got IOException [suppressing further warns]: " + e + ", uri=" + uri);
        }
        statusDetails = e.toString();
    } catch (JSONException e) {
        logger.warn("ping: got JSONException: " + e);
        statusDetails = e.toString();
    } catch (RuntimeException re) {
        logger.warn("ping: got RuntimeException: " + re, re);
        statusDetails = re.toString();
    } finally {
        putRequest.releaseConnection();
        lastInheritedAnnouncement = resultingAnnouncement;
        lastPingedAt = System.currentTimeMillis();
        try {
            httpClient.close();
        } catch (IOException e) {
            logger.error("disconnect: could not close httpClient: " + e, e);
        }
    }
}

From source file:org.votingsystem.util.HttpHelper.java

public <T> T getData(Class<T> type, TypeReference typeReference, String serverURL, String mediaType)
        throws Exception {
    log.info("getData - contentType: " + mediaType + " - serverURL: " + serverURL);
    CloseableHttpResponse response = null;
    HttpGet httpget = null;//  w w w  .  j av  a 2s  .c om
    String responseContentType = null;
    httpget = new HttpGet(serverURL);
    if (mediaType != null)
        httpget.setHeader("Content-Type", mediaType);
    response = httpClient.execute(httpget);
    log.info("----------------------------------------");
    /*Header[] headers = response.getAllHeaders();
    for (int i = 0; i < headers.length; i++) { System.out.println(headers[i]); }*/
    log.info(response.getStatusLine().toString() + " - connManager stats: "
            + connManager.getTotalStats().toString());
    log.info("----------------------------------------");
    Header header = response.getFirstHeader("Content-Type");
    if (header != null)
        responseContentType = header.getValue();
    try {
        byte[] responseBytes = EntityUtils.toByteArray(response.getEntity());
        if (ResponseVS.SC_OK == response.getStatusLine().getStatusCode()) {
            if (type != null)
                return JSON.getMapper().readValue(responseBytes, type);
            else
                return JSON.getMapper().readValue(responseBytes, typeReference);
        } else {
            MessageDto messageDto = null;
            String responseStr = null;
            if (responseContentType != null && responseContentType.contains(MediaTypeVS.JSON))
                messageDto = JSON.getMapper().readValue(responseBytes, MessageDto.class);
            else
                responseStr = new String(responseBytes, StandardCharsets.UTF_8);
            switch (response.getStatusLine().getStatusCode()) {
            case ResponseVS.SC_NOT_FOUND:
                throw new NotFoundExceptionVS(responseStr, messageDto);
            case ResponseVS.SC_ERROR_REQUEST_REPEATED:
                throw new RequestRepeatedExceptionVS(responseStr, messageDto);
            case ResponseVS.SC_ERROR_REQUEST:
                throw new BadRequestExceptionVS(responseStr, messageDto);
            case ResponseVS.SC_ERROR:
                throw new ServerExceptionVS(EntityUtils.toString(response.getEntity()), messageDto);
            default:
                throw new ExceptionVS(responseStr, messageDto);
            }
        }
    } finally {
        if (response != null)
            response.close();
    }
}

From source file:org.votingsystem.util.HttpHelper.java

public ResponseVS sendFile(File file, ContentTypeVS contentTypeVS, String serverURL, String... headerNames) {
    log.info("sendFile - contentType: " + contentTypeVS + " - serverURL: " + serverURL);
    ResponseVS responseVS = null;//from   w w  w.  j  a v  a  2 s. com
    HttpPost httpPost = null;
    ContentTypeVS responseContentType = null;
    CloseableHttpResponse response = null;
    try {
        httpPost = new HttpPost(serverURL);
        ContentType contentType = null;
        if (contentTypeVS != null)
            contentType = ContentType.create(contentTypeVS.getName());
        FileEntity entity = new FileEntity(file, contentType);
        httpPost.setEntity(entity);
        response = httpClient.execute(httpPost);
        log.info("----------------------------------------");
        log.info(response.getStatusLine().toString() + " - connManager stats: "
                + connManager.getTotalStats().toString());
        log.info("----------------------------------------");
        Header header = response.getFirstHeader("Content-Type");
        if (header != null)
            responseContentType = ContentTypeVS.getByName(header.getValue());
        byte[] responseBytes = EntityUtils.toByteArray(response.getEntity());
        responseVS = new ResponseVS(response.getStatusLine().getStatusCode(), responseBytes,
                responseContentType);
        if (headerNames != null) {
            List<String> headerValues = new ArrayList<String>();
            for (String headerName : headerNames) {
                org.apache.http.Header headerValue = response.getFirstHeader(headerName);
                headerValues.add(headerValue.getValue());
            }
            responseVS.setData(headerValues);
        }
    } catch (Exception ex) {
        log.log(Level.SEVERE, ex.getMessage(), ex);
        responseVS = new ResponseVS(ResponseVS.SC_ERROR, ex.getMessage());
        if (httpPost != null)
            httpPost.abort();
    } finally {
        try {
            if (response != null)
                response.close();
        } catch (Exception ex) {
            log.log(Level.SEVERE, ex.getMessage(), ex);
        }
        return responseVS;
    }
}

From source file:org.votingsystem.util.HttpHelper.java

public ResponseVS getData(String serverURL, ContentTypeVS contentType) {
    log.info("getData - contentType: " + contentType + " - serverURL: " + serverURL);
    ResponseVS responseVS = null;/*w ww .ja  v  a  2 s . c o  m*/
    CloseableHttpResponse response = null;
    HttpGet httpget = null;
    ContentTypeVS responseContentType = null;
    try {
        httpget = new HttpGet(serverURL);
        if (contentType != null)
            httpget.setHeader("Content-Type", contentType.getName());
        response = httpClient.execute(httpget);
        log.info("----------------------------------------");
        /*Header[] headers = response.getAllHeaders();
        for (int i = 0; i < headers.length; i++) { System.out.println(headers[i]); }*/
        log.info(response.getStatusLine().toString() + " - connManager stats: "
                + connManager.getTotalStats().toString());
        log.info("----------------------------------------");
        Header header = response.getFirstHeader("Content-Type");
        if (header != null)
            responseContentType = ContentTypeVS.getByName(header.getValue());
        if (ResponseVS.SC_OK == response.getStatusLine().getStatusCode()) {
            byte[] responseBytes = EntityUtils.toByteArray(response.getEntity());
            responseVS = new ResponseVS(response.getStatusLine().getStatusCode(), responseBytes,
                    responseContentType);
        } else {
            responseVS = new ResponseVS(response.getStatusLine().getStatusCode(),
                    EntityUtils.toString(response.getEntity()), responseContentType);
        }
    } catch (Exception ex) {
        log.log(Level.SEVERE, ex.getMessage(), ex);
        responseVS = new ResponseVS(ResponseVS.SC_ERROR,
                ContextVS.getInstance().getMessage("hostConnectionErrorMsg", serverURL));
        if (httpget != null)
            httpget.abort();
    } finally {
        try {
            if (response != null)
                response.close();
        } catch (Exception ex) {
            log.log(Level.SEVERE, ex.getMessage(), ex);
        }
        return responseVS;
    }
}

From source file:eu.peppol.outbound.transmission.As2MessageSender.java

/**
 * Handles the HTTP 200 POST response (the MDN with status indications)
 *
 * @param transmissionId the transmissionId (used in HTTP headers as Message-ID)
 * @param outboundMic    the calculated mic of the payload (should be verified against the one returned in MDN)
 * @param postResponse   the http response to be decoded as MDN
 * @return//from   w w w. jav  a 2s .c o  m
 */
MimeMessage handleTheHttpResponse(TransmissionId transmissionId, Mic outboundMic,
        CloseableHttpResponse postResponse, SmpLookupManager.PeppolEndpointData peppolEndpointData) {

    try {

        HttpEntity entity = postResponse.getEntity(); // Any textual results?
        if (entity == null) {
            throw new IllegalStateException(
                    "No contents in HTTP response with rc=" + postResponse.getStatusLine().getStatusCode());
        }

        String contents = EntityUtils.toString(entity);

        if (traceEnabled) {
            log.debug("HTTP-headers:");
            Header[] allHeaders = postResponse.getAllHeaders();
            for (Header header : allHeaders) {
                log.debug("" + header.getName() + ": " + header.getValue());
            }
            log.debug("Contents:\n" + contents);
            log.debug("---------------------------");
        }

        Header contentTypeHeader = postResponse.getFirstHeader("Content-Type");
        if (contentTypeHeader == null) {
            throw new IllegalStateException("No Content-Type header in response, probably a server error");
        }
        String contentType = contentTypeHeader.getValue();

        MimeMessage mimeMessage = null;
        try {
            mimeMessage = MimeMessageHelper.parseMultipart(contents, new MimeType(contentType));

            try {
                mimeMessage.writeTo(System.out);
            } catch (MessagingException e) {
                throw new IllegalStateException("Unable to print mime message");
            }

        } catch (MimeTypeParseException e) {
            throw new IllegalStateException("Invalid Content-Type header");
        }

        // verify the signature of the MDN, we warn about dodgy signatures
        try {
            SignedMimeMessage signedMimeMessage = new SignedMimeMessage(mimeMessage);
            X509Certificate cert = signedMimeMessage.getSignersX509Certificate();
            cert.checkValidity();

            // Verify if the certificate used by the receiving Access Point in
            // the response message does not match its certificate published by the SMP
            if (peppolEndpointData.getCommonName() == null || !CommonName
                    .valueOf(cert.getSubjectX500Principal()).equals(peppolEndpointData.getCommonName())) {
                throw new CertificateException(
                        "Common name in certificate from SMP does not match common name in AP certificate");
            }

            log.debug("MDN signature was verfied for : " + cert.getSubjectDN().toString());
        } catch (Exception ex) {
            log.warn("Exception when verifying MDN signature : " + ex.getMessage());
        }

        // Verifies the actual MDN
        MdnMimeMessageInspector mdnMimeMessageInspector = new MdnMimeMessageInspector(mimeMessage);
        String msg = mdnMimeMessageInspector.getPlainTextPartAsText();

        if (mdnMimeMessageInspector.isOkOrWarning(outboundMic)) {

            return mimeMessage;
        } else {
            log.error("AS2 transmission failed with some error message, msg :" + msg);
            log.error(contents);
            throw new IllegalStateException("AS2 transmission failed : " + msg);
        }

    } catch (IOException e) {
        throw new IllegalStateException("Unable to obtain the contents of the response: " + e.getMessage(), e);
    } finally {
        try {
            postResponse.close();
        } catch (IOException e) {
            throw new IllegalStateException("Unable to close http connection: " + e.getMessage(), e);
        }
    }

}

From source file:ss.udapi.sdk.services.HttpServices.java

public ServiceRequest processLogin(ServiceRequest loginReq, String relation, String name) throws Exception {

    if (loginReq == null)
        throw new IllegalArgumentException("loginReq must be a valid request");

    logger.info("Preparing request for: " + name);
    CloseableHttpClient httpClient = HttpClients.custom().setKeepAliveStrategy(loginTimeout).build();
    List<RestItem> serviceRestItems = null;
    ServiceRequest serviceRequest = new ServiceRequest();

    RestItem loginDetails = getRestItems(loginReq, name);
    if (loginDetails == null) {
        logger.error("Link not found for request " + name);
        return null;
    }//from   w  w w  .j ava 2 s  .c  om

    RestLink link = getLink(loginDetails, relation);
    if (link == null) {
        logger.error("Relation not found for relation: " + relation + " for " + name);
        return null;
    }

    CloseableHttpResponse response = null;
    try {

        HttpUriRequest httpAction = new HttpPost(link.getHref());
        if (compressionEnabled == true) {
            httpAction.setHeader("Accept-Encoding", "gzip");
        }

        httpAction.setHeader("X-Auth-User", SystemProperties.get("ss.username"));
        httpAction.setHeader("X-Auth-Key", SystemProperties.get("ss.password"));
        httpAction.setHeader("Content-Type", "application/json");

        // Send the request of to retrieve the Authentication Token and the
        // list of available services.
        response = httpClient.execute(httpAction);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new ClientProtocolException("Unexpected response status: "
                    + response.getStatusLine().getStatusCode() + " while retrieving services for: " + name);
        }

        if (response.getFirstHeader("X-Auth-Token") == null)
            throw new ClientProtocolException("Unexpected response: no auth token found");

        serviceAuthToken = response.getFirstHeader("X-Auth-Token").getValue();

        serviceRequest.setAuthToken(serviceAuthToken);
        HttpEntity entity = response.getEntity();
        String jsonResponse = new String(EntityUtils.toByteArray(entity));
        serviceRestItems = JsonHelper.toRestItems(jsonResponse);
        serviceRequest.setServiceRestItems(serviceRestItems);

        return serviceRequest;

    } catch (ClientProtocolException protEx) {
        logger.error(
                "Invalid Client Protocol: " + protEx.getMessage() + " while retrieving services for: " + name);
        throw protEx;
    } catch (IOException ioEx) {
        logger.error("Communication error" + ioEx.getCause() + " while retrieving services for: " + name);
        throw ioEx;
    } finally {
        try {
            httpClient.close();
        } catch (IOException ex) {
            // Can safely be ignored, either the server closed the
            // connection or we didn't open it so there's nothing to do
        }
    }
}

From source file:org.mule.module.http.functional.listener.HttpListenerAttachmentsTestCase.java

private void processAttachmentRequestAndResponse(String pathToCall, String expectedResponseContentType,
        boolean useChunkedMode) throws IOException, MuleException, ServletException {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {/* w ww. ja  va 2 s. c o  m*/
        HttpPost httpPost = new HttpPost(getUrl(pathToCall));
        HttpEntity multipart = createHttpEntity(useChunkedMode);
        httpPost.setEntity(multipart);
        final CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            final MuleMessage receivedMessage = muleContext.getClient().request(VM_MESSAGE_ENDPOINT, 1000);
            assertThat(receivedMessage.getPayload(), Is.<Object>is(NullPayload.getInstance()));
            assertThat(receivedMessage.getInboundAttachmentNames().size(), is(2));
            assertThat(receivedMessage.getInboundAttachmentNames().contains(TEXT_BODY_FIELD_NAME), is(true));
            assertThat(new String(((HttpPartDataSource) receivedMessage
                    .getInboundAttachment(TEXT_BODY_FIELD_NAME).getDataSource()).getContent()),
                    Is.<Object>is(TEXT_BODY_FIELD_VALUE));
            assertThat(receivedMessage.getInboundAttachmentNames().contains(FILE_BODY_FIELD_NAME), is(true));
            assertThat(new String(((HttpPartDataSource) receivedMessage
                    .getInboundAttachment(FILE_BODY_FIELD_NAME).getDataSource()).getContent()),
                    Is.<Object>is(FILE_BODY_FIELD_VALUE));

            final String contentType = response.getFirstHeader(HttpHeaders.Names.CONTENT_TYPE).getValue();
            assertThat(contentType, Matchers.containsString(expectedResponseContentType));

            final Collection<HttpPart> parts = HttpParser
                    .parseMultipartContent(response.getEntity().getContent(), contentType);
            assertThat(parts.size(), Is.is(2));
            Map<String, Part> partsAsMap = convertPartsToMap(parts);
            assertThat(partsAsMap.get(TEXT_BODY_FIELD_NAME), IsNull.notNullValue());
            assertThat(partsAsMap.get(FILE_BODY_FIELD_NAME), IsNull.notNullValue());
            assertThat(IOUtils.toString(partsAsMap.get(TEXT_BODY_FIELD_NAME).getInputStream()),
                    is(TEXT_BODY_FIELD_VALUE));
            assertThat(IOUtils.toString(partsAsMap.get(FILE_BODY_FIELD_NAME).getInputStream()),
                    is(FILE_BODY_FIELD_VALUE));
        } finally {
            response.close();
        }
    } finally {
        httpClient.close();
    }
}

From source file:org.coding.git.api.CodingNetConnection.java

@NotNull
private ResponsePage doRequest(@NotNull String uri, @Nullable String requestBody,
        @NotNull Collection<Header> headers, @NotNull HttpVerb verb) throws IOException {
    if (myAborted)
        throw new CodingNetOperationCanceledException();

    if (EventQueue.isDispatchThread() && !ApplicationManager.getApplication().isUnitTestMode()) {
        LOG.warn("Network operation in EDT"); // TODO: fix
    }//from   w  w w  . j  a v a2 s.c  om

    CloseableHttpResponse response = null;
    try {
        response = doREST(uri, requestBody, headers, verb);

        if (myAborted)
            throw new CodingNetOperationCanceledException();

        //--HTTP??
        checkStatusCode(response, requestBody);

        HttpEntity entity = response.getEntity();
        if (entity == null) {
            return createResponse(response);
        }

        JsonElement ret = parseResponse(entity.getContent());
        if (ret.isJsonNull()) {
            return createResponse(response);
        }

        //--CodingNet??
        checkCodingNetCode(ret);

        String nextPage = null;
        Header pageHeader = response.getFirstHeader("Link");
        if (pageHeader != null) {
            for (HeaderElement element : pageHeader.getElements()) {
                NameValuePair rel = element.getParameterByName("rel");
                if (rel != null && "next".equals(rel.getValue())) {
                    String urlString = element.toString();
                    int begin = urlString.indexOf('<');
                    int end = urlString.lastIndexOf('>');
                    if (begin == -1 || end == -1) {
                        LOG.error("Invalid 'Link' header", "{" + pageHeader.toString() + "}");
                        break;
                    }

                    nextPage = urlString.substring(begin + 1, end);
                    break;
                }
            }
        }

        return createResponse(ret, nextPage, response);
    } catch (SSLHandshakeException e) { // User canceled operation from CertificateManager
        if (e.getCause() instanceof CertificateException) {
            LOG.info("Host SSL certificate is not trusted", e);
            throw new CodingNetOperationCanceledException("Host SSL certificate is not trusted", e);
        }
        throw e;
    } catch (IOException e) {
        if (myAborted)
            throw new CodingNetOperationCanceledException("Operation canceled", e);
        throw e;
    } finally {
        myRequest = null;
        if (response != null) {
            response.close();
        }
        if (!myReusable) {
            myClient.close();
        }
    }
}