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

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

Introduction

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

Prototype

public PutMethod(String paramString) 

Source Link

Usage

From source file:org.josso.tc50.gateway.reverseproxy.ReverseProxyValve.java

/**
 * Intercepts Http request and redirects it to the configured SSO partner application.
 *
 * @param request The servlet request to be processed
 * @param response The servlet response to be created
 * @param valveContext The valve _context used to invoke the next valve
 *  in the current processing pipeline/*  w w w .  j  ava2  s. co  m*/
 * @exception IOException if an input/output error occurs
 * @exception javax.servlet.ServletException if a servlet error occurs
 */
public void invoke(Request request, Response response, ValveContext valveContext)
        throws IOException, javax.servlet.ServletException {

    if (debug >= 1)
        log("ReverseProxyValve Acting.");

    ProxyContextConfig[] contexts = _rpc.getProxyContexts();

    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();

    HttpServletRequest hsr = (HttpServletRequest) request.getRequest();
    String uri = hsr.getRequestURI();

    String uriContext = null;

    StringTokenizer st = new StringTokenizer(uri.substring(1), "/");
    while (st.hasMoreTokens()) {
        String token = st.nextToken();
        uriContext = "/" + token;
        break;
    }

    if (uriContext == null)
        uriContext = uri;

    // Obtain the target host from the
    String proxyForwardHost = null;
    String proxyForwardUri = null;

    for (int i = 0; i < contexts.length; i++) {
        if (contexts[i].getContext().equals(uriContext)) {
            log("Proxy context mapped to host/uri: " + contexts[i].getForwardHost()
                    + contexts[i].getForwardUri());
            proxyForwardHost = contexts[i].getForwardHost();
            proxyForwardUri = contexts[i].getForwardUri();
            break;
        }
    }

    if (proxyForwardHost == null) {
        log("URI '" + uri + "' can't be mapped to host");
        valveContext.invokeNext(request, response);
        return;
    }

    if (proxyForwardUri == null) {
        // trim the uri context before submitting the http request
        int uriTrailStartPos = uri.substring(1).indexOf("/") + 1;
        proxyForwardUri = uri.substring(uriTrailStartPos);
    } else {
        int uriTrailStartPos = uri.substring(1).indexOf("/") + 1;
        proxyForwardUri = proxyForwardUri + uri.substring(uriTrailStartPos);
    }

    // log ("Proxy request mapped to " + "http://" + proxyForwardHost + proxyForwardUri);

    HttpMethod method;

    // to be moved to a builder which instantiates and build concrete methods.
    if (hsr.getMethod().equals(METHOD_GET)) {
        // Create a method instance.
        HttpMethod getMethod = new GetMethod(proxyForwardHost + proxyForwardUri
                + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : ""));
        method = getMethod;
    } else if (hsr.getMethod().equals(METHOD_POST)) {
        // Create a method instance.
        PostMethod postMethod = new PostMethod(proxyForwardHost + proxyForwardUri
                + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : ""));
        postMethod.setRequestBody(hsr.getInputStream());
        method = postMethod;
    } else if (hsr.getMethod().equals(METHOD_HEAD)) {
        // Create a method instance.
        HeadMethod headMethod = new HeadMethod(proxyForwardHost + proxyForwardUri
                + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : ""));
        method = headMethod;
    } else if (hsr.getMethod().equals(METHOD_PUT)) {
        method = new PutMethod(proxyForwardHost + proxyForwardUri
                + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : ""));
    } else
        throw new java.lang.UnsupportedOperationException("Unknown method : " + hsr.getMethod());

    // copy incoming http headers to reverse proxy request
    Enumeration hne = hsr.getHeaderNames();
    while (hne.hasMoreElements()) {
        String hn = (String) hne.nextElement();

        // Map the received host header to the target host name
        // so that the configured virtual domain can
        // do the proper handling.
        if (hn.equalsIgnoreCase("host")) {
            method.addRequestHeader("Host", proxyForwardHost);
            continue;
        }

        Enumeration hvals = hsr.getHeaders(hn);
        while (hvals.hasMoreElements()) {
            String hv = (String) hvals.nextElement();
            method.addRequestHeader(hn, hv);
        }
    }

    // Add Reverse-Proxy-Host header
    String reverseProxyHost = getReverseProxyHost(request);
    method.addRequestHeader(Constants.JOSSO_REVERSE_PROXY_HEADER, reverseProxyHost);

    if (debug >= 1)
        log("Sending " + Constants.JOSSO_REVERSE_PROXY_HEADER + " " + reverseProxyHost);

    // DO NOT follow redirects !
    method.setFollowRedirects(false);

    // By default the httpclient uses HTTP v1.1. We are downgrading it
    // to v1.0 so that the target server doesn't set a reply using chunked
    // transfer encoding which doesn't seem to be handled properly.
    // Check how to make chunked transfer encoding work.
    client.getParams().setVersion(new HttpVersion(1, 0));

    // Execute the method.
    int statusCode = -1;
    try {
        // execute the method.
        statusCode = client.executeMethod(method);
    } catch (HttpRecoverableException e) {
        log("A recoverable exception occurred " + e.getMessage());
    } catch (IOException e) {
        log("Failed to connect.");
        e.printStackTrace();
    }

    // Check that we didn't run out of retries.
    if (statusCode == -1) {
        log("Failed to recover from exception.");
    }

    // Read the response body.
    byte[] responseBody = method.getResponseBody();

    // Release the connection.
    method.releaseConnection();

    HttpServletResponse sres = (HttpServletResponse) response.getResponse();

    // First thing to do is to copy status code to response, otherwise
    // catalina will do it as soon as we set a header or some other part of the response.
    sres.setStatus(method.getStatusCode());

    // copy proxy response headers to client response
    Header[] responseHeaders = method.getResponseHeaders();
    for (int i = 0; i < responseHeaders.length; i++) {
        Header responseHeader = responseHeaders[i];
        String name = responseHeader.getName();
        String value = responseHeader.getValue();

        // Adjust the URL in the Location, Content-Location and URI headers on HTTP redirect responses
        // This is essential to avoid by-passing the reverse proxy because of HTTP redirects on the
        // backend servers which stay behind the reverse proxy
        switch (method.getStatusCode()) {
        case HttpStatus.SC_MOVED_TEMPORARILY:
        case HttpStatus.SC_MOVED_PERMANENTLY:
        case HttpStatus.SC_SEE_OTHER:
        case HttpStatus.SC_TEMPORARY_REDIRECT:

            if ("Location".equalsIgnoreCase(name) || "Content-Location".equalsIgnoreCase(name)
                    || "URI".equalsIgnoreCase(name)) {

                // Check that this redirect must be adjusted.
                if (value.indexOf(proxyForwardHost) >= 0) {
                    String trail = value.substring(proxyForwardHost.length());
                    value = getReverseProxyHost(request) + trail;
                    if (debug >= 1)
                        log("Adjusting redirect header to " + value);
                }
            }
            break;

        } //end of switch
        sres.addHeader(name, value);

    }

    // Sometimes this is null, when no body is returned ...
    if (responseBody != null && responseBody.length > 0)
        sres.getOutputStream().write(responseBody);

    sres.getOutputStream().flush();

    if (debug >= 1)
        log("ReverseProxyValve finished.");

    return;
}

From source file:org.josso.tc55.gateway.reverseproxy.ReverseProxyValve.java

/**
 * Intercepts Http request and redirects it to the configured SSO partner application.
 *
 * @param request The servlet request to be processed
 * @param response The servlet response to be created
 *  in the current processing pipeline//  w w  w  . j a va2 s .  c o  m
 * @exception IOException if an input/output error occurs
 * @exception javax.servlet.ServletException if a servlet error occurs
 */
public void invoke(Request request, Response response) throws IOException, javax.servlet.ServletException {

    if (container.getLogger().isDebugEnabled())
        container.getLogger().debug("ReverseProxyValve Acting.");

    ProxyContextConfig[] contexts = _rpc.getProxyContexts();

    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();

    HttpServletRequest hsr = (HttpServletRequest) request.getRequest();
    String uri = hsr.getRequestURI();

    String uriContext = null;

    StringTokenizer st = new StringTokenizer(uri.substring(1), "/");
    while (st.hasMoreTokens()) {
        String token = st.nextToken();
        uriContext = "/" + token;
        break;
    }

    if (uriContext == null)
        uriContext = uri;

    // Obtain the target host from the
    String proxyForwardHost = null;
    String proxyForwardUri = null;

    for (int i = 0; i < contexts.length; i++) {
        if (contexts[i].getContext().equals(uriContext)) {
            log("Proxy context mapped to host/uri: " + contexts[i].getForwardHost()
                    + contexts[i].getForwardUri());
            proxyForwardHost = contexts[i].getForwardHost();
            proxyForwardUri = contexts[i].getForwardUri();
            break;
        }
    }

    if (proxyForwardHost == null) {
        log("URI '" + uri + "' can't be mapped to host");
        getNext().invoke(request, response);
        return;
    }

    if (proxyForwardUri == null) {
        // trim the uri context before submitting the http request
        int uriTrailStartPos = uri.substring(1).indexOf("/") + 1;
        proxyForwardUri = uri.substring(uriTrailStartPos);
    } else {
        int uriTrailStartPos = uri.substring(1).indexOf("/") + 1;
        proxyForwardUri = proxyForwardUri + uri.substring(uriTrailStartPos);
    }

    // log ("Proxy request mapped to " + "http://" + proxyForwardHost + proxyForwardUri);

    HttpMethod method;

    // to be moved to a builder which instantiates and build concrete methods.
    if (hsr.getMethod().equals(METHOD_GET)) {
        // Create a method instance.
        HttpMethod getMethod = new GetMethod(proxyForwardHost + proxyForwardUri
                + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : ""));
        method = getMethod;
    } else if (hsr.getMethod().equals(METHOD_POST)) {
        // Create a method instance.
        PostMethod postMethod = new PostMethod(proxyForwardHost + proxyForwardUri
                + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : ""));
        postMethod.setRequestBody(hsr.getInputStream());
        method = postMethod;
    } else if (hsr.getMethod().equals(METHOD_HEAD)) {
        // Create a method instance.
        HeadMethod headMethod = new HeadMethod(proxyForwardHost + proxyForwardUri
                + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : ""));
        method = headMethod;
    } else if (hsr.getMethod().equals(METHOD_PUT)) {
        method = new PutMethod(proxyForwardHost + proxyForwardUri
                + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : ""));
    } else
        throw new java.lang.UnsupportedOperationException("Unknown method : " + hsr.getMethod());

    // copy incoming http headers to reverse proxy request
    Enumeration hne = hsr.getHeaderNames();
    while (hne.hasMoreElements()) {
        String hn = (String) hne.nextElement();

        // Map the received host header to the target host name
        // so that the configured virtual domain can
        // do the proper handling.
        if (hn.equalsIgnoreCase("host")) {
            method.addRequestHeader("Host", proxyForwardHost);
            continue;
        }

        Enumeration hvals = hsr.getHeaders(hn);
        while (hvals.hasMoreElements()) {
            String hv = (String) hvals.nextElement();
            method.addRequestHeader(hn, hv);
        }
    }

    // Add Reverse-Proxy-Host header
    String reverseProxyHost = getReverseProxyHost(request);
    method.addRequestHeader(Constants.JOSSO_REVERSE_PROXY_HEADER, reverseProxyHost);

    if (container.getLogger().isDebugEnabled())
        container.getLogger().debug("Sending " + Constants.JOSSO_REVERSE_PROXY_HEADER + " " + reverseProxyHost);

    // DO NOT follow redirects !
    method.setFollowRedirects(false);

    // By default the httpclient uses HTTP v1.1. We are downgrading it
    // to v1.0 so that the target server doesn't set a reply using chunked
    // transfer encoding which doesn't seem to be handled properly.
    // Check how to make chunked transfer encoding work.
    client.getParams().setVersion(new HttpVersion(1, 0));

    // Execute the method.
    int statusCode = -1;
    try {
        // execute the method.
        statusCode = client.executeMethod(method);
    } catch (HttpRecoverableException e) {
        log("A recoverable exception occurred " + e.getMessage());
    } catch (IOException e) {
        log("Failed to connect.");
        e.printStackTrace();
    }

    // Check that we didn't run out of retries.
    if (statusCode == -1) {
        log("Failed to recover from exception.");
    }

    // Read the response body.
    byte[] responseBody = method.getResponseBody();

    // Release the connection.
    method.releaseConnection();

    HttpServletResponse sres = (HttpServletResponse) response.getResponse();

    // First thing to do is to copy status code to response, otherwise
    // catalina will do it as soon as we set a header or some other part of the response.
    sres.setStatus(method.getStatusCode());

    // copy proxy response headers to client response
    Header[] responseHeaders = method.getResponseHeaders();
    for (int i = 0; i < responseHeaders.length; i++) {
        Header responseHeader = responseHeaders[i];
        String name = responseHeader.getName();
        String value = responseHeader.getValue();

        // Adjust the URL in the Location, Content-Location and URI headers on HTTP redirect responses
        // This is essential to avoid by-passing the reverse proxy because of HTTP redirects on the
        // backend servers which stay behind the reverse proxy
        switch (method.getStatusCode()) {
        case HttpStatus.SC_MOVED_TEMPORARILY:
        case HttpStatus.SC_MOVED_PERMANENTLY:
        case HttpStatus.SC_SEE_OTHER:
        case HttpStatus.SC_TEMPORARY_REDIRECT:

            if ("Location".equalsIgnoreCase(name) || "Content-Location".equalsIgnoreCase(name)
                    || "URI".equalsIgnoreCase(name)) {

                // Check that this redirect must be adjusted.
                if (value.indexOf(proxyForwardHost) >= 0) {
                    String trail = value.substring(proxyForwardHost.length());
                    value = getReverseProxyHost(request) + trail;
                    if (container.getLogger().isDebugEnabled())
                        container.getLogger().debug("Adjusting redirect header to " + value);
                }
            }
            break;

        } //end of switch
        sres.addHeader(name, value);

    }

    // Sometimes this is null, when no body is returned ...
    if (responseBody != null && responseBody.length > 0)
        sres.getOutputStream().write(responseBody);

    sres.getOutputStream().flush();

    if (container.getLogger().isDebugEnabled())
        container.getLogger().debug("ReverseProxyValve finished.");

    return;
}

From source file:org.josso.tc60.gateway.reverseproxy.ReverseProxyValve.java

/**
 * Intercepts Http request and redirects it to the configured SSO partner application.
 *
 * @param request The servlet request to be processed
 * @param response The servlet response to be created
 *  in the current processing pipeline//from   w ww.j  a  v a2s.c o m
 * @exception IOException if an input/output error occurs
 * @exception javax.servlet.ServletException if a servlet error occurs
 */
public void invoke(Request request, Response response) throws IOException, javax.servlet.ServletException {

    if (container.getLogger().isDebugEnabled())
        container.getLogger().debug("ReverseProxyValve Acting.");

    ProxyContextConfig[] contexts = _rpc.getProxyContexts();

    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();

    HttpServletRequest hsr = (HttpServletRequest) request.getRequest();
    String uri = hsr.getRequestURI();

    String uriContext = null;

    StringTokenizer st = new StringTokenizer(uri.substring(1), "/");
    while (st.hasMoreTokens()) {
        String token = st.nextToken();
        uriContext = "/" + token;
        break;
    }

    if (uriContext == null)
        uriContext = uri;

    // Obtain the target host from the
    String proxyForwardHost = null;
    String proxyForwardUri = null;

    for (int i = 0; i < contexts.length; i++) {
        if (contexts[i].getContext().equals(uriContext)) {
            log("Proxy context mapped to host/uri: " + contexts[i].getForwardHost()
                    + contexts[i].getForwardUri());
            proxyForwardHost = contexts[i].getForwardHost();
            proxyForwardUri = contexts[i].getForwardUri();
            break;
        }
    }

    if (proxyForwardHost == null) {
        log("URI '" + uri + "' can't be mapped to host");
        getNext().invoke(request, response);
        return;
    }

    if (proxyForwardUri == null) {
        // trim the uri context before submitting the http request
        int uriTrailStartPos = uri.substring(1).indexOf("/") + 1;
        proxyForwardUri = uri.substring(uriTrailStartPos);
    } else {
        int uriTrailStartPos = uri.substring(1).indexOf("/") + 1;
        proxyForwardUri = proxyForwardUri + uri.substring(uriTrailStartPos);
    }

    // log ("Proxy request mapped to " + "http://" + proxyForwardHost + proxyForwardUri);

    HttpMethod method;

    // to be moved to a builder which instantiates and build concrete methods.
    if (hsr.getMethod().equals(METHOD_GET)) {
        // Create a method instance.
        HttpMethod getMethod = new GetMethod(proxyForwardHost + proxyForwardUri
                + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : ""));
        method = getMethod;
    } else if (hsr.getMethod().equals(METHOD_POST)) {
        // Create a method instance.
        PostMethod postMethod = new PostMethod(proxyForwardHost + proxyForwardUri
                + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : ""));
        postMethod.setRequestBody(hsr.getInputStream());
        method = postMethod;
    } else if (hsr.getMethod().equals(METHOD_HEAD)) {
        // Create a method instance.
        HeadMethod headMethod = new HeadMethod(proxyForwardHost + proxyForwardUri
                + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : ""));
        method = headMethod;
    } else if (hsr.getMethod().equals(METHOD_PUT)) {
        method = new PutMethod(proxyForwardHost + proxyForwardUri
                + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : ""));
    } else
        throw new java.lang.UnsupportedOperationException("Unknown method : " + hsr.getMethod());

    // copy incoming http headers to reverse proxy request
    Enumeration hne = hsr.getHeaderNames();
    while (hne.hasMoreElements()) {
        String hn = (String) hne.nextElement();

        // Map the received host header to the target host name
        // so that the configured virtual domain can
        // do the proper handling.
        if (hn.equalsIgnoreCase("host")) {
            method.addRequestHeader("Host", proxyForwardHost);
            continue;
        }

        Enumeration hvals = hsr.getHeaders(hn);
        while (hvals.hasMoreElements()) {
            String hv = (String) hvals.nextElement();
            method.addRequestHeader(hn, hv);
        }
    }

    // Add Reverse-Proxy-Host header
    String reverseProxyHost = getReverseProxyHost(request);
    method.addRequestHeader(Constants.JOSSO_REVERSE_PROXY_HEADER, reverseProxyHost);

    if (container.getLogger().isDebugEnabled())
        container.getLogger().debug("Sending " + Constants.JOSSO_REVERSE_PROXY_HEADER + " " + reverseProxyHost);

    // DO NOT follow redirects !
    method.setFollowRedirects(false);

    // By default the httpclient uses HTTP v1.1. We are downgrading it
    // to v1.0 so that the target server doesn't set a reply using chunked
    // transfer encoding which doesn't seem to be handled properly.
    client.getParams().setVersion(new HttpVersion(1, 0));

    // Execute the method.
    int statusCode = -1;
    try {
        // execute the method.
        statusCode = client.executeMethod(method);
    } catch (HttpRecoverableException e) {
        log("A recoverable exception occurred " + e.getMessage());
    } catch (IOException e) {
        log("Failed to connect.");
        e.printStackTrace();
    }

    // Check that we didn't run out of retries.
    if (statusCode == -1) {
        log("Failed to recover from exception.");
    }

    // Read the response body.
    byte[] responseBody = method.getResponseBody();

    // Release the connection.
    method.releaseConnection();

    HttpServletResponse sres = (HttpServletResponse) response.getResponse();

    // First thing to do is to copy status code to response, otherwise
    // catalina will do it as soon as we set a header or some other part of the response.
    sres.setStatus(method.getStatusCode());

    // copy proxy response headers to client response
    Header[] responseHeaders = method.getResponseHeaders();
    for (int i = 0; i < responseHeaders.length; i++) {
        Header responseHeader = responseHeaders[i];
        String name = responseHeader.getName();
        String value = responseHeader.getValue();

        // Adjust the URL in the Location, Content-Location and URI headers on HTTP redirect responses
        // This is essential to avoid by-passing the reverse proxy because of HTTP redirects on the
        // backend servers which stay behind the reverse proxy
        switch (method.getStatusCode()) {
        case HttpStatus.SC_MOVED_TEMPORARILY:
        case HttpStatus.SC_MOVED_PERMANENTLY:
        case HttpStatus.SC_SEE_OTHER:
        case HttpStatus.SC_TEMPORARY_REDIRECT:

            if ("Location".equalsIgnoreCase(name) || "Content-Location".equalsIgnoreCase(name)
                    || "URI".equalsIgnoreCase(name)) {

                // Check that this redirect must be adjusted.
                if (value.indexOf(proxyForwardHost) >= 0) {
                    String trail = value.substring(proxyForwardHost.length());
                    value = getReverseProxyHost(request) + trail;
                    if (container.getLogger().isDebugEnabled())
                        container.getLogger().debug("Adjusting redirect header to " + value);
                }
            }
            break;

        } //end of switch
        sres.addHeader(name, value);

    }

    // Sometimes this is null, when no body is returned ...
    if (responseBody != null && responseBody.length > 0)
        sres.getOutputStream().write(responseBody);

    sres.getOutputStream().flush();

    if (container.getLogger().isDebugEnabled())
        container.getLogger().debug("ReverseProxyValve finished.");

    return;
}

From source file:org.lgf.jahia.esni.service.ElasticSearchService.java

/**
 * //from  w ww. jav a2s . c om
 * Index un noeud <code>node</code> de type <code>type</code> (type elasticsearch)
 *  l'index <code>indexName</code>
 * 
 * @param node
 * @param indexName
 * @param type
 * @throws RepositoryException
 */
public void indexNode(JCRNodeWrapper node, String indexName, String type) throws RepositoryException {

    String baseUrl = "http://" + hostname + ":" + port + "/" + indexName + "/" + type + "/";
    HttpClient client = new HttpClient();

    String url = baseUrl + node.getIdentifier();
    logger.info("PUT " + url);

    try {

        PutMethod put = new PutMethod(url);
        put.setRequestBody(serializeNodeToJSON(node, 0).toString());

        client.executeMethod(put);

    } catch (IOException e) {
        logger.error("Error on PUT " + url, e);
    } catch (JSONException e) {
        logger.error("Error when serialize node to json", e);
    }

}

From source file:org.melati.admin.Admin.java

private String proxy(Melati melati, ServletTemplateContext context) {
    if (melati.getSession().getAttribute("generatedByMelatiClass") == null)
        throw new AnticipatedException("Only available from within an Admin generated page");
    String method = melati.getRequest().getMethod();
    String url = melati.getRequest().getQueryString();
    HttpServletResponse response = melati.getResponse();
    HttpMethod httpMethod = null;/*from  w  w  w .ja va2  s  .c o m*/
    try {

        HttpClient client = new HttpClient();
        if (method.equals("GET"))
            httpMethod = new GetMethod(url);
        else if (method.equals("POST"))
            httpMethod = new PostMethod(url);
        else if (method.equals("PUT"))
            httpMethod = new PutMethod(url);
        else if (method.equals("HEAD"))
            httpMethod = new HeadMethod(url);
        else
            throw new RuntimeException("Unexpected method '" + method + "'");
        try {
            httpMethod.setFollowRedirects(true);
            client.executeMethod(httpMethod);
            for (Header h : httpMethod.getResponseHeaders()) {
                response.setHeader(h.getName(), h.getValue());
            }
            response.setStatus(httpMethod.getStatusCode());
            response.setHeader("Cache-Control", "no-cache");
            byte[] outputBytes = httpMethod.getResponseBody();
            if (outputBytes != null) {
                response.setBufferSize(outputBytes.length);
                response.getWriter().write(new String(outputBytes));
                response.getWriter().flush();
            }
        } catch (Exception e) {
            throw new MelatiIOException(e);
        }
    } finally {
        if (httpMethod != null)
            httpMethod.releaseConnection();
    }
    return null;
}

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

private ZestResponse send(HttpClient httpclient, ZestRequest req) throws IOException {
    HttpMethod method;/* ww w.j  a va  2s  .  c o  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 testPut() throws Exception {
    PutMethod method = new PutMethod(getHttpEndpointAddress());
    int statusCode = client.executeMethod(method);
    assertEquals(HttpStatus.SC_OK, statusCode);
}

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

protected HttpMethod createPutMethod(MuleMessage msg, String outputEncoding) throws Exception {
    URI uri = getURI(msg);//from w ww . j ava  2 s .  c om
    PutMethod putMethod = new PutMethod(uri.toString());

    Object payload = msg.getPayload();
    setupEntityMethod(payload, outputEncoding, msg, putMethod);
    checkForContentType(msg, putMethod);
    return putMethod;
}

From source file:org.n52.wps.io.datahandler.generator.GeoServerUploader.java

private String sendRasterRequest(String target, String request, String method, String username, String password)
        throws HttpException, IOException {
    HttpClient client = new HttpClient();
    EntityEnclosingMethod requestMethod = null;
    if (method.equalsIgnoreCase("POST")) {
        requestMethod = new PostMethod(target);
        requestMethod.setRequestHeader("Content-type", "application/xml");
    }/*from  ww  w  .  j av a 2s . c om*/
    if (method.equalsIgnoreCase("PUT")) {
        requestMethod = new PutMethod(target);
        requestMethod.setRequestHeader("Content-type", "text/plain");

    }

    requestMethod.setRequestBody(request);

    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
    client.getState().setCredentials(null, null, creds);

    int statusCode = client.executeMethod(requestMethod);

    if (!((statusCode == HttpStatus.SC_OK) || (statusCode == HttpStatus.SC_CREATED))) {
        System.err.println("Method failed: " + requestMethod.getStatusLine());
    }

    // Read the response body.
    byte[] responseBody = requestMethod.getResponseBody();
    return new String(responseBody);
}

From source file:org.n52.wps.io.datahandler.generator.GeoServerUploader.java

private String sendShpRequest(String target, InputStream request, String method, String username,
        String password) throws HttpException, IOException {
    HttpClient client = new HttpClient();
    EntityEnclosingMethod requestMethod = null;
    if (method.equalsIgnoreCase("POST")) {
        requestMethod = new PostMethod(target);
        requestMethod.setRequestHeader("Content-type", "text/xml");
    }/*  w  ww . ja va  2  s. co m*/
    if (method.equalsIgnoreCase("PUT")) {
        requestMethod = new PutMethod(target);
        requestMethod.setRequestHeader("Content-type", "application/zip");

    }

    requestMethod.setRequestBody(request);

    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
    client.getState().setCredentials(null, null, creds);

    int statusCode = client.executeMethod(requestMethod);

    if (!((statusCode == HttpStatus.SC_OK) || (statusCode == HttpStatus.SC_CREATED))) {
        System.err.println("Method failed: " + requestMethod.getStatusLine());
    }

    // Read the response body.
    byte[] responseBody = requestMethod.getResponseBody();
    return new String(responseBody);
}