Package org.apache.commons.httpclient

Examples of org.apache.commons.httpclient.HttpMethodBase


        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);
            }


            savedClient = client;
            int statusCode = client.executeMethod(httpMethod);

            // Needs to be done after execute to pick up all the headers
            res.setRequestHeaders(getConnectionHeaders(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 {
            savedClient = null;
            JOrphanUtils.closeQuietly(instream);
            if (httpMethod != null) {
                httpMethod.releaseConnection();
            }
        }
    }
View Full Code Here


   @SuppressWarnings("unchecked")
   public ClientResponse execute(ClientRequest request) throws Exception
   {
      String uri = request.getUri();
      final HttpMethodBase httpMethod = createHttpMethod(uri, request.getHttpMethod());
      loadHttpMethod(request, httpMethod);

      int status = httpClient.executeMethod(httpMethod);

      BaseClientResponse response = new BaseClientResponse(new BaseClientResponseStreamFactory()
      {
         InputStream stream;

         public InputStream getInputStream() throws IOException
         {
            if (stream == null)
            {
               stream = new SelfExpandingBufferredInputStream(httpMethod.getResponseBodyAsStream());
            }
            return stream;
         }

         public void performReleaseConnection()
         {
            try
            {
               httpMethod.releaseConnection();
            }
            catch (Exception ignored) {}
            try
            {
               stream.close();
View Full Code Here

   @SuppressWarnings("unchecked")
   public ClientResponse execute(ClientRequest request) throws Exception
   {
      String uri = request.getUri();
      final HttpMethodBase httpMethod = createHttpMethod(uri, request.getHttpMethod());
      loadHttpMethod(request, httpMethod);

      int status = httpClient.executeMethod(httpMethod);

      BaseClientResponse response = new BaseClientResponse(new BaseClientResponseStreamFactory()
      {
         InputStream stream;

         public InputStream getInputStream() throws IOException
         {
            if (stream == null)
            {
               stream = new SelfExpandingBufferredInputStream(httpMethod.getResponseBodyAsStream());
            }
            return stream;
         }

         public void performReleaseConnection()
         {
            try
            {
               httpMethod.releaseConnection();
            }
            catch (Exception ignored) {}
            try
            {
               stream.close();
View Full Code Here

            }
        }

        logger.debug("Authenticating");
        Header[] headers = null;
        HttpMethodBase method = null;

        //Get Max connections
        int maxConnectionsPerHost = 30;
        int maxTotalConnections = 100;

        //Cookie Max Age
        int authMaxAge = -1;

        try {
            maxConnectionsPerHost =
                    new Integer(valveConf.getMaxConnectionsPerHost()).intValue();
            maxTotalConnections =
                    (new Integer(valveConf.getMaxTotalConnections())).intValue();
            authMaxAge = Integer.parseInt(valveConf.getAuthMaxAge());
        } catch (NumberFormatException nfe) {
            logger.error("Configuration error: chack the configuration file as the numbers set for any of the following parameters are not OK:");
            logger.error("  * maxConnectionsPerHost    * maxTotalConnections    * authMaxAge");
        }


        // Protection
        if (webProcessor == null) {
            // Instantiate Web processor
            if ((maxConnectionsPerHost != -1) && (maxTotalConnections != -1)) {
                webProcessor =
                        new WebProcessor(maxConnectionsPerHost, maxTotalConnections);
            } else {
                webProcessor = new WebProcessor();
            }
        }

        //
        // Launch the authentication process
        //

        // A fixed URL in the repository that all users have access to which can be used to authN a user
        // and capture the HTTP Authorization Header
        String authURL =
            valveConf.getRepository(id).getParameterValue("HTTPAuthPage");

        try {

            // Set HTTP headers
            headers = new Header[1];

            // Set User-Agent
            headers[0] =
                    new Header("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8) Gecko/20051111 Firefox/1.5");

            // Request page, testing if credentials are valid
            if (credentials != null) {
                logger.debug("Username: " + credentials.getUserName());
                logger.debug("URL: " + authURL);
            }

            //HTTP request
            method =
                    webProcessor.sendRequest(credentials, RequestType.GET_REQUEST,
                                             headers, null, authURL);

            //Read the auth header and store in the cookie, the authZ class will use this later
            headers = method.getRequestHeaders();

            Header authHeader = null;
            authHeader = method.getRequestHeader("Authorization");

            // Cache status code
            if (method != null)
                statusCode = method.getStatusCode();

            if (statusCode == HttpServletResponse.SC_OK) {
                //Authentication worked, so create the auth cookie to indicate it has worked
                Cookie extAuthCookie = null;
                extAuthCookie = new Cookie(BASIC_COOKIE, "");
View Full Code Here

       
        httpResponseStatusEnabled = ResponseStatus.isHttpEnabled(config);
    }

    public Message process(Message message) throws ActionProcessingException {
        HttpMethodBase method = null;
        try {
            if (unwrap) {
                    method = methodFactory.getInstance(message);
            } else {
                try {
                    Serializable payload = Util.serialize(message);
                    if (message.getType().equals(MessageType.JAVA_SERIALIZED)) {
                        String payloadStr = Encoding.encodeObject(payload);
                        method = methodFactory.getMethod(payloadStr, "application/x-java-serialized-object", Charset.defaultCharset().toString());
                    } else {
                        method = methodFactory.getMethod(payload.toString(), "text/xml", "UTF-8");
                    }
                } catch (ParserConfigurationException e) {
                    throw new ActionProcessingException(e);
                }
            }

            try {
                setRequestHeaders(method, message);
               
                int responseCode = httpclient.executeMethod(method);
                if(responseCode != HttpStatus.SC_OK) {
                    logger.warn("Received status code '" + responseCode + "' on HTTP " + method + " request to '" + endpointUrl + "'.");
                }
                attachResponseDetails(message, method, responseCode);

                InputStream resultStream = method.getResponseBodyAsStream();
                try {
                    byte[] bytes = readStream(resultStream);

                    if(responseType == ResponseType.STRING) {
                        getPayloadProxy().setPayload(message, new String(bytes, method.getResponseCharSet()));
                    } else {
                        getPayloadProxy().setPayload(message, bytes);
                    }
                } catch (MessageDeliverException e) {
                    throw new ActionProcessingException("problem setting message payload: " + e.getMessage(), e);
                } finally {
                    closeStream(resultStream);
                }
            } finally {
                method.releaseConnection();
            }
        } catch (IOException e) {
            throw new ActionProcessingException("problem processing HTTP I/O: " + e.getMessage(), e);
        }
View Full Code Here

public abstract class CacheHeaderTestBase extends SolrJettyTestBase {

  protected HttpMethodBase getSelectMethod(String method) {
    CommonsHttpSolrServer httpserver = (CommonsHttpSolrServer)getSolrServer();
    HttpMethodBase m = null;
    if ("GET".equals(method)) {
      m = new GetMethod(httpserver.getBaseURL() + "/select");
    } else if ("HEAD".equals(method)) {
      m = new HeadMethod(httpserver.getBaseURL() + "/select");
    } else if ("POST".equals(method)) {
      m = new PostMethod(httpserver.getBaseURL() + "/select");
    }
    m.setQueryString(new NameValuePair[] { new NameValuePair("q", "solr"),
          new NameValuePair("qt", "standard") });
    return m;
  }
View Full Code Here

    return m;
  }

  protected HttpMethodBase getUpdateMethod(String method) {
    CommonsHttpSolrServer httpserver = (CommonsHttpSolrServer)getSolrServer();
    HttpMethodBase m = null;
   
    if ("GET".equals(method)) {
      m=new GetMethod(httpserver.getBaseURL()+"/update/csv");
    } else if ("POST".equals(method)) {
      m=new PostMethod(httpserver.getBaseURL()+"/update/csv");
View Full Code Here

 
  @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");
    assertNull("We got a Last-Modified header", head);

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

    getClient().executeMethod(get);
    checkResponseBody(method, get);
    assertEquals("Expected 200 with If-Modified-Since header. We should never get a 304 here", 200,
        get.getStatusCode());

    get = getSelectMethod(method);
    get.addRequestHeader("If-Modified-Since", DateUtil.formatDate(new Date(System.currentTimeMillis()-10000)));
    getClient().executeMethod(get);
    checkResponseBody(method, get);
    assertEquals("Expected 200 with If-Modified-Since header. We should never get a 304 here",
        200, get.getStatusCode());

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

    getClient().executeMethod(get);
    checkResponseBody(method, get);
    assertEquals(
        "Expected 200 with If-Unmodified-Since header. We should never get a 304 here",
        200, get.getStatusCode());

    get = getSelectMethod(method);
    get
        .addRequestHeader("If-Unmodified-Since", DateUtil
            .formatDate(new Date()));
    getClient().executeMethod(get);
    checkResponseBody(method, get);
    assertEquals(
        "Expected 200 with If-Unmodified-Since header. We should never get a 304 here",
        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");
    assertNull("We got an ETag in the response", head);

    // 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());

    // 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 200 for star ETag", 200, 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 200 in response to non 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

        .getStatusCode());
  }

  @Override
  protected void doCacheControl(String method) throws Exception {
      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", head);
     
      head = m.getResponseHeader("Expires");
      assertNull("We got an Expires header in response", head);
  }
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.