Example usage for org.apache.commons.httpclient HostConfiguration getHostURL

List of usage examples for org.apache.commons.httpclient HostConfiguration getHostURL

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HostConfiguration getHostURL.

Prototype

public String getHostURL() 

Source Link

Usage

From source file:com.legstar.http.client.CicsHttpTest.java

/**
 * Try to create a host configuration./*w  w  w.  ja va  2 s  .  com*/
 */
public void testCreateHostConfiguration() {
    CicsHttp cicsHttp = new CicsHttp(getName(), getEndpoint());
    HostConfiguration hostConfiguration = cicsHttp.createHostConfiguration(getEndpoint());
    assertEquals("mainframe", hostConfiguration.getHost());
    assertEquals("http://mainframe:3080", hostConfiguration.getHostURL());
    assertEquals(3080, hostConfiguration.getPort());
    assertEquals("http:80", hostConfiguration.getProtocol().toString());
}

From source file:com.jivesoftware.os.jive.utils.http.client.ApacheHttpClient31BackedHttpClient.java

private String safeHostString(HostConfiguration hostConfiguration) {
    if (hostConfiguration.getHost() != null) {
        return hostConfiguration.getHostURL();
    }// w w w. jav  a 2 s  .co  m
    return "";
}

From source file:com.twinsoft.convertigo.beans.connectors.SiteClipperConnector.java

private void doProcessRequest(Shuttle shuttle) throws IOException, ServletException, EngineException {
    shuttle.statisticsTaskID = context.statistics.start(EngineStatistics.GET_DOCUMENT);
    try {/*w ww  . ja v a2 s. com*/
        shuttle.sharedScope = context.getSharedScope();

        String domain = shuttle.getRequest(QueryPart.host) + shuttle.getRequest(QueryPart.port);
        Engine.logSiteClipper.trace("(SiteClipperConnector) Prepare the request for the domain " + domain);
        if (!shouldRewrite(domain)) {
            Engine.logSiteClipper.info(
                    "(SiteClipperConnector) The domain " + domain + " is not allowed with this connector");
            shuttle.response.sendError(HttpServletResponse.SC_FORBIDDEN,
                    "The domain " + domain + " is not allowed with this connector");
            return;
        }

        String uri = shuttle.getRequest(QueryPart.uri);

        Engine.logSiteClipper.info("Preparing " + shuttle.request.getMethod() + " " + shuttle.getRequestUrl());

        HttpMethod httpMethod = null;
        XulRecorder xulRecorder = context.getXulRecorder();
        if (xulRecorder != null) {
            httpMethod = shuttle.httpMethod = xulRecorder.getRecord(shuttle.getRequestUrlAndQuery());
        }
        if (httpMethod == null) {
            try {
                switch (shuttle.getRequestHttpMethodType()) {
                case GET:
                    httpMethod = new GetMethod(uri);
                    break;
                case POST:
                    httpMethod = new PostMethod(uri);
                    ((PostMethod) httpMethod)
                            .setRequestEntity(new InputStreamRequestEntity(shuttle.request.getInputStream()));
                    break;
                case PUT:
                    httpMethod = new PutMethod(uri);
                    ((PutMethod) httpMethod)
                            .setRequestEntity(new InputStreamRequestEntity(shuttle.request.getInputStream()));
                    break;
                case DELETE:
                    httpMethod = new DeleteMethod(uri);
                    break;
                case HEAD:
                    httpMethod = new HeadMethod(uri);
                    break;
                case OPTIONS:
                    httpMethod = new OptionsMethod(uri);
                    break;
                case TRACE:
                    httpMethod = new TraceMethod(uri);
                    break;
                default:
                    throw new ServletException(
                            "(SiteClipperConnector) unknown http method " + shuttle.request.getMethod());
                }
                httpMethod.setFollowRedirects(false);
            } catch (Exception e) {
                throw new ServletException(
                        "(SiteClipperConnector) unexpected exception will building the http method : "
                                + e.getMessage());
            }
            shuttle.httpMethod = httpMethod;

            SiteClipperScreenClass screenClass = getCurrentScreenClass();
            Engine.logSiteClipper.info("Request screen class: " + screenClass.getName());

            for (String name : Collections
                    .list(GenericUtils.<Enumeration<String>>cast(shuttle.request.getHeaderNames()))) {
                if (requestHeadersToIgnore.contains(HeaderName.parse(name))) {
                    Engine.logSiteClipper.trace("(SiteClipperConnector) Ignoring request header " + name);
                } else {
                    String value = shuttle.request.getHeader(name);
                    Engine.logSiteClipper
                            .trace("(SiteClipperConnector) Copying request header " + name + "=" + value);
                    shuttle.setRequestCustomHeader(name, value);
                }
            }

            Engine.logSiteClipper.debug("(SiteClipperConnector) applying request rules for the screenclass "
                    + screenClass.getName());
            for (IRequestRule rule : screenClass.getRequestRules()) {
                if (rule.isEnabled()) {
                    Engine.logSiteClipper
                            .trace("(SiteClipperConnector) applying request rule " + rule.getName());
                    rule.fireEvents();
                    boolean done = rule.applyOnRequest(shuttle);
                    Engine.logSiteClipper.debug("(SiteClipperConnector) the request rule " + rule.getName()
                            + " is " + (done ? "well" : "not") + " applied");
                } else {
                    Engine.logSiteClipper
                            .trace("(SiteClipperConnector) skip the disabled request rule " + rule.getName());
                }
            }

            for (Entry<String, String> header : shuttle.requestCustomHeaders.entrySet()) {
                Engine.logSiteClipper.trace("(SiteClipperConnector) Push request header " + header.getKey()
                        + "=" + header.getValue());
                httpMethod.addRequestHeader(header.getKey(), header.getValue());
            }

            String queryString = shuttle.request.getQueryString();

            if (queryString != null) {
                try {
                    // Fake test in order to check query string validity
                    new URI("http://localhost/index?" + queryString, true,
                            httpMethod.getParams().getUriCharset());
                } catch (URIException e) {
                    // Bugfix #2103
                    StringBuffer newQuery = new StringBuffer();
                    for (String part : RegexpUtils.pattern_and.split(queryString)) {
                        String[] pair = RegexpUtils.pattern_equals.split(part, 2);
                        try {
                            newQuery.append('&')
                                    .append(URLEncoder.encode(URLDecoder.decode(pair[0], "UTF-8"), "UTF-8"));
                            if (pair.length > 1) {
                                newQuery.append('=').append(
                                        URLEncoder.encode(URLDecoder.decode(pair[1], "UTF-8"), "UTF-8"));
                            }
                        } catch (UnsupportedEncodingException ee) {
                            Engine.logSiteClipper
                                    .trace("(SiteClipperConnector) failed to encode query part : " + part);
                        }
                    }

                    queryString = newQuery.length() > 0 ? newQuery.substring(1) : newQuery.toString();
                    Engine.logSiteClipper.trace("(SiteClipperConnector) re-encode query : " + queryString);
                }
            }

            Engine.logSiteClipper.debug("(SiteClipperConnector) Copying the query string : " + queryString);
            httpMethod.setQueryString(queryString);

            //            if (context.httpState == null) {
            //               Engine.logSiteClipper.debug("(SiteClipperConnector) Creating new HttpState for context id " + context.contextID);
            //               context.httpState = new HttpState();
            //            } else {
            //               Engine.logSiteClipper.debug("(SiteClipperConnector) Using HttpState of context id " + context.contextID);
            //            }

            getHttpState(shuttle);

            HostConfiguration hostConfiguration = getHostConfiguration(shuttle);

            HttpMethodParams httpMethodParams = httpMethod.getParams();
            httpMethodParams.setBooleanParameter("http.connection.stalecheck", true);
            httpMethodParams.setParameter(HttpMethodParams.RETRY_HANDLER,
                    new DefaultHttpMethodRetryHandler(3, true));

            Engine.logSiteClipper.info("Requesting " + httpMethod.getName() + " "
                    + hostConfiguration.getHostURL() + httpMethod.getURI().toString());

            HttpClient httpClient = context.getHttpClient3(shuttle.getHttpPool());
            HttpUtils.logCurrentHttpConnection(httpClient, hostConfiguration, shuttle.getHttpPool());
            httpClient.executeMethod(hostConfiguration, httpMethod, context.httpState);
        } else {
            Engine.logSiteClipper.info("Retrieve recorded response from Context");
        }

        int status = httpMethod.getStatusCode();

        shuttle.processState = ProcessState.response;

        Engine.logSiteClipper.info("Request terminated with status " + status);
        shuttle.response.setStatus(status);

        if (Engine.isStudioMode() && status == HttpServletResponse.SC_OK
                && shuttle.getResponseMimeType().startsWith("text/")) {
            fireDataChanged(new ConnectorEvent(this, shuttle.getResponseAsString()));
        }

        SiteClipperScreenClass screenClass = getCurrentScreenClass();
        Engine.logSiteClipper.info("Response screen class: " + screenClass.getName());

        if (Engine.isStudioMode()) {
            Engine.theApp.fireObjectDetected(new EngineEvent(screenClass));
        }

        for (Header header : httpMethod.getResponseHeaders()) {
            String name = header.getName();
            if (responseHeadersToIgnore.contains(HeaderName.parse(name))) {
                Engine.logSiteClipper.trace("(SiteClipperConnector) Ignoring response header " + name);
            } else {
                String value = header.getValue();
                Engine.logSiteClipper
                        .trace("(SiteClipperConnector) Copying response header " + name + "=" + value);
                shuttle.responseCustomHeaders.put(name, value);
            }
        }

        Engine.logSiteClipper.debug(
                "(SiteClipperConnector) applying response rules for the screenclass " + screenClass.getName());
        for (IResponseRule rule : screenClass.getResponseRules()) {
            if (rule.isEnabled()) {
                Engine.logSiteClipper.trace("(SiteClipperConnector) applying response rule " + rule.getName());
                rule.fireEvents();
                boolean done = rule.applyOnResponse(shuttle);
                Engine.logSiteClipper.debug("(SiteClipperConnector) the response rule " + rule.getName()
                        + " is " + (done ? "well" : "not") + " applied");
            } else {
                Engine.logSiteClipper
                        .trace("(SiteClipperConnector) skip the disabled response rule " + rule.getName());
            }
        }

        for (Entry<String, String> header : shuttle.responseCustomHeaders.entrySet()) {
            Engine.logSiteClipper.trace(
                    "(SiteClipperConnector) Push request header " + header.getKey() + "=" + header.getValue());
            shuttle.response.addHeader(header.getKey(), header.getValue());
        }

        if (shuttle.postInstructions != null) {
            JSONArray instructions = new JSONArray();
            for (IClientInstruction instruction : shuttle.postInstructions) {
                try {
                    instructions.put(instruction.getInstruction());
                } catch (JSONException e) {
                    Engine.logSiteClipper.error(
                            "(SiteClipperConnector) Failed to add a post instruction due to a JSONException",
                            e);
                }
            }
            String codeToInject = "<script>C8O_postInstructions = " + instructions.toString() + "</script>\n"
                    + "<script src=\"" + shuttle.getRequest(QueryPart.full_convertigo_path)
                    + "/scripts/jquery.min.js\"></script>\n" + "<script src=\""
                    + shuttle.getRequest(QueryPart.full_convertigo_path)
                    + "/scripts/siteclipper.js\"></script>\n";

            String content = shuttle.getResponseAsString();
            Matcher matcher = HtmlLocation.head_top.matcher(content);
            String newContent = RegexpUtils.inject(matcher, codeToInject);
            if (newContent == null) {
                matcher = HtmlLocation.body_top.matcher(content);
                newContent = RegexpUtils.inject(matcher, codeToInject);
            }
            if (newContent != null) {
                shuttle.setResponseAsString(newContent);
            } else {
                Engine.logSiteClipper.info(
                        "(SiteClipperConnector) Failed to find a head or body tag in the response content");
                Engine.logSiteClipper.trace("(SiteClipperConnector) Response content : \"" + content + "\"");
            }
        }

        long nbBytes = 0L;
        if (shuttle.responseAsString != null
                && shuttle.responseAsString.hashCode() != shuttle.responseAsStringOriginal.hashCode()) {
            OutputStream os = shuttle.response.getOutputStream();
            switch (shuttle.getResponseContentEncoding()) {
            case gzip:
                os = new GZIPOutputStream(os);
                break;
            case deflate:
                os = new DeflaterOutputStream(os,
                        new Deflater(Deflater.DEFAULT_COMPRESSION | Deflater.DEFAULT_STRATEGY, true));
                break;
            default:
                break;
            }
            nbBytes = shuttle.responseAsByte.length;
            IOUtils.write(shuttle.responseAsString, os, shuttle.getResponseCharset());
            os.close();
        } else {
            InputStream is = (shuttle.responseAsByte == null) ? httpMethod.getResponseBodyAsStream()
                    : new ByteArrayInputStream(shuttle.responseAsByte);
            if (is != null) {
                nbBytes = 0;
                OutputStream os = shuttle.response.getOutputStream();
                int read = is.read();
                while (read >= 0) {
                    os.write(read);
                    os.flush();
                    read = is.read();
                    nbBytes++;
                }
                is.close();
                //               nbBytes = IOUtils.copyLarge(is, shuttle.response.getOutputStream());
                Engine.logSiteClipper
                        .trace("(SiteClipperConnector) Response body copyied (" + nbBytes + " bytes)");
            }
        }
        shuttle.response.getOutputStream().close();

        shuttle.score = getScore(nbBytes);
        Engine.logSiteClipper
                .debug("(SiteClipperConnector) Request terminated with a score of " + shuttle.score);
    } finally {
        long duration = context.statistics.stop(shuttle.statisticsTaskID);
        if (context.requestedObject != null) {
            try {
                Engine.theApp.billingManager.insertBilling(context, Long.valueOf(duration),
                        Long.valueOf(shuttle.score));
            } catch (Exception e) {
                Engine.logContext.warn("Unable to insert billing ticket (the billing is thus ignored): ["
                        + e.getClass().getName() + "] " + e.getMessage());
            }
        }
    }
}

From source file:gov.va.med.imaging.proxy.ImageXChangeHttpCommonsSender.java

/**
* invoke creates a socket connection, sends the request SOAP message and
* then reads the response SOAP message back from the SOAP server
* 
* @param msgContext//  w w w .  java  2  s. c om
*            the messsage context
* 
* @throws AxisFault
*/
public void invoke(MessageContext msgContext) throws AxisFault {
    HttpMethodBase method = null;
    log.debug(Messages.getMessage("enter00", "CommonsHttpSender::invoke"));
    try {
        URL targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL));

        // no need to retain these, as the cookies/credentials are
        // stored in the message context across multiple requests.
        // the underlying connection manager, however, is retained
        // so sockets get recycled when possible.
        HttpClient httpClient = new HttpClient(this.connectionManager);

        // the timeout value for allocation of connections from the pool
        httpClient.getParams().setConnectionManagerTimeout(this.clientProperties.getConnectionPoolTimeout());

        HostConfiguration hostConfiguration = getHostConfiguration(httpClient, msgContext, targetURL);

        boolean posting = true;

        // If we're SOAP 1.2, allow the web method to be set from the
        // MessageContext.
        if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
            String webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD);
            if (webMethod != null)
                posting = webMethod.equals(HTTPConstants.HEADER_POST);
        }

        if (posting) {
            Message reqMessage = msgContext.getRequestMessage();
            method = new PostMethod(targetURL.toString());
            log.info("POST message created with target [" + targetURL.toString() + "]");
            TransactionContext transactionContext = TransactionContextFactory.get();
            transactionContext
                    .addDebugInformation("POST message created with target [" + targetURL.toString() + "]");

            // set false as default, addContetInfo can overwrite
            method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);

            addContextInfo(method, httpClient, msgContext, targetURL);

            Credentials cred = httpClient.getState().getCredentials(AuthScope.ANY);
            if (cred instanceof UsernamePasswordCredentials) {
                log.trace("POST message created on client with credentials ["
                        + ((UsernamePasswordCredentials) cred).getUserName() + ", "
                        + ((UsernamePasswordCredentials) cred).getPassword() + "].");
            }

            MessageRequestEntity requestEntity = null;
            if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
                requestEntity = new GzipMessageRequestEntity(method, reqMessage, httpChunkStream);
                log.info("HTTPCommonsSender - zipping request.");
            } else {
                requestEntity = new MessageRequestEntity(method, reqMessage, httpChunkStream);
                log.info("HTTPCommonsSender - not zipping request");
            }
            ((PostMethod) method).setRequestEntity(requestEntity);
        } else {
            method = new GetMethod(targetURL.toString());
            log.info("GET message created with target [" + targetURL.toString() + "]");
            addContextInfo(method, httpClient, msgContext, targetURL);
        }

        if (msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP))
            log.info("HTTPCommonsSender - accepting GZIP");
        else
            log.info("HTTPCommonsSender - NOT accepting GZIP");

        String httpVersion = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION);
        if (httpVersion != null && httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_V10))
            method.getParams().setVersion(HttpVersion.HTTP_1_0);

        // don't forget the cookies!
        // Cookies need to be set on HttpState, since HttpMethodBase
        // overwrites the cookies from HttpState
        if (msgContext.getMaintainSession()) {
            HttpState state = httpClient.getState();
            method.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
            String host = hostConfiguration.getHost();
            String path = targetURL.getPath();

            boolean secure = hostConfiguration.getProtocol().isSecure();
            fillHeaders(msgContext, state, HTTPConstants.HEADER_COOKIE, host, path, secure);
            fillHeaders(msgContext, state, HTTPConstants.HEADER_COOKIE2, host, path, secure);
            httpClient.setState(state);
        }

        // add HTTP header fields that the application thinks are "interesting"
        // the expectation is that these would be non-standard HTTP headers, 
        // by convention starting with "xxx-"
        VistaRealmPrincipal principal = VistaRealmSecurityContext.get();

        if (principal != null) {
            log.info("SecurityContext credentials for '" + principal.getAccessCode() + "' are available.");
            String duz = principal.getDuz();
            if (duz != null && duz.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderDuz, duz);

            String fullname = principal.getFullName();
            if (fullname != null && fullname.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderFullName, fullname);

            String sitename = principal.getSiteName();
            if (sitename != null && sitename.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderSiteName, sitename);

            String sitenumber = principal.getSiteNumber();
            if (sitenumber != null && sitenumber.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderSiteNumber, sitenumber);

            String ssn = principal.getSsn();
            if (ssn != null && ssn.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderSSN, ssn);

            String securityToken = principal.getSecurityToken();
            if (securityToken != null && securityToken.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderBrokerSecurityTokenId,
                        securityToken);

            String cacheLocationId = principal.getCacheLocationId();
            if (cacheLocationId != null && cacheLocationId.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderCacheLocationId,
                        cacheLocationId);

            String userDivision = principal.getUserDivision();
            if (userDivision != null && userDivision.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderUserDivision, userDivision);
        } else
            log.debug("SecurityContext credentials are NOT available.");

        method.addRequestHeader(HTTPConstants.HEADER_CACHE_CONTROL, "no-cache,no-store");
        method.addRequestHeader(HTTPConstants.HEADER_PRAGMA, "no-cache");

        try {
            log.info("Executing method [" + method.getPath() + "] on target [" + hostConfiguration.getHostURL()
                    + "]");
        } catch (IllegalStateException isX) {
        }

        // send the HTTP request and wait for a response 
        int returnCode = httpClient.executeMethod(hostConfiguration, method, null);

        TransactionContext transactionContext = TransactionContextFactory.get();
        // don't set the response code here - this is not the response code we send out, but the resposne code we get back from the data source
        //transactionContext.setResponseCode (String.valueOf (returnCode));

        // How many bytes received?
        transactionContext.setDataSourceBytesReceived(method.getBytesReceived());

        // How long did it take to start getting a response coming back?
        Long timeSent = method.getTimeRequestSent();
        Long timeReceived = method.getTimeFirstByteReceived();
        if (timeSent != null && timeReceived != null) {
            long timeTook = timeReceived.longValue() - timeSent.longValue();
            transactionContext.setTimeToFirstByte(new Long(timeTook));
        }

        // Looks like it wasn't found in cache - is there a place to set this to true if it was?
        transactionContext.setItemCached(Boolean.FALSE);

        // extract the basic HTTP header fields for content type, location and length
        String contentType = getHeader(method, HTTPConstants.HEADER_CONTENT_TYPE);
        String contentLocation = getHeader(method, HTTPConstants.HEADER_CONTENT_LOCATION);
        String contentLength = getHeader(method, HTTPConstants.HEADER_CONTENT_LENGTH);

        if ((returnCode > 199) && (returnCode < 300)) {

            // SOAP return is OK - so fall through
        } else if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
            // For now, if we're SOAP 1.2, fall through, since the range of
            // valid result codes is much greater
        } else if ((contentType != null) && !contentType.equals("text/html")
                && ((returnCode > 499) && (returnCode < 600))) {

            // SOAP Fault should be in here - so fall through
        } else {
            String statusMessage = method.getStatusText();
            try {
                log.warn("Method [" + method.getPath() + "] on target [" + hostConfiguration.getHostURL()
                        + "] failed - '" + statusMessage + "'.");
            } catch (IllegalStateException isX) {
            }

            AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null);

            try {
                fault.setFaultDetailString(
                        Messages.getMessage("return01", "" + returnCode, method.getResponseBodyAsString()));
                fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(returnCode));
                throw fault;
            } finally {
                method.releaseConnection(); // release connection back to
                // pool.
            }
        }

        // wrap the response body stream so that close() also releases
        // the connection back to the pool.
        InputStream releaseConnectionOnCloseStream = createConnectionReleasingInputStream(method);

        Header contentEncoding = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_ENCODING);
        log.info("HTTPCommonsSender - " + HTTPConstants.HEADER_CONTENT_ENCODING + "="
                + (contentEncoding == null ? "null" : contentEncoding.getValue()));

        if (contentEncoding != null) {
            if (HTTPConstants.COMPRESSION_GZIP.equalsIgnoreCase(contentEncoding.getValue())) {
                releaseConnectionOnCloseStream = new GZIPInputStream(releaseConnectionOnCloseStream);

                log.debug("HTTPCommonsSender - receiving gzipped stream.");
            } else if (ENCODING_DEFLATE.equalsIgnoreCase(contentEncoding.getValue())) {
                releaseConnectionOnCloseStream = new java.util.zip.InflaterInputStream(
                        releaseConnectionOnCloseStream);

                log.debug("HTTPCommonsSender - receiving 'deflated' stream.");
            } else {
                AxisFault fault = new AxisFault("HTTP",
                        "unsupported content-encoding of '" + contentEncoding.getValue() + "' found", null,
                        null);
                log.warn(fault.getMessage());
                throw fault;
            }

        }
        try {
            log.warn("Method [" + method.getPath() + "] on target [" + hostConfiguration.getHostURL()
                    + "] succeeded, parsing response.");
        } catch (IllegalStateException isX) {
        }

        Message outMsg = new Message(releaseConnectionOnCloseStream, false, contentType, contentLocation);
        // Transfer HTTP headers of HTTP message to MIME headers of SOAP
        // message
        Header[] responseHeaders = method.getResponseHeaders();
        MimeHeaders responseMimeHeaders = outMsg.getMimeHeaders();
        for (int i = 0; i < responseHeaders.length; i++) {
            Header responseHeader = responseHeaders[i];
            responseMimeHeaders.addHeader(responseHeader.getName(), responseHeader.getValue());
        }
        outMsg.setMessageType(Message.RESPONSE);
        msgContext.setResponseMessage(outMsg);
        if (log.isTraceEnabled()) {
            if (null == contentLength)
                log.trace("\n" + Messages.getMessage("no00", "Content-Length"));
            log.trace("\n" + Messages.getMessage("xmlRecd00"));
            log.trace("-----------------------------------------------");
            log.trace(outMsg.getSOAPPartAsString());
        }

        // if we are maintaining session state,
        // handle cookies (if any)
        if (msgContext.getMaintainSession()) {
            Header[] headers = method.getResponseHeaders();

            for (int i = 0; i < headers.length; i++) {
                if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE)) {
                    handleCookie(HTTPConstants.HEADER_COOKIE, headers[i].getValue(), msgContext);
                } else if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE2)) {
                    handleCookie(HTTPConstants.HEADER_COOKIE2, headers[i].getValue(), msgContext);
                }
            }
        }

        // always release the connection back to the pool if
        // it was one way invocation
        if (msgContext.isPropertyTrue("axis.one.way")) {
            method.releaseConnection();
        }

    } catch (Exception e) {
        log.debug(e);
        throw AxisFault.makeFault(e);
    }

    if (log.isDebugEnabled()) {
        log.debug(Messages.getMessage("exit00", "CommonsHTTPSender::invoke"));
    }
}

From source file:nl.nn.adapterframework.http.HttpSender.java

public String sendMessageWithTimeoutGuarded(String correlationID, String message,
        ParameterResolutionContext prc) throws SenderException, TimeOutException {
    ParameterValueList pvl = null;/*from www . j  a  v  a2  s .  c om*/
    try {
        if (prc != null && paramList != null) {
            pvl = prc.getValues(paramList);
        }
    } catch (ParameterException e) {
        throw new SenderException(
                getLogPrefix() + "Sender [" + getName() + "] caught exception evaluating parameters", e);
    }
    URI uri;
    HttpMethod httpmethod;
    HostConfiguration hostconfiguration = new HostConfiguration(hostconfigurationBase);
    try {
        if (urlParameter != null) {
            String url = (String) pvl.getParameterValue(getUrlParam()).getValue();
            uri = getURI(url);
        } else {
            uri = staticUri;
        }

        Map<String, String> headersParamsMap = new HashMap<String, String>();
        if (headersParams != null) {
            StringTokenizer st = new StringTokenizer(headersParams, ",");
            while (st.hasMoreElements()) {
                headersParamsMap.put(st.nextToken(), null);
            }
        }

        if (!isParamsInUrl()) {
            httpmethod = getPostMethodWithParamsInBody(uri, message, pvl, headersParamsMap, prc);
        } else {
            httpmethod = getMethod(uri, message, pvl, headersParamsMap);
            if (!"POST".equals(getMethodType()) && !"PUT".equals(getMethodType())
                    && !"REPORT".equals(getMethodType())) {
                httpmethod.setFollowRedirects(isFollowRedirects());
            }
        }

        int port = getPort(uri);

        if (socketfactory != null && "https".equals(uri.getScheme())) {
            Protocol authhttps = new Protocol(uri.getScheme(), socketfactory, port);
            hostconfiguration.setHost(uri.getHost(), port, authhttps);
        } else {
            hostconfiguration.setHost(uri.getHost(), port, uri.getScheme());
        }
        log.info(getLogPrefix() + "configured httpclient for host [" + hostconfiguration.getHostURL() + "]");

        if (credentials != null) {
            httpState.setCredentials(null, uri.getHost(), credentials);
        }
    } catch (URIException e) {
        throw new SenderException(e);
    }

    String result = null;
    int statusCode = -1;
    int count = getMaxExecuteRetries();
    String msg = null;
    while (count-- >= 0 && statusCode == -1) {
        try {
            if (log.isDebugEnabled())
                log.debug(getLogPrefix() + "executing method");
            statusCode = httpclient.executeMethod(hostconfiguration, httpmethod, httpState);
            if (log.isDebugEnabled())
                log.debug(getLogPrefix() + "executed method");

            if (statusCode != HttpServletResponse.SC_OK) {
                StatusLine statusline = httpmethod.getStatusLine();
                if (statusline != null) {
                    log.warn(getLogPrefix() + "status [" + statusline.toString() + "]");
                } else {
                    log.warn(getLogPrefix() + "no statusline found");
                }
            } else {
                if (log.isDebugEnabled())
                    log.debug(getLogPrefix() + "status [" + statusCode + "]");
            }
            HttpServletResponse response = null;
            if (isStreamResultToServlet()) {
                response = (HttpServletResponse) prc.getSession().get("restListenerServletResponse");
            }
            String fileName = null;
            if (StringUtils.isNotEmpty(getStreamResultToFileNameSessionKey())) {
                fileName = (String) prc.getSession().get(getStreamResultToFileNameSessionKey());
            }
            result = extractResult(httpmethod, prc, response, fileName);
            if (log.isDebugEnabled())
                log.debug(getLogPrefix() + "retrieved result [" + result + "]");
        } catch (HttpException e) {
            Throwable throwable = e.getCause();
            String cause = null;
            if (throwable != null) {
                cause = throwable.toString();
            }
            msg = e.getMessage();
            log.warn(getLogPrefix() + "httpException with message [" + msg + "] and cause [" + cause
                    + "], executeRetries left [" + count + "]");
        } catch (IOException e) {
            httpmethod.abort();
            if (e instanceof SocketTimeoutException) {
                throw new TimeOutException(e);
            }
            throw new SenderException(e);
        } finally {
            // In case of storeResultAsStreamInSessionKey release connection
            // is done by ReleaseConnectionAfterReadInputStream.
            if (StringUtils.isEmpty(getStoreResultAsStreamInSessionKey())) {
                httpmethod.releaseConnection();
            }
        }
    }

    if (statusCode == -1) {
        if (StringUtils.contains(msg.toUpperCase(), "TIMEOUTEXCEPTION")) {
            //java.net.SocketTimeoutException: Read timed out
            throw new TimeOutException("Failed to recover from timeout exception");
        }
        throw new SenderException("Failed to recover from exception");
    }

    if (isXhtml() && StringUtils.isNotEmpty(result)) {
        result = XmlUtils.skipDocTypeDeclaration(result.trim());
        if (result.startsWith("<html>") || result.startsWith("<html ")) {
            CleanerProperties props = new CleanerProperties();
            HtmlCleaner cleaner = new HtmlCleaner(props);
            TagNode tagNode = cleaner.clean(result);
            result = new SimpleXmlSerializer(props).getXmlAsString(tagNode);

            if (transformerPool != null) {
                log.debug(getLogPrefix() + " transforming result [" + result + "]");
                ParameterResolutionContext prc_xslt = new ParameterResolutionContext(result, null, true, true);
                try {
                    result = transformerPool.transform(prc_xslt.getInputSource(), null);
                } catch (Exception e) {
                    throw new SenderException("Exception on transforming input", e);
                }
            }
        }
    }
    return result;
}