Example usage for org.apache.commons.httpclient.methods OptionsMethod OptionsMethod

List of usage examples for org.apache.commons.httpclient.methods OptionsMethod OptionsMethod

Introduction

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

Prototype

public OptionsMethod(String paramString) 

Source Link

Usage

From source file:org.infoscoop.request.ProxyRequest.java

public int executeOptions() throws Exception {
    OptionsMethod method = null;/* ww w. j a va2  s .c o  m*/
    try {
        HttpClient client = this.newHttpClient();
        method = new OptionsMethod(this.getTargetURL());
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(1, false));
        ProxyFilterContainer filterContainer = (ProxyFilterContainer) SpringUtil.getBean(filterType);
        return filterContainer.invoke(client, method, this);
    } catch (ProxyAuthenticationException e) {
        if (e.isTraceOn()) {
            log.error(this.getTargetURL());
            log.error("", e);
        } else {
            log.warn(this.getTargetURL() + " : " + e.getMessage());
        }
        return 401;
    }
}

From source file:org.jaggeryjs2.xhr.XMLHttpRequest.java

private void sendRequest(Object obj) throws Exception {
    final HttpMethodBase method;
    if ("GET".equalsIgnoreCase(methodName)) {
        method = new GetMethod(this.url);
    } else if ("HEAD".equalsIgnoreCase(methodName)) {
        method = new HeadMethod(this.url);
    } else if ("POST".equalsIgnoreCase(methodName)) {
        PostMethod post = new PostMethod(this.url);
        if (obj instanceof FormData) {
            FormData fd = ((FormData) obj);
            List<Part> parts = new ArrayList<Part>();
            for (Map.Entry<String, String> entry : fd) {
                parts.add(new StringPart(entry.getKey(), entry.getValue()));
            }/*from w  w w. j a  va  2s.c  o  m*/
            post.setRequestEntity(
                    new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams()));
        } else {
            String content = getRequestContent(obj);
            if (content != null) {
                post.setRequestEntity(
                        new InputStreamRequestEntity(new ByteArrayInputStream(content.getBytes())));
            }
        }
        method = post;
    } else if ("PUT".equalsIgnoreCase(methodName)) {
        PutMethod put = new PutMethod(this.url);
        String content = getRequestContent(obj);
        if (content != null) {
            put.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(content.getBytes())));
        }
        method = put;
    } else if ("DELETE".equalsIgnoreCase(methodName)) {
        method = new DeleteMethod(this.url);
    } else if ("TRACE".equalsIgnoreCase(methodName)) {
        method = new TraceMethod(this.url);
    } else if ("OPTIONS".equalsIgnoreCase(methodName)) {
        method = new OptionsMethod(this.url);
    } else {
        throw new Exception("Unknown HTTP method : " + methodName);
    }
    for (Header header : requestHeaders) {
        method.addRequestHeader(header);
    }
    if (username != null) {
        httpClient.getState().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(username, password));
    }
    this.method = method;
    final XMLHttpRequest xhr = this;
    if (async) {
        updateReadyState(xhr, LOADING);
        final ExecutorService es = Executors.newSingleThreadExecutor();
        es.submit(new Callable() {
            public Object call() throws Exception {
                try {
                    executeRequest(xhr);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                } finally {
                    es.shutdown();
                }
                return null;
            }
        });
    } else {
        executeRequest(xhr);
    }
}

From source file:org.jboss.web.loadbalancer.Loadbalancer.java

protected HttpMethod createMethod(HttpServletRequest request, HttpServletResponse response, int requestMethod)
        throws NoHostAvailableException {
    String url = null;//from w ww .  java2s.  c  o m
    HttpMethod method = null;

    // get target host from scheduler
    url = scheduler.getHost(request, response).toExternalForm();

    String path = url.substring(0, url.length() - 1) + request.getRequestURI();

    switch (requestMethod) {
    case Constants.HTTP_METHOD_GET:
        method = new GetMethod(path);
        break;
    case Constants.HTTP_METHOD_POST:
        method = new PostMethod(path);
        break;
    case Constants.HTTP_METHOD_DELETE:
        method = new DeleteMethod(path);
        break;
    case Constants.HTTP_METHOD_HEAD:
        method = new HeadMethod(path);
        break;
    case Constants.HTTP_METHOD_OPTIONS:
        method = new OptionsMethod(path);
        break;
    case Constants.HTTP_METHOD_PUT:
        method = new PutMethod(path);
        break;
    default:
        throw new IllegalStateException("Unknown Request Method " + request.getMethod());
    }

    return method;
}

From source file:org.mozilla.zest.impl.ZestBasicRunner.java

private ZestResponse send(HttpClient httpclient, ZestRequest req) throws IOException {
    HttpMethod method;//from  w ww.jav a  2 s .  co  m
    URI uri = new URI(req.getUrl().toString(), false);

    switch (req.getMethod()) {
    case "GET":
        method = new GetMethod(uri.toString());
        // Can only redirect on GETs
        method.setFollowRedirects(req.isFollowRedirects());
        break;
    case "POST":
        method = new PostMethod(uri.toString());
        break;
    case "OPTIONS":
        method = new OptionsMethod(uri.toString());
        break;
    case "HEAD":
        method = new HeadMethod(uri.toString());
        break;
    case "PUT":
        method = new PutMethod(uri.toString());
        break;
    case "DELETE":
        method = new DeleteMethod(uri.toString());
        break;
    case "TRACE":
        method = new TraceMethod(uri.toString());
        break;
    default:
        throw new IllegalArgumentException("Method not supported: " + req.getMethod());
    }

    setHeaders(method, req.getHeaders());

    for (Cookie cookie : req.getCookies()) {
        // Replace any Zest variables in the value
        cookie.setValue(this.replaceVariablesInString(cookie.getValue(), false));
        httpclient.getState().addCookie(cookie);
    }

    if (req.getMethod().equals("POST")) {
        // The setRequestEntity call trashes any Content-Type specified, so record it and reapply it after
        Header contentType = method.getRequestHeader("Content-Type");
        RequestEntity requestEntity = new StringRequestEntity(req.getData(), null, null);

        ((PostMethod) method).setRequestEntity(requestEntity);

        if (contentType != null) {
            method.setRequestHeader(contentType);
        }
    }

    int code = 0;
    String responseHeader = null;
    String responseBody = null;
    Date start = new Date();
    try {
        this.debug(req.getMethod() + " : " + req.getUrl());
        code = httpclient.executeMethod(method);

        responseHeader = method.getStatusLine().toString() + "\r\n" + arrayToStr(method.getResponseHeaders());
        responseBody = method.getResponseBodyAsString();

    } finally {
        method.releaseConnection();
    }
    // Update the headers with the ones actually sent
    req.setHeaders(arrayToStr(method.getRequestHeaders()));

    if (method.getStatusCode() == 302 && req.isFollowRedirects() && !req.getMethod().equals("GET")) {
        // Follow the redirect 'manually' as the httpclient lib only supports them for GET requests
        method = new GetMethod(method.getResponseHeader("Location").getValue());
        // Just in case there are multiple redirects
        method.setFollowRedirects(req.isFollowRedirects());

        try {
            this.debug(req.getMethod() + " : " + req.getUrl());
            code = httpclient.executeMethod(method);

            responseHeader = method.getStatusLine().toString() + "\r\n"
                    + arrayToStr(method.getResponseHeaders());
            responseBody = method.getResponseBodyAsString();

        } finally {
            method.releaseConnection();
        }
    }

    return new ZestResponse(req.getUrl(), responseHeader, responseBody, code,
            new Date().getTime() - start.getTime());
}

From source file:org.mule.transport.http.functional.HttpMethodTestCase.java

@Test
public void testOptions() throws Exception {
    OptionsMethod method = new OptionsMethod(getHttpEndpointAddress());
    int statusCode = client.executeMethod(method);
    assertEquals(HttpStatus.SC_OK, statusCode);
}

From source file:org.mule.transport.http.transformers.ObjectToHttpClientMethodRequest.java

protected HttpMethod createOptionsMethod(MuleMessage message) throws Exception {
    URI uri = getURI(message);//from   www.  j a  v a 2 s . com
    return new OptionsMethod(uri.toString());
}

From source file:org.obm.caldav.client.AbstractPushTest.java

protected void optionQuery() throws Exception {
    OptionsMethod pfq = new OptionsMethod(url);
    appendHeader(pfq, new ByteArrayOutputStream());
    doRequest(pfq);//from   w  w  w.j  ava 2 s  .  co m
    pfq = new OptionsMethod(url);
    appendHeader(pfq, new ByteArrayOutputStream());
    doRequest(pfq);
}

From source file:org.owtf.runtime.core.ZestBasicRunner.java

private ZestResponse send(HttpClient httpclient, ZestRequest req) throws IOException {
    HttpMethod method;/*from w  w w.  j  a va  2 s.c om*/
    URI uri = new URI(req.getUrl().toString(), false);

    switch (req.getMethod()) {
    case "GET":
        method = new GetMethod(uri.toString());
        // Can only redirect on GETs
        method.setFollowRedirects(req.isFollowRedirects());
        break;
    case "POST":
        method = new PostMethod(uri.toString());
        break;
    case "OPTIONS":
        method = new OptionsMethod(uri.toString());
        break;
    case "HEAD":
        method = new HeadMethod(uri.toString());
        break;
    case "PUT":
        method = new PutMethod(uri.toString());
        break;
    case "DELETE":
        method = new DeleteMethod(uri.toString());
        break;
    case "TRACE":
        method = new TraceMethod(uri.toString());
        break;
    default:
        throw new IllegalArgumentException("Method not supported: " + req.getMethod());
    }

    setHeaders(method, req.getHeaders());

    for (Cookie cookie : req.getCookies()) {
        // Replace any Zest variables in the value
        cookie.setValue(this.replaceVariablesInString(cookie.getValue(), false));
        httpclient.getState().addCookie(cookie);
    }

    if (req.getMethod().equals("POST")) {
        // Do this after setting the headers so the length is corrected
        RequestEntity requestEntity = new StringRequestEntity(req.getData(), null, null);
        ((PostMethod) method).setRequestEntity(requestEntity);
    }

    int code = 0;
    String responseHeader = null;
    String responseBody = null;
    Date start = new Date();
    try {
        this.debug(req.getMethod() + " : " + req.getUrl());
        code = httpclient.executeMethod(method);
        responseHeader = method.getStatusLine().toString() + "\n" + arrayToStr(method.getResponseHeaders());
        //   httpclient.getParams().setParameter("http.method.response.buffer.warnlimit",new Integer(1000000000));
        responseBody = method.getResponseBodyAsString();

    } finally {
        method.releaseConnection();
    }
    // Update the headers with the ones actually sent
    req.setHeaders(arrayToStr(method.getRequestHeaders()));

    return new ZestResponse(req.getUrl(), responseHeader, responseBody, code,
            new Date().getTime() - start.getTime());
}

From source file:org.pentaho.di.baserver.utils.web.HttpConnectionHelper.java

protected HttpMethod getHttpMethod(String url, Map<String, String> queryParameters, String httpMethod) {
    org.pentaho.di.baserver.utils.inspector.HttpMethod method;
    if (httpMethod == null) {
        httpMethod = "";
    }/*from ww  w  .  java2 s  .  co  m*/
    try {
        method = org.pentaho.di.baserver.utils.inspector.HttpMethod.valueOf(httpMethod);
    } catch (IllegalArgumentException e) {
        logger.warn("Method '" + httpMethod + "' is not supported - using 'GET'");
        method = org.pentaho.di.baserver.utils.inspector.HttpMethod.GET;
    }

    switch (method) {
    case GET:
        return new GetMethod(url + constructQueryString(queryParameters));
    case POST:
        PostMethod postMethod = new PostMethod(url);
        setRequestEntity(postMethod, queryParameters);
        return postMethod;
    case PUT:
        PutMethod putMethod = new PutMethod(url);
        setRequestEntity(putMethod, queryParameters);
        return putMethod;
    case DELETE:
        return new DeleteMethod(url + constructQueryString(queryParameters));
    case HEAD:
        return new HeadMethod(url + constructQueryString(queryParameters));
    case OPTIONS:
        return new OptionsMethod(url + constructQueryString(queryParameters));
    default:
        return new GetMethod(url + constructQueryString(queryParameters));
    }
}

From source file:org.sakaiproject.kernel.proxy.ProxyClientServiceImpl.java

/**
 * Executes a HTTP call using a path in the JCR to point to a template and a map of
 * properties to populate that template with. An example might be a SOAP call.
 * /*from  w  w  w.j a  va  2 s. c  om*/
 * <pre>
 * {http://www.w3.org/2001/12/soap-envelope}Envelope:{
 *  {http://www.w3.org/2001/12/soap-envelope}Body:{
 *   {http://www.example.org/stock}GetStockPriceResponse:{
 *    &gt;body:[       ]
 *    {http://www.example.org/stock}Price:{
 *     &gt;body:[34.5]
 *    }
 *   }
 *   &gt;body:[  ]
 *  }
 *  &gt;body:[   ]
 *  {http://www.w3.org/2001/12/soap-envelope}encodingStyle:[http://www.w3.org/2001/12/soap-encoding]
 * }
 * 
 * </pre>
 * 
 * @param resource
 *          the resource containing the proxy end point specification.
 * @param headers
 *          a map of headers to set int the request.
 * @param input
 *          a map of parameters for all templates (both url and body)
 * @param requestInputStream
 *          containing the request body (can be null if the call requires no body or the
 *          template will be used to generate the body)
 * @param requestContentLength
 *          if the requestImputStream is specified, the length specifies the lenght of
 *          the body.
 * @param requerstContentType
 *          the content type of the request, if null the node property
 *          sakai:proxy-request-content-type will be used.
 * @throws ProxyClientException
 */
public ProxyResponse executeCall(Node node, Map<String, String> headers, Map<String, String> input,
        InputStream requestInputStream, long requestContentLength, String requestContentType)
        throws ProxyClientException {
    try {
        bindNode(node);

        if (node != null && node.hasProperty(SAKAI_REQUEST_PROXY_ENDPOINT)) {

            VelocityContext context = new VelocityContext(input);

            // setup the post request
            String endpointURL = JcrUtils.getMultiValueString(node.getProperty(SAKAI_REQUEST_PROXY_ENDPOINT));
            Reader urlTemplateReader = new StringReader(endpointURL);
            StringWriter urlWriter = new StringWriter();
            velocityEngine.evaluate(context, urlWriter, "urlprocessing", urlTemplateReader);
            endpointURL = urlWriter.toString();

            ProxyMethod proxyMethod = ProxyMethod.GET;
            if (node.hasProperty(SAKAI_REQUEST_PROXY_METHOD)) {
                try {
                    proxyMethod = ProxyMethod.valueOf(node.getProperty(SAKAI_REQUEST_PROXY_METHOD).getString());
                } catch (Exception e) {

                }
            }
            HttpMethod method = null;
            switch (proxyMethod) {
            case GET:
                method = new GetMethod(endpointURL);
                // redirects work automatically for get, options and head, but not for put and
                // post
                method.setFollowRedirects(true);
                break;
            case HEAD:
                method = new HeadMethod(endpointURL);
                // redirects work automatically for get, options and head, but not for put and
                // post
                method.setFollowRedirects(true);
                break;
            case OPTIONS:
                method = new OptionsMethod(endpointURL);
                // redirects work automatically for get, options and head, but not for put and
                // post
                method.setFollowRedirects(true);
                break;
            case POST:
                method = new PostMethod(endpointURL);
                break;
            case PUT:
                method = new PutMethod(endpointURL);
                break;
            default:
                method = new GetMethod(endpointURL);
                // redirects work automatically for get, options and head, but not for put and
                // post
                method.setFollowRedirects(true);

            }
            // follow redirects, but dont auto process 401's and the like.
            // credentials should be provided
            method.setDoAuthentication(false);

            for (Entry<String, String> header : headers.entrySet()) {
                method.addRequestHeader(header.getKey(), header.getValue());
            }

            Value[] additionalHeaders = JcrUtils.getValues(node, SAKAI_PROXY_HEADER);
            for (Value v : additionalHeaders) {
                String header = v.getString();
                String[] keyVal = StringUtils.split(header, ':', 2);
                method.addRequestHeader(keyVal[0].trim(), keyVal[1].trim());
            }

            if (method instanceof EntityEnclosingMethod) {
                String contentType = requestContentType;
                if (contentType == null && node.hasProperty(SAKAI_REQUEST_CONTENT_TYPE)) {
                    contentType = node.getProperty(SAKAI_REQUEST_CONTENT_TYPE).getString();

                }
                if (contentType == null) {
                    contentType = APPLICATION_OCTET_STREAM;
                }
                EntityEnclosingMethod eemethod = (EntityEnclosingMethod) method;
                if (requestInputStream != null) {
                    eemethod.setRequestEntity(new InputStreamRequestEntity(requestInputStream,
                            requestContentLength, contentType));
                } else {
                    // build the request
                    Template template = velocityEngine.getTemplate(node.getPath());
                    StringWriter body = new StringWriter();
                    template.merge(context, body);
                    byte[] soapBodyContent = body.toString().getBytes("UTF-8");
                    eemethod.setRequestEntity(new ByteArrayRequestEntity(soapBodyContent, contentType));

                }
            }

            int result = httpClient.executeMethod(method);
            if (result == 302 && method instanceof EntityEnclosingMethod) {
                // handle redirects on post and put
                String url = method.getResponseHeader("Location").getValue();
                method = new GetMethod(url);
                method.setFollowRedirects(true);
                method.setDoAuthentication(false);
                result = httpClient.executeMethod(method);
            }

            return new ProxyResponseImpl(result, method);
        }

    } catch (Exception e) {
        throw new ProxyClientException("The Proxy request specified by  " + node + " failed, cause follows:",
                e);
    } finally {
        unbindNode();
    }
    throw new ProxyClientException(
            "The Proxy request specified by " + node + " does not contain a valid endpoint specification ");
}