Example usage for org.apache.commons.httpclient HttpMethod getResponseHeader

List of usage examples for org.apache.commons.httpclient HttpMethod getResponseHeader

Introduction

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

Prototype

public abstract Header getResponseHeader(String paramString);

Source Link

Usage

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

@Test
public void testValidatingIncorrectCredentials() throws Exception {
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new NameValuePair("j_username", "garbage"));
    params.add(new NameValuePair("j_password", "garbage"));
    params.add(new NameValuePair("j_validate", "true"));
    HttpMethod post = H.assertPostStatus(HttpTest.HTTP_BASE_URL + "/j_security_check",
            HttpServletResponse.SC_FORBIDDEN, params, null);
    assertNotNull(post.getResponseHeader("X-Reason"));
}

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

private void assertXReason(final HttpMethod method) throws IOException {
    // expected the X-Reason header
    final Header reason = method.getResponseHeader("X-Reason");
    assertNotNull(reason);/*from   w w  w  .j  a  v a 2  s.  com*/

    // expect the response to be the same as the reason (SLING-1831)
    assertEquals(reason.getValue(), method.getResponseBodyAsString().trim());
}

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  ava  2  s . c  om
    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.FiltersTest.java

public void testCounters() throws IOException {
    HttpMethod get = assertHttpStatus(HTTP_BASE_URL + "/index.html", HttpServletResponse.SC_OK);
    final String[] headers = { "FILTER_COUNTER_SLING", "FILTER_COUNTER_NOPROP" };
    for (String header : headers) {
        assertNotNull("Expecting header '" + header + "'", get.getResponseHeader(header));
        assertEquals("Expecting value 1 for header '" + header + "'", "1",
                get.getResponseHeader(header).getValue());
    }//  ww w .  j ava 2 s .  c o m
    assertNull(get.getResponseHeader("FILTER_COUNTER_SLING_WITH_PATTERN"));
}

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

public void testCounters() throws IOException {
    HttpMethod get = assertHttpStatus(HTTP_BASE_URL + "/system.json", HttpServletResponse.SC_OK);
    final String[] headers = { "FILTER_COUNTER_HTTPSERVICE", "FILTER_COUNTER_SLING", "FILTER_COUNTER_NOPROP",
            "FILTER_COUNTER_SLING_WITH_PATTERN" };
    for (String header : headers) {
        assertNotNull("Expecting header '" + header + "'", get.getResponseHeader(header));
        assertEquals("Expecting value 1 for header '" + header + "'", "1",
                get.getResponseHeader(header).getValue());
    }//from   w w w .  jav  a  2  s  .  co m
}

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

private void assertResponseHeader(HttpMethod m, String name, String expectedRegex) {
    final Header h = m.getResponseHeader(name);
    assertNotNull("Expecting header " + name, h);
    final String value = h.getValue();
    assertTrue("Expected regexp " + expectedRegex + " for header " + name + ", header value is " + value,
            Pattern.matches(expectedRegex, value));
}

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

/**
 * Test for SLING-2072//from w ww.  j  a v  a2s.  c o m
 * @throws IOException
 */
@Test
public void testDisableUser() throws IOException {
    testUserId = H.createTestUser();

    //login before the user is disabled, so login should work
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new NameValuePair("j_username", testUserId));
    params.add(new NameValuePair("j_password", "testPwd"));
    params.add(new NameValuePair("j_validate", "true"));
    HttpMethod post = H.assertPostStatus(HttpTest.HTTP_BASE_URL + "/j_security_check",
            HttpServletResponse.SC_OK, params, null);
    assertNull(post.getResponseHeader("X-Reason"));
    H.getHttpClient().getState().clearCredentials();
    H.getHttpClient().getState().clearCookies();

    //update the user to disable it
    String postUrl = HttpTest.HTTP_BASE_URL + "/system/userManager/user/" + testUserId + ".update.html";
    List<NameValuePair> postParams = new ArrayList<NameValuePair>();
    postParams.add(new NameValuePair(":disabled", "true"));
    postParams.add(new NameValuePair(":disabledReason", "Just Testing"));
    H.assertAuthenticatedAdminPostStatus(postUrl, HttpServletResponse.SC_OK, postParams, null);

    //the user is now disabled, so login should fail
    post = H.assertPostStatus(HttpTest.HTTP_BASE_URL + "/j_security_check", HttpServletResponse.SC_FORBIDDEN,
            params, null);
    assertNotNull(post.getResponseHeader("X-Reason"));
    H.getHttpClient().getState().clearCredentials();
    H.getHttpClient().getState().clearCookies();

    //enable the user again
    postParams = new ArrayList<NameValuePair>();
    postParams.add(new NameValuePair(":disabled", "false"));
    H.assertAuthenticatedAdminPostStatus(postUrl, HttpServletResponse.SC_OK, postParams, null);

    //login after the user is enabled, so login should work
    post = H.assertPostStatus(HttpTest.HTTP_BASE_URL + "/j_security_check", HttpServletResponse.SC_OK, params,
            null);
    assertNull(post.getResponseHeader("X-Reason"));
    H.getHttpClient().getState().clearCredentials();
    H.getHttpClient().getState().clearCookies();
}

From source file:org.apache.solr.client.solrj.impl.CommonsHttpSolrServer.java

public NamedList<Object> request(final SolrRequest request, ResponseParser processor)
        throws SolrServerException, IOException {
    HttpMethod method = null;
    InputStream is = null;//  www .j  av a 2 s  .  c  om
    SolrParams params = request.getParams();
    Collection<ContentStream> streams = requestWriter.getContentStreams(request);
    String path = requestWriter.getPath(request);
    if (path == null || !path.startsWith("/")) {
        path = "/select";
    }

    ResponseParser parser = request.getResponseParser();
    if (parser == null) {
        parser = _parser;
    }

    // The parser 'wt=' and 'version=' params are used instead of the original params
    ModifiableSolrParams wparams = new ModifiableSolrParams();
    wparams.set(CommonParams.WT, parser.getWriterType());
    wparams.set(CommonParams.VERSION, parser.getVersion());
    if (params == null) {
        params = wparams;
    } else {
        params = new DefaultSolrParams(wparams, params);
    }

    if (_invariantParams != null) {
        params = new DefaultSolrParams(_invariantParams, params);
    }

    int tries = _maxRetries + 1;
    try {
        while (tries-- > 0) {
            // Note: since we aren't do intermittent time keeping
            // ourselves, the potential non-timeout latency could be as
            // much as tries-times (plus scheduling effects) the given
            // timeAllowed.
            try {
                if (SolrRequest.METHOD.GET == request.getMethod()) {
                    if (streams != null) {
                        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!");
                    }
                    method = new GetMethod(_baseURL + path + ClientUtils.toQueryString(params, false));
                } else if (SolrRequest.METHOD.POST == request.getMethod()) {

                    String url = _baseURL + path;
                    boolean isMultipart = (streams != null && streams.size() > 1);

                    if (streams == null || isMultipart) {
                        PostMethod post = new PostMethod(url);
                        post.getParams().setContentCharset("UTF-8");
                        if (!this.useMultiPartPost && !isMultipart) {
                            post.addRequestHeader("Content-Type",
                                    "application/x-www-form-urlencoded; charset=UTF-8");
                        }

                        List<Part> parts = new LinkedList<Part>();
                        Iterator<String> iter = params.getParameterNamesIterator();
                        while (iter.hasNext()) {
                            String p = iter.next();
                            String[] vals = params.getParams(p);
                            if (vals != null) {
                                for (String v : vals) {
                                    if (this.useMultiPartPost || isMultipart) {
                                        parts.add(new StringPart(p, v, "UTF-8"));
                                    } else {
                                        post.addParameter(p, v);
                                    }
                                }
                            }
                        }

                        if (isMultipart) {
                            int i = 0;
                            for (ContentStream content : streams) {
                                final ContentStream c = content;

                                String charSet = null;
                                PartSource source = new PartSource() {
                                    public long getLength() {
                                        return c.getSize();
                                    }

                                    public String getFileName() {
                                        return c.getName();
                                    }

                                    public InputStream createInputStream() throws IOException {
                                        return c.getStream();
                                    }
                                };

                                parts.add(new FilePart(c.getName(), source, c.getContentType(), charSet));
                            }
                        }
                        if (parts.size() > 0) {
                            post.setRequestEntity(new MultipartRequestEntity(
                                    parts.toArray(new Part[parts.size()]), post.getParams()));
                        }

                        method = post;
                    }
                    // It is has one stream, it is the post body, put the params in the URL
                    else {
                        String pstr = ClientUtils.toQueryString(params, false);
                        PostMethod post = new PostMethod(url + pstr);
                        //              post.setRequestHeader("connection", "close");

                        // Single stream as body
                        // Using a loop just to get the first one
                        final ContentStream[] contentStream = new ContentStream[1];
                        for (ContentStream content : streams) {
                            contentStream[0] = content;
                            break;
                        }
                        if (contentStream[0] instanceof RequestWriter.LazyContentStream) {
                            post.setRequestEntity(new RequestEntity() {
                                public long getContentLength() {
                                    return -1;
                                }

                                public String getContentType() {
                                    return contentStream[0].getContentType();
                                }

                                public boolean isRepeatable() {
                                    return false;
                                }

                                public void writeRequest(OutputStream outputStream) throws IOException {
                                    ((RequestWriter.LazyContentStream) contentStream[0]).writeTo(outputStream);
                                }
                            });

                        } else {
                            is = contentStream[0].getStream();
                            post.setRequestEntity(
                                    new InputStreamRequestEntity(is, contentStream[0].getContentType()));
                        }
                        method = post;
                    }
                } else {
                    throw new SolrServerException("Unsupported method: " + request.getMethod());
                }
            } catch (NoHttpResponseException r) {
                // This is generally safe to retry on
                method.releaseConnection();
                method = null;
                if (is != null) {
                    is.close();
                }
                // If out of tries then just rethrow (as normal error).
                if ((tries < 1)) {
                    throw r;
                }
                //log.warn( "Caught: " + r + ". Retrying..." );
            }
        }
    } catch (IOException ex) {
        log.error("####request####", ex);
        throw new SolrServerException("error reading streams", ex);
    }

    method.setFollowRedirects(_followRedirects);
    method.addRequestHeader("User-Agent", AGENT);
    if (_allowCompression) {
        method.setRequestHeader(new Header("Accept-Encoding", "gzip,deflate"));
    }
    //    method.setRequestHeader("connection", "close");

    try {
        // Execute the method.
        //System.out.println( "EXECUTE:"+method.getURI() );

        int statusCode = _httpClient.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            StringBuilder msg = new StringBuilder();
            msg.append(method.getStatusLine().getReasonPhrase());
            msg.append("\n\n");
            msg.append(method.getStatusText());
            msg.append("\n\n");
            msg.append("request: " + method.getURI());
            throw new SolrException(statusCode, java.net.URLDecoder.decode(msg.toString(), "UTF-8"));
        }

        // Read the contents
        String charset = "UTF-8";
        if (method instanceof HttpMethodBase) {
            charset = ((HttpMethodBase) method).getResponseCharSet();
        }
        InputStream respBody = method.getResponseBodyAsStream();
        // Jakarta Commons HTTPClient doesn't handle any
        // compression natively.  Handle gzip or deflate
        // here if applicable.
        if (_allowCompression) {
            Header contentEncodingHeader = method.getResponseHeader("Content-Encoding");
            if (contentEncodingHeader != null) {
                String contentEncoding = contentEncodingHeader.getValue();
                if (contentEncoding.contains("gzip")) {
                    //log.debug( "wrapping response in GZIPInputStream" );
                    respBody = new GZIPInputStream(respBody);
                } else if (contentEncoding.contains("deflate")) {
                    //log.debug( "wrapping response in InflaterInputStream" );
                    respBody = new InflaterInputStream(respBody);
                }
            } else {
                Header contentTypeHeader = method.getResponseHeader("Content-Type");
                if (contentTypeHeader != null) {
                    String contentType = contentTypeHeader.getValue();
                    if (contentType != null) {
                        if (contentType.startsWith("application/x-gzip-compressed")) {
                            //log.debug( "wrapping response in GZIPInputStream" );
                            respBody = new GZIPInputStream(respBody);
                        } else if (contentType.startsWith("application/x-deflate")) {
                            //log.debug( "wrapping response in InflaterInputStream" );
                            respBody = new InflaterInputStream(respBody);
                        }
                    }
                }
            }
        }
        return processor.processResponse(respBody, charset);
    } catch (HttpException e) {
        throw new SolrServerException(e);
    } catch (IOException e) {
        throw new SolrServerException(e);
    } finally {
        method.releaseConnection();
        if (is != null) {
            is.close();
        }
    }
}