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

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

Introduction

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

Prototype

public void setRequestEntity(RequestEntity paramRequestEntity) 

Source Link

Usage

From source file:org.gradle.api.internal.artifacts.repositories.transport.http.HttpResourceCollection.java

private void doPut(File source, String destination) throws IOException {
    PutMethod method = new PutMethod(destination);
    configureMethod(method);/*from   ww  w .  j  av  a  2  s  .  com*/
    method.setRequestEntity(new FileRequestEntity(source));
    int result = executeMethod(method);
    if (!wasSuccessful(result)) {
        throw new IOException(String.format("Could not PUT '%s'. Received status code %s from server: %s",
                destination, result, method.getStatusText()));
    }
}

From source file:org.hydracache.client.http.HttpHydraCacheClient.java

@Override
public void put(Object key, Data data) {
    Identity identity = nodePartition.get(key);
    String uri = constructUri(key, identity);

    try {//from  w ww  .  ja v  a 2s. co  m
        PutMethod putMethod = new PutMethod(uri);
        Buffer buffer = Buffer.allocate();
        protocolEncoder.encode(new BlobDataMessage(data), buffer.asDataOutpuStream());

        RequestEntity requestEntity = new InputStreamRequestEntity(buffer.asDataInputStream());
        putMethod.setRequestEntity(requestEntity);

        validateResponseCode(httpClient.executeMethod(putMethod));
    } catch (IOException ioe) {
        logger.error("Cannot write to connection.", ioe);
    }
}

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

public int executePut() throws Exception {
    PutMethod method = null;
    try {/*from ww  w.ja v  a  2 s . c om*/
        HttpClient client = this.newHttpClient();
        method = new PutMethod(this.getTargetURL());
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(1, false));
        if (this.getRequestBody() != null)
            method.setRequestEntity(new InputStreamRequestEntity(this.getRequestBody()));
        ProxyFilterContainer filterContainer = (ProxyFilterContainer) SpringUtil.getBean(filterType);
        return filterContainer.invoke(client, method, this);
    } catch (ProxyAuthenticationException e) {
        if (e.isTraceOn()) {
            log.error(this.getTargetURL());
            log.error("", e);
        } else {
            log.warn(this.getTargetURL() + " : " + e.getMessage());
        }
        return 401;
    }
}

From source file:org.intalio.tempo.workflow.tas.core.WDSStorageStrategy.java

public String storeAttachment(Property[] props, AttachmentMetadata metadata, InputStream payload)
        throws IOException {
    // need to sanitize the filename because of some browsers (e.g. Internet Exploder)
    String filename = TASUtil.sanitize(metadata.getFilename());
    String uri = java.util.UUID.randomUUID().toString() + "/" + filename;
    String fullUrl = _wdsEndpoint + ATTACHMENT_URI_PREFIX + uri;

    PutMethod putMethod = new PutMethod(fullUrl);
    setUpMethod(putMethod);/*from w  w w  .j a  v  a 2  s  . c  o m*/
    putMethod.setRequestEntity(new InputStreamRequestEntity(payload));
    putMethod.setRequestHeader("Content-type", metadata.getMimeType());

    //HttpClient httpClient = new HttpClient();
    HttpClient httpClient = getClient();
    int code = httpClient.executeMethod(putMethod);
    if (code != 200) {
        throw new RuntimeException("Error code: " + code);
    }
    _logger.debug("Stored attachment at: '" + fullUrl + "'");
    return fullUrl;
}

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

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

From source file:org.jboss.examples.simpleRESTWS.client.Client.java

public static void main(String args[]) throws Exception {

    /**//from  w ww .java2  s  .co  m
     * HTTP GET http://localhost:8181/cxf/crm/customerservice/customers/123
     * returns the XML document representing customer 123
     *
     * On the server side, it matches the CustomerService's getCustomer() method
     */
    System.out.println("Sent HTTP GET request to query customer info");
    URL url = new URL("http://localhost:8181/cxf/crm/customerservice/customers/123");
    InputStream in = url.openStream();
    System.out.println(getStringFromInputStream(in));

    /**
     * HTTP GET http://localhost:8181/cxf/crm/customerservice/orders/223/products/323
     * returns the XML document representing product 323 in order 223
     *
     * On the server side, it matches the Order's getProduct() method
     */
    System.out.println("\n");
    System.out.println("Sent HTTP GET request to query sub resource product info");
    url = new URL("http://localhost:8181/cxf/crm/customerservice/orders/223/products/323");
    in = url.openStream();
    System.out.println(getStringFromInputStream(in));

    /**
     * HTTP PUT http://localhost:8181/cxf/crm/customerservice/customers is used to upload the contents of
     * the update_customer.xml file to update the customer information for customer 123.
     *
     * On the server side, it matches the CustomerService's updateCustomer() method
     */
    System.out.println("\n");
    System.out.println("Sent HTTP PUT request to update customer info");
    Client client = new Client();
    String inputFile = client.getClass().getResource("update_customer.xml").getFile();
    File input = new File(inputFile);
    PutMethod put = new PutMethod("http://localhost:8181/cxf/crm/customerservice/customers");
    RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    put.setRequestEntity(entity);
    HttpClient httpclient = new HttpClient();

    try {
        int result = httpclient.executeMethod(put);
        System.out.println("Response status code: " + result);
        System.out.println("Response body: ");
        System.out.println(put.getResponseBodyAsString());
    } finally {
        // Release current connection to the connection pool once you are
        // done
        put.releaseConnection();
    }

    /**
     * HTTP POST http://localhost:8181/cxf/crm/customerservice/customers is used to upload the contents of
     * the add_customer.xml file to add a new customer to the system.
     *
     * On the server side, it matches the CustomerService's addCustomer() method
     */
    System.out.println("\n");
    System.out.println("Sent HTTP POST request to add customer");
    inputFile = client.getClass().getResource("add_customer.xml").getFile();
    input = new File(inputFile);
    PostMethod post = new PostMethod("http://localhost:8181/cxf/crm/customerservice/customers");
    post.addRequestHeader("Accept", "text/xml");
    entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    post.setRequestEntity(entity);
    httpclient = new HttpClient();

    try {
        int result = httpclient.executeMethod(post);
        System.out.println("Response status code: " + result);
        System.out.println("Response body: ");
        System.out.println(post.getResponseBodyAsString());
    } finally {
        // Release current connection to the connection pool once you are
        // done
        post.releaseConnection();
    }

    System.out.println("\n");
    System.exit(0);
}

From source file:org.jboss.fuse.examples.cxf.jaxrs.security.client.Client.java

public static void main(String args[]) throws Exception {
    // Now we need to use the basic authentication to send the request
    HttpClient httpClient = new HttpClient();
    httpClient.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("admin", "admin"));
    // Use basic authentication
    AuthScheme scheme = new BasicScheme();

    /**/*from   w  w  w.  ja v  a2 s  .c  o m*/
     * HTTP GET http://localhost:8181/cxf/securecrm/customerservice/customers/123
     * returns the XML document representing customer 123
     *
     * On the server side, it matches the CustomerService's getCustomer() method
     */
    System.out.println("Sent HTTP GET request to query customer info with basic authentication info.");
    GetMethod get = new GetMethod("http://localhost:8181/cxf/securecrm/customerservice/customers/123");
    get.getHostAuthState().setAuthScheme(scheme);
    try {
        httpClient.executeMethod(get);
        System.out.println(get.getResponseBodyAsString());
    } finally {
        get.releaseConnection();
    }

    /**
     * HTTP GET http://localhost:8181/cxf/securecrm/customerservice/customers/123
     * without passing along authentication credentials - this will result in a security exception in the response.
     */
    System.out.println("\n");
    System.out.println("Sent HTTP GET request to query customer info without basic authentication info.");
    get = new GetMethod("http://localhost:8181/cxf/securecrm/customerservice/customers/123");
    try {
        httpClient.executeMethod(get);
        // we should get the security exception here
        System.out.println(get.getResponseBodyAsString());
    } finally {
        get.releaseConnection();
    }

    /**
     * HTTP GET http://localhost:8181/cxf/securecrm/customerservice/orders/223/products/323
     * returns the XML document representing product 323 in order 223
     *
     * On the server side, it matches the Order's getProduct() method
     */
    System.out.println("\n");
    System.out.println("Sent HTTP GET request to query sub resource product info");
    get = new GetMethod("http://localhost:8181/cxf/securecrm/customerservice/orders/223/products/323");
    get.getHostAuthState().setAuthScheme(scheme);
    try {
        httpClient.executeMethod(get);
        System.out.println(get.getResponseBodyAsString());
    } finally {
        get.releaseConnection();
    }

    /**
     * HTTP PUT http://localhost:8181/cxf/securecrm/customerservice/customers is used to upload the contents of
     * the update_customer.xml file to update the customer information for customer 123.
     *
     * On the server side, it matches the CustomerService's updateCustomer() method
     */
    System.out.println("\n");
    System.out.println("Sent HTTP PUT request to update customer info");

    String inputFile = Client.class.getResource("update_customer.xml").getFile();
    File input = new File(inputFile);
    PutMethod put = new PutMethod("http://localhost:8181/cxf/securecrm/customerservice/customers");
    put.getHostAuthState().setAuthScheme(scheme);
    RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    put.setRequestEntity(entity);

    try {
        int result = httpClient.executeMethod(put);
        System.out.println("Response status code: " + result);
        System.out.println("Response body: ");
        System.out.println(put.getResponseBodyAsString());
    } finally {
        // Release current connection to the connection pool once you are
        // done
        put.releaseConnection();
    }

    /**
     * HTTP POST http://localhost:8181/cxf/securecrm/customerservice/customers is used to upload the contents of
     * the add_customer.xml file to add a new customer to the system.
     *
     * On the server side, it matches the CustomerService's addCustomer() method
     */
    System.out.println("\n");
    System.out.println("Sent HTTP POST request to add customer");
    inputFile = Client.class.getResource("add_customer.xml").getFile();
    input = new File(inputFile);
    PostMethod post = new PostMethod("http://localhost:8181/cxf/securecrm/customerservice/customers");
    post.getHostAuthState().setAuthScheme(scheme);
    post.addRequestHeader("Accept", "text/xml");
    entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    post.setRequestEntity(entity);

    try {
        int result = httpClient.executeMethod(post);
        System.out.println("Response status code: " + result);
        System.out.println("Response body: ");
        System.out.println(post.getResponseBodyAsString());
    } finally {
        // Release current connection to the connection pool once you are
        // done
        post.releaseConnection();
    }

    System.out.println("\n");
    System.exit(0);
}

From source file:org.jboss.quickstarts.fuse.rest.CrmTest.java

/**
 * HTTP PUT http://localhost:8181/cxf/crm/customerservice/customers is used to upload the contents of
 * the update_customer.xml file to update the customer information for customer 123.
 * <p/>//w  w  w. j  av a2  s  .  c  om
 * On the server side, it matches the CustomerService's updateCustomer() method
 *
 * @throws Exception
 */
@Test
public void putCutomerTest() throws IOException {

    LOG.info("Sent HTTP PUT request to update customer info");

    String inputFile = this.getClass().getResource("/update_customer.xml").getFile();
    File input = new File(inputFile);
    PutMethod put = new PutMethod(CUSTOMER_SERVICE_URL);
    RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    put.setRequestEntity(entity);
    HttpClient httpclient = new HttpClient();
    int result = 0;
    try {
        result = httpclient.executeMethod(put);
        LOG.info("Response status code: " + result);
        LOG.info("Response body: ");
        LOG.info(put.getResponseBodyAsString());
    } catch (IOException e) {
        LOG.error("Error connecting to {}", CUSTOMER_SERVICE_URL);
        LOG.error(
                "You should build the 'rest' quick start and deploy it to a local Fuse before running this test");
        LOG.error("Please read the README.md file in 'rest' quick start root");
        Assert.fail("Connection error");
    } finally {
        // Release current connection to the connection pool once you are
        // done
        put.releaseConnection();
    }

    Assert.assertEquals(result, 200);
}

From source file:org.jboss.quickstarts.fuse.rest.secure.CrmSecureTest.java

/**
 * HTTP PUT http://localhost:8181/cxf/crm/customerservice/customers is used to upload the contents of
 * the update_customer.xml file to update the customer information for customer 123.
 * <p/>// w  w w . j  a  v a 2  s  . c  o m
 * On the server side, it matches the CustomerService's updateCustomer() method
 *
 * @throws Exception
 */
@Test
public void putCutomerTest() throws IOException {

    LOG.info("============================================");
    LOG.info("Sent HTTP PUT request to update customer info");

    String inputFile = this.getClass().getResource("/update_customer.xml").getFile();
    File input = new File(inputFile);
    PutMethod put = new PutMethod(CUSTOMER_SERVICE_URL);
    put.getHostAuthState().setAuthScheme(scheme);
    RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    put.setRequestEntity(entity);

    int result = 0;
    try {
        result = httpClient.executeMethod(put);
        LOG.info("Response status code: " + result);
        LOG.info("Response body: ");
        LOG.info(put.getResponseBodyAsString());
    } catch (IOException e) {
        LOG.error("Error connecting to {}", CUSTOMER_SERVICE_URL);
        LOG.error(
                "You should build the 'rest' quick start and deploy it to a local Fuse before running this test");
        LOG.error("Please read the README.md file in 'rest' quick start root");
        Assert.fail("Connection error");
    } finally {
        // Release current connection to the connection pool once you are
        // done
        put.releaseConnection();
    }

    Assert.assertEquals(result, 200);
}

From source file:org.jboss.wise.core.client.jaxrs.impl.RSDynamicClientImpl.java

public InvocationResult invoke(RequestEntity requestEntity, WiseMapper mapper) {
    InvocationResult result = null;//from   w w  w  .ja  va 2  s. c  om
    Map<String, Object> responseHolder = new HashMap<String, Object>();

    if (HttpMethod.GET == httpMethod) {
        GetMethod get = new GetMethod(resourceURI);
        setRequestHeaders(get);

        try {
            int statusCode = httpClient.executeMethod(get);
            // TODO: Use InputStream
            String response = get.getResponseBodyAsString();
            responseHolder.put(InvocationResult.STATUS, Integer.valueOf(statusCode));

            result = new InvocationResultImpl(InvocationResult.RESPONSE, null, response, responseHolder);

            // System.out.print(response);
        } catch (IOException e) {
            // TODO:
        } finally {
            get.releaseConnection();
        }
    } else if (HttpMethod.POST == httpMethod) {
        PostMethod post = new PostMethod(resourceURI);
        setRequestHeaders(post);

        post.setRequestEntity(requestEntity);

        try {
            int statusCode = httpClient.executeMethod(post);
            String response = post.getResponseBodyAsString();
            responseHolder.put(InvocationResult.STATUS, Integer.valueOf(statusCode));

            result = new InvocationResultImpl(InvocationResult.RESPONSE, null, response, responseHolder);

            // System.out.print(response);
        } catch (IOException e) {
            // TODO:
        } finally {
            post.releaseConnection();
        }
    } else if (HttpMethod.PUT == httpMethod) {
        PutMethod put = new PutMethod(resourceURI);
        setRequestHeaders(put);

        put.setRequestEntity(requestEntity);

        try {
            int statusCode = httpClient.executeMethod(put);
            String response = put.getResponseBodyAsString();
            responseHolder.put(InvocationResult.STATUS, Integer.valueOf(statusCode));

            result = new InvocationResultImpl(InvocationResult.RESPONSE, null, response, responseHolder);

            // System.out.print(response);
        } catch (IOException e) {
            // TODO:
        } finally {
            put.releaseConnection();
        }
    } else if (HttpMethod.DELETE == httpMethod) {
        DeleteMethod delete = new DeleteMethod(resourceURI);
        setRequestHeaders(delete);

        try {
            int statusCode = httpClient.executeMethod(delete);
            String response = delete.getResponseBodyAsString();
            responseHolder.put(InvocationResult.STATUS, Integer.valueOf(statusCode));

            result = new InvocationResultImpl(InvocationResult.RESPONSE, null, response, responseHolder);

            // System.out.print(response);
        } catch (IOException e) {
            // TODO:
        } finally {
            delete.releaseConnection();
        }
    }

    return result;
}