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:jenkins.plugins.office365connector.HttpWorker.java

private HttpClient getHttpClient() {
    HttpClient client = new HttpClient();
    Jenkins jen = Jenkins.getInstance();
    if (jen != null) {
        ProxyConfiguration proxy;//from   ww w.ja  v  a  2s . c o m
        proxy = jen.proxy;
        if (proxy != null) {
            client.getHostConfiguration().setProxy(proxy.name, proxy.port);
            String username = proxy.getUserName();
            String password = proxy.getPassword();
            // Consider it to be passed if username specified. Sufficient?
            if (StringUtils.isNotBlank(username)) {
                client.getState().setProxyCredentials(AuthScope.ANY,
                        new UsernamePasswordCredentials(username, password));
            }
        }
    }
    return client;
}

From source file:com.antelink.sourcesquare.query.RestClient.java

protected RestTemplate getTemplate(String baseDomain) {
    HttpClient client = new HttpClient();

    // Managing HTTP proxy - if any
    String proxyHost = System.getProperty("http.proxyHost");
    String proxyPort = System.getProperty("http.proxyPort");
    if (proxyHost != null && proxyPort != null) {
        client.getHostConfiguration().setProxy(proxyHost, Integer.parseInt(proxyPort));
    }//from   w  w w .j a  v  a  2  s .  c om

    // Managing HTTP proxy authentication - if any
    String proxyUser = System.getProperty("http.proxyUser");
    String proxyPassword = System.getProperty("http.proxyPassword");
    AuthScope auth;
    if (proxyHost != null && proxyUser != null && proxyPassword != null) {
        auth = new AuthScope(proxyHost, Integer.parseInt(proxyPort));
        client.getState().setProxyCredentials(auth, new UsernamePasswordCredentials(proxyUser, proxyPassword));
    } else {
        auth = new AuthScope(baseDomain, AuthScope.ANY_PORT);
        client.getState().setCredentials(auth, null);
    }

    CommonsClientHttpRequestFactory commons = new CommonsClientHttpRequestFactory(client) {
        @Override
        public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
            ClientHttpRequest createRequest = super.createRequest(uri, httpMethod);
            createRequest.getHeaders().add("User-Agent", "SourceSquare");
            return createRequest;
        }
    };
    return new RestTemplate(commons);
}

From source file:com.google.api.ads.dfp.lib.AuthToken.java

/**
 * Sets the proxy for the HTTP client./*  w  w  w . j a v  a 2  s .co m*/
 *
 * @param httpClient the HTTP client to set the proxy for
 */
private void setProxy(HttpClient httpClient) {
    if (System.getProperty("http.proxyHost") != null && System.getProperty("http.proxyPort") != null) {
        httpClient.getHostConfiguration().setProxy(System.getProperty("http.proxyHost"),
                Integer.parseInt(System.getProperty("http.proxyPort")));

        if (System.getProperty("http.proxyUser") != null && System.getProperty("http.proxyPassword") != null) {
            HttpState state = new HttpState();
            state.setProxyCredentials(
                    new AuthScope(System.getProperty("http.proxyHost"),
                            Integer.parseInt(System.getProperty("http.proxyPort"))),
                    new UsernamePasswordCredentials(System.getProperty("http.proxyUser"),
                            System.getProperty("http.proxyPassword")));
            httpClient.setState(state);
        }
    }
}

From source file:com.epam.wilma.gepard.testclient.HttpPostRequestSender.java

/**
 * Sends a new HTTP request to a server through a proxy. Also logs request and response with gepard framework.
 *
 * @param tc                is the caller Test Case.
 * @param requestParameters a set of parameters that will set the content of the request
 *                          and specify the proxy it should go through
 * @return with Response Holder class.//from w w w . java 2s  . c om
 * @throws IOException                  in case error occurs
 * @throws ParserConfigurationException in case error occurs
 * @throws SAXException                 in case error occurs
 */
public ResponseHolder callWilmaTestServer(final WilmaTestCase tc, final RequestParameters requestParameters)
        throws IOException, ParserConfigurationException, SAXException {
    String responseCode;
    ResponseHolder responseMessage;

    HttpClient httpClient = new HttpClient();
    PostMethod httpPost = new PostMethod(requestParameters.getTestServerUrl());
    if (requestParameters.isUseProxy()) {
        httpClient.getHostConfiguration().setProxy(requestParameters.getWilmaHost(),
                requestParameters.getWilmaPort());
    }
    createRequest(requestParameters, httpPost);
    tc.logPostRequestEvent(requestParameters); //this dumps the request

    String sendBuffer;
    try {
        sendBuffer = tc.getTestClassExecutionData().getEnvironment().getProperty("http.socket.sendbuffer");
    } catch (NullPointerException e) {
        sendBuffer = DEFAULT_BUFFER_SIZE_STRING;
    }
    String receiveBuffer;
    try {
        receiveBuffer = tc.getTestClassExecutionData().getEnvironment()
                .getProperty("http.socket.receivebuffer");
    } catch (NullPointerException e) {
        receiveBuffer = DEFAULT_BUFFER_SIZE_STRING;
    }

    httpClient.getHttpConnectionManager().getParams().setSendBufferSize(Integer.valueOf(sendBuffer));
    httpClient.getHttpConnectionManager().getParams().setReceiveBufferSize(Integer.valueOf(receiveBuffer));
    int statusCode;
    statusCode = httpClient.executeMethod(httpPost);
    responseCode = "status code: " + statusCode + "\n";
    responseMessage = createResponse(httpPost);
    responseMessage.setResponseCode(responseCode);
    tc.setActualResponseCode(statusCode);
    Header contentTypeHeader = httpPost.getResponseHeader("Content-Type");
    if (contentTypeHeader != null) {
        tc.setActualResponseContentType(contentTypeHeader.getValue());
    }
    Header sequenceHeader = httpPost.getResponseHeader("Wilma-Sequence");
    if (sequenceHeader != null) {
        tc.setActualDialogDescriptor(sequenceHeader.getValue());
    }
    tc.logResponseEvent(responseMessage); //this dumps the response

    return responseMessage;
}

From source file:net.sf.taverna.raven.plugins.PluginManager.java

public static void setProxy(HttpClient client) {
    String host = System.getProperty("http.proxyHost");
    String port = System.getProperty("http.proxyPort");
    String user = System.getProperty("http.proxyUser");
    String password = System.getProperty("http.proxyPassword");

    if (host != null && port != null) {
        try {//from www.  ja  va2s.  co m
            int portInteger = Integer.parseInt(port);
            client.getHostConfiguration().setProxy(host, portInteger);
            if (user != null && password != null) {
                client.getState().setProxyCredentials(new AuthScope(host, portInteger),
                        new UsernamePasswordCredentials(user, password));
            }
        } catch (NumberFormatException e) {
            logger.error("Proxy port not an integer", e);
        }
    }
}

From source file:com.benfante.jslideshare.SlideShareConnectorImpl.java

private HttpClient createHttpClient() {
    HttpClient client = new HttpClient();
    client.getParams().setSoTimeout(this.soTimeout);
    if (this.getProxyHost() != null) {
        client.getHostConfiguration().setProxy(this.proxyHost, this.proxyPort);
        if (this.proxyUsername != null && this.proxyPassword != null) {
            client.getState().setProxyCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(this.proxyUsername, this.proxyPassword));
        }/*  w  w w.j a va2 s  . com*/
    }
    return client;
}

From source file:com.kodokux.github.api.GithubApiUtil.java

@NotNull
private static HttpClient getHttpClient(@Nullable GithubAuthData.BasicAuth basicAuth, boolean useProxy) {
    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 (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()));
        }//  ww w .j a v  a2 s .  c  om
    }
    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.alternatecomputing.jschnizzle.renderer.YUMLRenderer.java

public BufferedImage render(Diagram diagram) {
    String script = diagram.getScript();
    if (script == null) {
        throw new RendererException("no script defined.");
    }//from ww w  . j  av a 2s  .c  o  m
    StringTokenizer st = new StringTokenizer(script.trim(), "\n");
    StringBuilder buffer = new StringBuilder();
    while (st.hasMoreTokens()) {
        String token = st.nextToken();
        if (token.startsWith("#")) {
            continue; // skip over comments
        }
        buffer.append(token.trim());
        if (st.hasMoreTokens()) {
            buffer.append(", ");
        }
    }
    buffer.append(".svg");

    String style = diagram.getStyle().getValue();
    String baseURL = getBaseURL();
    try {
        HttpClient client = new HttpClient();
        String proxyHost = System.getProperty("http.proxyHost");
        String proxyPort = System.getProperty("http.proxyPort");
        if (StringUtils.isNotBlank(proxyHost) && StringUtils.isNotBlank(proxyPort)) {
            client.getHostConfiguration().setProxy(proxyHost, Integer.parseInt(proxyPort));
        }

        String postURI = baseURL + "diagram/" + style + "/" + diagram.getType().getUrlModifier() + "/";
        LOGGER.debug(postURI);
        PostMethod postMethod = new PostMethod(postURI);
        postMethod.addParameter("dsl_text", buffer.toString());
        client.executeMethod(postMethod);
        String svgResourceName = postMethod.getResponseBodyAsString();
        postMethod.releaseConnection();
        LOGGER.debug(svgResourceName);

        String getURI = baseURL + svgResourceName;
        LOGGER.debug(getURI);
        GetMethod getMethod = new GetMethod(getURI);
        client.executeMethod(getMethod);
        String svgContents = getMethod.getResponseBodyAsString();
        getMethod.releaseConnection();
        LOGGER.debug(svgContents);

        diagram.setEncodedImage(svgContents);
        TranscoderInput input = new TranscoderInput(new ByteArrayInputStream(svgContents.getBytes()));
        BufferedImageTranscoder imageTranscoder = new BufferedImageTranscoder();
        imageTranscoder.transcode(input, null);

        return imageTranscoder.getBufferedImage();
    } catch (MalformedURLException e) {
        throw new RendererException(e);
    } catch (IOException e) {
        throw new RendererException(e);
    } catch (TranscoderException e) {
        throw new RendererException(e);
    }
}

From source file:com.intellij.tasks.impl.BaseRepositoryImpl.java

protected void configureHttpClient(HttpClient client) {
    client.getParams().setConnectionManagerTimeout(3000);
    client.getParams().setSoTimeout(TaskSettings.getInstance().CONNECTION_TIMEOUT);
    if (isUseProxy()) {
        HttpConfigurable proxy = HttpConfigurable.getInstance();
        client.getHostConfiguration().setProxy(proxy.PROXY_HOST, proxy.PROXY_PORT);
        if (proxy.PROXY_AUTHENTICATION) {
            AuthScope authScope = new AuthScope(proxy.PROXY_HOST, proxy.PROXY_PORT);
            Credentials credentials = getCredentials(proxy.getProxyLogin(), proxy.getPlainProxyPassword(),
                    proxy.PROXY_HOST);/*from w  w  w  .j  av  a  2 s  .  com*/
            client.getState().setProxyCredentials(authScope, credentials);
        }
    }
    if (isUseHttpAuthentication()) {
        client.getParams().setCredentialCharset("UTF-8");
        client.getParams().setAuthenticationPreemptive(true);
        client.getState().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(getUsername(), getPassword()));
    } else {
        client.getState().clearCredentials();
        client.getParams().setAuthenticationPreemptive(false);
    }
}

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

private static List<DownloadsWeb> getDownloadsFromUrl(final String downloadsUrl) {
    List<DownloadsWeb> downloadsList = new ArrayList<DownloadsWeb>();

    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 {//  w  w w  . ja  v a2 s .co  m
            httpClient.getHostConfiguration().setProxyHost(new ProxyHost(proxyHost));
        }
    }
    GetMethod method = new GetMethod(downloadsUrl);
    Integer timeoutMs = new Integer(3 * 1000);
    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);
        }
        String entries[] = str.split("[\\r\\n]+");
        for (int i = 0; i < entries.length; i++) {
            String entry[] = entries[i].split("\\t");
            if (entry.length == 3) {
                downloadsList.add(new DownloadsWeb(entry[0], entry[1], entry[2]));
            }
        }

    } 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 downloadsList;
}