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.sakaiproject.entitybroker.util.http.HttpRESTUtils.java

/**
 * Fire off a request to a URL using the specified method but reuse the client for efficiency,
 * include optional params and data in the request,
 * the response data will be returned in the object if the request can be carried out
 * /*from w w w  .j a  v a  2 s.  c om*/
 * @param httpClientWrapper (optional) allows the http client to be reused for efficiency,
 * if null a new one will be created each time, use {@link #makeReusableHttpClient(boolean, int)} to
 * create a reusable instance
 * @param URL the url to send the request to (absolute or relative, can include query params)
 * @param method the method to use (e.g. GET, POST, etc.)
 * @param params (optional) params to send along with the request, will be encoded in the query string or in the body depending on the method
 * @param params (optional) headers to send along with the request, will be encoded in the headers
 * @param data (optional) data to send along in the body of the request, this only works for POST and PUT requests, ignored for the other types
 * @param guaranteeSSL if this is true then the request is sent in a mode which will allow self signed certs to work,
 * otherwise https requests will fail if the certs cannot be centrally verified
 * @return an object representing the response, includes data about the response
 * @throws HttpRequestException if the request cannot be processed for some reason (this is unrecoverable)
 */
@SuppressWarnings("deprecation")
public static HttpResponse fireRequest(HttpClientWrapper httpClientWrapper, String URL, Method method,
        Map<String, String> params, Map<String, String> headers, Object data, boolean guaranteeSSL) {
    if (guaranteeSSL) {
        // added this to attempt to force the SSL self signed certs to work
        Protocol myhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
        Protocol.registerProtocol("https", myhttps);
    }

    if (httpClientWrapper == null || httpClientWrapper.getHttpClient() == null) {
        httpClientWrapper = makeReusableHttpClient(false, 0, null);
    }

    HttpMethod httpMethod = null;
    if (method.equals(Method.GET)) {
        GetMethod gm = new GetMethod(URL);
        // put params into query string
        gm.setQueryString(mergeQueryStringWithParams(gm.getQueryString(), params));
        // warn about data being set
        if (data != null) {
            System.out.println(
                    "WARN: data cannot be passed in GET requests, data will be ignored (org.sakaiproject.entitybroker.util.http.HttpUtils#fireRequest)");
        }
        gm.setFollowRedirects(true);
        httpMethod = gm;
    } else if (method.equals(Method.POST)) {
        PostMethod pm = new PostMethod(URL);
        // special handling for post params
        if (params != null) {
            for (Entry<String, String> entry : params.entrySet()) {
                if (entry.getKey() == null || entry.getValue() == null) {
                    System.out.println("WARN: null value supplied for param name (" + entry.getKey()
                            + ") or value (" + entry.getValue()
                            + ") (org.sakaiproject.entitybroker.util.http.HttpUtils#fireRequest)");
                }
                pm.addParameter(entry.getKey(), entry.getValue());
            }
        }
        // handle data
        handleRequestData(pm, data);
        httpMethod = pm;
    } else if (method.equals(Method.PUT)) {
        PutMethod pm = new PutMethod(URL);
        // put params into query string
        pm.setQueryString(mergeQueryStringWithParams(pm.getQueryString(), params));
        // handle data
        handleRequestData(pm, data);
        httpMethod = pm;
    } else if (method.equals(Method.DELETE)) {
        DeleteMethod dm = new DeleteMethod(URL);
        // put params into query string
        dm.setQueryString(mergeQueryStringWithParams(dm.getQueryString(), params));
        // warn about data being set
        if (data != null) {
            System.out.println(
                    "WARN: data cannot be passed in DELETE requests, data will be ignored (org.sakaiproject.entitybroker.util.http.HttpUtils#fireRequest)");
        }
        httpMethod = dm;
    } else {
        throw new IllegalArgumentException("Cannot handle method: " + method);
    }
    // set the headers for the request
    if (headers != null) {
        for (Entry<String, String> entry : headers.entrySet()) {
            httpMethod.addRequestHeader(entry.getKey(), entry.getValue());
        }
    }

    HttpResponse response = null;
    try {
        int responseCode = httpClientWrapper.getHttpClient().executeMethod(httpMethod);
        response = new HttpResponse(responseCode);

        // Avoid DOS because of large responses using up all memory in the system - https://jira.sakaiproject.org/browse/SAK-20405
        InputStream is = httpMethod.getResponseBodyAsStream();
        StringBuffer out = new StringBuffer();
        byte[] b = new byte[4096];
        for (int n; (n = is.read(b)) != -1;) {
            out.append(new String(b, 0, n));
            if (out.length() > MAX_RESPONSE_SIZE_CHARS) {
                // die if the response exceeds the maximum chars allowed
                throw new HttpRequestException("Response size (" + out.length() + " chars) from url (" + URL
                        + ") exceeded the maximum allowed batch response size (" + MAX_RESPONSE_SIZE_CHARS
                        + " chars) while processing the response");
            }
        }
        String body = out.toString();

        //String body = httpMethod.getResponseBodyAsString();
        //         byte[] responseBody = httpMethod.getResponseBody();
        //         if (responseBody != null) {
        //            body = new String(responseBody, "UTF-8");
        //         }
        response.setResponseBody(body);
        response.setResponseMessage(httpMethod.getStatusText());
        // now get the headers
        HashMap<String, String[]> responseHeaders = new HashMap<String, String[]>();
        Header[] respHeaders = httpMethod.getResponseHeaders();
        for (int i = 0; i < respHeaders.length; i++) {
            Header header = respHeaders[i];
            // now we convert the headers from these odd pairs into something more like servlets expect
            HeaderElement[] elements = header.getElements();
            if (elements == null || elements.length == 0) {
                continue;
            } else if (elements.length >= 1) {
                String[] values = new String[elements.length];
                StringBuilder sb = new StringBuilder();
                for (int j = 0; j < elements.length; j++) {
                    sb.setLength(0); // clear the StringBuilder
                    sb.append(elements[j].getName());
                    if (elements[j].getValue() != null) {
                        sb.append("=");
                        sb.append(elements[j].getValue());
                    }
                    values[j] = sb.toString();
                }
                responseHeaders.put(header.getName(), values);
            }
        }
        response.setResponseHeaders(responseHeaders);
    } catch (HttpException he) {
        // error contained in he.getMessage()
        throw new HttpRequestException(
                "Fatal HTTP Request Error: " + "Could not sucessfully fire request to url (" + URL
                        + ") using method (" + method + ")  :: " + he.getMessage(),
                he);
    } catch (IOException ioe) {
        // other exception
        throw new HttpIOException(
                "IOException (transport/connection) Error: " + "Could not sucessfully fire request to url ("
                        + URL + ") using method (" + method + ")  :: " + ioe.getMessage(),
                ioe);
    } finally {
        httpMethod.releaseConnection();
    }
    return response;
}

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  .ja v a2s  .  c o m*/
 * <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 ");
}

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   w  w  w. j a  v a  2  s.  c o  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 ");
}

From source file:org.sipfoundry.sipxconfig.conference.ActiveConferenceContextImpl.java

@Override
public String executeCommand(Conference conference, String[] arguments) {
    HttpClient client = new HttpClient();
    String uri = getConferenceManagerRestUrl(conference, arguments);
    PutMethod putMethod = new PutMethod(uri);
    int statusCode = HttpStatus.SC_OK;
    String response = null;/*  w ww .  j a  va  2  s  .  c o m*/
    try {
        statusCode = client.executeMethod(putMethod);
        if (statusCode == HttpStatus.SC_OK) {
            response = putMethod.getResponseBodyAsString();
        }
    } catch (Exception ex) {
        response = "ERROR: " + ex.getMessage();
    }
    return response;
}

From source file:org.sipfoundry.sipxconfig.vm.MailboxManagerImpl.java

private void invokeWebservice(String uri) {
    PutMethod httpPut = null;//from   w ww  .ja v a  2 s  .c  o  m
    String host = null;
    String port = null;
    SipxIvrService ivrService = (SipxIvrService) m_sipxServiceManager
            .getServiceByBeanId(SipxIvrService.BEAN_ID);

    Location ivrLocation = (Location) singleResult(m_locationsManager.getLocationsForService(ivrService));
    if (ivrLocation == null) {
        throw new UserException("&voicemail.install.error");
    }
    try {
        HttpClient client = new HttpClient();
        host = ivrLocation.getFqdn();
        port = ivrService.getHttpsPort();
        httpPut = new PutMethod(getMailboxServerUrl(host, Integer.parseInt(port)) + uri);
        int statusCode = client.executeMethod(httpPut);
        if (statusCode != 200) {
            throw new UserException("&error.https.server.status.code", host, String.valueOf(statusCode));
        }
    } catch (HttpException ex) {
        throw new UserException("&error.https.server", host, ex.getMessage());
    } catch (IOException ex) {
        throw new UserException("&error.io.exception", host, ex.getMessage());
    } finally {
        if (httpPut != null) {
            httpPut.releaseConnection();
        }
    }
}

From source file:org.soa4all.dashboard.gwt.module.wsmolite.server.WsmoLiteDataServiceImpl.java

@Override
public String proxifyRequest(String method, String url, Map<String, String> headers) throws Exception {

    HttpMethod httpMtd;/*from w  ww.j  a  va 2  s .c  om*/
    if (method.equalsIgnoreCase("post")) {
        httpMtd = new PostMethod(url);
    }
    if (method.equalsIgnoreCase("put")) {
        httpMtd = new PutMethod(url);
    }
    if (method.equalsIgnoreCase("delete")) {
        httpMtd = new DeleteMethod(url);
    } else {
        httpMtd = new GetMethod(url);
    }

    if (headers != null) {
        for (String key : headers.keySet()) {
            httpMtd.addRequestHeader(key, headers.get(key));
        }
    }

    HttpClient httpclient = new HttpClient();
    try {
        int result = httpclient.executeMethod(httpMtd);
        if (result != 200) {
            if (httpMtd.getResponseHeader("Error") != null) {
                throw new Exception(httpMtd.getResponseHeader("Error").getValue());
            }
            throw new Exception("Service error code - " + result);
        }
        BufferedInputStream response = new BufferedInputStream(httpMtd.getResponseBodyAsStream());
        ByteArrayOutputStream resultBuffer = new ByteArrayOutputStream();

        byte[] buffer = new byte[1000];
        int i;
        do {
            i = response.read(buffer);
            if (i > 0) {
                resultBuffer.write(buffer, 0, i);
            }
        } while (i > 0);
        httpMtd.releaseConnection();

        return resultBuffer.toString("UTF-8");
    } catch (Exception exc) {
        httpMtd.releaseConnection();
        throw new Exception(exc.getClass().getSimpleName() + " : " + exc.getMessage());
    }
}

From source file:org.sonar.wsclient.connectors.HttpClient3Connector.java

private HttpMethodBase newPutRequest(UpdateQuery<?> query) {
    PutMethod method = new PutMethod(server.getHost() + query.getUrl());
    initRequest(method, query);//from   w  w w.  j  a  va 2s.c o  m
    setRequestEntity(method, query);
    return method;
}

From source file:org.sonatype.nexus.integrationtests.nexus4548.Nexus4548RepoTargetPermissionMatchesPathInRepoIT.java

private HttpMethod put(final String gavPath, final int code) throws Exception {
    PutMethod putMethod = new PutMethod(getNexusTestRepoUrl() + gavPath);
    putMethod.setRequestEntity(new FileRequestEntity(getTestFile("pom-a.pom"), "text/xml"));

    final HttpMethod httpMethod = RequestFacade.executeHTTPClientMethod(putMethod);
    assertThat(httpMethod.getStatusCode(), Matchers.is(code));

    return httpMethod;
}

From source file:org.sonatype.nexus.integrationtests.nxcm970.ContinuousDeployer.java

public void run() {
    PutMethod method = new PutMethod(targetUrl);

    method.setRequestEntity(new InputStreamRequestEntity(new EndlessBlockingInputStream(this)));

    try {//from   www. j av a2s.  c om
        result = httpClient.executeMethod(method);
    } catch (Exception e) {
        result = -2;

        e.printStackTrace();
    }
}

From source file:org.sonatype.nexus.proxy.storage.remote.commonshttpclient.CommonsHttpClientRemoteStorage.java

@Override
public void storeItem(ProxyRepository repository, StorageItem item)
        throws UnsupportedStorageOperationException, RemoteStorageException {
    if (!(item instanceof StorageFileItem)) {
        throw new UnsupportedStorageOperationException("Storing of non-files remotely is not supported!");
    }/* www .  j a v  a2s.  c o  m*/

    StorageFileItem fItem = (StorageFileItem) item;

    ResourceStoreRequest request = new ResourceStoreRequest(item);

    URL remoteURL = getAbsoluteUrlFromBase(repository, request);

    PutMethod method = new PutMethod(remoteURL.toString());

    try {
        method.setRequestEntity(
                new InputStreamRequestEntity(fItem.getInputStream(), fItem.getLength(), fItem.getMimeType()));

        int response = executeMethod(repository, request, method, remoteURL);

        if (response != HttpStatus.SC_OK && response != HttpStatus.SC_CREATED
                && response != HttpStatus.SC_NO_CONTENT && response != HttpStatus.SC_ACCEPTED) {
            throw new RemoteStorageException("Unexpected response code while executing " + method.getName()
                    + " method [repositoryId=\"" + repository.getId() + "\", requestPath=\""
                    + request.getRequestPath() + "\", remoteUrl=\"" + remoteURL.toString()
                    + "\"]. Expected: \"any success (2xx)\". Received: " + response + " : "
                    + HttpStatus.getStatusText(response));
        }
    } catch (IOException e) {
        throw new RemoteStorageException(
                e.getMessage() + " [repositoryId=\"" + repository.getId() + "\", requestPath=\""
                        + request.getRequestPath() + "\", remoteUrl=\"" + remoteURL.toString() + "\"]",
                e);
    } finally {
        method.releaseConnection();
    }
}