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:org.eclipse.mylyn.internal.provisional.commons.soap.CommonsHttpSender.java

/**
 * Extracts info from message context.//from  ww w. ja  va 2 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
 */
protected 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() : ""; //$NON-NLS-1$

    if (action == null) {
        action = ""; //$NON-NLS-1$
    }

    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 + "\"")); //$NON-NLS-1$ //$NON-NLS-2$
    method.setRequestHeader(new Header(HTTPConstants.HEADER_USER_AGENT, Messages.getMessage("axisUserAgent"))); //$NON-NLS-1$
    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("\\"); //$NON-NLS-1$
        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 {
                // let plug-ins using SOAP be able to set their own user-agent header (i.e. for tracking purposes)
                if (HTTPConstants.HEADER_USER_AGENT.equalsIgnoreCase(key)) {
                    method.setRequestHeader(key, value);
                } else {
                    method.addRequestHeader(key, value);
                }
            }
        }
    }
}

From source file:org.eclipse.mylyn.internal.trac.core.client.AbstractTracClient.java

/**
 * Check if authentication cookie has been set.
 * //from   w w  w.  j a v a  2s . c  o m
 * @throws TracLoginException
 *             thrown if the cookie has not been set
 */
protected void validateAuthenticationState(HttpClient httpClient) throws TracLoginException {
    Cookie[] cookies = httpClient.getState().getCookies();
    for (Cookie cookie : cookies) {
        if (LOGIN_COOKIE_NAME.equals(cookie.getName())) {
            return;
        }
    }

    if (CoreUtil.TEST_MODE) {
        System.err.println(" Authentication failed: " + httpClient.getState()); //$NON-NLS-1$
    }

    throw new TracLoginException();
}

From source file:org.eclipse.php.composer.core.HttpHelper.java

private static HttpClient createHttpClient(String url, IProxyService proxyService)
        throws IOException, URISyntaxException {
    HttpClient httpClient = new HttpClient();

    if (proxyService.isProxiesEnabled()) {
        IProxyData[] proxyData = proxyService.select(new URI(url));

        if (proxyData.length != 0) {
            IProxyData proxy = proxyData[0];
            String proxyHostName = proxy.getHost();
            if (proxyHostName != null) {
                int portNumber = proxy.getPort();
                if (portNumber == -1) {
                    portNumber = 80;//ww  w  .  jav  a  2  s .  c  o  m
                }
                httpClient.getHostConfiguration().setProxy(proxyHostName, portNumber);
                if (proxy.isRequiresAuthentication()) {
                    String userName = proxy.getUserId();
                    if (userName != null) {
                        String password = proxy.getPassword();
                        Credentials credentials = new UsernamePasswordCredentials(userName, password);
                        httpClient.getState().setProxyCredentials(
                                new AuthScope(null, AuthScope.ANY_PORT, null, AuthScope.ANY_SCHEME),
                                credentials);
                    }
                }
            }
        }
    }

    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);

    return httpClient;
}

From source file:org.eclipse.smarthome.io.net.http.HttpUtil.java

/**
 * Executes the given <code>url</code> with the given <code>httpMethod</code>
 * /* w  w  w.j ava  2 s  .  c o  m*/
 * @param httpMethod the HTTP method to use
 * @param url the url to execute (in milliseconds)
 * @param httpHeaders optional HTTP headers which has to be set on request
 * @param content the content to be send to the given <code>url</code> or 
 * <code>null</code> if no content should be send.
 * @param contentType the content type of the given <code>content</code>
 * @param timeout the socket timeout to wait for data
 * @param proxyHost the hostname of the proxy
 * @param proxyPort the port of the proxy
 * @param proxyUser the username to authenticate with the proxy
 * @param proxyPassword the password to authenticate with the proxy
 * @param nonProxyHosts the hosts that won't be routed through the proxy
 * @return the response body or <code>NULL</code> when the request went wrong
 */
public static String executeUrl(String httpMethod, String url, Properties httpHeaders, InputStream content,
        String contentType, int timeout, String proxyHost, Integer proxyPort, String proxyUser,
        String proxyPassword, String nonProxyHosts) {

    HttpClient client = new HttpClient();

    // only configure a proxy if a host is provided
    if (StringUtils.isNotBlank(proxyHost) && proxyPort != null && shouldUseProxy(url, nonProxyHosts)) {
        client.getHostConfiguration().setProxy(proxyHost, proxyPort);
        if (StringUtils.isNotBlank(proxyUser)) {
            client.getState().setProxyCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(proxyUser, proxyPassword));
        }
    }

    HttpMethod method = HttpUtil.createHttpMethod(httpMethod, url);
    method.getParams().setSoTimeout(timeout);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    if (httpHeaders != null) {
        for (String httpHeaderKey : httpHeaders.stringPropertyNames()) {
            method.addRequestHeader(new Header(httpHeaderKey, httpHeaders.getProperty(httpHeaderKey)));
        }
    }
    // add content if a valid method is given ...
    if (method instanceof EntityEnclosingMethod && content != null) {
        EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method;
        eeMethod.setRequestEntity(new InputStreamRequestEntity(content, contentType));
    }

    Credentials credentials = extractCredentials(url);
    if (credentials != null) {
        client.getParams().setAuthenticationPreemptive(true);
        client.getState().setCredentials(AuthScope.ANY, credentials);
    }

    if (logger.isDebugEnabled()) {
        try {
            logger.debug("About to execute '" + method.getURI().toString() + "'");
        } catch (URIException e) {
            logger.debug(e.getMessage());
        }
    }

    try {

        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            logger.warn("Method failed: " + method.getStatusLine());
        }

        String responseBody = IOUtils.toString(method.getResponseBodyAsStream());
        if (!responseBody.isEmpty()) {
            logger.debug(responseBody);
        }

        return responseBody;
    } catch (HttpException he) {
        logger.error("Fatal protocol violation: {}", he.toString());
    } catch (IOException ioe) {
        logger.error("Fatal transport error: {}", ioe.toString());
    } finally {
        method.releaseConnection();
    }

    return null;
}

From source file:org.eclipse.smarthome.ui.internal.proxy.ProxyServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String sitemapName = request.getParameter("sitemap");
    String widgetId = request.getParameter("widgetId");

    if (sitemapName == null) {
        throw new ServletException("Parameter 'sitemap' must be provided!");
    }/*from w  w w  .j  a  v  a  2 s. c om*/
    if (widgetId == null) {
        throw new ServletException("Parameter 'widget' must be provided!");
    }

    String uriString = null;

    Sitemap sitemap = (Sitemap) modelRepository.getModel(sitemapName);
    if (sitemap != null) {
        Widget widget = itemUIRegistry.getWidget(sitemap, widgetId);
        if (widget instanceof Image) {
            Image image = (Image) widget;
            uriString = image.getUrl();
        } else if (widget instanceof Video) {
            Video video = (Video) widget;
            uriString = video.getUrl();
        } else {
            if (widget == null) {
                throw new ServletException("Widget '" + widgetId + "' could not be found!");
            } else {
                throw new ServletException(
                        "Widget type '" + widget.getClass().getName() + "' is not supported!");
            }
        }
    } else {
        throw new ServletException("Sitemap '" + sitemapName + "' could not be found!");
    }

    HttpClient httpClient = new HttpClient();

    try {
        // check if the uri uses credentials and configure the http client accordingly
        URI uri = URI.create(uriString);

        if (uri.getUserInfo() != null) {
            String[] userInfo = uri.getUserInfo().split(":");
            httpClient.getParams().setAuthenticationPreemptive(true);
            Credentials creds = new UsernamePasswordCredentials(userInfo[0], userInfo[1]);
            httpClient.getState()
                    .setCredentials(new AuthScope(uri.getHost(), uri.getPort(), AuthScope.ANY_REALM), creds);
        }
    } catch (IllegalArgumentException e) {
        throw new ServletException("URI '" + uriString + "' is not valid: " + e.getMessage());
    }

    // do the client request
    GetMethod method = new GetMethod(uriString);
    httpClient.executeMethod(method);

    // copy all headers
    for (Header header : method.getResponseHeaders()) {
        response.setHeader(header.getName(), header.getValue());
    }

    // now copy/stream the body content
    IOUtils.copy(method.getResponseBodyAsStream(), response.getOutputStream());
    method.releaseConnection();
}

From source file:org.eclipse.virgo.ide.runtime.internal.core.utils.WebDownloadUtils.java

private static void configureHttpClientProxy(String url, HttpClient client,
        HostConfiguration hostConfiguration) {
    ServiceReference services = ServerCorePlugin.getDefault().getBundle().getBundleContext()
            .getServiceReference(IProxyService.class.getName());
    if (services != null) {
        IProxyService proxyService = (IProxyService) ServerCorePlugin.getDefault().getBundle()
                .getBundleContext().getService(services);
        IProxyData proxyData = proxyService.getProxyDataForHost(getHost(url), IProxyData.HTTP_PROXY_TYPE);
        if (proxyService.isProxiesEnabled() && proxyData != null) {
            hostConfiguration.setProxy(proxyData.getHost(), proxyData.getPort());
        }//from ww w .j  a v a 2 s  . c o  m
        if (proxyData != null && proxyData.isRequiresAuthentication()) {
            client.getState().setProxyCredentials(AuthScope.ANY, getCredentials(proxyData, getHost(url)));
        }
    }
}

From source file:org.eclipse.virgo.qa.performance.UrlWaitLatch.java

public static void waitFor(String url, String username, String password, long interval, long duration) {
    HttpClient client = new HttpClient();
    client.getParams().setAuthenticationPreemptive(true);
    client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
    wait(url, client, interval, duration);
}

From source file:org.eclipsetrader.directa.internal.core.connector.StreamingConnector.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private void setupProxy(HttpClient client, String host) throws URISyntaxException {
    if (Activator.getDefault() != null) {
        BundleContext context = Activator.getDefault().getBundle().getBundleContext();
        ServiceReference reference = context.getServiceReference(IProxyService.class.getName());
        if (reference != null) {
            IProxyService proxyService = (IProxyService) context.getService(reference);
            IProxyData[] proxyData = proxyService.select(new URI(null, host, null, null));
            for (int i = 0; i < proxyData.length; i++) {
                if (IProxyData.HTTP_PROXY_TYPE.equals(proxyData[i].getType())) {
                    IProxyData data = proxyData[i];
                    if (data.getHost() != null) {
                        client.getHostConfiguration().setProxy(data.getHost(), data.getPort());
                    }//  w w  w. j a v a 2 s.  com
                    if (data.isRequiresAuthentication()) {
                        client.getState().setProxyCredentials(AuthScope.ANY,
                                new UsernamePasswordCredentials(data.getUserId(), data.getPassword()));
                    }
                    break;
                }
            }
            context.ungetService(reference);
        }
    }
}

From source file:org.eclipsetrader.directa.internal.core.WebConnector.java

private void setupProxy(HttpClient client, String host) throws URISyntaxException {
    if (Activator.getDefault() != null) {
        BundleContext context = Activator.getDefault().getBundle().getBundleContext();
        ServiceReference reference = context.getServiceReference(IProxyService.class.getName());
        if (reference != null) {
            IProxyService proxyService = (IProxyService) context.getService(reference);
            IProxyData[] proxyData = proxyService.select(new URI(null, host, null, null));
            for (int i = 0; i < proxyData.length; i++) {
                if (IProxyData.HTTP_PROXY_TYPE.equals(proxyData[i].getType())) {
                    IProxyData data = proxyData[i];
                    if (data.getHost() != null) {
                        client.getHostConfiguration().setProxy(data.getHost(), data.getPort());
                    }//from  w ww.  j a va 2 s  . c o m
                    if (data.isRequiresAuthentication()) {
                        client.getState().setProxyCredentials(AuthScope.ANY,
                                new UsernamePasswordCredentials(data.getUserId(), data.getPassword()));
                    }
                    break;
                }
            }
            context.ungetService(reference);
        }
    }
}

From source file:org.eclipsetrader.directaworld.internal.core.connector.SnapshotConnector.java

private void setupProxy(HttpClient client, String host) throws URISyntaxException {
    if (Activator.getDefault() != null) {
        BundleContext context = Activator.getDefault().getBundle().getBundleContext();
        ServiceReference<IProxyService> reference = context.getServiceReference(IProxyService.class);
        if (reference != null) {
            IProxyService proxyService = context.getService(reference);
            IProxyData[] proxyData = proxyService.select(new URI(null, host, null, null));
            for (int i = 0; i < proxyData.length; i++) {
                if (IProxyData.HTTP_PROXY_TYPE.equals(proxyData[i].getType())) {
                    IProxyData data = proxyData[i];
                    if (data.getHost() != null) {
                        client.getHostConfiguration().setProxy(data.getHost(), data.getPort());
                    }// w  w  w.j a va  2s.  com
                    if (data.isRequiresAuthentication()) {
                        client.getState().setProxyCredentials(AuthScope.ANY,
                                new UsernamePasswordCredentials(data.getUserId(), data.getPassword()));
                    }
                    break;
                }
            }
            context.ungetService(reference);
        }
    }
}