Package org.apache.commons.httpclient

Examples of org.apache.commons.httpclient.HttpMethodBase


  @Override
  protected void doLastModified(String method) throws Exception {
    // We do a first request to get the last modified
    // This must result in a 200 OK response
    HttpMethodBase get = getSelectMethod(method);
    getClient().executeMethod(get);
    checkResponseBody(method, get);

    assertEquals("Got no response code 200 in initial request", 200, get
        .getStatusCode());

    Header head = get.getResponseHeader("Last-Modified");
    assertNotNull("We got no Last-Modified header", head);

    Date lastModified = DateUtil.parseDate(head.getValue());

    // If-Modified-Since tests
    get = getSelectMethod(method);
    get.addRequestHeader("If-Modified-Since", DateUtil.formatDate(new Date()));

    getClient().executeMethod(get);
    checkResponseBody(method, get);
    assertEquals("Expected 304 NotModified response with current date", 304,
        get.getStatusCode());

    get = getSelectMethod(method);
    get.addRequestHeader("If-Modified-Since", DateUtil.formatDate(new Date(
        lastModified.getTime() - 10000)));
    getClient().executeMethod(get);
    checkResponseBody(method, get);
    assertEquals("Expected 200 OK response with If-Modified-Since in the past",
        200, get.getStatusCode());

    // If-Unmodified-Since tests
    get = getSelectMethod(method);
    get.addRequestHeader("If-Unmodified-Since", DateUtil.formatDate(new Date(
        lastModified.getTime() - 10000)));

    getClient().executeMethod(get);
    checkResponseBody(method, get);
    assertEquals(
        "Expected 412 Precondition failed with If-Unmodified-Since in the past",
        412, get.getStatusCode());

    get = getSelectMethod(method);
    get
        .addRequestHeader("If-Unmodified-Since", DateUtil
            .formatDate(new Date()));
    getClient().executeMethod(get);
    checkResponseBody(method, get);
    assertEquals(
        "Expected 200 OK response with If-Unmodified-Since and current date",
        200, get.getStatusCode());
  }
View Full Code Here


  }

  // test ETag
  @Override
  protected void doETag(String method) throws Exception {
    HttpMethodBase get = getSelectMethod(method);
    getClient().executeMethod(get);
    checkResponseBody(method, get);

    assertEquals("Got no response code 200 in initial request", 200, get
        .getStatusCode());

    Header head = get.getResponseHeader("ETag");
    assertNotNull("We got no ETag in the response", head);
    assertTrue("Not a valid ETag", head.getValue().startsWith("\"")
        && head.getValue().endsWith("\""));

    String etag = head.getValue();

    // If-None-Match tests
    // we set a non matching ETag
    get = getSelectMethod(method);
    get.addRequestHeader("If-None-Match", "\"xyz123456\"");
    getClient().executeMethod(get);
    checkResponseBody(method, get);
    assertEquals(
        "If-None-Match: Got no response code 200 in response to non matching ETag",
        200, get.getStatusCode());

    // now we set matching ETags
    get = getSelectMethod(method);
    get.addRequestHeader("If-None-Match", "\"xyz1223\"");
    get.addRequestHeader("If-None-Match", "\"1231323423\", \"1211211\",   "
        + etag);
    getClient().executeMethod(get);
    checkResponseBody(method, get);
    assertEquals("If-None-Match: Got no response 304 to matching ETag", 304,
        get.getStatusCode());

    // we now set the special star ETag
    get = getSelectMethod(method);
    get.addRequestHeader("If-None-Match", "*");
    getClient().executeMethod(get);
    checkResponseBody(method, get);
    assertEquals("If-None-Match: Got no response 304 for star ETag", 304, get
        .getStatusCode());

    // If-Match tests
    // we set a non matching ETag
    get = getSelectMethod(method);
    get.addRequestHeader("If-Match", "\"xyz123456\"");
    getClient().executeMethod(get);
    checkResponseBody(method, get);
    assertEquals(
        "If-Match: Got no response code 412 in response to non matching ETag",
        412, get.getStatusCode());

    // now we set matching ETags
    get = getSelectMethod(method);
    get.addRequestHeader("If-Match", "\"xyz1223\"");
    get.addRequestHeader("If-Match", "\"1231323423\", \"1211211\",   " + etag);
    getClient().executeMethod(get);
    checkResponseBody(method, get);
    assertEquals("If-Match: Got no response 200 to matching ETag", 200, get
        .getStatusCode());

    // now we set the special star ETag
    get = getSelectMethod(method);
    get.addRequestHeader("If-Match", "*");
    getClient().executeMethod(get);
    checkResponseBody(method, get);
    assertEquals("If-Match: Got no response 200 to star ETag", 200, get
        .getStatusCode());
  }
View Full Code Here

  }

  @Override
  protected void doCacheControl(String method) throws Exception {
    if ("POST".equals(method)) {
      HttpMethodBase m = getSelectMethod(method);
      getClient().executeMethod(m);
      checkResponseBody(method, m);

      Header head = m.getResponseHeader("Cache-Control");
      assertNull("We got a cache-control header in response to POST", head);

      head = m.getResponseHeader("Expires");
      assertNull("We got an Expires  header in response to POST", head);
    } else {
      HttpMethodBase m = getSelectMethod(method);
      getClient().executeMethod(m);
      checkResponseBody(method, m);

      Header head = m.getResponseHeader("Cache-Control");
      assertNotNull("We got no cache-control header", head);

      head = m.getResponseHeader("Expires");
      assertNotNull("We got no Expires header in response", head);
    }
  }
View Full Code Here

    String urlStr = url.toString();

    log.debug("Start : sample " + urlStr);
    log.debug("method " + method);

        HttpMethodBase httpMethod = null;

    HTTPSampleResult res = new HTTPSampleResult();
    res.setMonitor(isMonitor());
       
    res.setSampleLabel(urlStr); // May be replaced later
        res.setHTTPMethod(method);
    res.sampleStart(); // Count the retries as well in the time
        HttpClient client = null;
        InputStream instream = null;
    try {
      // May generate IllegalArgumentException
      if (method.equals(POST)) {
          httpMethod = new PostMethod(urlStr);
      } else if (method.equals(PUT)){
          httpMethod = new PutMethod(urlStr);
      } else if (method.equals(HEAD)){
          httpMethod = new HeadMethod(urlStr);
      } else if (method.equals(TRACE)){
          httpMethod = new TraceMethod(urlStr);
      } else if (method.equals(OPTIONS)){
          httpMethod = new OptionsMethod(urlStr);
      } else if (method.equals(DELETE)){
          httpMethod = new DeleteMethod(urlStr);
      } else if (method.equals(GET)){
          httpMethod = new GetMethod(urlStr);
      } else {
        log.error("Unexpected method (converted to GET): "+method);
          httpMethod = new GetMethod(urlStr);
      }

      // Set any default request headers
      setDefaultRequestHeaders(httpMethod);
            // Setup connection
      client = setupConnection(url, httpMethod, res);
      // Handle the various methods
      if (method.equals(POST)) {
        String postBody = sendPostData((PostMethod)httpMethod);
        res.setQueryString(postBody);
      } else if (method.equals(PUT)) {
                String putBody = sendPutData((PutMethod)httpMethod);
                res.setQueryString(putBody);
            }

            res.setRequestHeaders(getConnectionHeaders(httpMethod));

      int statusCode = client.executeMethod(httpMethod);

      // Request sent. Now get the response:
            instream = httpMethod.getResponseBodyAsStream();
           
            if (instream != null) {// will be null for HEAD
           
                Header responseHeader = httpMethod.getResponseHeader(HEADER_CONTENT_ENCODING);
                if (responseHeader!= null && ENCODING_GZIP.equals(responseHeader.getValue())) {
                    instream = new GZIPInputStream(instream);
                }
                res.setResponseData(readResponse(res, instream, (int) httpMethod.getResponseContentLength()));
            }
           
      res.sampleEnd();
      // Done with the sampling proper.

      // Now collect the results into the HTTPSampleResult:

      res.setSampleLabel(httpMethod.getURI().toString());
            // Pick up Actual path (after redirects)
           
      res.setResponseCode(Integer.toString(statusCode));
      res.setSuccessful(isSuccessCode(statusCode));

      res.setResponseMessage(httpMethod.getStatusText());

      String ct = null;
      org.apache.commons.httpclient.Header h
                = httpMethod.getResponseHeader(HEADER_CONTENT_TYPE);
      if (h != null)// Can be missing, e.g. on redirect
      {
        ct = h.getValue();
        res.setContentType(ct);// e.g. text/html; charset=ISO-8859-1
                res.setEncodingAndType(ct);
      }

      res.setResponseHeaders(getResponseHeaders(httpMethod));
      if (res.isRedirect()) {
        final Header headerLocation = httpMethod.getResponseHeader(HEADER_LOCATION);
        if (headerLocation == null) { // HTTP protocol violation, but avoids NPE
          throw new IllegalArgumentException("Missing location header");
        }
        res.setRedirectLocation(headerLocation.getValue());
      }

            // If we redirected automatically, the URL may have changed
            if (getAutoRedirects()){
                res.setURL(new URL(httpMethod.getURI().toString()));
            }
           
      // Store any cookies received in the cookie manager:
      saveConnectionCookies(httpMethod, res.getURL(), getCookieManager());
     
      // Save cache information
            final CacheManager cacheManager = getCacheManager();
            if (cacheManager != null){
                cacheManager.saveDetails(httpMethod, res);
            }

      // Follow redirects and download page resources if appropriate:
      res = resultProcessing(areFollowingRedirect, frameDepth, res);

      log.debug("End : sample");
      httpMethod.releaseConnection();
      return res;
    } catch (IllegalArgumentException e)// e.g. some kinds of invalid URL
    {
      res.sampleEnd();
      HTTPSampleResult err = errorResult(e, res);
      err.setSampleLabel("Error: " + url.toString());
      return err;
    } catch (IOException e) {
      res.sampleEnd();
      HTTPSampleResult err = errorResult(e, res);
      err.setSampleLabel("Error: " + url.toString());
      return err;
    } finally {
            JOrphanUtils.closeQuietly(instream);
      if (httpMethod != null) {
        httpMethod.releaseConnection();
      }
    }
  }
View Full Code Here

        String urlStr = url.toString();

        log.debug("Start : sample " + urlStr);
        log.debug("method " + method);

        HttpMethodBase httpMethod = null;

        HTTPSampleResult res = new HTTPSampleResult();
        res.setMonitor(isMonitor());

        res.setSampleLabel(urlStr); // May be replaced later
        res.setHTTPMethod(method);
        res.setURL(url);

        res.sampleStart(); // Count the retries as well in the time
        try {
            // May generate IllegalArgumentException
            if (method.equals(HTTPConstants.POST)) {
                httpMethod = new PostMethod(urlStr);
            } else if (method.equals(HTTPConstants.PUT)){
                httpMethod = new PutMethod(urlStr);
            } else if (method.equals(HTTPConstants.HEAD)){
                httpMethod = new HeadMethod(urlStr);
            } else if (method.equals(HTTPConstants.TRACE)){
                httpMethod = new TraceMethod(urlStr);
            } else if (method.equals(HTTPConstants.OPTIONS)){
                httpMethod = new OptionsMethod(urlStr);
            } else if (method.equals(HTTPConstants.DELETE)){
                httpMethod = new EntityEnclosingMethod(urlStr) {
                    @Override
                    public String getName() { // HC3.1 does not have the method
                        return HTTPConstants.DELETE;
                    }
                };
            } else if (method.equals(HTTPConstants.GET)){
                httpMethod = new GetMethod(urlStr);
            } else if (method.equals(HTTPConstants.PATCH)){
                httpMethod = new EntityEnclosingMethod(urlStr) {
                    @Override
                    public String getName() { // HC3.1 does not have the method
                        return HTTPConstants.PATCH;
                    }
                };
            } else {
                throw new IllegalArgumentException("Unexpected method: '"+method+"'");
            }

            final CacheManager cacheManager = getCacheManager();
            if (cacheManager != null && HTTPConstants.GET.equalsIgnoreCase(method)) {
               if (cacheManager.inCache(url)) {
                   res.sampleEnd();
                   res.setResponseNoContent();
                   res.setSuccessful(true);
                   return res;
               }
            }

            // Set any default request headers
            setDefaultRequestHeaders(httpMethod);

            // Setup connection
            HttpClient client = setupConnection(url, httpMethod, res);
            savedClient = client;

            // Handle the various methods
            if (method.equals(HTTPConstants.POST)) {
                String postBody = sendPostData((PostMethod)httpMethod);
                res.setQueryString(postBody);
            } else if (method.equals(HTTPConstants.PUT) || method.equals(HTTPConstants.PATCH)
                    || method.equals(HTTPConstants.DELETE)) {
                String putBody = sendEntityData((EntityEnclosingMethod) httpMethod);
                res.setQueryString(putBody);
            }

            int statusCode = client.executeMethod(httpMethod);

            // We've finished with the request, so we can add the LocalAddress to it for display
            final InetAddress localAddr = client.getHostConfiguration().getLocalAddress();
            if (localAddr != null) {
                httpMethod.addRequestHeader(HEADER_LOCAL_ADDRESS, localAddr.toString());
            }
            // Needs to be done after execute to pick up all the headers
            res.setRequestHeaders(getConnectionHeaders(httpMethod));

            // Request sent. Now get the response:
            InputStream instream = httpMethod.getResponseBodyAsStream();

            if (instream != null) {// will be null for HEAD
                instream = new CountingInputStream(instream);
                try {
                    Header responseHeader = httpMethod.getResponseHeader(HTTPConstants.HEADER_CONTENT_ENCODING);
                    if (responseHeader!= null && HTTPConstants.ENCODING_GZIP.equals(responseHeader.getValue())) {
                        InputStream tmpInput = new GZIPInputStream(instream); // tmp inputstream needs to have a good counting
                        res.setResponseData(readResponse(res, tmpInput, (int) httpMethod.getResponseContentLength()));                       
                    } else {
                        res.setResponseData(readResponse(res, instream, (int) httpMethod.getResponseContentLength()));
                    }
                } finally {
                    JOrphanUtils.closeQuietly(instream);
                }
            }

            res.sampleEnd();
            // Done with the sampling proper.

            // Now collect the results into the HTTPSampleResult:

            res.setSampleLabel(httpMethod.getURI().toString());
            // Pick up Actual path (after redirects)

            res.setResponseCode(Integer.toString(statusCode));
            res.setSuccessful(isSuccessCode(statusCode));

            res.setResponseMessage(httpMethod.getStatusText());

            String ct = null;
            Header h = httpMethod.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE);
            if (h != null)// Can be missing, e.g. on redirect
            {
                ct = h.getValue();
                res.setContentType(ct);// e.g. text/html; charset=ISO-8859-1
                res.setEncodingAndType(ct);
            }

            res.setResponseHeaders(getResponseHeaders(httpMethod));
            if (res.isRedirect()) {
                final Header headerLocation = httpMethod.getResponseHeader(HTTPConstants.HEADER_LOCATION);
                if (headerLocation == null) { // HTTP protocol violation, but avoids NPE
                    throw new IllegalArgumentException("Missing location header");
                }
                try {
                    res.setRedirectLocation(ConversionUtils.sanitizeUrl(new URL(headerLocation.getValue())).toString());
                } catch (Exception e) {
                    log.error("Error sanitizing URL:"+headerLocation.getValue()+", message:"+e.getMessage());
                }
            }

            // record some sizes to allow HTTPSampleResult.getBytes() with different options
            if (instream != null) {
                res.setBodySize(((CountingInputStream) instream).getCount());
            }
            res.setHeadersSize(calculateHeadersSize(httpMethod));
            if (log.isDebugEnabled()) {
                log.debug("Response headersSize=" + res.getHeadersSize() + " bodySize=" + res.getBodySize()
                        + " Total=" + (res.getHeadersSize() + res.getBodySize()));
            }
           
            // If we redirected automatically, the URL may have changed
            if (getAutoRedirects()){
                res.setURL(new URL(httpMethod.getURI().toString()));
            }

            // Store any cookies received in the cookie manager:
            saveConnectionCookies(httpMethod, res.getURL(), getCookieManager());

            // Save cache information
            if (cacheManager != null){
                cacheManager.saveDetails(httpMethod, res);
            }

            // Follow redirects and download page resources if appropriate:
            res = resultProcessing(areFollowingRedirect, frameDepth, res);

            log.debug("End : sample");
            return res;
        } catch (IllegalArgumentException e) { // e.g. some kinds of invalid URL
            res.sampleEnd();
            // pick up headers if failed to execute the request
            // httpMethod can be null if method is unexpected
            if(httpMethod != null) {
                res.setRequestHeaders(getConnectionHeaders(httpMethod));
            }
            errorResult(e, res);
            return res;
        } catch (IOException e) {
            res.sampleEnd();
            // pick up headers if failed to execute the request
            res.setRequestHeaders(getConnectionHeaders(httpMethod));
            errorResult(e, res);
            return res;
        } finally {
            savedClient = null;
            if (httpMethod != null) {
                httpMethod.releaseConnection();
            }
        }
    }
View Full Code Here

    */
   public void testGetEntitlementsFromServlet() throws Exception
   {
      // call the ACLServlet using the identity "Administrator" as a parameter.
      URL url = new URL(HttpUtils.getBaseURL() + "acl-integration/acl?identity=Administrator");
      HttpMethodBase response = HttpUtils.accessURL(url, "JBoss ACL Test", HttpURLConnection.HTTP_OK);
      // each line of the response has the following format: resource_id:permissions
      List<String> entitlements = this.readEntitlementsFromResponse(response);
      assertEquals("ACLServlet retrieved an invalid number of entitlement entries", 2, entitlements.size());
      // Administrator should have CREATE,READ,UPDATE and DELETE permissions on both resources (id=1 and id=2).
      assertTrue("Invalid entitlement entry found", entitlements.contains("1:CREATE,READ,UPDATE,DELETE"));
View Full Code Here

   public void testPackedAllowedPermissions()
      throws Exception
   {
      URL url = new URL(baseURL+"packed/FileAccessServlet?file=allow");
      HttpMethodBase request = HttpUtils.accessURL(url);
      Header hdr = request.getResponseHeader("X-CodeSource");
      log.info("X-CodeSource: "+hdr);
      assertTrue("X-CodeSource("+hdr+") is NOT null", hdr != null);
      hdr = request.getResponseHeader("X-RealPath");
      log.info("X-RealPath: "+hdr);
      assertTrue("X-RealPath("+hdr+") is NOT null", hdr != null);
      hdr = request.getResponseHeader("X-Exception");
      log.info("X-Exception: "+hdr);
      assertTrue("X-Exception("+hdr+") is null", hdr == null);
   }
View Full Code Here

   }
   public void testUnpackedAllowedPermissions()
      throws Exception
   {
      URL url = new URL(baseURL+"unpacked/FileAccessServlet?file=allow");
      HttpMethodBase request = HttpUtils.accessURL(url);
      Header hdr = request.getResponseHeader("X-CodeSource");
      log.info("X-CodeSource: "+hdr);
      assertTrue("X-CodeSource("+hdr+") is NOT null", hdr != null);
      hdr = request.getResponseHeader("X-RealPath");
      log.info("X-RealPath: "+hdr);
      assertTrue("X-RealPath("+hdr+") is NOT null", hdr != null);
      hdr = request.getResponseHeader("X-Exception");
      log.info("X-Exception: "+hdr);
      assertTrue("X-Exception("+hdr+") is null", hdr == null);
   }
View Full Code Here

            + "&array=1,2,3,4,5,6,7,8,9,10");
      try
      {
         deploy("staticarray.sar");
         // Set the static array value to a non-default from war1
         HttpMethodBase request = HttpUtils.accessURL(url);
         Header errors = request.getResponseHeader("X-Error");
         log.info("war1 X-Error: "+errors);
         assertTrue("war1 X-Error("+errors+") is null", errors == null);
         // Validate that war2 sees the changed values
         url = new URL(baseURL+"staticarray-web2/validate.jsp"
               + "?Sequencer.info.expected=1,2,3,4,5,6,7,8,9,10");
         request = HttpUtils.accessURL(url);
         errors = request.getResponseHeader("X-Error");
         log.info("war2 X-Error: "+errors);
         assertTrue("war2 X-Error("+errors+") is null", errors == null);
        
      }
      catch(Exception e)
View Full Code Here

    */
   public void testAltRequestInfoServlet()
      throws Exception
   {
      URL url = new URL(baseURL+"simple-xmlonly/ENCServlet");
      HttpMethodBase request = HttpUtils.accessURL(url);
      Header errors = request.getResponseHeader("X-Exception");
      log.info("X-Exception: "+errors);
      assertTrue("X-Exception("+errors+") is null", errors == null);     
   }
View Full Code Here

TOP

Related Classes of org.apache.commons.httpclient.HttpMethodBase

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.