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.exist.xquery.modules.httpclient.PUTFunction.java

public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    Sequence response = null;/*  w w  w  . j  a v  a 2 s  .c o m*/

    // must be a URL
    if (args[0].isEmpty()) {
        return (Sequence.EMPTY_SEQUENCE);
    }

    //get the url
    String url = args[0].itemAt(0).getStringValue();

    //get the payload
    Item payload = args[1].itemAt(0);

    //get the persist state
    boolean persistState = args[2].effectiveBooleanValue();

    String indentLevel = (args.length >= 5 && !args[4].isEmpty()) ? args[4].itemAt(0).toString() : null;

    RequestEntity entity = null;

    if (Type.subTypeOf(payload.getType(), Type.NODE)) {
        //serialize the node to SAX
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        OutputStreamWriter osw = new OutputStreamWriter(baos, UTF_8);

        IndentingXMLWriter xmlWriter = new IndentingXMLWriter(osw);
        Properties outputProperties = new Properties();
        outputProperties.setProperty(OutputKeys.ENCODING, "UTF-8");
        if (indentLevel != null) {
            outputProperties.setProperty(OutputKeys.INDENT, "yes");
            outputProperties.setProperty(EXistOutputKeys.INDENT_SPACES, indentLevel);
        } else {
            outputProperties.setProperty(OutputKeys.INDENT, "no");
        }
        xmlWriter.setOutputProperties(outputProperties);

        SAXSerializer sax = new SAXSerializer();

        sax.setReceiver(xmlWriter);

        try {
            payload.toSAX(context.getBroker(), sax, new Properties());
            osw.flush();
            osw.close();
        } catch (Exception e) {
            throw new XPathException(this, e);
        }
        entity = new ByteArrayRequestEntity(baos.toByteArray(), "application/xml; charset=utf-8");

    } else if (Type.subTypeOf(payload.getType(), Type.BASE64_BINARY)) {

        entity = new ByteArrayRequestEntity(payload.toJavaObject(byte[].class));

    } else {

        try {
            entity = new StringRequestEntity(payload.getStringValue(), "text/text; charset=utf-8", "UTF-8");
        } catch (UnsupportedEncodingException uee) {
            uee.printStackTrace();
        }
    }

    //setup PUT request
    PutMethod put = new PutMethod(url);

    put.setRequestEntity(entity);

    //setup PUT Request Headers
    if (!args[3].isEmpty()) {
        setHeaders(put, ((NodeValue) args[3].itemAt(0)).getNode());
    }

    try {

        //execute the request
        response = doRequest(context, put, persistState, null, null);

    } catch (IOException ioe) {
        throw (new XPathException(this, ioe.getMessage(), ioe));
    } finally {
        put.releaseConnection();
    }

    return (response);
}

From source file:org.exjello.mail.Exchange2003Connection.java

public void send(MimeMessage message) throws Exception {
    Address[] bccRecipients = message.getRecipients(Message.RecipientType.BCC);
    if (bccRecipients == null || bccRecipients.length == 0) {
        bccRecipients = null;//from ww w .  j  a  v a  2s  . co  m
    }
    message.setRecipients(Message.RecipientType.BCC, (Address[]) null);
    synchronized (this) {
        if (!isConnected()) {
            throw new IllegalStateException("Not connected.");
        }
        if (!canSend()) {
            throw new IllegalStateException("Unable to access outbox.");
        }
        HttpClient client = getClient();
        String path = drafts;
        if (!path.endsWith("/"))
            path += "/";
        String messageName = generateMessageName();
        path += escape(messageName + ".eml");
        PutMethod op = new PutMethod(path);
        op.setRequestHeader("Content-Type", MESSAGE_CONTENT_TYPE);
        op.setRequestEntity(createMessageEntity(message));
        InputStream stream = null;
        try {
            int status = client.executeMethod(op);
            stream = op.getResponseBodyAsStream();
            if (status >= 300) {
                throw new IllegalStateException("Unable to post message to draft folder.");
            }
        } finally {
            try {
                if (stream != null) {
                    byte[] buf = new byte[65536];
                    try {
                        if (session.getDebug()) {
                            PrintStream log = session.getDebugOut();
                            log.println("Response Body:");
                            int count;
                            while ((count = stream.read(buf, 0, 65536)) != -1) {
                                log.write(buf, 0, count);
                            }
                            log.flush();
                            log.println();
                        } else {
                            while (stream.read(buf, 0, 65536) != -1)
                                ;
                        }
                    } catch (Exception ignore) {
                    } finally {
                        try {
                            stream.close();
                        } catch (Exception ignore2) {
                        }
                    }
                }
            } finally {
                op.releaseConnection();
            }
        }
        if (bccRecipients != null) {
            ExchangeMethod patch = new ExchangeMethod(PROPPATCH_METHOD, path);
            patch.setHeader("Content-Type", XML_CONTENT_TYPE);
            patch.addHeader("Depth", "0");
            patch.addHeader("Translate", "f");
            patch.addHeader("Brief", "t");
            patch.setRequestEntity(createAddBccEntity(bccRecipients));
            stream = null;
            try {
                int status = client.executeMethod(patch);
                stream = patch.getResponseBodyAsStream();
                if (status >= 300) {
                    throw new IllegalStateException("Unable to add BCC recipients. Status: " + status);
                }
            } finally {
                try {
                    if (stream != null) {
                        byte[] buf = new byte[65536];
                        try {
                            if (session.getDebug()) {
                                PrintStream log = session.getDebugOut();
                                log.println("Response Body:");
                                int count;
                                while ((count = stream.read(buf, 0, 65536)) != -1) {
                                    log.write(buf, 0, count);
                                }
                                log.flush();
                                log.println();
                            } else {
                                while (stream.read(buf, 0, 65536) != -1)
                                    ;
                            }
                        } catch (Exception ignore) {
                        } finally {
                            try {
                                stream.close();
                            } catch (Exception ignore2) {
                            }
                        }
                    }
                } finally {
                    patch.releaseConnection();
                }
            }
        }
        ExchangeMethod move = new ExchangeMethod(MOVE_METHOD, path);
        String destination = submissionUri;
        if (!destination.endsWith("/"))
            destination += "/";
        move.setHeader("Destination", destination);
        stream = null;
        try {
            int status = client.executeMethod(move);
            stream = move.getResponseBodyAsStream();
            if (status >= 300) {
                throw new IllegalStateException("Unable to move message to outbox: Status " + status);
            }
        } finally {
            try {
                if (stream != null) {
                    byte[] buf = new byte[65536];
                    try {
                        if (session.getDebug()) {
                            PrintStream log = session.getDebugOut();
                            log.println("Response Body:");
                            int count;
                            while ((count = stream.read(buf, 0, 65536)) != -1) {
                                log.write(buf, 0, count);
                            }
                            log.flush();
                            log.println();
                        } else {
                            while (stream.read(buf, 0, 65536) != -1)
                                ;
                        }
                    } catch (Exception ignore) {
                    } finally {
                        try {
                            stream.close();
                        } catch (Exception ignore2) {
                        }
                    }
                }
            } finally {
                move.releaseConnection();
            }
        }
        if (session.getDebug()) {
            session.getDebugOut().println("Sent successfully.");
        }
    }
}

From source file:org.fabric8.demo.cxf.test.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/>/*from   ww w.ja v  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, "application/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();
    }
    LOG.info("HTTP: " + result);

    Assert.assertEquals(result, 200);
}

From source file:org.fao.geonet.services.publisher.GeoServerRest.java

/**
 * /*w w  w. j a v a2 s . com*/
 * @param method
 *            e.g. 'POST', 'GET', 'PUT' or 'DELETE'
 * @param urlParams
 *            REST API parameter
 * @param postData
 *            XML data
 * @param file
 *            File to upload
 * @param contentType
 *            type of content in case of post data or file updload.
 * @param saveResponse
 * @return
 * @throws IOException
 */
public int sendREST(String method, String urlParams, String postData, File file, String contentType,
        Boolean saveResponse) throws IOException {

    response = "";
    final HttpClient c = httpClientFactory.newHttpClient();
    String url = this.restUrl + urlParams;
    if (Log.isDebugEnabled(LOGGER_NAME)) {
        Log.debug(LOGGER_NAME, "url:" + url);
        Log.debug(LOGGER_NAME, "method:" + method);
        Log.debug(LOGGER_NAME, "postData:" + postData);
    }

    HttpMethod m;
    if (method.equals(METHOD_PUT)) {
        m = new PutMethod(url);
        if (file != null) {
            ((PutMethod) m).setRequestEntity(new InputStreamRequestEntity(new FileInputStream(file)));
        }
        if (postData != null) {
            ((PutMethod) m).setRequestEntity(new StringRequestEntity(postData, contentType, "UTF-8"));
        }
    } else if (method.equals(METHOD_DELETE)) {
        m = new DeleteMethod(url);
    } else if (method.equals(METHOD_POST)) {
        m = new PostMethod(url);
        if (postData != null) {
            ((PostMethod) m).setRequestEntity(new StringRequestEntity(postData, contentType, "UTF-8"));
        }

    } else {
        m = new GetMethod(url);
    }

    if (contentType != null && !"".equals(contentType)) {
        m.setRequestHeader("Content-type", contentType);
    }

    m.setDoAuthentication(true);

    status = c.executeMethod(m);
    if (Log.isDebugEnabled(LOGGER_NAME))
        Log.debug(LOGGER_NAME, "status:" + status);
    if (saveResponse)
        this.response = m.getResponseBodyAsString();

    return status;
}

From source file:org.geoserver.script.js.RemoteConsole.java

private String eval(String input) {
    BufferedReader reader;/*from  ww w .  j a v  a2  s  .  co  m*/
    String sessionUrl = url.toString() + sessionId;
    PutMethod method = new PutMethod(sessionUrl);
    String result = "";
    try {
        RequestEntity entity = new StringRequestEntity(input, "text/plain", "UTF-8");
        method.setRequestEntity(entity);
        client.executeMethod(method);
        reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
        String line;
        while (((line = reader.readLine()) != null)) {
            result = result + line;
        }
    } catch (HttpException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        method.releaseConnection();
    }
    return result;
}

From source file:org.geotools.data.couchdb.client.CouchDBClient.java

/**
 * Send a PUT with a body (for creating documents)
 * @param path//w  w  w  . j a v a  2s .  com
 * @param content
 * @return
 * @throws IOException  
 */
public CouchDBResponse put(String path, String content) throws IOException {
    PutMethod put = new PutMethod(url(path));
    if (content != null) {
        try {
            put.setRequestEntity(new StringRequestEntity(content, MIME_TYPE_JSON, DEFAULT_CHARSET));
        } catch (UnsupportedEncodingException ex) {
            throw new RuntimeException(ex);
        }
    }
    return executeMethod(put);
}

From source file:org.gradle.api.internal.artifacts.repositories.CommonsHttpClientBackedRepository.java

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

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  a  va  2 s .c om*/
    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.httpobjects.tck.IntegrationTest.java

@Test
public void happyPathForPut() {
    assertResource(withBody(new PutMethod("http://localhost:8080/app/inbox/abc"), "hello world"), "hello world",
            200);/*w  ww. java  2  s. c  o  m*/
}

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 {// w  ww. j a va  2  s  . c o 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);
    }
}