Example usage for org.apache.commons.httpclient SimpleHttpConnectionManager getParams

List of usage examples for org.apache.commons.httpclient SimpleHttpConnectionManager getParams

Introduction

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

Prototype

public HttpConnectionManagerParams getParams() 

Source Link

Usage

From source file:jp.go.nict.langrid.servicesupervisor.invocationprocessor.executor.ServiceInvoker.java

/**
 * /*  w  w  w.  j a  v a 2s  . c o  m*/
 * 
 */
public static int invoke(URL url, String userName, String password, Map<String, String> headers,
        InputStream input, HttpServletResponse output, OutputStream errorOut, int connectionTimeout,
        int soTimeout) throws IOException, SocketTimeoutException {
    HttpClient client = HttpClientUtil.createHttpClientWithHostConfig(url);
    SimpleHttpConnectionManager manager = new SimpleHttpConnectionManager(true);
    manager.getParams().setConnectionTimeout(connectionTimeout);
    manager.getParams().setSoTimeout(soTimeout);
    manager.getParams().setMaxConnectionsPerHost(client.getHostConfiguration(), 2);
    client.setHttpConnectionManager(manager);
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(0, false));

    PostMethod method = new PostMethod(url.getFile());
    method.setRequestEntity(new InputStreamRequestEntity(input));
    for (Map.Entry<String, String> e : headers.entrySet()) {
        method.addRequestHeader(e.getKey(), e.getValue());
    }
    if (!headers.containsKey("Content-Type"))
        method.addRequestHeader("Content-Type", "text/xml; charset=utf-8");
    if (!headers.containsKey("Accept"))
        method.addRequestHeader("Accept", "application/soap+xml, application/dime, multipart/related, text/*");
    if (!headers.containsKey("SOAPAction"))
        method.addRequestHeader("SOAPAction", "\"\"");
    if (!headers.containsKey("User-Agent"))
        method.addRequestHeader("User-Agent", "Langrid Service Invoker/1.0");
    if (userName != null) {
        int port = url.getPort();
        if (port == -1) {
            port = url.getDefaultPort();
            if (port == -1) {
                port = 80;
            }
        }
        if (password == null) {
            password = "";
        }
        client.getState().setCredentials(new AuthScope(url.getHost(), port, null),
                new UsernamePasswordCredentials(userName, password));
        client.getParams().setAuthenticationPreemptive(true);
        method.setDoAuthentication(true);
    }

    try {
        int status;
        try {
            status = client.executeMethod(method);
        } catch (SocketTimeoutException e) {
            status = HttpServletResponse.SC_REQUEST_TIMEOUT;
        }
        output.setStatus(status);
        if (status == 200) {
            for (Header h : method.getResponseHeaders()) {
                String name = h.getName();
                if (name.startsWith("X-Langrid") || (!throughHeaders.contains(name.toLowerCase())))
                    continue;
                String value = h.getValue();
                output.addHeader(name, value);
            }
            OutputStream os = output.getOutputStream();
            StreamUtil.transfer(method.getResponseBodyAsStream(), os);
            os.flush();
        } else if (status == HttpServletResponse.SC_REQUEST_TIMEOUT) {
        } else {
            StreamUtil.transfer(method.getResponseBodyAsStream(), errorOut);
        }
        return status;
    } finally {
        manager.shutdown();
    }
}

From source file:edu.utah.further.core.ws.HttpUtil.java

/**
 * Open an HTTP GET method connection to a URL and read the returned response into an
 * object./*from  w w  w .ja v  a  2 s.  co m*/
 * 
 * @param <T>
 *            return type
 * @param url
 *            remote URL (usually a web service's URL)
 * @param timeoutSecs
 *            HTTP socket connection timeout [seconds]
 * @return <code>HttpClient</code> {@link HttpMethod} transfer object, containing the
 *         response headers and body
 * @throws WsException
 *             if an error as occurred either in transport or protocol
 */
public static HttpResponseTo getHttpGetResponseBody(final String url, final int timeoutSecs)
        throws WsException {
    // Create an instance of HttpClient with appropriate parameters
    final SimpleHttpConnectionManager cm = new SimpleHttpConnectionManager();
    final HttpConnectionManagerParams params = cm.getParams();
    params.setConnectionTimeout(timeoutSecs * 1000);
    params.setSoTimeout(timeoutSecs * 1000);
    cm.setParams(params);
    final HttpClient client = new HttpClient(cm);

    // Create a method instance
    final GetMethod method = new GetMethod(url);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(NUMBER_HTTP_REQUEST_TRIALS, false));
    try {
        // Execute the method
        /* final int statusCode = */client.executeMethod(method);
        // if (statusCode != HttpStatus.SC_OK)
        // {
        // log.error("Method failed: " + method.getStatusLine());
        // }
        return new HttpResponseTo(method);
    } catch (final HttpException e) {
        // HTTP protocol violation (e.g. bad method?!)
        throw new WsException(PROTOCOL_VIOLATION, e.getMessage());
    } catch (final IOException e) {
        // Transport error. Could be an invalid URL
        throw new WsException(TRANSPORT_ERROR, e.getMessage());
    } catch (final Throwable e) {
        // Exceptions
        throw new WsException(SERVER_ERROR, e.getMessage());
    } finally {
        // Important: release the connection
        method.releaseConnection();
    }
}

From source file:org.apache.ode.tools.sendsoap.cline.HttpSoapSender.java

public static String doSend(URL u, InputStream is, String proxyServer, int proxyPort, String username,
        String password, String soapAction) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream(8192);
    StreamUtils.copy(bos, is);//from  w ww.j  a v  a  2  s .  c  om
    String now = Long.toString(System.currentTimeMillis());
    int c = 1;
    String data = new String(bos.toByteArray());
    Matcher m = SEQ.matcher(data);
    StringBuffer sb = new StringBuffer(8192);
    while (m.find()) {
        m.appendReplacement(sb, now + "-" + c++);
    }
    m.appendTail(sb);
    SimpleHttpConnectionManager mgr = new SimpleHttpConnectionManager();
    try {
        mgr.getParams().setConnectionTimeout(60000);
        mgr.getParams().setSoTimeout(60000);
        HttpClient httpClient = new HttpClient(mgr);
        PostMethod httpPostMethod = new PostMethod(u.toExternalForm());
        if (proxyServer != null && proxyServer.length() > 0) {
            httpClient.getState().setCredentials(new AuthScope(proxyServer, proxyPort),
                    new UsernamePasswordCredentials(username, password));
            httpPostMethod.setDoAuthentication(true);
        }
        if (soapAction == null)
            soapAction = "";
        httpPostMethod.setRequestHeader("SOAPAction", "\"" + soapAction + "\"");
        httpPostMethod.setRequestHeader("Content-Type", "text/xml");
        httpPostMethod.setRequestEntity(new StringRequestEntity(sb.toString()));
        httpClient.executeMethod(httpPostMethod);
        return httpPostMethod.getResponseBodyAsString() + "\n";
    } finally {
        mgr.shutdown();
    }
}

From source file:org.cloudfoundry.identity.uaa.login.saml.SamlIdentityProviderConfigurator.java

protected ExtendedMetadataDelegate configureURLMetadata(SamlIdentityProviderDefinition def)
        throws MetadataProviderException {
    Class<ProtocolSocketFactory> socketFactory = null;
    try {/*  w w w. ja v  a 2  s  . c o m*/
        def = def.clone();
        socketFactory = (Class<ProtocolSocketFactory>) Class.forName(def.getSocketFactoryClassName());
        ExtendedMetadata extendedMetadata = new ExtendedMetadata();
        extendedMetadata.setAlias(def.getIdpEntityAlias());
        SimpleHttpConnectionManager connectionManager = new SimpleHttpConnectionManager(true);
        connectionManager.getParams().setDefaults(getClientParams());
        HttpClient client = new HttpClient(connectionManager);
        FixedHttpMetaDataProvider fixedHttpMetaDataProvider = new FixedHttpMetaDataProvider(dummyTimer, client,
                adjustURIForPort(def.getMetaDataLocation()));
        fixedHttpMetaDataProvider.setSocketFactory(socketFactory.newInstance());
        byte[] metadata = fixedHttpMetaDataProvider.fetchMetadata();
        def.setMetaDataLocation(new String(metadata, StandardCharsets.UTF_8));
        return configureXMLMetadata(def);
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("Invalid socket factory(invalid URI):" + def.getMetaDataLocation(),
                e);
    } catch (ClassNotFoundException e) {
        throw new IllegalArgumentException("Invalid socket factory:" + def.getSocketFactoryClassName(), e);
    } catch (InstantiationException e) {
        throw new IllegalArgumentException("Invalid socket factory:" + def.getSocketFactoryClassName(), e);
    } catch (IllegalAccessException e) {
        throw new IllegalArgumentException("Invalid socket factory:" + def.getSocketFactoryClassName(), e);
    }
}

From source file:org.cloudfoundry.identity.uaa.provider.saml.FixedHttpMetaDataProvider.java

public static FixedHttpMetaDataProvider buildProvider(Timer backgroundTaskTimer, HttpClientParams params,
        String metadataURL, RestTemplate template, UrlContentCache cache) throws MetadataProviderException {
    SimpleHttpConnectionManager connectionManager = new SimpleHttpConnectionManager(true);
    connectionManager.getParams().setDefaults(params);
    HttpClient client = new HttpClient(connectionManager);
    return new FixedHttpMetaDataProvider(backgroundTaskTimer, client, metadataURL, template, cache);
}