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:com.exalead.io.failover.MonitoredHttpConnectionManager.java

public synchronized void addHost(URI uri, int power) {
    HostState hs = new HostState();
    hs.configuration = new HostConfiguration();
    hs.configuration.setHost(uri);/*from  w  ww .  j  a v  a 2 s.  c o  m*/

    hs.power = power;

    if (hostsMap.containsKey(hs.configuration)) {
        throw new IllegalArgumentException("Host: " + uri.toString() + " already exists");
    }

    hosts.add(hs);

    for (int i = 0; i < power; i++)
        hostsForSelection.add(hs);

    hostsMap.put(hs.configuration, hs);
    nextToMonitorList.add(hs);
}

From source file:dk.netarkivet.viewerproxy.WebProxyTester.java

/**
 * Test the general integration of the WebProxy access through the running Jetty true:
 *//*w  ww .  j  av  a2s .c  o m*/
@Test
public void testJettyIntegration() throws Exception {
    TestURIResolver uriResolver = new TestURIResolver();
    proxy = new WebProxy(uriResolver);

    try {
        new Socket(InetAddress.getLocalHost(), httpPort);
    } catch (IOException e) {
        fail("Port not in use after starting server");
    }

    // GET request
    HttpClient client = new HttpClient();
    HostConfiguration hc = new HostConfiguration();
    String hostName = SystemUtils.getLocalHostName();
    hc.setProxy(hostName, httpPort);
    client.setHostConfiguration(hc);
    GetMethod get = new GetMethod("http://foo.bar/");
    client.executeMethod(get);

    assertEquals("Status code should be what URI resolver gives", 242, get.getStatusCode());
    assertEquals("Body should contain what URI resolver wrote", "Test", get.getResponseBodyAsString());
    get.releaseConnection();

    // POST request
    PostMethod post = new PostMethod("http://foo2.bar/");
    post.addParameter("a", "x");
    post.addParameter("a", "y");
    client.executeMethod(post);

    // Check request received by URIResolver
    assertEquals("URI resolver lookup should be called.", 2, uriResolver.lookupCount);
    assertEquals("URI resolver lookup should be called with right URI.", new URI("http://foo2.bar/"),
            uriResolver.lookupRequestArgument);
    assertEquals("Posted parameter should be received.", 1, uriResolver.lookupRequestParameteres.size());
    assertNotNull("Posted parameter should be received.", uriResolver.lookupRequestParameteres.get("a"));
    assertEquals("Posted parameter should be received.", 2,
            uriResolver.lookupRequestParameteres.get("a").length);
    assertEquals("Posted parameter should be received.", "x", uriResolver.lookupRequestParameteres.get("a")[0]);
    assertEquals("Posted parameter should be received.", "y", uriResolver.lookupRequestParameteres.get("a")[1]);
    assertEquals("Status code should be what URI resolver gives", 242, post.getStatusCode());
    assertEquals("Body should contain what URI resolver wrote", "Test", post.getResponseBodyAsString());
    post.releaseConnection();

    // Request with parameter and portno
    get = new GetMethod("http://foo2.bar:8090/?baz=boo");
    client.executeMethod(get);

    // Check request received by URIResolver
    assertEquals("URI resolver lookup should be called.", 3, uriResolver.lookupCount);
    assertEquals("URI resolver 2 lookup should be called with right URI.",
            new URI("http://foo2.bar:8090/?baz=boo"), uriResolver.lookupRequestArgument);
    assertEquals("Status code should be what URI resolver gives", 242, get.getStatusCode());
    assertEquals("Body should contain what URI resolver wrote", "Test", get.getResponseBodyAsString());
    get.releaseConnection();
}

From source file:games.strategy.triplea.pbem.AxisAndAlliesForumPoster.java

/**
 * Logs into axisandallies.org//from w  ww  .j  a v  a2s. c o m
 * nb: Username and password are posted in clear text
 * 
 * @throws Exception
 *             if login fails
 */
private void login() throws Exception {
    // creates and configures a new http client
    m_client = new HttpClient();
    m_client.getParams().setParameter("http.protocol.single-cookie-header", true);
    m_client.getParams().setParameter("http.useragent",
            "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)");
    m_httpState = new HttpState();
    m_hostConfiguration = new HostConfiguration();
    // add the proxy
    GameRunner2.addProxy(m_hostConfiguration);
    m_hostConfiguration.setHost("www.axisandallies.org");

    final PostMethod post = new PostMethod("http://www.axisandallies.org/forums/index.php?action=login2");
    try {
        post.addRequestHeader("Accept", "*/*");
        post.addRequestHeader("Accept-Language", "en-us");
        post.addRequestHeader("Cache-Control", "no-cache");
        post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        final List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        parameters.add(new NameValuePair("user", getUsername()));
        parameters.add(new NameValuePair("passwrd", getPassword()));
        post.setRequestBody(parameters.toArray(new NameValuePair[parameters.size()]));

        int status = m_client.executeMethod(m_hostConfiguration, post, m_httpState);
        if (status == 200) {
            final String body = post.getResponseBodyAsString();
            if (body.toLowerCase().contains("password incorrect")) {
                throw new Exception("Incorrect Password");
            }
            // site responds with 200, and a refresh header
            final Header refreshHeader = post.getResponseHeader("Refresh");
            if (refreshHeader == null) {
                throw new Exception("Missing refresh header after login");
            }

            final String value = refreshHeader.getValue(); // refresh: 0; URL=http://...
            final Pattern p = Pattern.compile("[^;]*;\\s*url=(.*)", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
            final Matcher m = p.matcher(value);
            if (m.matches()) {
                final String url = m.group(1);
                final GetMethod getRefreshPage = new GetMethod(url);

                try {
                    status = m_client.executeMethod(m_hostConfiguration, getRefreshPage, m_httpState);
                    if (status != 200) {
                        // something is probably wrong, but there is not much we can do about it, we handle errors when we post
                    }
                } finally {
                    getRefreshPage.releaseConnection();
                }
            } else {
                throw new Exception("The refresh header didn't contain a URL");
            }
        } else {
            throw new Exception("Failed to login to forum, server responded with status code: " + status);
        }
    } finally {
        post.releaseConnection();
    }
}

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

@Test(expectedExceptions = HttpClientException.class)
public void testPostJsonStringThrowsException() 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("https"));
    when(httpClient.getHostConfiguration()).thenReturn(hostConfiguration);
    when(httpClient.executeMethod(Matchers.<HttpMethod>any())).thenThrow(new IOException());

    client.postJson(path, "body");
}

From source file:com.twinsoft.convertigo.beans.core.RequestableStep.java

@Override
public RequestableStep clone() throws CloneNotSupportedException {
    RequestableStep clonedObject = (RequestableStep) super.clone();
    clonedObject.vVariables = new LinkedList<StepVariable>();
    clonedObject.vAllVariables = null;//from ww w.ja  v a2  s.c  o  m
    clonedObject.xmlHttpDocument = null;
    clonedObject.hostConfiguration = new HostConfiguration();
    clonedObject.targetUrl = null;
    clonedObject.method = null;
    return clonedObject;
}

From source file:com.eviware.soapui.impl.wsdl.monitor.jettyproxy.TunnelServlet.java

public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
    monitor.fireOnRequest(request, response);
    if (response.isCommitted())
        return;/*  ww w . j  av a2  s.  com*/

    ExtendedHttpMethod postMethod;

    // for this create ui server and port, properties.
    InetSocketAddress inetAddress = new InetSocketAddress(sslEndPoint, sslPort);
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    if (httpRequest.getMethod().equals("GET"))
        postMethod = new ExtendedGetMethod();
    else
        postMethod = new ExtendedPostMethod();

    JProxyServletWsdlMonitorMessageExchange capturedData = new JProxyServletWsdlMonitorMessageExchange(project);
    capturedData.setRequestHost(httpRequest.getRemoteHost());
    capturedData.setRequestHeader(httpRequest);
    capturedData.setTargetURL(this.prot + inetAddress.getHostName());

    CaptureInputStream capture = new CaptureInputStream(httpRequest.getInputStream());

    // copy headers
    Enumeration<?> headerNames = httpRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String hdr = (String) headerNames.nextElement();
        String lhdr = hdr.toLowerCase();

        if ("host".equals(lhdr)) {
            Enumeration<?> vals = httpRequest.getHeaders(hdr);
            while (vals.hasMoreElements()) {
                String val = (String) vals.nextElement();
                if (val.startsWith("127.0.0.1")) {
                    postMethod.addRequestHeader(hdr, sslEndPoint);
                }
            }
            continue;
        }

        Enumeration<?> vals = httpRequest.getHeaders(hdr);
        while (vals.hasMoreElements()) {
            String val = (String) vals.nextElement();
            if (val != null) {
                postMethod.addRequestHeader(hdr, val);
            }
        }

    }

    if (postMethod instanceof ExtendedPostMethod)
        ((ExtendedPostMethod) postMethod)
                .setRequestEntity(new InputStreamRequestEntity(capture, request.getContentType()));

    HostConfiguration hostConfiguration = new HostConfiguration();

    httpRequest.getProtocol();
    hostConfiguration.getParams().setParameter(SoapUIHostConfiguration.SOAPUI_SSL_CONFIG,
            settings.getString(SecurityTabForm.SSLTUNNEL_KEYSTOREPATH, "") + " "
                    + settings.getString(SecurityTabForm.SSLTUNNEL_KEYSTOREPASSWORD, ""));
    hostConfiguration.setHost(new URI(this.prot + sslEndPoint, true));

    hostConfiguration = ProxyUtils.initProxySettings(settings, httpState, hostConfiguration, prot + sslEndPoint,
            new DefaultPropertyExpansionContext(project));

    if (sslEndPoint.indexOf("/") < 0)
        postMethod.setPath("/");
    else
        postMethod.setPath(sslEndPoint.substring(sslEndPoint.indexOf("/"), sslEndPoint.length()));

    monitor.fireBeforeProxy(request, response, postMethod, hostConfiguration);

    if (settings.getBoolean(LaunchForm.SSLTUNNEL_REUSESTATE)) {
        if (httpState == null)
            httpState = new HttpState();
        HttpClientSupport.getHttpClient().executeMethod(hostConfiguration, postMethod, httpState);
    } else {
        HttpClientSupport.getHttpClient().executeMethod(hostConfiguration, postMethod);
    }
    capturedData.stopCapture();

    capturedData.setRequest(capture.getCapturedData());
    capturedData.setRawResponseBody(postMethod.getResponseBody());
    capturedData.setResponseHeader(postMethod);
    capturedData.setRawRequestData(getRequestToBytes(request.toString(), postMethod, capture));
    capturedData.setRawResponseData(
            getResponseToBytes(response.toString(), postMethod, capturedData.getRawResponseBody()));

    monitor.fireAfterProxy(request, response, postMethod, capturedData);

    StringToStringsMap responseHeaders = capturedData.getResponseHeaders();
    // copy headers to response
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    for (String name : responseHeaders.keySet()) {
        for (String header : responseHeaders.get(name))
            httpResponse.addHeader(name, header);

    }

    IO.copy(new ByteArrayInputStream(capturedData.getRawResponseBody()), httpResponse.getOutputStream());

    postMethod.releaseConnection();

    synchronized (this) {
        monitor.addMessageExchange(capturedData);
    }

    capturedData = null;
}

From source file:com.predic8.membrane.integration.AccessControlInterceptorIntegrationTest.java

private HttpClient getClient(byte[] ip) throws UnknownHostException {
    HttpClient client = new HttpClient();
    HostConfiguration config = new HostConfiguration();
    config.setLocalAddress(InetAddress.getByAddress(ip));
    client.setHostConfiguration(config);
    return client;
}

From source file:com.exalead.io.failover.MonitoredHttpConnectionManager.java

public synchronized void addHost(String host, int port, int power) {
    HostState hs = new HostState();
    hs.configuration = new HostConfiguration();
    hs.configuration.setHost(host, port);

    hs.power = power;/*from w ww .  j  a  va 2s .  co  m*/

    if (hostsMap.containsKey(hs.configuration)) {
        throw new IllegalArgumentException("Host: " + host + ":" + port + " already exists");
    }

    hosts.add(hs);

    for (int i = 0; i < power; i++)
        hostsForSelection.add(hs);

    hostsMap.put(hs.configuration, hs);
    nextToMonitorList.add(hs);
}

From source file:com.smartitengineering.util.rest.client.jersey.cache.CustomApacheHttpClientResponseResolver.java

/**
 * Determines the HttpClient's request method from the HTTPMethod enum.
 *
 * @param method     the HTTPCache enum that determines
 * @param requestURI the request URI./*from  www  .  j av a2s .c om*/
 * @return a new HttpMethod subclass.
 */
protected HttpMethod getMethod(HTTPMethod method, URI requestURI) {
    if (CONNECT.equals(method)) {
        HostConfiguration config = new HostConfiguration();
        config.setHost(requestURI.getHost(), requestURI.getPort(), requestURI.getScheme());
        return new ConnectMethod(config);
    } else if (DELETE.equals(method)) {
        return new CustomHttpMethod(HTTPMethod.DELETE.name(), requestURI.toString());
    } else if (GET.equals(method)) {
        return new GetMethod(requestURI.toString());
    } else if (HEAD.equals(method)) {
        return new HeadMethod(requestURI.toString());
    } else if (OPTIONS.equals(method)) {
        return new OptionsMethod(requestURI.toString());
    } else if (POST.equals(method)) {
        return new PostMethod(requestURI.toString());
    } else if (PUT.equals(method)) {
        return new PutMethod(requestURI.toString());
    } else if (TRACE.equals(method)) {
        return new TraceMethod(requestURI.toString());
    } else {
        return new CustomHttpMethod(method.name(), requestURI.toString());
    }
}

From source file:com.exalead.io.failover.MonitoredHttpConnectionManager.java

public synchronized void removeHost(String host, int port) {
    HostConfiguration hc = new HostConfiguration();
    hc.setHost(host, port);/*from   w  w  w  .  j  av  a  2s . c o m*/

    if (hosts.size() == 1) {
        throw new IllegalArgumentException("Can't remove last host of pool");
    }

    hostsMap.remove(hc);

    /* Clean-up the round robin structure */
    Iterator<HostState> iter = hostsForSelection.listIterator();
    while (iter.hasNext()) {
        HostState hs = iter.next();
        if (hs.configuration.equals(hc)) {
            iter.remove();
        }
    }
    currentHost = 0;

    /* Cleanup the monitoring structure and the main list */

    nextToMonitorList.clear();
    alreadyMonitored.clear();

    iter = hosts.listIterator();
    while (iter.hasNext()) {
        HostState hs = iter.next();
        if (hs.configuration.equals(hc)) {
            iter.remove();
        } else {
            nextToMonitorList.add(hs);
        }
    }
}