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.apache.abdera.ext.oauth.OAuthScheme.java

private HttpMethod resolveMethod(String method, String uri) throws AuthenticationException {
    if (method.equalsIgnoreCase("get")) {
        return new GetMethod(uri);
    } else if (method.equalsIgnoreCase("post")) {
        return new PostMethod(uri);
    } else if (method.equalsIgnoreCase("put")) {
        return new PutMethod(uri);
    } else if (method.equalsIgnoreCase("delete")) {
        return new DeleteMethod(uri);
    } else if (method.equalsIgnoreCase("head")) {
        return new HeadMethod(uri);
    } else if (method.equalsIgnoreCase("options")) {
        return new OptionsMethod(uri);
    } else {/*from w w w  .  java 2s .c  o  m*/
        // throw new AuthenticationException("unsupported http method : " + method);
        return new MethodHelper.ExtensionMethod(method, uri);
    }
}

From source file:org.apache.abdera.protocol.client.util.MethodHelper.java

public static HttpMethod createMethod(String method, String uri, RequestEntity entity, RequestOptions options) {
    if (method == null)
        return null;
    Method m = Method.fromString(method);
    Method actual = null;/*from w  ww. j a  va2 s  . c o  m*/
    HttpMethod httpMethod = null;
    if (options.isUsePostOverride()) {
        if (m.equals(Method.PUT)) {
            actual = m;
        } else if (m.equals(Method.DELETE)) {
            actual = m;
        }
        if (actual != null)
            m = Method.POST;
    }
    switch (m) {
    case GET:
        httpMethod = new GetMethod(uri);
        break;
    case POST:
        httpMethod = getMethod(new PostMethod(uri), entity);
        break;
    case PUT:
        httpMethod = getMethod(new PutMethod(uri), entity);
        break;
    case DELETE:
        httpMethod = new DeleteMethod(uri);
        break;
    case HEAD:
        httpMethod = new HeadMethod(uri);
        break;
    case OPTIONS:
        httpMethod = new OptionsMethod(uri);
        break;
    case TRACE:
        httpMethod = new TraceMethod(uri);
        break;
    default:
        httpMethod = getMethod(new ExtensionMethod(method, uri), entity);
    }
    if (actual != null) {
        httpMethod.addRequestHeader("X-HTTP-Method-Override", actual.name());
    }
    initHeaders(options, httpMethod);

    // by default use expect-continue is enabled on the client
    // only disable if explicitly disabled
    if (!options.isUseExpectContinue())
        httpMethod.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);

    // should we follow redirects, default is true
    if (!(httpMethod instanceof EntityEnclosingMethod))
        httpMethod.setFollowRedirects(options.isFollowRedirects());

    return httpMethod;
}

From source file:org.apache.ambari.funtest.server.AmbariHttpWebRequest.java

/**
 * Constructs a PutMethod instance and sets the request data on it.
 *
 * @return - PutMethod.//w  ww.ja  v  a 2 s.  c  o  m
 */
@SuppressWarnings("deprecation")
private PutMethod getPutMethod() {
    PutMethod putMethod = new PutMethod(getUrl());

    putMethod.setRequestBody(getContent());

    return putMethod;
}

From source file:org.apache.camel.component.jetty.HttpRouteTest.java

@Test
public void testPutParameterInURI() throws Exception {
    HttpClient client = new HttpClient();
    PutMethod put = new PutMethod(
            "http://localhost:" + port1 + "/parameter?request=PutParameter&others=bloggs");
    StringRequestEntity entity = new StringRequestEntity(POST_MESSAGE, "application/xml", "UTF-8");
    put.setRequestEntity(entity);//from w  w  w . j a va 2 s  .  c  o  m
    client.executeMethod(put);
    InputStream response = put.getResponseBodyAsStream();
    String out = context.getTypeConverter().convertTo(String.class, response);
    assertEquals("Get a wrong output ", "PutParameter", out);
}

From source file:org.apache.cloudstack.network.element.SspClient.java

public SspClient(String apiUrl, String username, String password) {
    super();//www .  j  a v  a2  s  .com
    this.apiUrl = apiUrl;
    this.username = username;
    this.password = password;
    client = new HttpClient(s_httpclient_params, s_httpclient_manager);
    postMethod = new PostMethod(apiUrl);
    deleteMethod = new DeleteMethod(apiUrl);
    putMethod = new PutMethod(apiUrl);
}

From source file:org.apache.cocoon.HtmlUnitTestCase.java

/**
 * Sends HTTP PUT request and loads response object.
 *//*from  w  w w. jav a2  s  . c o m*/
protected void loadPutResponse(String pageURL, String content) throws Exception {
    URL url = new URL(baseURL, pageURL);
    PutMethod method = new PutMethod(url.toExternalForm());
    method.setRequestEntity(new StringRequestEntity(content));
    this.response = new HttpClientResponse(url, method);
}

From source file:org.apache.cocoon.transformation.SparqlTransformer.java

private void executeRequest(String url, String method, Map httpHeaders, SourceParameters requestParameters)
        throws ProcessingException, IOException, SAXException {
    HttpClient httpclient = new HttpClient();
    if (System.getProperty("http.proxyHost") != null) {
        // getLogger().warn("PROXY: "+System.getProperty("http.proxyHost"));
        String nonProxyHostsRE = System.getProperty("http.nonProxyHosts", "");
        if (nonProxyHostsRE.length() > 0) {
            String[] pHosts = nonProxyHostsRE.replaceAll("\\.", "\\\\.").replaceAll("\\*", ".*").split("\\|");
            nonProxyHostsRE = "";
            for (String pHost : pHosts) {
                nonProxyHostsRE += "|(^https?://" + pHost + ".*$)";
            }//from  w w w  .j a v  a 2  s.  c o  m
            nonProxyHostsRE = nonProxyHostsRE.substring(1);
        }
        if (nonProxyHostsRE.length() == 0 || !url.matches(nonProxyHostsRE)) {
            try {
                HostConfiguration hostConfiguration = httpclient.getHostConfiguration();
                hostConfiguration.setProxy(System.getProperty("http.proxyHost"),
                        Integer.parseInt(System.getProperty("http.proxyPort", "80")));
                httpclient.setHostConfiguration(hostConfiguration);
            } catch (Exception e) {
                throw new ProcessingException("Cannot set proxy!", e);
            }
        }
    }
    // Make the HttpMethod.
    HttpMethod httpMethod = null;
    // Do not use empty query parameter.
    if (requestParameters.getParameter(parameterName).trim().equals("")) {
        requestParameters.removeParameter(parameterName);
    }
    // Instantiate different HTTP methods.
    if ("GET".equalsIgnoreCase(method)) {
        httpMethod = new GetMethod(url);
        if (requestParameters.getEncodedQueryString() != null) {
            httpMethod.setQueryString(
                    requestParameters.getEncodedQueryString().replace("\"", "%22")); /* Also escape '"' */
        } else {
            httpMethod.setQueryString("");
        }
    } else if ("POST".equalsIgnoreCase(method)) {
        PostMethod httpPostMethod = new PostMethod(url);
        if (httpHeaders.containsKey(HTTP_CONTENT_TYPE) && ((String) httpHeaders.get(HTTP_CONTENT_TYPE))
                .startsWith("application/x-www-form-urlencoded")) {
            // Encode parameters in POST body.
            Iterator parNames = requestParameters.getParameterNames();
            while (parNames.hasNext()) {
                String parName = (String) parNames.next();
                httpPostMethod.addParameter(parName, requestParameters.getParameter(parName));
            }
        } else {
            // Use query parameter as POST body
            httpPostMethod.setRequestBody(requestParameters.getParameter(parameterName));
            // Add other parameters to query string
            requestParameters.removeParameter(parameterName);
            if (requestParameters.getEncodedQueryString() != null) {
                httpPostMethod.setQueryString(
                        requestParameters.getEncodedQueryString().replace("\"", "%22")); /* Also escape '"' */
            } else {
                httpPostMethod.setQueryString("");
            }
        }
        httpMethod = httpPostMethod;
    } else if ("PUT".equalsIgnoreCase(method)) {
        PutMethod httpPutMethod = new PutMethod(url);
        httpPutMethod.setRequestBody(requestParameters.getParameter(parameterName));
        requestParameters.removeParameter(parameterName);
        httpPutMethod.setQueryString(requestParameters.getEncodedQueryString());
        httpMethod = httpPutMethod;
    } else if ("DELETE".equalsIgnoreCase(method)) {
        httpMethod = new DeleteMethod(url);
        httpMethod.setQueryString(requestParameters.getEncodedQueryString());
    } else {
        throw new ProcessingException("Unsupported method: " + method);
    }
    // Authentication (optional).
    if (credentials != null && credentials.length() > 0) {
        String[] unpw = credentials.split("\t");
        httpclient.getParams().setAuthenticationPreemptive(true);
        httpclient.getState().setCredentials(new AuthScope(httpMethod.getURI().getHost(),
                httpMethod.getURI().getPort(), AuthScope.ANY_REALM),
                new UsernamePasswordCredentials(unpw[0], unpw[1]));
    }
    // Add request headers.
    Iterator headers = httpHeaders.entrySet().iterator();
    while (headers.hasNext()) {
        Map.Entry header = (Map.Entry) headers.next();
        httpMethod.addRequestHeader((String) header.getKey(), (String) header.getValue());
    }
    // Declare some variables before the try-block.
    XMLizer xmlizer = null;
    try {
        // Execute the request.
        int responseCode;
        responseCode = httpclient.executeMethod(httpMethod);
        // Handle errors, if any.
        if (responseCode < 200 || responseCode >= 300) {
            if (showErrors) {
                AttributesImpl attrs = new AttributesImpl();
                attrs.addCDATAAttribute("status", "" + responseCode);
                xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "error", "sparql:error", attrs);
                String responseBody = httpMethod.getStatusText(); //httpMethod.getResponseBodyAsString();
                xmlConsumer.characters(responseBody.toCharArray(), 0, responseBody.length());
                xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "error", "sparql:error");
                return; // Not a nice, but quick and dirty way to end.
            } else {
                throw new ProcessingException("Received HTTP status code " + responseCode + " "
                        + httpMethod.getStatusText() + ":\n" + httpMethod.getResponseBodyAsString());
            }
        }
        // Parse the response
        if (responseCode == 204) { // No content.
            String statusLine = httpMethod.getStatusLine().toString();
            xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "result", "sparql:result", EMPTY_ATTRIBUTES);
            xmlConsumer.characters(statusLine.toCharArray(), 0, statusLine.length());
            xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "result", "sparql:result");
        } else if (parse.equalsIgnoreCase("xml")) {
            InputStream responseBodyStream = httpMethod.getResponseBodyAsStream();
            xmlizer = (XMLizer) manager.lookup(XMLizer.ROLE);
            xmlizer.toSAX(responseBodyStream, "text/xml", httpMethod.getURI().toString(),
                    new IncludeXMLConsumer(xmlConsumer));
            responseBodyStream.close();
        } else if (parse.equalsIgnoreCase("text")) {
            xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "result", "sparql:result", EMPTY_ATTRIBUTES);
            String responseBody = httpMethod.getResponseBodyAsString();
            xmlConsumer.characters(responseBody.toCharArray(), 0, responseBody.length());
            xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "result", "sparql:result");
        } else {
            throw new ProcessingException("Unknown parse type: " + parse);
        }
    } catch (ServiceException e) {
        throw new ProcessingException("Cannot find the right XMLizer for " + XMLizer.ROLE, e);
    } finally {
        if (xmlizer != null)
            manager.release((Component) xmlizer);
        httpMethod.releaseConnection();
    }
}

From source file:org.apache.cxf.systest.jaxrs.JAXRSClientServerBookTest.java

@Test
public void testUpdateBook() throws Exception {
    String endpointAddress = "http://localhost:" + PORT + "/bookstore/books";

    File input = new File(getClass().getResource("resources/update_book.txt").toURI());
    PutMethod put = new PutMethod(endpointAddress);
    RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    put.setRequestEntity(entity);//from www .  j a  v a2s  .  c  o  m
    HttpClient httpclient = new HttpClient();

    try {
        int result = httpclient.executeMethod(put);
        assertEquals(200, result);
        InputStream expected = getClass().getResourceAsStream("resources/expected_update_book.txt");
        assertEquals(stripXmlInstructionIfNeeded(getStringFromInputStream(expected)),
                stripXmlInstructionIfNeeded(getStringFromInputStream(put.getResponseBodyAsStream())));
    } finally {
        // Release current connection to the connection pool once you are
        // done
        put.releaseConnection();
    }
}

From source file:org.apache.cxf.systest.jaxrs.JAXRSClientServerBookTest.java

@Test
public void testUpdateBookWithDom() throws Exception {
    String endpointAddress = "http://localhost:" + PORT + "/bookstore/bookswithdom";

    File input = new File(getClass().getResource("resources/update_book.txt").toURI());
    PutMethod put = new PutMethod(endpointAddress);
    RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    put.setRequestEntity(entity);/*from w w  w .j  a  va  2s.  c  o m*/
    HttpClient httpclient = new HttpClient();
    try {
        int result = httpclient.executeMethod(put);
        assertEquals(200, result);
        String resp = put.getResponseBodyAsString();
        InputStream expected = getClass().getResourceAsStream("resources/update_book.txt");
        String s = getStringFromInputStream(expected);
        //System.out.println(resp);
        //System.out.println(s);
        assertTrue(resp.indexOf(s) >= 0);
    } finally {
        // Release current connection to the connection pool once you are
        // done
        put.releaseConnection();
    }
}

From source file:org.apache.cxf.systest.jaxrs.JAXRSClientServerBookTest.java

@Test
public void testUpdateBookWithJSON() throws Exception {
    String endpointAddress = "http://localhost:" + PORT + "/bookstore/bookswithjson";

    File input = new File(getClass().getResource("resources/update_book_json.txt").toURI());
    PutMethod put = new PutMethod(endpointAddress);
    RequestEntity entity = new FileRequestEntity(input, "application/json; charset=ISO-8859-1");
    put.setRequestEntity(entity);//from  w  ww .ja  v a2 s  .  co  m
    HttpClient httpclient = new HttpClient();

    try {
        int result = httpclient.executeMethod(put);
        assertEquals(200, result);
        InputStream expected = getClass().getResourceAsStream("resources/expected_update_book.txt");
        assertEquals(stripXmlInstructionIfNeeded(getStringFromInputStream(expected)),
                stripXmlInstructionIfNeeded(getStringFromInputStream(put.getResponseBodyAsStream())));
    } finally {
        // Release current connection to the connection pool once you are
        // done
        put.releaseConnection();
    }
}