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:net.sf.dsig.verify.OCSPHelper.java

private HostConfiguration getHostConfiguration() {
    HostConfiguration config = new HostConfiguration();

    if (proxyHost != null && proxyPort != -1) {
        logger.debug("Setting proxy" + "; proxyHost=" + proxyHost + "; proxyPort=" + proxyPort);
        config.setProxy(proxyHost, proxyPort);
    }//from  www  . j a va2 s.co m

    return config;
}

From source file:com.navercorp.pinpoint.plugin.httpclient3.HttpClientIT.java

@Test
public void hostConfig() throws Exception {
    HttpClient client = new HttpClient();
    client.getParams().setConnectionManagerTimeout(CONNECTION_TIMEOUT);
    client.getParams().setSoTimeout(SO_TIMEOUT);

    HostConfiguration config = new HostConfiguration();
    config.setHost("weather.naver.com", 80, "http");
    GetMethod method = new GetMethod("/rgn/cityWetrMain.nhn");

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    method.setQueryString(new NameValuePair[] { new NameValuePair("key2", "value2") });

    try {//from w  w w .  j  av  a  2  s .  com
        // Execute the method.
        client.executeMethod(config, method);
    } catch (Exception ignored) {
    } finally {
        method.releaseConnection();
    }

    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();
}

From source file:com.twinsoft.convertigo.engine.admin.services.mobiles.GetBuildStatus.java

@Override
protected void getServiceResult(HttpServletRequest request, Document document) throws Exception {
    String project = Keys.project.value(request);

    MobileApplication mobileApplication = getMobileApplication(project);

    if (mobileApplication == null) {
        throw new ServiceException("no such mobile application");
    } else {//  w ww  . ja  va2  s . c om
        boolean bAdminRole = Engine.authenticatedSessionManager.hasRole(request.getSession(), Role.WEB_ADMIN);
        if (!bAdminRole && mobileApplication.getAccessibility() == Accessibility.Private) {
            throw new AuthenticationException("Authentication failure: user has not sufficient rights!");
        }
    }

    String platformName = Keys.platform.value(request);

    String mobileBuilderPlatformURL = EnginePropertiesManager
            .getProperty(PropertyName.MOBILE_BUILDER_PLATFORM_URL);

    URL url = new URL(mobileBuilderPlatformURL + "/getstatus");

    HostConfiguration hostConfiguration = new HostConfiguration();
    hostConfiguration.setHost(url.getHost());
    HttpState httpState = new HttpState();
    Engine.theApp.proxyManager.setProxy(hostConfiguration, httpState, url);

    PostMethod method = new PostMethod(url.toString());

    JSONObject jsonResult;
    try {
        HeaderName.ContentType.setRequestHeader(method, MimeType.WwwForm.value());
        method.setRequestBody(new NameValuePair[] {
                new NameValuePair("application", mobileApplication.getComputedApplicationName()),
                new NameValuePair("platformName", platformName),
                new NameValuePair("auth_token", mobileApplication.getComputedAuthenticationToken()),
                new NameValuePair("endpoint", mobileApplication.getComputedEndpoint(request)) });

        int methodStatusCode = Engine.theApp.httpClient.executeMethod(hostConfiguration, method, httpState);

        InputStream methodBodyContentInputStream = method.getResponseBodyAsStream();
        byte[] httpBytes = IOUtils.toByteArray(methodBodyContentInputStream);
        String sResult = new String(httpBytes, "UTF-8");

        if (methodStatusCode != HttpStatus.SC_OK) {
            throw new ServiceException(
                    "Unable to get building status for application '" + project + "' (final app name: '"
                            + mobileApplication.getComputedApplicationName() + "').\n" + sResult);
        }

        jsonResult = new JSONObject(sResult);
    } finally {
        method.releaseConnection();
    }

    Element statusElement = document.createElement("build");
    statusElement.setAttribute(Keys.project.name(), project);
    statusElement.setAttribute(Keys.platform.name(), platformName);

    if (jsonResult.has(platformName + "_status")) {
        statusElement.setAttribute("status", jsonResult.getString(platformName + "_status"));
    } else {
        statusElement.setAttribute("status", "none");
    }

    if (jsonResult.has(platformName + "_error")) {
        statusElement.setAttribute("error", jsonResult.getString(platformName + "_error"));
    }

    statusElement.setAttribute("version", jsonResult.has("version") ? jsonResult.getString("version") : "n/a");
    statusElement.setAttribute("phonegap_version",
            jsonResult.has("phonegap_version") ? jsonResult.getString("phonegap_version") : "n/a");

    statusElement.setAttribute("revision",
            jsonResult.has("revision") ? jsonResult.getString("revision") : "n/a");
    statusElement.setAttribute("endpoint",
            jsonResult.has("endpoint") ? jsonResult.getString("endpoint") : "n/a");

    document.getDocumentElement().appendChild(statusElement);
}

From source file:com.orange.mmp.net.http.HttpConnectionManager.java

public Connection getConnection() throws MMPNetException {
    SimpleHttpConnectionManager shcm = new SimpleHttpConnectionManager();

    HttpClientParams defaultHttpParams = new HttpClientParams();
    defaultHttpParams.setParameter(HttpMethodParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    defaultHttpParams.setParameter(HttpConnectionParams.TCP_NODELAY, true);
    defaultHttpParams.setParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, false);
    defaultHttpParams.setParameter(HttpConnectionParams.SO_LINGER, 0);
    defaultHttpParams.setParameter(HttpClientParams.MAX_REDIRECTS, 3);
    defaultHttpParams.setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, false);

    HttpClient httpClient2 = new HttpClient(defaultHttpParams, shcm);

    if (HttpConnectionManager.proxyHost != null) {
        defaultHttpParams.setParameter("http.route.default-proxy",
                new HttpHost(HttpConnectionManager.proxyHost, HttpConnectionManager.proxyPort)); // TODO Host configuration !
        if (HttpConnectionManager.proxyHost != null/* && this.useProxy*/) {
            HostConfiguration config = new HostConfiguration();
            config.setProxy(HttpConnectionManager.proxyHost, HttpConnectionManager.proxyPort);
            httpClient2.setHostConfiguration(config);
        } else {/*from w w w  . j  a  va  2s. c o  m*/
            HostConfiguration config = new HostConfiguration();
            config.setProxyHost(null);
            httpClient2.setHostConfiguration(config);
        }
    }

    return new HttpConnection(httpClient2);
}

From source file:com.silverpeas.openoffice.windows.webdav.WebdavManager.java

/**
 * Prepare HTTP connections to the WebDav server
 *
 * @param host the webdav server host name.
 * @param login the login for the user on the webdav server.
 * @param password the login for the user on the webdav server.
 *//*from  w  w  w  .  j  a v a2  s .  co  m*/
public WebdavManager(String host, String login, String password) {
    HostConfiguration hostConfig = new HostConfiguration();
    hostConfig.setHost(host);
    HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    HttpConnectionManagerParams connectionParams = new HttpConnectionManagerParams();
    int maxHostConnections = 20;
    connectionParams.setMaxConnectionsPerHost(hostConfig, maxHostConnections);
    connectionManager.setParams(connectionParams);
    HttpClientParams clientParams = new HttpClientParams();
    clientParams.setParameter(HttpClientParams.CREDENTIAL_CHARSET, "UTF-8");
    clientParams.setParameter(HttpClientParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    client = new HttpClient(clientParams, connectionManager);
    Credentials creds = new UsernamePasswordCredentials(login, password);
    client.getState().setCredentials(AuthScope.ANY, creds);
    client.setHostConfiguration(hostConfig);
}

From source file:com.twinsoft.convertigo.engine.admin.services.mobiles.GetPackage.java

@Override
protected void writeResponseResult(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String project = Keys.project.value(request);

    MobileApplication mobileApplication = GetBuildStatus.getMobileApplication(project);

    if (mobileApplication == null) {
        throw new ServiceException("no such mobile application");
    } else {/*from   ww  w .  jav a  2 s  .  c  om*/
        boolean bAdminRole = Engine.authenticatedSessionManager.hasRole(request.getSession(), Role.WEB_ADMIN);
        if (!bAdminRole && mobileApplication.getAccessibility() == Accessibility.Private) {
            throw new AuthenticationException("Authentication failure: user has not sufficient rights!");
        }
    }

    String platformName = Keys.platform.value(request);
    String finalApplicationName = mobileApplication.getComputedApplicationName();

    String mobileBuilderPlatformURL = EnginePropertiesManager
            .getProperty(PropertyName.MOBILE_BUILDER_PLATFORM_URL);

    PostMethod method;
    int methodStatusCode;
    InputStream methodBodyContentInputStream;

    URL url = new URL(mobileBuilderPlatformURL + "/getpackage");

    HostConfiguration hostConfiguration = new HostConfiguration();
    hostConfiguration.setHost(new URI(url.toString(), true));
    HttpState httpState = new HttpState();
    Engine.theApp.proxyManager.setProxy(hostConfiguration, httpState, url);

    method = new PostMethod(url.toString());

    try {
        HeaderName.ContentType.setRequestHeader(method, MimeType.WwwForm.value());
        method.setRequestBody(new NameValuePair[] { new NameValuePair("application", finalApplicationName),
                new NameValuePair("platformName", platformName),
                new NameValuePair("auth_token", mobileApplication.getComputedAuthenticationToken()),
                new NameValuePair("endpoint", mobileApplication.getComputedEndpoint(request)) });

        methodStatusCode = Engine.theApp.httpClient.executeMethod(hostConfiguration, method, httpState);
        methodBodyContentInputStream = method.getResponseBodyAsStream();

        if (methodStatusCode != HttpStatus.SC_OK) {
            byte[] httpBytes = IOUtils.toByteArray(methodBodyContentInputStream);
            String sResult = new String(httpBytes, "UTF-8");
            throw new ServiceException("Unable to get package for project '" + project + "' (final app name: '"
                    + finalApplicationName + "').\n" + sResult);
        }

        try {
            String contentDisposition = method.getResponseHeader(HeaderName.ContentDisposition.value())
                    .getValue();
            HeaderName.ContentDisposition.setHeader(response, contentDisposition);
        } catch (Exception e) {
            HeaderName.ContentDisposition.setHeader(response, "attachment; filename=\"" + project + "\"");
        }

        try {
            response.setContentType(method.getResponseHeader(HeaderName.ContentType.value()).getValue());
        } catch (Exception e) {
            response.setContentType(MimeType.OctetStream.value());
        }

        OutputStream responseOutputStream = response.getOutputStream();
        IOUtils.copy(methodBodyContentInputStream, responseOutputStream);
    } catch (IOException ioex) { // Fix for ticket #4698
        if (!ioex.getClass().getSimpleName().equalsIgnoreCase("ClientAbortException")) {
            // fix for #5042
            throw ioex;
        }
    } finally {
        method.releaseConnection();
    }
}

From source file:com.jivesoftware.os.jive.utils.http.client.ApacheHttpClient31BackedHttpClientTest.java

@Test(expectedExceptions = HttpClientException.class)
public void testGetThrowsException() throws Exception {
    ApacheHttpClient31BackedHttpClient client = new ApacheHttpClient31BackedHttpClient(httpClient,
            new HashMap<String, String>());

    final String path = "/path/to/endpoint";

    HostConfiguration hostConfiguration = new HostConfiguration();
    hostConfiguration.setHost("foobar.com", 3456, Protocol.getProtocol("http"));
    when(httpClient.getHostConfiguration()).thenReturn(hostConfiguration);
    when(httpClient.executeMethod(Matchers.<HttpMethod>any())).thenThrow(new IOException());

    client.get(path);/*from  ww w  .j a va  2s. c o  m*/
}

From source file:com.twistbyte.affiliate.HttpUtility.java

/**
 * Do a get request to the given url and set the header values passed
 *
 * @param url//from w w w .j a va2s.c  om
 * @param headerValues
 * @return
 */
public HttpResult doGet(String url, Map<String, String> headerValues) {

    String resp = "";

    logger.info("url : " + url);
    GetMethod method = new GetMethod(url);

    logger.info("Now use connection timeout: " + connectionTimeout);
    httpclient.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, connectionTimeout);

    if (headerValues != null) {
        for (Map.Entry<String, String> entry : headerValues.entrySet()) {

            method.setRequestHeader(entry.getKey(), entry.getValue());
        }
    }

    HttpResult serviceResult = new HttpResult();
    serviceResult.setSuccess(false);
    serviceResult.setHttpStatus(404);
    Reader reader = null;
    try {

        int result = httpclient.executeMethod(new HostConfiguration(), method, new HttpState());
        logger.info("http result : " + result);
        resp = method.getResponseBodyAsString();

        logger.info("response: " + resp);

        serviceResult.setHttpStatus(result);
        serviceResult.setBody(resp);
        serviceResult.setSuccess(200 == serviceResult.getHttpStatus());
    } catch (java.net.ConnectException ce) {
        logger.warn("ConnectException: " + ce.getMessage());
    } catch (IOException e) {
        logger.error("IOException sending request to " + url + " Reason:" + e.getMessage(), e);
    } finally {
        method.releaseConnection();
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {

            }
        }
    }

    return serviceResult;
}

From source file:jhc.redsniff.webdriver.download.FileDownloader.java

private HostConfiguration mimicHostConfiguration(String hostURL, int hostPort) {
    HostConfiguration hostConfig = new HostConfiguration();
    hostConfig.setHost(hostURL, hostPort);
    return hostConfig;
}

From source file:com.basus.fins.data.YahooQuote.java

public void initQuote() {
    yahooHost = new HostConfiguration();
    method = new GetMethod();
    client = new HttpClient();

    yahooHost.setHost(quoteParams.getHostUri());
    quoteParams.createQueryString();//from   w ww.ja v  a  2 s  . c o m
    try {
        method.setPath(URIUtil.encodePathQuery(quoteParams.getPath()));
        method.setQueryString(URIUtil.encodePathQuery(strQuery));
    } catch (URIException uriEx) {
        log.error(uriEx);
    }
}