Example usage for org.apache.commons.httpclient Header Header

List of usage examples for org.apache.commons.httpclient Header Header

Introduction

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

Prototype

public Header(String paramString1, String paramString2) 

Source Link

Usage

From source file:org.apache.nutch.protocol.webdriver.Http.java

/**
 * Configures the HTTP client/*  w  w w . jav  a2 s .  co m*/
 */
private void configureClient() {

    // Set up an HTTPS socket factory that accepts self-signed certs.
    ProtocolSocketFactory factory = new SSLProtocolSocketFactory();
    Protocol https = new Protocol("https", factory, 443);
    Protocol.registerProtocol("https", https);

    HttpConnectionManagerParams params = connectionManager.getParams();
    params.setConnectionTimeout(timeout);
    params.setSoTimeout(timeout);
    params.setSendBufferSize(BUFFER_SIZE);
    params.setReceiveBufferSize(BUFFER_SIZE);
    params.setMaxTotalConnections(maxThreadsTotal);

    // Also set max connections per host to maxThreadsTotal since all threads
    // might be used to fetch from the same host - otherwise timeout errors can
    // occur
    params.setDefaultMaxConnectionsPerHost(maxThreadsTotal);

    // executeMethod(HttpMethod) seems to ignore the connection timeout on
    // the connection manager.
    // set it explicitly on the HttpClient.
    client.getParams().setConnectionManagerTimeout(timeout);

    HostConfiguration hostConf = client.getHostConfiguration();
    if (useProxy) {
        hostConf.setProxy(proxyHost, proxyPort);
    }
    ArrayList<Header> headers = new ArrayList<Header>();
    // prefer English
    headers.add(new Header("Accept-Language", "en-us,en-gb,en;q=0.7,*;q=0.3"));
    // prefer UTF-8
    headers.add(new Header("Accept-Charset", "utf-8,ISO-8859-1;q=0.7,*;q=0.7"));
    // prefer understandable formats
    headers.add(new Header("Accept",
            "text/html,application/xml;q=0.9,application/xhtml+xml,text/xml;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"));
    // accept gzipped content
    // headers.add(new Header("Accept-Encoding", "x-gzip, gzip, deflate"));
    hostConf.getParams().setParameter("http.default-headers", headers);
}

From source file:org.apache.ode.axis2.Properties.java

public static Object[] getProxyAndHeaders(Map<String, String> properties) {
    ArrayList<Header> headers = null; // /!\ Axis2 requires an ArrayList (not a List implementation)
    HttpTransportProperties.ProxyProperties proxy = null;
    for (Map.Entry<String, String> e : properties.entrySet()) {
        final String k = e.getKey();
        final String v = e.getValue();
        if (k.startsWith(PROP_HTTP_HEADER_PREFIX)) {
            if (headers == null)
                headers = new ArrayList<Header>();
            // extract the header name
            String name = k.substring(PROP_HTTP_HEADER_PREFIX.length());
            headers.add(new Header(name, v));
        } else if (k.startsWith(PROP_HTTP_PROXY_PREFIX)) {
            if (proxy == null)
                proxy = new HttpTransportProperties.ProxyProperties();

            if (PROP_HTTP_PROXY_HOST.equals(k))
                proxy.setProxyName(v);/*from www. jav  a 2  s .  c o  m*/
            else if (PROP_HTTP_PROXY_PORT.equals(k))
                proxy.setProxyPort(Integer.parseInt(v));
            else if (PROP_HTTP_PROXY_DOMAIN.equals(k))
                proxy.setDomain(v);
            else if (PROP_HTTP_PROXY_USER.equals(k))
                proxy.setUserName(v);
            else if (PROP_HTTP_PROXY_PASSWORD.equals(k))
                proxy.setPassWord(v);
            else if (log.isWarnEnabled())
                log.warn("Unknown proxy properties [" + k + "]. " + PROP_HTTP_PROXY_PREFIX
                        + " is a refix reserved for proxy properties.");
        }
    }
    if (proxy != null) {
        String host = proxy.getProxyHostName();
        if (host == null || host.length() == 0) {
            // disable proxy if the host is not null
            proxy = null;
            if (log.isDebugEnabled())
                log.debug("Proxy host is null. Proxy will not be taken into account.");
        }
    }

    return new Object[] { proxy, headers };
}

From source file:org.apache.sling.discovery.impl.topology.connector.TopologyRequestValidatorTest.java

@Test
public void testTrustResponse() throws IOException {
    final HttpServletRequest request = context.mock(HttpServletRequest.class);
    context.checking(new Expectations() {
        {//from   w  w w  .  j  a va  2s  . c  o  m
            allowing(request).getRequestURI();
            will(returnValue("/Test/Uri2"));
        }
    });

    final HttpServletResponse response = context.mock(HttpServletResponse.class);
    final Map<Object, Object> headers = new HashMap<Object, Object>();
    context.checking(new Expectations() {
        {
            allowing(response).setHeader(with(any(String.class)), with(any(String.class)));
            will(new Action() {

                public void describeTo(Description desc) {
                    desc.appendText("Setting header ");
                }

                public Object invoke(Invocation invocation) throws Throwable {
                    headers.put(invocation.getParameter(0), invocation.getParameter(1));
                    return null;
                }

            });
        }
    });

    String clearMessage = "TestMessage2";
    final String message = topologyRequestValidator.encodeMessage(clearMessage);
    topologyRequestValidator.trustMessage(response, request, message);

    final HttpMethod method = context.mock(HttpMethod.class);
    context.checking(new Expectations() {
        {
            allowing(method).getResponseHeader(with(any(String.class)));
            will(new Action() {
                public void describeTo(Description desc) {
                    desc.appendText("Getting header ");
                }

                public Object invoke(Invocation invocation) throws Throwable {
                    return new Header((String) invocation.getParameter(0),
                            (String) headers.get(invocation.getParameter(0)));
                }

            });

            allowing(method).getPath();
            will(returnValue("/Test/Uri2"));

            allowing(method).getResponseBodyAsString();
            will(returnValue(message));
        }
    });
    topologyRequestValidator.isTrusted(method);
    topologyRequestValidator.decodeMessage(method);

}

From source file:org.apache.sling.launchpad.webapp.integrationtest.auth.AuthenticationResponseCodeTest.java

@Test
public void testValidatingIncorrectCookie() throws Exception {
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new NameValuePair("j_validate", "true"));

    List<Header> headers = new ArrayList<Header>();
    headers.add(new Header("Cookie", "sling.formauth=garbage"));

    HttpMethod post = assertPostStatus(HttpTest.HTTP_BASE_URL + "/j_security_check",
            HttpServletResponse.SC_FORBIDDEN, params, headers, null);
    assertXReason(post);/*from w  w  w.j av a 2 s  .  c om*/
}

From source file:org.apache.sling.launchpad.webapp.integrationtest.auth.AuthenticationResponseCodeTest.java

@Test
public void testPreventLoopIncorrectFormCredentials() throws Exception {
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new NameValuePair("j_username", "garbage"));
    params.add(new NameValuePair("j_password", "garbage"));

    final String requestUrl = HttpTest.HTTP_BASE_URL + "/j_security_check";
    List<Header> headers = new ArrayList<Header>();
    headers.add(new Header("Referer", requestUrl));
    headers.add(new Header("User-Agent", "Mozilla/5.0 Sling Integration Test"));

    HttpMethod post = assertPostStatus(requestUrl, HttpServletResponse.SC_FORBIDDEN, params, headers, null);
    assertNotNull(post.getResponseHeader("X-Reason"));
    assertEquals("Username and Password do not match", post.getResponseHeader("X-Reason").getValue());
}

From source file:org.apache.sling.launchpad.webapp.integrationtest.auth.AuthenticationResponseCodeTest.java

@Test
public void testXRequestedWithIncorrectCredentials() throws Exception {
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new NameValuePair("j_username", "garbage"));
    params.add(new NameValuePair("j_password", "garbage"));

    List<Header> headers = new ArrayList<Header>();
    headers.add(new Header("X-Requested-With", "XMLHttpRequest"));
    headers.add(new Header("User-Agent", "Mozilla/5.0 Sling Integration Test"));

    HttpMethod post = assertPostStatus(HttpTest.HTTP_BASE_URL + "/j_security_check",
            HttpServletResponse.SC_FORBIDDEN, params, headers, null);
    assertNotNull(post.getResponseHeader("X-Reason"));
    assertEquals("Username and Password do not match", post.getResponseHeader("X-Reason").getValue());
}

From source file:org.apache.sling.launchpad.webapp.integrationtest.auth.AuthenticationResponseCodeTest.java

@Test
public void testWithNonHtmlAcceptHeaderIncorrectCredentials() throws Exception {
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new NameValuePair("j_username", "garbage"));
    params.add(new NameValuePair("j_password", "garbage"));

    List<Header> headers = new ArrayList<Header>();
    headers.add(new Header("User-Agent", "Mozilla/5.0 Sling Integration Test"));

    assertPostStatus(HttpTest.HTTP_BASE_URL + "/j_security_check", HttpServletResponse.SC_MOVED_TEMPORARILY,
            params, headers, null);// www .  j av  a2 s  .  c om
}

From source file:org.apache.sling.launchpad.webapp.integrationtest.auth.SelectorAuthenticationResponseCodeTest.java

@Test
public void testWithAcceptHeaderIncorrectCredentials() throws Exception {
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new NameValuePair("j_username", "garbage"));
    params.add(new NameValuePair("j_password", "garbage"));

    // simulate a browser request
    List<Header> headers = new ArrayList<Header>();
    headers.add(new Header("User-Agent", "Mozilla/5.0 Sling Integration Test"));

    HttpMethod post = assertPostStatus(HttpTest.HTTP_BASE_URL + "/j_security_check",
            HttpServletResponse.SC_MOVED_TEMPORARILY, params, headers, null);

    final String location = post.getResponseHeader("Location").getValue();
    assertNotNull(location);// w  w w.j  a  va  2  s .c o m
    assertTrue(location.startsWith(HttpTest.HTTP_BASE_URL + "/system/sling/selector/login?"));
    assertTrue(location.contains("resource=%2F"));
    assertTrue(location.contains("j_reason=INVALID_CREDENTIALS"));
}

From source file:org.apache.sling.launchpad.webapp.integrationtest.RangeStreamingTest.java

public void test_wrong_ranges() throws IOException {
    GetMethod get = new GetMethod(rootUrl);
    get.setRequestHeader(new Header("Range", "unit 1-10"));
    int status = httpClient.executeMethod(get);
    assertEquals("Expect 416 for unsupported unit", 416, status);

    get = new GetMethod(rootUrl);
    get.setRequestHeader(new Header("Range", "bytes 5"));
    status = httpClient.executeMethod(get);
    assertEquals("Expect 416 for missing dash", 416, status);

    get = new GetMethod(rootUrl);
    get.setRequestHeader(new Header("Range", "bytes -x"));
    status = httpClient.executeMethod(get);
    assertEquals("Expect 416 for illegal negative number", 416, status);

    get = new GetMethod(rootUrl);
    get.setRequestHeader(new Header("Range", "bytes -x"));
    status = httpClient.executeMethod(get);
    assertEquals("Expect 416 for illegal negative number", 416, status);

    get = new GetMethod(rootUrl);
    get.setRequestHeader(new Header("Range", "bytes y-10"));
    status = httpClient.executeMethod(get);
    assertEquals("Expect 416 for unparseable number", 416, status);

    get = new GetMethod(rootUrl);
    get.setRequestHeader(new Header("Range", "bytes 10-5"));
    status = httpClient.executeMethod(get);
    assertEquals("Expect 416 for end < start", 416, status);
}

From source file:org.apache.sling.launchpad.webapp.integrationtest.RangeStreamingTest.java

public void test_single_range() throws IOException {
    GetMethod get = new GetMethod(rootUrl);
    get.setRequestHeader(new Header("Range", "bytes 0-9"));
    int status = httpClient.executeMethod(get);
    assertEquals("Expect 206/PARTIAL CONTENT", 206, status);
    assertEquals(10, get.getResponseContentLength());
    assertEquals("The quick ", get.getResponseBodyAsString());

    get = new GetMethod(rootUrl);
    get.setRequestHeader(new Header("Range", "bytes -10"));
    status = httpClient.executeMethod(get);
    assertEquals("Expect 206/PARTIAL CONTENT", 206, status);
    assertEquals(10, get.getResponseContentLength());
    assertEquals("corpus sic", get.getResponseBodyAsString());

    get = new GetMethod(rootUrl);
    get.setRequestHeader(new Header("Range", "bytes 16-38"));
    status = httpClient.executeMethod(get);
    assertEquals("Expect 206/PARTIAL CONTENT", 206, status);
    assertEquals(23, get.getResponseContentLength());
    assertEquals("fox jumps over the lazy", get.getResponseBodyAsString());
}