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:sos.scheduler.job.JobSchedulerCheckUpdates.java

private int sendRequest(final String contentType, final String url) throws Exception {
    int rc = 0;//from   w  w  w.  j a v  a2 s . c o m

    try {

        spooler_log_debug3("... Send request:" + url);
        PostMethod post = new PostMethod(url);
        post.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(contentType.getBytes())));
        post.setRequestHeader("Content-type", "xml");

        HttpClient httpClient = new HttpClient();
        if (!http_proxy.equals("")) {
            httpClient.getHostConfiguration().setProxy(http_proxy, http_proxy_port);
        }
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(timeout);

        // deprecated httpClient.setTimeout(30*1000);
        rc = httpClient.executeMethod(post);
        spooler_log_debug3("... request (flgOperationWasSuccessful):" + rc);

        getResponse(post.getResponseBodyAsStream());
        return rc;

    } catch (Exception e) {
        throw new Exception(
                "could not connect to SOS Web Service, an error occurred in HTTP POST: " + e.getMessage());
    }
}

From source file:test.integ.be.fedict.eid.idp.OpenIDAssociationsTest.java

@Test
public void testEstablishAssociation() throws Exception {
    // setup//w w  w .  j  a v  a 2s .c  o m
    AssociationSessionType associationSessionType = AssociationSessionType.NO_ENCRYPTION_SHA1MAC;
    String opEndpoint = "https://www.e-contract.be/eid-idp/protocol/openid/auth";

    // operate
    DiffieHellmanSession dhSession;
    if (null != associationSessionType.getHAlgorithm()) {
        // Diffie-Hellman
        DHParameterSpec dhParameterSpec = DiffieHellmanSession.getDefaultParameter();
        dhSession = DiffieHellmanSession.create(associationSessionType, dhParameterSpec);

    } else {
        dhSession = null;
    }
    AssociationRequest associationRequest = AssociationRequest.createAssociationRequest(associationSessionType,
            dhSession);
    LOG.debug("association type: " + associationRequest.getType().getAssociationType());
    LOG.debug("session type: " + associationRequest.getType().getSessionType());

    Map<String, String> parameters = associationRequest.getParameterMap();

    HttpClient httpClient = new HttpClient();
    httpClient.getHostConfiguration().setProxy("proxy.yourict.net", 8080);
    PostMethod postMethod = new PostMethod(opEndpoint);
    for (Map.Entry<String, String> parameter : parameters.entrySet()) {
        postMethod.addParameter(parameter.getKey(), parameter.getValue());
    }

    int statusCode = httpClient.executeMethod(postMethod);
    LOG.debug("status code: " + statusCode);
    assertEquals(HttpURLConnection.HTTP_OK, statusCode);

    postMethod.getResponseBody();

    ParameterList responseParameterList = ParameterList
            .createFromKeyValueForm(postMethod.getResponseBodyAsString());
    AssociationResponse associationResponse = AssociationResponse
            .createAssociationResponse(responseParameterList);

    Association association = associationResponse.getAssociation(dhSession);
    LOG.debug("association type: " + association.getType());
    LOG.debug("association handle: " + association.getHandle());
    LOG.debug("association expiry: " + association.getExpiry());
    SecretKey secretKey = association.getMacKey();
    LOG.debug("association MAC key algo: " + secretKey.getAlgorithm());
}

From source file:test.integ.be.fedict.eid.idp.OpenIDAssociationsTest.java

/**
 * http://code.google.com/p/openid4java/issues/detail?id=192
 * /*from w w w  .j  av a2 s  .c  o m*/
 * @throws Exception
 */
@Test
public void testEstablishAssociationSteam() throws Exception {
    // setup
    AssociationSessionType associationSessionType = AssociationSessionType.NO_ENCRYPTION_SHA1MAC;
    String opEndpoint = "https://steamcommunity.com/openid/login";

    // operate
    DiffieHellmanSession dhSession;
    if (null != associationSessionType.getHAlgorithm()) {
        // Diffie-Hellman
        DHParameterSpec dhParameterSpec = DiffieHellmanSession.getDefaultParameter();
        dhSession = DiffieHellmanSession.create(associationSessionType, dhParameterSpec);

    } else {
        dhSession = null;
    }
    AssociationRequest associationRequest = AssociationRequest.createAssociationRequest(associationSessionType,
            dhSession);
    LOG.debug("association type: " + associationRequest.getType().getAssociationType());
    LOG.debug("session type: " + associationRequest.getType().getSessionType());

    Map<String, String> parameters = associationRequest.getParameterMap();

    HttpClient httpClient = new HttpClient();
    httpClient.getHostConfiguration().setProxy("proxy.yourict.net", 8080);
    PostMethod postMethod = new PostMethod(opEndpoint);
    for (Map.Entry<String, String> parameter : parameters.entrySet()) {
        postMethod.addParameter(parameter.getKey(), parameter.getValue());
    }

    int statusCode = httpClient.executeMethod(postMethod);
    LOG.debug("status code: " + statusCode);
    assertEquals(HttpURLConnection.HTTP_OK, statusCode);

    postMethod.getResponseBody();

    ParameterList responseParameterList = ParameterList
            .createFromKeyValueForm(postMethod.getResponseBodyAsString());
    AssociationResponse associationResponse = AssociationResponse
            .createAssociationResponse(responseParameterList);

    Association association = associationResponse.getAssociation(dhSession);
    LOG.debug("association type: " + association.getType());
    LOG.debug("association handle: " + association.getHandle());
    LOG.debug("association expiry: " + association.getExpiry());
    SecretKey secretKey = association.getMacKey();
    LOG.debug("association MAC key algo: " + secretKey.getAlgorithm());
}

From source file:test.integ.be.fedict.trust.TSATest.java

@Test
public void testTSA() throws Exception {

    // setup//ww w  .j a va 2 s .  c  o  m
    TimeStampRequestGenerator requestGen = new TimeStampRequestGenerator();
    requestGen.setCertReq(true);
    TimeStampRequest request = requestGen.generate(TSPAlgorithms.SHA1, new byte[20], BigInteger.valueOf(100));
    byte[] requestData = request.getEncoded();

    HttpClient httpClient = new HttpClient();
    httpClient.getHostConfiguration().setProxy("proxy.yourict.net", 8080);
    PostMethod postMethod = new PostMethod(tsa_location);
    postMethod.setRequestEntity(new ByteArrayRequestEntity(requestData, "application/timestamp-query"));

    // operate
    int statusCode = httpClient.executeMethod(postMethod);
    if (statusCode != HttpStatus.SC_OK) {
        LOG.error("Error contacting TSP server " + tsa_location);
        throw new Exception("Error contacting TSP server " + tsa_location);
    }

    TimeStampResponse tspResponse = new TimeStampResponse(postMethod.getResponseBodyAsStream());
    postMethod.releaseConnection();

    CertStore certStore = tspResponse.getTimeStampToken().getCertificatesAndCRLs("Collection", "BC");

    Collection<? extends Certificate> certificates = certStore.getCertificates(null);
    List<X509Certificate> certificateChain = new LinkedList<X509Certificate>();
    for (Certificate certificate : certificates) {
        LOG.debug("certificate: " + certificate.toString());
        certificateChain.add(0, (X509Certificate) certificate);
    }

    LOG.debug("token received");
    // send token to trust service
    XKMS2Client client = new XKMS2Client("https://www.e-contract.be/eid-trust-service-ws/xkms2");
    client.setProxy("proxy.yourict.net", 8080);
    client.validate(TrustServiceDomains.BELGIAN_TSA_TRUST_DOMAIN, certificateChain, true);
}

From source file:uk.co.firstzero.webdav.Common.java

/**
 * Sets the proxy params//from  ww  w  .  j  ava 2s .  c  o m
 * @param httpClient The HTTP Client transport to use
 * @param proxyHost Proxy host
 * @param proxyPort Proxy port
 * @param proxyUser Proxy user
 * @param proxyPassword Proxy password
 * @return
 */
public static HttpClient setProxy(HttpClient httpClient, String proxyHost, int proxyPort, String proxyUser,
        String proxyPassword) {
    logger.trace("proxyHost is " + proxyHost);
    logger.trace("proxyPort is " + proxyPort);
    logger.trace("proxyUser is " + proxyUser);

    if (proxyHost != null && proxyPort != Integer.MIN_VALUE) {
        logger.trace("Setting up proxy");

        Credentials credsProxy;

        if (proxyUser != null)
            credsProxy = new UsernamePasswordCredentials(proxyUser, proxyPassword);
        else {
            logger.trace("proxyUser is null");
            credsProxy = new UsernamePasswordCredentials("", "");
        }

        logger.trace("Applying host and port proxy");
        httpClient.getHostConfiguration().setProxy(proxyHost, proxyPort);

        logger.trace("Applying authentication scope and credentials");
        httpClient.getState().setCredentials(new AuthScope(proxyHost, proxyPort), credsProxy);
    }

    logger.trace("Completed setup of proxy");
    return httpClient;
}

From source file:velo.adapters.GenericHttpClientAdapter.java

public boolean connect() throws AdapterException {
    logger.fine("Connecting by '" + GenericHttpClientAdapter.class.getName() + "', to Resource: '"
            + getResource().getDisplayName() + "'");
    String host = getResourceDescriptor().getString("specific.host");
    Integer port = getResourceDescriptor().getInt("specific.port");
    String protocol = getResourceDescriptor().getString("specific.protocol");

    if (logger.isLoggable(Level.FINEST)) {
        logger.finest("Connecting to host: " + host);
        logger.finest("Connecting with host: " + port);
        logger.finest("Connecting with protocol: " + protocol);
    }/*from   w w w. j  a v a  2s .  co  m*/

    HttpClient client = new HttpClient();
    client.getHostConfiguration().setHost(host, port, protocol);
    //Set by default coockie policy to 'browser_compatibility'
    //needed?      client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

    setConnected(true);
    setHttpClient(client);

    return true;
}

From source file:voldemort.performance.HttpClientBench.java

private static HttpClient createClient() {
    HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    HttpClient httpClient = new HttpClient(connectionManager);
    HttpClientParams clientParams = httpClient.getParams();
    clientParams.setConnectionManagerTimeout(DEFAULT_CONNECTION_MANAGER_TIMEOUT);
    clientParams.setSoTimeout(500);/*from ww w. j  av  a  2s .c om*/
    clientParams.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));
    clientParams.setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
    clientParams.setBooleanParameter("http.tcp.nodelay", false);
    clientParams.setIntParameter("http.socket.receivebuffer", 60000);
    clientParams.setParameter("http.useragent", VOLDEMORT_USER_AGENT);
    HostConfiguration hostConfig = new HostConfiguration();
    hostConfig.setHost("localhost");
    hostConfig.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
    httpClient.setHostConfiguration(hostConfig);
    HttpConnectionManagerParams managerParams = httpClient.getHttpConnectionManager().getParams();
    managerParams.setConnectionTimeout(DEFAULT_CONNECTION_MANAGER_TIMEOUT);
    managerParams.setMaxTotalConnections(DEFAULT_MAX_CONNECTIONS);
    managerParams.setMaxConnectionsPerHost(httpClient.getHostConfiguration(), DEFAULT_MAX_HOST_CONNECTIONS);
    managerParams.setStaleCheckingEnabled(false);

    return httpClient;
}

From source file:voldemort.performance.RemoteStoreComparisonTest.java

public static void main(String[] args) throws Exception {
    if (args.length != 2)
        Utils.croak("USAGE: java " + RemoteStoreComparisonTest.class.getName()
                + " numRequests numThreads [useNio]");

    int numRequests = Integer.parseInt(args[0]);
    int numThreads = Integer.parseInt(args[1]);
    boolean useNio = args.length > 2 ? args[2].equals("true") : false;

    /** * In memory test ** */
    final Store<byte[], byte[], byte[]> memStore = new InMemoryStorageEngine<byte[], byte[], byte[]>("test");
    PerformanceTest memWriteTest = new PerformanceTest() {

        @Override// w  ww. j a v a2 s.  com
        public void doOperation(int i) {
            byte[] key = String.valueOf(i).getBytes();
            memStore.put(key, new Versioned<byte[]>(key), null);
        }
    };
    System.out.println("###########################################");
    System.out.println("Performing memory write test.");
    memWriteTest.run(numRequests, numThreads);
    memWriteTest.printStats();
    System.out.println();

    PerformanceTest memReadTest = new PerformanceTest() {

        @Override
        public void doOperation(int i) {
            try {
                memStore.get(String.valueOf(i).getBytes(), null);
            } catch (Exception e) {
                System.out.println("Failure on i = " + i);
                e.printStackTrace();
            }
        }
    };
    System.out.println("Performing memory read test.");
    memReadTest.run(numRequests, numThreads);
    memReadTest.printStats();
    System.out.println();
    System.out.println();

    /** * Do Socket tests ** */
    String storeName = "test";
    StoreRepository repository = new StoreRepository();
    repository.addLocalStore(new InMemoryStorageEngine<ByteArray, byte[], byte[]>(storeName));
    SocketStoreFactory storeFactory = new ClientRequestExecutorPool(10, 1000, 1000, 32 * 1024);
    final Store<ByteArray, byte[], byte[]> socketStore = storeFactory.create(storeName, "localhost", 6666,
            RequestFormatType.VOLDEMORT_V1, RequestRoutingType.NORMAL);
    RequestHandlerFactory factory = ServerTestUtils.getSocketRequestHandlerFactory(repository);
    AbstractSocketService socketService = ServerTestUtils.getSocketService(useNio, factory, 6666, 50, 50, 1000);
    socketService.start();

    PerformanceTest socketWriteTest = new PerformanceTest() {

        @Override
        public void doOperation(int i) {
            byte[] bytes = String.valueOf(i).getBytes();
            ByteArray key = new ByteArray(bytes);
            socketStore.put(key, new Versioned<byte[]>(bytes), null);
        }
    };
    System.out.println("###########################################");
    System.out.println("Performing socket write test.");
    socketWriteTest.run(numRequests, numThreads);
    socketWriteTest.printStats();
    System.out.println();

    PerformanceTest socketReadTest = new PerformanceTest() {

        @Override
        public void doOperation(int i) {
            try {
                socketStore.get(TestUtils.toByteArray(String.valueOf(i)), null);
            } catch (Exception e) {
                System.out.println("Failure on i = " + i);
                e.printStackTrace();
            }
        }
    };
    System.out.println("Performing socket read test.");
    socketReadTest.run(numRequests, 1);
    socketReadTest.printStats();
    System.out.println();
    System.out.println();

    socketStore.close();
    storeFactory.close();
    socketService.stop();

    /** * Do HTTP tests ** */
    repository.addLocalStore(new InMemoryStorageEngine<ByteArray, byte[], byte[]>(storeName));
    HttpService httpService = new HttpService(null, null, repository, RequestFormatType.VOLDEMORT_V0,
            numThreads, 8080);
    httpService.start();
    HttpClient httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());
    HttpClientParams clientParams = httpClient.getParams();
    clientParams.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));
    clientParams.setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
    clientParams.setParameter("http.useragent", "test-agent");
    HostConfiguration hostConfig = new HostConfiguration();
    hostConfig.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
    httpClient.setHostConfiguration(hostConfig);
    HttpConnectionManagerParams managerParams = httpClient.getHttpConnectionManager().getParams();
    managerParams.setConnectionTimeout(10000);
    managerParams.setMaxTotalConnections(numThreads);
    managerParams.setStaleCheckingEnabled(false);
    managerParams.setMaxConnectionsPerHost(httpClient.getHostConfiguration(), numThreads);
    final HttpStore httpStore = new HttpStore("test", "localhost", 8080, httpClient,
            new RequestFormatFactory().getRequestFormat(RequestFormatType.VOLDEMORT_V0), false);
    Thread.sleep(400);

    PerformanceTest httpWriteTest = new PerformanceTest() {

        @Override
        public void doOperation(int i) {
            byte[] key = String.valueOf(i).getBytes();
            httpStore.put(new ByteArray(key), new Versioned<byte[]>(key), null);
        }
    };
    System.out.println("###########################################");
    System.out.println("Performing HTTP write test.");
    httpWriteTest.run(numRequests, numThreads);
    httpWriteTest.printStats();
    System.out.println();

    PerformanceTest httpReadTest = new PerformanceTest() {

        @Override
        public void doOperation(int i) {
            httpStore.get(new ByteArray(String.valueOf(i).getBytes()), null);
        }
    };
    System.out.println("Performing HTTP read test.");
    httpReadTest.run(numRequests, numThreads);
    httpReadTest.printStats();

    httpService.stop();
}