Example usage for org.apache.commons.httpclient.params HttpMethodParams HttpMethodParams

List of usage examples for org.apache.commons.httpclient.params HttpMethodParams HttpMethodParams

Introduction

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

Prototype

public HttpMethodParams(HttpParams paramHttpParams) 

Source Link

Usage

From source file:org.sakaiproject.nakamura.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.
 *
 * <pre>//from   ww  w  . ja v a  2s. co  m
 * {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, Object> input,
        InputStream requestInputStream, long requestContentLength, String requestContentType)
        throws ProxyClientException {
    try {
        bindNode(node);

        if (node != null && node.hasProperty(SAKAI_REQUEST_PROXY_ENDPOINT)) {
            // setup the post request
            String endpointURL = JcrUtils.getMultiValueString(node.getProperty(SAKAI_REQUEST_PROXY_ENDPOINT));
            if (isUnsafeProxyDefinition(node)) {
                try {
                    URL u = new URL(endpointURL);
                    String host = u.getHost();
                    if (host.indexOf('$') >= 0) {
                        throw new ProxyClientException(
                                "Invalid Endpoint template, relies on request to resolve valid URL " + u);
                    }
                } catch (MalformedURLException e) {
                    throw new ProxyClientException(
                            "Invalid Endpoint template, relies on request to resolve valid URL", e);
                }
            }

            // Find all velocity replacement variable(s) in the endpointURL,
            // copy any equivalent keys from the input Map, to a new Map that
            // can be process by Velocity. In the new Map, the Map value field
            // has been changed from RequestParameter[] to String.

            Map<String, String> inputContext = new HashMap<String, String>();

            int startPosition = endpointURL.indexOf("${");
            while (startPosition > -1) {
                int endPosition = endpointURL.indexOf("}", startPosition);
                if (endPosition > -1) {
                    String key = endpointURL.substring(startPosition + 2, endPosition);
                    Object value = input.get(key);
                    if (value instanceof RequestParameter[]) {
                        // now change input value object from RequestParameter[] to String
                        // and add to inputContext Map.
                        RequestParameter[] requestParameters = (RequestParameter[]) value;
                        inputContext.put(key, requestParameters[0].getString());
                    } else {
                        // KERN-1346 regression; see KERN-1409
                        inputContext.put(key, String.valueOf(value));
                    }
                    // look for the next velocity replacement variable
                    startPosition = endpointURL.indexOf("${", endPosition);
                } else {
                    break;
                }
            }

            VelocityContext context = new VelocityContext(inputContext);

            // add in the config properties from the bundle overwriting everythign else.
            context.put("config", configProperties);

            endpointURL = processUrlTemplate(endpointURL, context);

            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) {
                    logger.debug("The Proxy request specified by  " + node + " failed, cause follows:", e);
                }
            }
            HttpMethod method = null;
            switch (proxyMethod) {
            case GET:
                if (node.hasProperty(SAKAI_LIMIT_GET_SIZE)) {
                    long maxSize = node.getProperty(SAKAI_LIMIT_GET_SIZE).getLong();
                    method = new HeadMethod(endpointURL);
                    HttpMethodParams params = new HttpMethodParams(method.getParams());
                    // make certain we reject the body of a head
                    params.setBooleanParameter("http.protocol.reject-head-body", true);
                    method.setParams(params);
                    method.setFollowRedirects(true);
                    populateMethod(method, node, headers);
                    int result = httpClient.executeMethod(method);
                    if (externalAuthenticatingProxy && result == 407) {
                        method.releaseConnection();
                        method.setDoAuthentication(true);
                        result = httpClient.executeMethod(method);
                    }
                    if (result == 200) {
                        // Check if the content-length is smaller than the maximum (if any).
                        Header contentLengthHeader = method.getResponseHeader("Content-Length");
                        if (contentLengthHeader != null) {
                            long length = Long.parseLong(contentLengthHeader.getValue());
                            if (length > maxSize) {
                                return new ProxyResponseImpl(HttpServletResponse.SC_PRECONDITION_FAILED,
                                        "Response too large", method);
                            }
                        }
                    } else {
                        return new ProxyResponseImpl(result, method);
                    }
                }
                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);
                HttpMethodParams params = new HttpMethodParams(method.getParams());
                // make certain we reject the body of a head
                params.setBooleanParameter("http.protocol.reject-head-body", true);
                method.setParams(params);
                // 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);

            }

            populateMethod(method, node, headers);

            if (requestInputStream == null && !node.hasProperty(SAKAI_PROXY_REQUEST_TEMPLATE)) {
                if (method instanceof PostMethod) {
                    PostMethod postMethod = (PostMethod) method;
                    ArrayList<Part> parts = new ArrayList<Part>();
                    for (Entry<String, Object> param : input.entrySet()) {
                        String key = param.getKey();
                        Object value = param.getValue();
                        if (value instanceof RequestParameter[]) {
                            for (RequestParameter val : (RequestParameter[]) param.getValue()) {
                                Part part = null;
                                if (val.isFormField()) {
                                    part = new StringPart(param.getKey(), val.getString());
                                } else {
                                    ByteArrayPartSource source = new ByteArrayPartSource(key, val.get());
                                    part = new FilePart(key, source);
                                }
                                parts.add(part);
                            }
                        } else {
                            parts.add(new StringPart(key, value.toString()));
                        }
                        Part[] partsArray = parts.toArray(new Part[parts.size()]);
                        postMethod.setRequestEntity(new MultipartRequestEntity(partsArray, method.getParams()));
                    }
                }
            } else {

                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 (externalAuthenticatingProxy && result == 407) {
                method.releaseConnection();
                method.setDoAuthentication(true);
                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);
                if (externalAuthenticatingProxy && result == 407) {
                    method.releaseConnection();
                    method.setDoAuthentication(true);
                    result = httpClient.executeMethod(method);
                }
            }

            return new ProxyResponseImpl(result, method);
        }

    } catch (ProxyClientException e) {
        throw e;
    } 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 ");
}