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

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

Introduction

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

Prototype

public HostConfiguration() 

Source Link

Usage

From source file:ome.formats.importer.util.HtmlMessenger.java

/**
 * Instantiate html messenger/*from  w ww  .  j av  a2  s.  c  om*/
 *
 * @param url
 * @param postList - variables list in post
 * @throws HtmlMessengerException
 */
public HtmlMessenger(String url, List<Part> postList) throws HtmlMessengerException {
    try {
        HostConfiguration cfg = new HostConfiguration();
        cfg.setHost(url);
        String proxyHost = System.getProperty(PROXY_HOST);
        String proxyPort = System.getProperty(PROXY_PORT);
        if (proxyHost != null && proxyPort != null) {
            int port = Integer.parseInt(proxyPort);
            cfg.setProxy(proxyHost, port);
        }

        client = new HttpClient();
        client.setHostConfiguration(cfg);
        HttpClientParams params = new HttpClientParams();
        params.setConnectionManagerTimeout(CONN_TIMEOUT);
        params.setSoTimeout(CONN_TIMEOUT);
        client.setParams(params);

        method = new PostMethod(url);

        Part[] parts = new Part[postList.size()];

        int i = 0;
        for (Part part : postList) {
            parts[i] = part;
            i++;
        }

        MultipartRequestEntity mpre = new MultipartRequestEntity(parts, method.getParams());

        ProgressListener listener = new ProgressListener() {
            /* (non-Javadoc)
             * @see ome.formats.importer.util.FileUploadCounter.ProgressListener#update(long)
             */
            public void update(long bytesRead) {
            }
        };

        FileUploadCounter hfre = new FileUploadCounter(mpre, listener);

        method.setRequestEntity(hfre);

    } catch (Exception e) {
        e.printStackTrace();
        throw new HtmlMessengerException("Error creating post parameters", e);
    }

}

From source file:org.activebpel.rt.axis.bpel.handlers.AeHTTPSender.java

/**
 * @deprecated/*from w w w  .j a va 2  s.co m*/
 */
private HostConfiguration getHostConfiguration(HttpClient client, URL targetURL) {
    TransportClientProperties tcp = TransportClientPropertiesFactory.create(targetURL.getProtocol()); // http or https
    int port = targetURL.getPort();
    boolean hostInNonProxyList = isHostInNonProxyList(targetURL.getHost(), tcp.getNonProxyHosts());

    HostConfiguration config = new HostConfiguration();

    if (port == -1) {
        port = 80; // even for https
    }

    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());
                client.getState().setProxyCredentials(null, null, proxyCred);
            }
            int proxyPort = new Integer(tcp.getProxyPort()).intValue();
            config.setProxy(tcp.getProxyHost(), proxyPort);
        }
    }
    return config;
}

From source file:org.aksonov.mages.connection.ConnectionManager.java

/**
 * Gets the connection.//  ww  w.java 2 s .  c  o  m
 * 
 * @param host the host
 * 
 * @return the connection
 */
private static HttpConnection getConnection(String host) {
    try {
        synchronized (hosts) {
            if (!hosts.contains(host)) {
                HttpURL httpURL = new HttpURL(host);
                HostConfiguration hostConfig = new HostConfiguration();
                hostConfig.setHost(httpURL.getHost(), httpURL.getPort());
                hosts.put(host, hostConfig);
            }
        }
        HostConfiguration hostConfig = hosts.get(host);
        //Log.d("ConnectionManager", "Retrieving connection from the pool");
        HttpConnection connection = connectionManager.getConnectionWithTimeout(hostConfig, TIMEOUT);

        return connection;
    } catch (Exception e) {
        Log.e("ConnectionManager.getConnection", e);
        return null;
    }
}

From source file:org.alfresco.repo.transfer.HttpClientTransmitterImpl.java

/**
 * @param target TransferTarget/*  w w w.j  ava  2  s  .c  om*/
 * @return HostConfiguration
 */
private HostConfiguration getHostConfig(TransferTarget target) {
    String requiredProtocol = target.getEndpointProtocol();
    if (requiredProtocol == null) {
        throw new TransferException(MSG_UNSUPPORTED_PROTOCOL, new Object[] { target.getEndpointProtocol() });
    }

    Protocol protocol = protocolMap.get(requiredProtocol.toLowerCase().trim());
    if (protocol == null) {
        log.error("Unsupported protocol: " + target.getEndpointProtocol());
        throw new TransferException(MSG_UNSUPPORTED_PROTOCOL, new Object[] { target.getEndpointProtocol() });
    }

    HostConfiguration hostConfig = new HostConfiguration();
    hostConfig.setHost(target.getEndpointHost(), target.getEndpointPort(), protocol);
    return hostConfig;
}

From source file:org.alfresco.repo.urlshortening.BitlyUrlShortenerImpl.java

public BitlyUrlShortenerImpl() {
    httpClient = new HttpClient();
    httpClient.setHttpConnectionManager(new MultiThreadedHttpConnectionManager());
    HostConfiguration hostConfiguration = new HostConfiguration();
    hostConfiguration.setHost("api-ssl.bitly.com", 443, Protocol.getProtocol("https"));
    httpClient.setHostConfiguration(hostConfiguration);
}

From source file:org.apache.axis.transport.http.CommonsHTTPSender.java

protected HostConfiguration getHostConfiguration(HttpClient client, MessageContext context, URL targetURL) {
    TransportClientProperties tcp = TransportClientPropertiesFactory.create(targetURL.getProtocol()); // http or 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
        }//from ww  w. j  a  v  a  2 s . co  m
    }

    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:org.apache.axis2.transport.http.AbstractHTTPSender.java

/**
 * getting host configuration to support standard http/s, proxy and NTLM support
 *
 * @param client active HttpClient//from w w w.  j  a  v  a  2s  .  co  m
 * @param msgCtx active MessageContext
 * @param targetURL the target URL
 * @return a HostConfiguration set up with proxy information
 * @throws AxisFault if problems occur
 */
protected HostConfiguration getHostConfiguration(HttpClient client, MessageContext msgCtx, URL targetURL)
        throws AxisFault {

    boolean isAuthenticationEnabled = isAuthenticationEnabled(msgCtx);
    int port = targetURL.getPort();

    String protocol = targetURL.getProtocol();
    if (port == -1) {
        if (PROTOCOL_HTTP.equals(protocol)) {
            port = 80;
        } else if (PROTOCOL_HTTPS.equals(protocol)) {
            port = 443;
        }

    }

    // to see the host is a proxy and in the proxy list - available in axis2.xml
    HostConfiguration config = new HostConfiguration();

    // one might need to set his own socket factory. Let's allow that case as well.
    Protocol protocolHandler = (Protocol) msgCtx.getOptions()
            .getProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER);

    // setting the real host configuration
    // I assume the 90% case, or even 99% case will be no protocol handler case.
    if (protocolHandler == null) {
        config.setHost(targetURL.getHost(), port, targetURL.getProtocol());
    } else {
        config.setHost(targetURL.getHost(), port, protocolHandler);
    }

    if (isAuthenticationEnabled) {
        // Basic, Digest, NTLM and custom authentications.
        this.setAuthenticationInfo(client, msgCtx, config);
    }
    // proxy configuration

    if (HTTPProxyConfigurationUtil.isProxyEnabled(msgCtx, targetURL)) {
        if (log.isDebugEnabled()) {
            log.debug("Configuring HTTP proxy.");
        }
        HTTPProxyConfigurationUtil.configure(msgCtx, client, config);
    }

    return config;
}

From source file:org.apache.axis2.transport.http.impl.httpclient3.HTTPSenderImpl.java

/**
 * getting host configuration to support standard http/s, proxy and NTLM
 * support//from   w w w.j  a v  a 2s  .  com
 * 
 * @param client
 *            active HttpClient
 * @param msgCtx
 *            active MessageContext
 * @param targetURL
 *            the target URL
 * @return a HostConfiguration set up with proxy information
 * @throws AxisFault
 *             if problems occur
 */
protected HostConfiguration getHostConfiguration(HttpClient client, MessageContext msgCtx, URL targetURL)
        throws AxisFault {

    boolean isAuthenticationEnabled = isAuthenticationEnabled(msgCtx);
    int port = targetURL.getPort();

    String protocol = targetURL.getProtocol();
    if (port == -1) {
        if (HTTPTransportConstants.PROTOCOL_HTTP.equals(protocol)) {
            port = 80;
        } else if (HTTPTransportConstants.PROTOCOL_HTTPS.equals(protocol)) {
            port = 443;
        }

    }

    // to see the host is a proxy and in the proxy list - available in
    // axis2.xml
    HostConfiguration config = client.getHostConfiguration();
    if (config == null) {
        config = new HostConfiguration();
    }

    // one might need to set his own socket factory. Let's allow that case
    // as well.
    Protocol protocolHandler = (Protocol) msgCtx.getOptions()
            .getProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER);

    // setting the real host configuration
    // I assume the 90% case, or even 99% case will be no protocol handler
    // case.
    if (protocolHandler == null) {
        config.setHost(targetURL.getHost(), port, targetURL.getProtocol());
    } else {
        config.setHost(targetURL.getHost(), port, protocolHandler);
    }

    if (isAuthenticationEnabled) {
        // Basic, Digest, NTLM and custom authentications.
        this.setAuthenticationInfo(client, msgCtx, config);
    }
    // proxy configuration

    if (HTTPProxyConfigurator.isProxyEnabled(msgCtx, targetURL)) {
        if (log.isDebugEnabled()) {
            log.debug("Configuring HTTP proxy.");
        }
        HTTPProxyConfigurator.configure(msgCtx, client, config);
    }

    return config;
}

From source file:org.apache.cactus.internal.client.connector.http.HttpClientConnectionHelper.java

/**
 * {@inheritDoc}/*from   www  .j a  v  a  2  s .  com*/
 * @see ConnectionHelper#connect(WebRequest, Configuration)
 */
public HttpURLConnection connect(WebRequest theRequest, Configuration theConfiguration) throws Throwable {
    URL url = new URL(this.url);

    HttpState state = new HttpState();

    // Choose the method that we will use to post data :
    // - If at least one parameter is to be sent in the request body, then
    //   we are doing a POST.
    // - If user data has been specified, then we are doing a POST
    if (theRequest.getParameterNamesPost().hasMoreElements() || (theRequest.getUserData() != null)) {
        this.method = new PostMethod();
    } else {
        this.method = new GetMethod();
    }

    // Add Authentication headers, if necessary. This is the first
    // step to allow authentication to add extra headers, HTTP parameters,
    // etc.
    Authentication authentication = theRequest.getAuthentication();

    if (authentication != null) {
        authentication.configure(state, this.method, theRequest, theConfiguration);
    }

    // Add the parameters that need to be passed as part of the URL
    url = HttpUtil.addHttpGetParameters(theRequest, url);

    this.method.setFollowRedirects(false);
    this.method.setPath(UrlUtil.getPath(url));
    this.method.setQueryString(UrlUtil.getQuery(url));

    // Sets the content type
    this.method.setRequestHeader("Content-type", theRequest.getContentType());

    // Add the other header fields
    addHeaders(theRequest);

    // Add the POST parameters if no user data has been specified (user data
    // overried post parameters)
    if (theRequest.getUserData() != null) {
        addUserData(theRequest);
    } else {
        addHttpPostParameters(theRequest);
    }

    // Add the cookies to the state
    state.addCookies(CookieUtil.createHttpClientCookies(theRequest, url));

    // Open the connection and get the result
    HttpClient client = new HttpClient();
    HostConfiguration hostConfiguration = new HostConfiguration();
    hostConfiguration.setHost(url.getHost(), url.getPort(), Protocol.getProtocol(url.getProtocol()));
    client.setState(state);
    client.executeMethod(hostConfiguration, this.method);

    // Wrap the HttpClient method in a java.net.HttpURLConnection object
    return new org.apache.commons.httpclient.util.HttpURLConnection(this.method, url);
}

From source file:org.apache.cocoon.generation.HttpProxyGenerator.java

/**
 * Setup this <code>Generator</code> with its runtime configurations and parameters
 * specified in the sitemap, and prepare it for generation.
 *
 * @param sourceResolver The <code>SourceResolver</code> instance resolving sources by
 *                       system identifiers.
 * @param objectModel The Cocoon "object model" <code>Map</code>
 * @param parameters The runtime <code>Parameters</code> instance.
 * @throws ProcessingException If this instance could not be setup.
 * @throws SAXException If a SAX error occurred during setup.
 * @throws IOException If an I/O error occurred during setup.
 * @see #recycle()//from w  w  w. j ava 2  s .  c om
 */
public void setup(SourceResolver sourceResolver, Map objectModel, String source, Parameters parameters)
        throws ProcessingException, SAXException, IOException {
    /* Do the usual stuff */
    super.setup(sourceResolver, objectModel, source, parameters);

    /*
     * Parameter handling: In case the method is a POST method, query
     * parameters and request parameters will be two different arrays
     * (one for the body, one for the query string, otherwise it's going
     * to be the same one, as all parameters are passed on the query string
     */
    ArrayList req = new ArrayList();
    ArrayList qry = req;
    if (this.method instanceof PostMethod)
        qry = new ArrayList();
    req.addAll(this.reqParams);
    qry.addAll(this.qryParams);

    /*
     * Parameter handling: complete or override the configured parameters with
     * those specified in the pipeline.
     */
    String names[] = parameters.getNames();
    for (int x = 0; x < names.length; x++) {
        String name = names[x];
        String value = parameters.getParameter(name, null);
        if (value == null)
            continue;

        if (name.startsWith("query:")) {
            name = name.substring("query:".length());
            qry.add(new NameValuePair(name, value));
        } else if (name.startsWith("param:")) {
            name = name.substring("param:".length());
            req.add(new NameValuePair(name, value));
        } else if (name.startsWith("query-override:")) {
            name = name.substring("query-override:".length());
            qry = overrideParams(qry, name, value);
        } else if (name.startsWith("param-override:")) {
            name = name.substring("param-override:".length());
            req = overrideParams(req, name, value);
        }
    }

    /* Process the current source URL in relation to the configured one */
    HttpURL src = (super.source == null ? null : new HttpURL(super.source));
    if (this.url != null)
        src = (src == null ? this.url : new HttpURL(this.url, src));
    if (src == null)
        throw new ProcessingException("No URL specified");
    if (src.isRelativeURI()) {
        throw new ProcessingException("Invalid URL \"" + src.toString() + "\"");
    }

    /* Configure the method with the resolved URL */
    HostConfiguration hc = new HostConfiguration();
    hc.setHost(src);
    this.method.setHostConfiguration(hc);
    this.method.setPath(src.getPath());
    this.method.setQueryString(src.getQuery());

    /* And now process the query string (from the parameters above) */
    if (qry.size() > 0) {
        String qs = this.method.getQueryString();
        NameValuePair nvpa[] = new NameValuePair[qry.size()];
        this.method.setQueryString((NameValuePair[]) qry.toArray(nvpa));
        if (qs != null) {
            this.method.setQueryString(qs + "&" + this.method.getQueryString());
        }
    }

    /* Finally process the body parameters */
    if ((this.method instanceof PostMethod) && (req.size() > 0)) {
        PostMethod post = (PostMethod) this.method;
        NameValuePair nvpa[] = new NameValuePair[req.size()];
        post.setRequestBody((NameValuePair[]) req.toArray(nvpa));
    }

    /* Check the debugging flag */
    this.debug = parameters.getParameterAsBoolean("debug", false);
}