Example usage for org.apache.commons.httpclient HttpClient getState

List of usage examples for org.apache.commons.httpclient HttpClient getState

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpClient getState.

Prototype

public HttpState getState()

Source Link

Usage

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/*from   ww  w. j  a v  a2s.c o  m*/
*            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:davmail.http.DavGatewayHttpClientFacade.java

/**
 * Update http client configuration (proxy)
 *
 * @param httpClient current Http client
 * @param url        target url/* w w  w. j  av  a2 s .  com*/
 * @throws DavMailException on error
 */
public static void configureClient(HttpClient httpClient, String url) throws DavMailException {
    setClientHost(httpClient, url);

    /*if (Settings.getBooleanProperty("davmail.enableKerberos", false)) {
    AuthPolicy.registerAuthScheme("Negotiate", NegotiateScheme.class);
    ArrayList<String> authPrefs = new ArrayList<String>();
    authPrefs.add("Negotiate");
    httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
    } else */if (!needNTLM) {
        ArrayList<String> authPrefs = new ArrayList<String>();
        authPrefs.add(AuthPolicy.DIGEST);
        authPrefs.add(AuthPolicy.BASIC);
        // exclude NTLM authentication scheme
        httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
    }

    boolean enableProxy = Settings.getBooleanProperty("davmail.enableProxy");
    boolean useSystemProxies = Settings.getBooleanProperty("davmail.useSystemProxies", Boolean.FALSE);
    String proxyHost = null;
    int proxyPort = 0;
    String proxyUser = null;
    String proxyPassword = null;

    try {
        java.net.URI uri = new java.net.URI(url);
        if (isNoProxyFor(uri)) {
            LOGGER.debug("no proxy for " + uri.getHost());
        } else if (useSystemProxies) {
            // get proxy for url from system settings
            System.setProperty("java.net.useSystemProxies", "true");
            List<Proxy> proxyList = getProxyForURI(uri);
            if (!proxyList.isEmpty() && proxyList.get(0).address() != null) {
                InetSocketAddress inetSocketAddress = (InetSocketAddress) proxyList.get(0).address();
                proxyHost = inetSocketAddress.getHostName();
                proxyPort = inetSocketAddress.getPort();

                // we may still need authentication credentials
                proxyUser = Settings.getProperty("davmail.proxyUser");
                proxyPassword = Settings.getProperty("davmail.proxyPassword");
            }
        } else if (enableProxy) {
            proxyHost = Settings.getProperty("davmail.proxyHost");
            proxyPort = Settings.getIntProperty("davmail.proxyPort");
            proxyUser = Settings.getProperty("davmail.proxyUser");
            proxyPassword = Settings.getProperty("davmail.proxyPassword");
        }
    } catch (URISyntaxException e) {
        throw new DavMailException("LOG_INVALID_URL", url);
    }

    // configure proxy
    if (proxyHost != null && proxyHost.length() > 0) {
        httpClient.getHostConfiguration().setProxy(proxyHost, proxyPort);
        if (proxyUser != null && proxyUser.length() > 0) {

            AuthScope authScope = new AuthScope(proxyHost, proxyPort, AuthScope.ANY_REALM);

            // detect ntlm authentication (windows domain name in user name)
            int backslashindex = proxyUser.indexOf('\\');
            if (backslashindex > 0) {
                httpClient.getState().setProxyCredentials(authScope,
                        new NTCredentials(proxyUser.substring(backslashindex + 1), proxyPassword, "UNKNOWN",
                                proxyUser.substring(0, backslashindex)));
            } else {
                httpClient.getState().setProxyCredentials(authScope,
                        new NTCredentials(proxyUser, proxyPassword, "UNKNOWN", ""));
            }
        }
    }

}

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

protected HostConfiguration getHostConfiguration(HttpClient client, MessageContext context, URL targetURL) {
    TransportClientProperties tcp = TransportClientPropertiesFactory.create(targetURL.getProtocol()); // http
    // or//from ww w. j  a v a2 s  . co m
    // https
    int port = targetURL.getPort();
    boolean hostInNonProxyList = isHostInNonProxyList(targetURL.getHost(), tcp.getNonProxyHosts());

    HostConfiguration config = new HostConfiguration();

    if (port == -1) {
        if (targetURL.getProtocol().equalsIgnoreCase("https")) {
            port = 443; // default port for https being 443
        } else { // it must be http
            port = 80; // default port for http being 80
        }
    }

    if (hostInNonProxyList) {
        config.setHost(targetURL.getHost(), port, targetURL.getProtocol());
    } else {
        if (tcp.getProxyHost().length() == 0 || tcp.getProxyPort().length() == 0) {
            config.setHost(targetURL.getHost(), port, targetURL.getProtocol());
        } else {
            if (tcp.getProxyUser().length() != 0) {
                Credentials proxyCred = new UsernamePasswordCredentials(tcp.getProxyUser(),
                        tcp.getProxyPassword());
                // if the username is in the form "user\domain"
                // then use NTCredentials instead.
                int domainIndex = tcp.getProxyUser().indexOf("\\");
                if (domainIndex > 0) {
                    String domain = tcp.getProxyUser().substring(0, domainIndex);
                    if (tcp.getProxyUser().length() > domainIndex + 1) {
                        String user = tcp.getProxyUser().substring(domainIndex + 1);
                        proxyCred = new NTCredentials(user, tcp.getProxyPassword(), tcp.getProxyHost(), domain);
                    }
                }
                client.getState().setProxyCredentials(AuthScope.ANY, proxyCred);
            }
            int proxyPort = new Integer(tcp.getProxyPort()).intValue();
            config.setProxy(tcp.getProxyHost(), proxyPort);
        }
    }
    return config;
}

From source file:com.jaspersoft.ireport.jasperserver.ws.CommonsHTTPSender.java

/**
 *  This method has been modified from the original one provided by Axis
 * in order to use the NetBeans proxy settings...
 * //from  w  ww.  j  a  va  2 s .co m
 * @param client
 * @param context
 * @param targetURL
 * @return 
 */
protected HostConfiguration getHostConfiguration(HttpClient client, MessageContext context, URL targetURL) {

    ProxySettings proxySettings = new ProxySettings();

    TransportClientProperties tcp = TransportClientPropertiesFactory.create(targetURL.getProtocol()); // http or https

    int port = targetURL.getPort();
    boolean hostInNonProxyList = proxySettings.isHostInNonProxyList(targetURL.getHost());
    //isHostInNonProxyList(targetURL.getHost(), tcp.getNonProxyHosts());

    HostConfiguration config = client.getHostConfiguration();

    if (port == -1) {
        if (targetURL.getProtocol().equalsIgnoreCase("https")) {
            port = 443; // default port for https being 443
        } else { // it must be http
            port = 80; // default port for http being 80
        }
    }

    // System.out.println("Connecting to port: " + port);

    if (!hostInNonProxyList && proxySettings.getHttpHost().length() != 0 && proxySettings.getHttpPort() > 0) {

        if (proxySettings.getUsername() != null && proxySettings.getUsername().length() != 0) {
            Credentials proxyCred = new UsernamePasswordCredentials(proxySettings.getUsername(),
                    proxySettings.getPassword());
            // if the username is in the form "user\domain" 
            // then use NTCredentials instead.
            int domainIndex = proxySettings.getUsername().indexOf("\\");
            if (domainIndex > 0) {
                String domain = proxySettings.getUsername().substring(0, domainIndex);
                if (proxySettings.getUsername().length() > domainIndex + 1) {
                    String user = proxySettings.getUsername().substring(domainIndex + 1);
                    proxyCred = new NTCredentials(user, proxySettings.getPassword(),
                            proxySettings.getHttpHost(), domain);
                }
            }
            client.getState().setProxyCredentials(AuthScope.ANY, proxyCred);
        }
        int proxyPort = proxySettings.getHttpPort();
        config.setProxy(proxySettings.getHttpHost(), proxyPort);
    } else {
        config.setHost(targetURL.getHost(), port, targetURL.getProtocol());
    }

    /*
    if(hostInNonProxyList){
    config.setHost(targetURL.getHost(), port, targetURL.getProtocol());
    } else {
    if (tcp.getProxyHost().length() == 0 ||
        tcp.getProxyPort().length() == 0) {
        config.setHost(targetURL.getHost(), port, targetURL.getProtocol());
    } else {
        if (tcp.getProxyUser().length() != 0) {
            Credentials proxyCred = 
                new UsernamePasswordCredentials(tcp.getProxyUser(),
                                                tcp.getProxyPassword());
            // if the username is in the form "user\domain" 
            // then use NTCredentials instead.
            int domainIndex = tcp.getProxyUser().indexOf("\\");
            if (domainIndex > 0) {
                String domain = tcp.getProxyUser().substring(0, domainIndex);
                if (tcp.getProxyUser().length() > domainIndex + 1) {
                    String user = tcp.getProxyUser().substring(domainIndex + 1);
                    proxyCred = new NTCredentials(user,
                                    tcp.getProxyPassword(),
                                    tcp.getProxyHost(), domain);
                }
            }
            client.getState().setProxyCredentials(AuthScope.ANY, proxyCred);
        }
        int proxyPort = new Integer(tcp.getProxyPort()).intValue();
        config.setProxy(tcp.getProxyHost(), proxyPort);
    }
    }
     * 
     */

    //System.out.println("Host Configuration:");
    //System.out.println("Proxy:" + config.getProxyHost() + ":" + config.getProxyPort());
    //System.out.flush();
    return config;
}

From source file:com.polarion.alm.ws.client.internal.connection.CommonsHTTPSender.java

/**
 * Extracts info from message context./*from  www  . j  a  va 2s.  c o m*/
 * 
 * @param method
 *            Post method
 * @param httpClient
 *            The client used for posting
 * @param msgContext
 *            the message context
 * @param tmpURL
 *            the url to post to.
 * 
 * @throws Exception
 */
private void addContextInfo(HttpMethodBase method, HttpClient httpClient, MessageContext msgContext, URL tmpURL)
        throws Exception {

    // optionally set a timeout for the request
    if (msgContext.getTimeout() != 0) {
        /*
         * ISSUE: these are not the same, but MessageContext has only one
         * definition of timeout
         */
        // SO_TIMEOUT -- timeout for blocking reads
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(msgContext.getTimeout());
        // timeout for initial connection
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(msgContext.getTimeout());
    }

    // Get SOAPAction, default to ""
    String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : "";

    if (action == null) {
        action = "";
    }

    Message msg = msgContext.getRequestMessage();
    if (msg != null) {
        method.setRequestHeader(new Header(HTTPConstants.HEADER_CONTENT_TYPE,
                msg.getContentType(msgContext.getSOAPConstants())));
    }
    method.setRequestHeader(new Header(HTTPConstants.HEADER_SOAP_ACTION, "\"" + action + "\""));
    method.setRequestHeader(new Header(HTTPConstants.HEADER_USER_AGENT, Messages.getMessage("axisUserAgent")));
    String userID = msgContext.getUsername();
    String passwd = msgContext.getPassword();

    // if UserID is not part of the context, but is in the URL, use
    // the one in the URL.
    if ((userID == null) && (tmpURL.getUserInfo() != null)) {
        String info = tmpURL.getUserInfo();
        int sep = info.indexOf(':');

        if ((sep >= 0) && (sep + 1 < info.length())) {
            userID = info.substring(0, sep);
            passwd = info.substring(sep + 1);
        } else {
            userID = info;
        }
    }
    if (userID != null) {
        Credentials proxyCred = new UsernamePasswordCredentials(userID, passwd);
        // if the username is in the form "user\domain"
        // then use NTCredentials instead.
        int domainIndex = userID.indexOf("\\");
        if (domainIndex > 0) {
            String domain = userID.substring(0, domainIndex);
            if (userID.length() > domainIndex + 1) {
                String user = userID.substring(domainIndex + 1);
                proxyCred = new NTCredentials(user, passwd, NetworkUtils.getLocalHostname(), domain);
            }
        }
        httpClient.getState().setCredentials(AuthScope.ANY, proxyCred);
    }

    // add compression headers if needed
    if (msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP)) {
        method.addRequestHeader(HTTPConstants.HEADER_ACCEPT_ENCODING, HTTPConstants.COMPRESSION_GZIP);
    }
    if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
        method.addRequestHeader(HTTPConstants.HEADER_CONTENT_ENCODING, HTTPConstants.COMPRESSION_GZIP);
    }

    // Transfer MIME headers of SOAPMessage to HTTP headers.
    MimeHeaders mimeHeaders = msg.getMimeHeaders();
    if (mimeHeaders != null) {
        for (Iterator i = mimeHeaders.getAllHeaders(); i.hasNext();) {
            MimeHeader mimeHeader = (MimeHeader) i.next();
            // HEADER_CONTENT_TYPE and HEADER_SOAP_ACTION are already set.
            // Let's not duplicate them.
            String headerName = mimeHeader.getName();
            if (headerName.equals(HTTPConstants.HEADER_CONTENT_TYPE)
                    || headerName.equals(HTTPConstants.HEADER_SOAP_ACTION)) {
                continue;
            }
            method.addRequestHeader(mimeHeader.getName(), mimeHeader.getValue());
        }
    }

    // process user defined headers for information.
    Hashtable userHeaderTable = (Hashtable) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS);

    if (userHeaderTable != null) {
        for (Iterator e = userHeaderTable.entrySet().iterator(); e.hasNext();) {
            Map.Entry me = (Map.Entry) e.next();
            Object keyObj = me.getKey();

            if (null == keyObj) {
                continue;
            }
            String key = keyObj.toString().trim();
            String value = me.getValue().toString().trim();

            if (key.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT)
                    && value.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT_100_Continue)) {
                method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
            } else if (key.equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED)) {
                String val = me.getValue().toString();
                if (null != val) {
                    httpChunkStream = JavaUtils.isTrue(val);
                }
            } else {
                method.addRequestHeader(key, value);
            }
        }
    }
}

From source file:com.jaspersoft.ireport.jasperserver.ws.CommonsHTTPSender.java

/**
 * Extracts info from message context./*from  ww  w .  j a v  a2s  . c  o  m*/
 *
 * @param method Post method
 * @param httpClient The client used for posting
 * @param msgContext the message context
 * @param tmpURL the url to post to.
 *
 * @throws Exception
 */
private void addContextInfo(HttpMethodBase method, HttpClient httpClient, MessageContext msgContext, URL tmpURL)
        throws Exception {

    // optionally set a timeout for the request
    if (msgContext.getTimeout() != 0) {
        /* ISSUE: these are not the same, but MessageContext has only one
              definition of timeout */
        // SO_TIMEOUT -- timeout for blocking reads
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(msgContext.getTimeout());
        // timeout for initial connection
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(msgContext.getTimeout());
    }

    // Get SOAPAction, default to ""
    String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : "";

    if (action == null) {
        action = "";
    }

    Message msg = msgContext.getRequestMessage();
    if (msg != null) {
        method.setRequestHeader(new Header(HTTPConstants.HEADER_CONTENT_TYPE,
                msg.getContentType(msgContext.getSOAPConstants())));
    }
    method.setRequestHeader(new Header(HTTPConstants.HEADER_SOAP_ACTION, "\"" + action + "\""));
    method.setRequestHeader(new Header(HTTPConstants.HEADER_USER_AGENT, Messages.getMessage("axisUserAgent")));
    String userID = msgContext.getUsername();
    String passwd = msgContext.getPassword();

    // if UserID is not part of the context, but is in the URL, use
    // the one in the URL.
    if ((userID == null) && (tmpURL.getUserInfo() != null)) {
        String info = tmpURL.getUserInfo();
        int sep = info.indexOf(':');

        if ((sep >= 0) && (sep + 1 < info.length())) {
            userID = info.substring(0, sep);
            passwd = info.substring(sep + 1);
        } else {
            userID = info;
        }
    }
    if (userID != null) {
        Credentials proxyCred = new UsernamePasswordCredentials(userID, passwd);
        // if the username is in the form "user\domain"
        // then use NTCredentials instead.
        int domainIndex = userID.indexOf("\\");
        if (domainIndex > 0) {
            String domain = userID.substring(0, domainIndex);
            if (userID.length() > domainIndex + 1) {
                String user = userID.substring(domainIndex + 1);
                proxyCred = new NTCredentials(user, passwd, NetworkUtils.getLocalHostname(), domain);
            }
        }
        httpClient.getState().setCredentials(AuthScope.ANY, proxyCred);
    }

    // add compression headers if needed
    if (msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP)) {
        method.addRequestHeader(HTTPConstants.HEADER_ACCEPT_ENCODING, HTTPConstants.COMPRESSION_GZIP);
    }
    if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
        method.addRequestHeader(HTTPConstants.HEADER_CONTENT_ENCODING, HTTPConstants.COMPRESSION_GZIP);
    }

    // Transfer MIME headers of SOAPMessage to HTTP headers. 
    MimeHeaders mimeHeaders = msg.getMimeHeaders();
    if (mimeHeaders != null) {
        for (Iterator i = mimeHeaders.getAllHeaders(); i.hasNext();) {
            MimeHeader mimeHeader = (MimeHeader) i.next();
            //HEADER_CONTENT_TYPE and HEADER_SOAP_ACTION are already set.
            //Let's not duplicate them.
            String headerName = mimeHeader.getName();
            if (headerName.equals(HTTPConstants.HEADER_CONTENT_TYPE)
                    || headerName.equals(HTTPConstants.HEADER_SOAP_ACTION)) {
                continue;
            }
            method.addRequestHeader(mimeHeader.getName(), mimeHeader.getValue());
        }
    }

    // process user defined headers for information.
    Hashtable userHeaderTable = (Hashtable) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS);

    if (userHeaderTable != null) {
        for (Iterator e = userHeaderTable.entrySet().iterator(); e.hasNext();) {
            Map.Entry me = (Map.Entry) e.next();
            Object keyObj = me.getKey();

            if (null == keyObj) {
                continue;
            }
            String key = keyObj.toString().trim();
            String value = me.getValue().toString().trim();

            if (key.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT)
                    && value.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT_100_Continue)) {
                method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
            } else if (key.equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED)) {
                String val = me.getValue().toString();
                if (null != val) {
                    httpChunkStream = JavaUtils.isTrue(val);
                }
            } else {
                method.addRequestHeader(key, value);
            }
        }
    }
}

From source file:com.polarion.alm.ws.client.internal.connection.CommonsHTTPSender.java

/**
 * invoke creates a socket connection, sends the request SOAP message and
 * then reads the response SOAP message back from the SOAP server
 * //w w  w.  j  a  v a  2 s  . c  om
 * @param msgContext
 *            the messsage context
 * 
 * @throws AxisFault
 */
public void invoke(MessageContext msgContext) throws AxisFault {
    HttpMethodBase method = null;
    if (log.isDebugEnabled()) {
        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());
        httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new RetryHandler());

        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());

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

            addContextInfo(method, httpClient, msgContext, targetURL);

            MessageRequestEntity requestEntity = null;
            if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
                requestEntity = new GzipMessageRequestEntity(method, reqMessage, httpChunkStream);
            } else {
                requestEntity = new MessageRequestEntity(method, reqMessage, httpChunkStream);
            }
            ((PostMethod) method).setRequestEntity(requestEntity);
        } else {
            method = new GetMethod(targetURL.toString());
            addContextInfo(method, httpClient, msgContext, targetURL);
        }

        String httpVersion = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION);
        if (httpVersion != null) {
            if (httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_V10)) {
                method.getParams().setVersion(HttpVersion.HTTP_1_0);
            }
            // assume 1.1
        }

        // 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);
        }

        int returnCode = httpClient.executeMethod(hostConfiguration, method, null);

        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();
            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);
        if (contentEncoding != null) {
            if (contentEncoding.getValue().equalsIgnoreCase(HTTPConstants.COMPRESSION_GZIP)) {
                releaseConnectionOnCloseStream = new GZIPInputStream(releaseConnectionOnCloseStream);
            } else {
                AxisFault fault = new AxisFault("HTTP",
                        "unsupported content-encoding of '" + contentEncoding.getValue() + "' found", null,
                        null);
                throw fault;
            }

        }
        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.isDebugEnabled()) {
            if (null == contentLength) {
                log.debug("\n" + Messages.getMessage("no00", "Content-Length"));
            }
            log.debug("\n" + Messages.getMessage("xmlRecd00"));
            log.debug("-----------------------------------------------");
            log.debug(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:com.jaspersoft.ireport.jasperserver.ws.CommonsHTTPSender.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 the messsage context
 *
 * @throws AxisFault/* w w  w. j  a  v a 2 s.  c  o  m*/
 */
public void invoke(MessageContext msgContext) throws AxisFault {

    //test();

    HttpMethodBase method = null;
    if (log.isDebugEnabled()) {
        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.

        //org.apache.log4j.LogManager.getRootLogger().setLevel(org.apache.log4j.Level.DEBUG);

        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());

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

            addContextInfo(method, httpClient, msgContext, targetURL);

            MessageRequestEntity requestEntity = null;
            if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
                requestEntity = new GzipMessageRequestEntity(method, reqMessage, httpChunkStream);
            } else {
                requestEntity = new MessageRequestEntity(method, reqMessage, httpChunkStream);
            }

            method.addRequestHeader(HTTPConstants.HEADER_CONTENT_LENGTH, "" + requestEntity.getContentLength());
            ((PostMethod) method).setRequestEntity(requestEntity);
        } else {
            method = new GetMethod(targetURL.toString());
            addContextInfo(method, httpClient, msgContext, targetURL);
        }

        String httpVersion = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION);
        if (httpVersion != null) {
            if (httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_V10)) {
                method.getParams().setVersion(HttpVersion.HTTP_1_0);
            }
            // assume 1.1
        }

        // 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 = targetURL.getHost();
            String path = targetURL.getPath();
            boolean secure = targetURL.getProtocol().equals("https");

            fillHeaders(msgContext, state, HTTPConstants.HEADER_COOKIE, host, path, secure);
            fillHeaders(msgContext, state, HTTPConstants.HEADER_COOKIE2, host, path, secure);

            httpClient.setState(state);

        }

        int returnCode = httpClient.executeMethod(method);

        org.apache.log4j.LogManager.getRootLogger().setLevel(org.apache.log4j.Level.ERROR);

        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();
            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);
        if (contentEncoding != null) {
            if (contentEncoding.getValue().equalsIgnoreCase(HTTPConstants.COMPRESSION_GZIP)) {
                releaseConnectionOnCloseStream = new GZIPInputStream(releaseConnectionOnCloseStream);
            } else {
                AxisFault fault = new AxisFault("HTTP",
                        "unsupported content-encoding of '" + contentEncoding.getValue() + "' found", null,
                        null);
                throw fault;
            }

        }
        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.isDebugEnabled()) {
            if (null == contentLength) {
                log.debug("\n" + Messages.getMessage("no00", "Content-Length"));
            }
            log.debug("\n" + Messages.getMessage("xmlRecd00"));
            log.debug("-----------------------------------------------");
            log.debug(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:davmail.exchange.ExchangeSession.java

protected HttpMethod postLogonMethod(HttpClient httpClient, HttpMethod logonMethod, String userName,
        String password) throws IOException {

    setAuthFormFields(logonMethod, httpClient, password);

    // add exchange 2010 PBack cookie in compatibility mode
    httpClient.getState()
            .addCookie(new Cookie(httpClient.getHostConfiguration().getHost(), "PBack", "0", "/", null, false));

    logonMethod = DavGatewayHttpClientFacade.executeFollowRedirects(httpClient, logonMethod);

    // test form based authentication
    checkFormLoginQueryString(logonMethod);

    // workaround for post logon script redirect
    if (!isAuthenticated()) {
        // try to get new method from script based redirection
        logonMethod = buildLogonMethod(httpClient, logonMethod);

        if (otpPreAuthFound && otpPreAuthRetries < MAX_OTP_RETRIES) {
            // A OTP pre-auth page has been found, it is needed to restart the login process.
            // This applies to both the case the user entered a good OTP code (the usual login process
            // takes place) and the case the user entered a wrong OTP code (another code will be asked to him).
            // The user has up to MAX_OTP_RETRIES chances to input a valid OTP key.
            return postLogonMethod(httpClient, logonMethod, userName, password);
        }// ww  w .  ja v a  2 s  .c  o  m

        if (logonMethod != null) {
            // if logonMethod is not null, try to follow redirection
            logonMethod = DavGatewayHttpClientFacade.executeFollowRedirects(httpClient, logonMethod);
            checkFormLoginQueryString(logonMethod);
            // also check cookies
            if (!isAuthenticated()) {
                throwAuthenticationFailed();
            }
        } else {
            // authentication failed
            throwAuthenticationFailed();
        }
    }

    // check for language selection form
    if (logonMethod != null && "/owa/languageselection.aspx".equals(logonMethod.getPath())) {
        // need to submit form
        logonMethod = submitLanguageSelectionForm(logonMethod);
    }
    return logonMethod;
}

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

/**
* Extracts info from message context./*ww  w  . j  a v  a2 s .c o  m*/
* 
* @param method
*            Post method
* @param httpClient
*            The client used for posting
* @param msgContext
*            the message context
* @param tmpURL
*            the url to post to.
* 
* @throws Exception
*/
private void addContextInfo(HttpMethodBase method, HttpClient httpClient, MessageContext msgContext, URL tmpURL)
        throws Exception {

    // optionally set a timeout for the request
    if (msgContext.getTimeout() != 0) {
        /*
        * ISSUE: these are not the same, but MessageContext has only one
        * definition of timeout
        */
        // SO_TIMEOUT -- timeout for blocking reads
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(msgContext.getTimeout());
        // timeout for initial connection
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(msgContext.getTimeout());
    }

    // Get SOAPAction, default to ""
    String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : "";

    if (action == null) {
        action = "";
    }

    Message msg = msgContext.getRequestMessage();
    if (msg != null) {
        method.setRequestHeader(new Header(HTTPConstants.HEADER_CONTENT_TYPE,
                msg.getContentType(msgContext.getSOAPConstants())));
    }
    method.setRequestHeader(new Header(HTTPConstants.HEADER_SOAP_ACTION, "\"" + action + "\""));
    method.setRequestHeader(new Header(HTTPConstants.HEADER_USER_AGENT, Messages.getMessage("axisUserAgent")));
    //method.setRequestHeader(
    //   new Header(HTTPConstants.HEADER_USER_AGENT, "Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 2.0.5072)")
    //);

    String userID = msgContext.getUsername();
    String passwd = msgContext.getPassword();
    //System.out.println("ImageXChangeHttpCommonsSender setting credentials = '" + userID + ". " + passwd + "'");

    // if UserID is not part of the context, but is in the URL, use
    // the one in the URL.
    if ((userID == null) && (tmpURL.getUserInfo() != null)) {
        String info = tmpURL.getUserInfo();
        int sep = info.indexOf(':');

        if ((sep >= 0) && (sep + 1 < info.length())) {
            userID = info.substring(0, sep);
            passwd = info.substring(sep + 1);
        } else {
            userID = info;
        }
    }
    if (userID != null) {
        Credentials proxyCred = new UsernamePasswordCredentials(userID, passwd);
        // if the username is in the form "user\domain"
        // then use NTCredentials instead.
        int domainIndex = userID.indexOf("\\");
        if (domainIndex > 0) {
            String domain = userID.substring(0, domainIndex);
            if (userID.length() > domainIndex + 1) {
                String user = userID.substring(domainIndex + 1);
                proxyCred = new NTCredentials(user, passwd, NetworkUtils.getLocalHostname(), domain);
            }
        }
        httpClient.getState().setCredentials(AuthScope.ANY, proxyCred);
        //System.out.println("ImageXChangeHttpCommonsSender setting credentials = '" + userID + ". " + passwd + "'");
    }

    // add compression headers if needed
    // if we accept GZIP then add the accept-encoding header
    if (msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP)) {
        // accept both gzip and deflate if the gzip property is set
        method.addRequestHeader(HTTPConstants.HEADER_ACCEPT_ENCODING,
                HTTPConstants.COMPRESSION_GZIP + "," + COMPRESSION_DEFLATE);
        //method.addRequestHeader(HTTPConstants.HEADER_ACCEPT_ENCODING, COMPRESSION_DEFLATE);
    }

    // if we will gzip the request then add the content-encoding header
    if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
        method.addRequestHeader(HTTPConstants.HEADER_CONTENT_ENCODING, HTTPConstants.COMPRESSION_GZIP);
    }

    // Transfer MIME headers of SOAPMessage to HTTP headers.
    MimeHeaders mimeHeaders = msg.getMimeHeaders();
    if (mimeHeaders != null) {
        for (Iterator i = mimeHeaders.getAllHeaders(); i.hasNext();) {
            MimeHeader mimeHeader = (MimeHeader) i.next();
            // HEADER_CONTENT_TYPE and HEADER_SOAP_ACTION are already set.
            // Let's not duplicate them.
            String headerName = mimeHeader.getName();
            if (headerName.equals(HTTPConstants.HEADER_CONTENT_TYPE)
                    || headerName.equals(HTTPConstants.HEADER_SOAP_ACTION))
                continue;
            method.addRequestHeader(mimeHeader.getName(), mimeHeader.getValue());
        }
    }

    // process user defined headers for information.
    Hashtable userHeaderTable = (Hashtable) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS);

    if (userHeaderTable != null) {
        for (Iterator e = userHeaderTable.entrySet().iterator(); e.hasNext();) {
            Map.Entry me = (Map.Entry) e.next();
            Object keyObj = me.getKey();

            if (null == keyObj) {
                continue;
            }
            String key = keyObj.toString().trim();
            String value = me.getValue().toString().trim();

            if (key.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT)
                    && value.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT_100_Continue)) {
                method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
            } else if (key.equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED)) {
                String val = me.getValue().toString();
                if (null != val) {
                    httpChunkStream = JavaUtils.isTrue(val);
                }
            } else {
                method.addRequestHeader(key, value);
            }
        }
    }
}