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

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

Introduction

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

Prototype

public HostConfiguration getHostConfiguration()

Source Link

Usage

From source file:com.nokia.carbide.installpackages.InstallPackages.java

public static void setProxyData(HttpClient client, GetMethod getMethod) {
    java.net.URI uri = getURI(getMethod);
    if (uri == null)
        return;/* w  ww.j a va 2 s .c o  m*/
    IProxyData proxyData = ProxyUtils.getProxyData(uri);
    if (proxyData == null)
        return;
    String host = proxyData.getHost();
    int port = proxyData.getPort();
    client.getHostConfiguration().setProxy(host, port);
    if (proxyData.isRequiresAuthentication()) {
        String userId = proxyData.getUserId();
        String password = proxyData.getPassword();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userId, password);
        AuthScope authScope = new AuthScope(host, port);
        client.getState().setCredentials(authScope, credentials);
        getMethod.setDoAuthentication(true);
    }
}

From source file:com.atlassian.connector.intellij.util.HttpClientFactory.java

public static HttpClient getClient() throws HttpProxySettingsException {
    HttpClient httpClient = new HttpClient(connectionManager);
    httpClient.getParams().setConnectionManagerTimeout(getConnectionManagerTimeout());
    httpClient.getParams().setSoTimeout(getDataTimeout());
    HttpConfigurableAdapter httpConfigurableAdapter = ConfigurationFactory.getConfiguration()
            .transientGetHttpConfigurable();
    boolean useIdeaProxySettings = ConfigurationFactory.getConfiguration().getGeneralConfigurationData()
            .getUseIdeaProxySettings();//from  w w w. j  ava  2  s .  c o  m
    if (useIdeaProxySettings && (httpConfigurableAdapter != null)) {
        if (httpConfigurableAdapter.isUseHttpProxy()) {
            httpClient.getHostConfiguration().setProxy(httpConfigurableAdapter.getProxyHost(),
                    httpConfigurableAdapter.getProxyPort());
            if (httpConfigurableAdapter.isProxyAuthentication()) {

                if (httpConfigurableAdapter.getPlainProxyPassword().length() == 0
                        && !httpConfigurableAdapter.isKeepProxyPassowrd()) { //ask user for proxy passowrd

                    throw new HttpProxySettingsException("HTTP Proxy password is incorrect");
                }

                Credentials creds = null;

                //
                // code below stolen from AXIS: /transport/http/CommonsHTTPSender.java
                //
                String proxyUser = httpConfigurableAdapter.getProxyLogin();
                int domainIndex = proxyUser.indexOf("\\");
                if (domainIndex > 0) {
                    // if the username is in the form "user\domain"
                    // then use NTCredentials instead of UsernamePasswordCredentials
                    String domain = proxyUser.substring(0, domainIndex);
                    if (proxyUser.length() > domainIndex + 1) {
                        String user = proxyUser.substring(domainIndex + 1);
                        creds = new NTCredentials(user, httpConfigurableAdapter.getPlainProxyPassword(),
                                httpConfigurableAdapter.getProxyHost(), domain);
                    }
                } else {
                    creds = new UsernamePasswordCredentials(proxyUser,
                            httpConfigurableAdapter.getPlainProxyPassword());
                }
                //
                // end of code stolen from AXIS
                //

                httpClient.getState().setProxyCredentials(new AuthScope(httpConfigurableAdapter.getProxyHost(),
                        httpConfigurableAdapter.getProxyPort()), creds);
            }
        }
    }

    return httpClient;
}

From source file:com.urswolfer.intellij.plugin.gerrit.rest.GerritApiUtil.java

@NotNull
private static HttpClient getHttpClient(@Nullable final String login, @Nullable final String password) {
    final HttpClient client = new HttpClient();
    HttpConnectionManagerParams params = client.getHttpConnectionManager().getParams();
    params.setConnectionTimeout(CONNECTION_TIMEOUT); //set connection timeout (how long it takes to connect to remote host)
    params.setSoTimeout(CONNECTION_TIMEOUT); //set socket timeout (how long it takes to retrieve data from remote host)

    client.getParams().setContentCharset("UTF-8");
    // Configure proxySettings if it is required
    final HttpConfigurable proxySettings = HttpConfigurable.getInstance();
    if (proxySettings.USE_HTTP_PROXY && !StringUtil.isEmptyOrSpaces(proxySettings.PROXY_HOST)) {
        client.getHostConfiguration().setProxy(proxySettings.PROXY_HOST, proxySettings.PROXY_PORT);
        if (proxySettings.PROXY_AUTHENTICATION) {
            client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                    proxySettings.PROXY_LOGIN, proxySettings.getPlainProxyPassword()));
        }//www .  j av  a 2  s  .  c  om
    }
    if (login != null && password != null) {
        client.getParams().setCredentialCharset("UTF-8");
        client.getParams().setAuthenticationPreemptive(true);
        client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(login, password));
    }
    return client;
}

From source file:es.uvigo.ei.sing.jarvest.core.HTTPUtils.java

public synchronized static InputStream doPost(String urlstring, String queryString, String separator,
        Map<String, String> additionalHeaders, StringBuffer charsetb) throws HttpException, IOException {
    System.err.println("posting to: " + urlstring + ". query string: " + queryString);
    HashMap<String, String> query = parseQueryString(queryString, separator);
    HttpClient client = getClient();

    URL url = new URL(urlstring);
    int port = url.getPort();
    if (port == -1) {
        if (url.getProtocol().equalsIgnoreCase("http")) {
            port = 80;// w ww .j  a v  a  2s .co  m
        }
        if (url.getProtocol().equalsIgnoreCase("https")) {
            port = 443;
        }
    }

    client.getHostConfiguration().setHost(url.getHost(), port, url.getProtocol());
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

    final PostMethod post = new PostMethod(url.getFile());
    addHeaders(additionalHeaders, post);
    post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    post.setRequestHeader("Accept", "*/*");
    // Prepare login parameters
    NameValuePair[] valuePairs = new NameValuePair[query.size()];

    int counter = 0;

    for (String key : query.keySet()) {
        //System.out.println("Adding pair: "+key+": "+query.get(key));
        valuePairs[counter++] = new NameValuePair(key, query.get(key));

    }

    post.setRequestBody(valuePairs);
    //authpost.setRequestEntity(new StringRequestEntity(requestEntity));

    client.executeMethod(post);

    int statuscode = post.getStatusCode();
    InputStream toret = null;
    if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
            || (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
        Header header = post.getResponseHeader("location");
        if (header != null) {
            String newuri = header.getValue();
            if ((newuri == null) || (newuri.equals(""))) {
                newuri = "/";
            }

        } else {
            System.out.println("Invalid redirect");
            System.exit(1);
        }
    } else {
        charsetb.append(post.getResponseCharSet());
        final InputStream in = post.getResponseBodyAsStream();

        toret = new InputStream() {

            @Override
            public int read() throws IOException {
                return in.read();
            }

            @Override
            public void close() {
                post.releaseConnection();
            }

        };

    }

    return toret;
}

From source file:davmail.http.DavGatewayHttpClientFacade.java

/**
 * Set http client current host configuration.
 *
 * @param httpClient current Http client
 * @param url        target url//from w w  w.j a v a  2  s. c o  m
 * @throws DavMailException on error
 */
public static void setClientHost(HttpClient httpClient, String url) throws DavMailException {
    try {
        HostConfiguration hostConfig = httpClient.getHostConfiguration();
        URI httpURI = new URI(url, true);
        hostConfig.setHost(httpURI);
    } catch (URIException e) {
        throw new DavMailException("LOG_INVALID_URL", url);
    }
}

From source file:edu.ucsb.eucalyptus.admin.server.EucalyptusManagement.java

private static String getExternalIpAddress() {
    String ipAddr = null;/*from ww w  . j av a 2s. c o m*/
    HttpClient httpClient = new HttpClient();
    //support for http proxy
    if (HttpServerBootstrapper.httpProxyHost != null && (HttpServerBootstrapper.httpProxyHost.length() > 0)) {
        String proxyHost = HttpServerBootstrapper.httpProxyHost;
        if (HttpServerBootstrapper.httpProxyPort != null
                && (HttpServerBootstrapper.httpProxyPort.length() > 0)) {
            int proxyPort = Integer.parseInt(HttpServerBootstrapper.httpProxyPort);
            httpClient.getHostConfiguration().setProxy(proxyHost, proxyPort);
        } else {
            httpClient.getHostConfiguration().setProxyHost(new ProxyHost(proxyHost));
        }
    }
    // Use Rightscale's "whoami" service
    GetMethod method = new GetMethod("https://my.rightscale.com/whoami?api_version=1.0&cloud=0");
    Integer timeoutMs = new Integer(3 * 1000); // TODO: is this working?
    method.getParams().setSoTimeout(timeoutMs);

    try {
        httpClient.executeMethod(method);
        String str = "";
        InputStream in = method.getResponseBodyAsStream();
        byte[] readBytes = new byte[1024];
        int bytesRead = -1;
        while ((bytesRead = in.read(readBytes)) > 0) {
            str += new String(readBytes, 0, bytesRead);
        }
        Matcher matcher = Pattern.compile(".*your ip is (.*)").matcher(str);
        if (matcher.find()) {
            ipAddr = matcher.group(1);
        }

    } catch (MalformedURLException e) {
        LOG.warn("Malformed URL exception: " + e.getMessage());
        e.printStackTrace();

    } catch (IOException e) {
        LOG.warn("I/O exception: " + e.getMessage());
        e.printStackTrace();

    } finally {
        method.releaseConnection();
    }

    return ipAddr;
}

From source file:liveplugin.toolwindow.addplugin.git.jetbrains.plugins.github.api.GithubApiUtil.java

@NotNull
private static HttpClient getHttpClient(@Nullable GithubAuthData.BasicAuth basicAuth, boolean useProxy) {
    int timeout = GithubSettings.getInstance().getConnectionTimeout();
    final HttpClient client = new HttpClient();
    HttpConnectionManagerParams params = client.getHttpConnectionManager().getParams();
    params.setConnectionTimeout(timeout); //set connection timeout (how long it takes to connect to remote host)
    params.setSoTimeout(timeout); //set socket timeout (how long it takes to retrieve data from remote host)

    client.getParams().setContentCharset("UTF-8");
    // Configure proxySettings if it is required
    final HttpConfigurable proxySettings = HttpConfigurable.getInstance();
    if (useProxy && proxySettings.USE_HTTP_PROXY && !StringUtil.isEmptyOrSpaces(proxySettings.PROXY_HOST)) {
        client.getHostConfiguration().setProxy(proxySettings.PROXY_HOST, proxySettings.PROXY_PORT);
        if (proxySettings.PROXY_AUTHENTICATION) {
            client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                    proxySettings.PROXY_LOGIN, proxySettings.getPlainProxyPassword()));
        }//from  ww  w .j  a  va  2  s.c  o  m
    }
    if (basicAuth != null) {
        client.getParams().setCredentialCharset("UTF-8");
        client.getParams().setAuthenticationPreemptive(true);
        client.getState().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(basicAuth.getLogin(), basicAuth.getPassword()));
    }
    return client;
}

From source file:com.mindquarry.desktop.util.HttpUtilities.java

private static HttpClient createHttpClient(String login, String pwd, String address)
        throws MalformedURLException {
    URL url = new URL(address);

    HttpClient client = new HttpClient();
    client.getParams().setSoTimeout(SOCKET_TIMEOUT);
    client.getParams().setParameter("http.connection.timeout", CONNECTION_TIMEOUT);
    client.getParams().setAuthenticationPreemptive(true);
    client.getState().setCredentials(new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM),
            new UsernamePasswordCredentials(login, pwd));

    // apply proxy settings if necessary
    if ((store != null) && (store.getBoolean(ProxySettingsPage.PREF_PROXY_ENABLED))) {
        URL proxyUrl = new URL(store.getString(ProxySettingsPage.PREF_PROXY_URL));
        String proxyLogin = store.getString(ProxySettingsPage.PREF_PROXY_LOGIN);
        String proxyPwd = store.getString(ProxySettingsPage.PREF_PROXY_PASSWORD);

        client.getHostConfiguration().setProxy(proxyUrl.getHost(), proxyUrl.getPort());
        client.getState().setProxyCredentials(new AuthScope(proxyUrl.getHost(), proxyUrl.getPort()),
                new UsernamePasswordCredentials(proxyLogin, proxyPwd));
    }/*  ww w .  j  a  v  a2 s . com*/
    return client;
}

From source file:com.collabnet.tracker.common.httpClient.TrackerHttpSender.java

public static void setupHttpClient(HttpClient client, String repositoryUrl, String user, String password) {

    setupHttpClientParams(client, null);

    if (user != null && password != null) {
        AuthScope authScope = new AuthScope(getDomain(repositoryUrl), getPort(repositoryUrl),
                AuthScope.ANY_REALM);/*w w w  .j  a  v a  2s  . c o m*/
        try {
            client.getState().setCredentials(authScope,
                    getCredentials(user, password, InetAddress.getLocalHost()));
        } catch (UnknownHostException e) {
            client.getState().setCredentials(authScope, getCredentials(user, password, null));
        }
    }

    if (isRepositoryHttps(repositoryUrl)) {
        Protocol acceptAllSsl = new Protocol("https",
                (ProtocolSocketFactory) SslProtocolSocketFactory.getInstance(), getPort(repositoryUrl));
        client.getHostConfiguration().setHost(getDomain(repositoryUrl), getPort(repositoryUrl), acceptAllSsl);
        Protocol.registerProtocol("https", acceptAllSsl);
    } else {
        client.getHostConfiguration().setHost(getDomain(repositoryUrl), getPort(repositoryUrl));
    }
}

From source file:com.zimbra.cs.util.SpamExtract.java

private static void extract(String authToken, Account account, Server server, String query, File outdir,
        boolean delete, boolean raw) throws ServiceException, HttpException, SoapFaultException, IOException {
    String soapURL = getSoapURL(server, false);

    URL restURL = getServerURL(server, false);
    HttpClient hc = new HttpClient(); // CLI only, don't need conn mgr
    HttpState state = new HttpState();
    GetMethod gm = new GetMethod();
    gm.setFollowRedirects(true);//from  www  . j a v a  2  s.c om
    Cookie authCookie = new Cookie(restURL.getHost(), ZimbraCookie.COOKIE_ZM_AUTH_TOKEN, authToken, "/", -1,
            false);
    state.addCookie(authCookie);
    hc.setState(state);
    hc.getHostConfiguration().setHost(restURL.getHost(), restURL.getPort(),
            Protocol.getProtocol(restURL.getProtocol()));
    gm.getParams().setSoTimeout(60000);

    if (verbose) {
        LOG.info("Mailbox requests to: " + restURL);
    }

    SoapHttpTransport transport = new SoapHttpTransport(soapURL);
    transport.setRetryCount(1);
    transport.setTimeout(0);
    transport.setAuthToken(authToken);

    int totalProcessed = 0;
    boolean haveMore = true;
    int offset = 0;
    while (haveMore) {
        Element searchReq = new Element.XMLElement(MailConstants.SEARCH_REQUEST);
        searchReq.addElement(MailConstants.A_QUERY).setText(query);
        searchReq.addAttribute(MailConstants.A_SEARCH_TYPES, MailItem.Type.MESSAGE.toString());
        searchReq.addAttribute(MailConstants.A_QUERY_OFFSET, offset);
        searchReq.addAttribute(MailConstants.A_LIMIT, BATCH_SIZE);

        try {
            if (LOG.isDebugEnabled()) {
                LOG.debug(searchReq.prettyPrint());
            }
            Element searchResp = transport.invoke(searchReq, false, true, account.getId());
            if (LOG.isDebugEnabled()) {
                LOG.debug(searchResp.prettyPrint());
            }

            StringBuilder deleteList = new StringBuilder();

            List<String> ids = new ArrayList<String>();
            for (Iterator<Element> iter = searchResp.elementIterator(MailConstants.E_MSG); iter.hasNext();) {
                offset++;
                Element e = iter.next();
                String mid = e.getAttribute(MailConstants.A_ID);
                if (mid == null) {
                    LOG.warn("null message id SOAP response");
                    continue;
                }

                LOG.debug("adding id %s", mid);
                ids.add(mid);
                if (ids.size() >= BATCH_SIZE || !iter.hasNext()) {
                    StringBuilder path = new StringBuilder("/service/user/" + account.getName()
                            + "/?fmt=tgz&list=" + StringUtils.join(ids, ","));
                    LOG.debug("sending request for path %s", path.toString());
                    List<String> extractedIds = extractMessages(hc, gm, path.toString(), outdir, raw);
                    if (ids.size() > extractedIds.size()) {
                        ids.removeAll(extractedIds);
                        LOG.warn("failed to extract %s", ids);
                    }
                    for (String id : extractedIds) {
                        deleteList.append(id).append(',');
                    }

                    ids.clear();
                }
                totalProcessed++;
            }

            haveMore = false;
            String more = searchResp.getAttribute(MailConstants.A_QUERY_MORE);
            if (more != null && more.length() > 0) {
                try {
                    int m = Integer.parseInt(more);
                    if (m > 0) {
                        haveMore = true;
                        try {
                            Thread.sleep(SLEEP_TIME);
                        } catch (InterruptedException e) {
                        }
                    }
                } catch (NumberFormatException nfe) {
                    LOG.warn("more flag from server not a number: " + more, nfe);
                }
            }

            if (delete && deleteList.length() > 0) {
                deleteList.deleteCharAt(deleteList.length() - 1); // -1 removes trailing comma
                Element msgActionReq = new Element.XMLElement(MailConstants.MSG_ACTION_REQUEST);
                Element action = msgActionReq.addElement(MailConstants.E_ACTION);
                action.addAttribute(MailConstants.A_ID, deleteList.toString());
                action.addAttribute(MailConstants.A_OPERATION, ItemAction.OP_HARD_DELETE);

                if (LOG.isDebugEnabled()) {
                    LOG.debug(msgActionReq.prettyPrint());
                }
                Element msgActionResp = transport.invoke(msgActionReq, false, true, account.getId());
                if (LOG.isDebugEnabled()) {
                    LOG.debug(msgActionResp.prettyPrint());
                }
                offset = 0; //put offset back to 0 so we always get top N messages even after delete
            }
        } finally {
            gm.releaseConnection();
        }

    }
    LOG.info("Total messages processed: " + totalProcessed);
}