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:io.fabric8.quickstarts.restdsl.spark.CrmIT.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 . j av  a2s . c  o  m
 * On the server side, it matches the CustomerService's updateCustomer() method
 *
 * @throws Exception
 */
@Test
@Ignore
public void putCustomerTest() 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 Fabric8 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:de.mpg.mpdl.inge.pubman.web.multipleimport.processor.ZfNProcessor.java

/**
 * Uploads a file to the staging servlet and returns the corresponding URL.
 * /*from   w w w  . j a  v  a2 s .c  o m*/
 * @param InputStream to upload
 * @param mimetype The mimetype of the file
 * @param userHandle The userhandle to use for upload
 * @return The URL of the uploaded file.
 * @throws Exception If anything goes wrong...
 */
private URL uploadFile(InputStream in, String mimetype, String userHandle) throws Exception {
    // Prepare the HttpMethod.
    String fwUrl = PropertyReader.getFrameworkUrl();
    PutMethod method = new PutMethod(fwUrl + "/st/staging-file");
    method.setRequestEntity(new InputStreamRequestEntity(in, -1));
    method.setRequestHeader("Content-Type", mimetype);
    method.setRequestHeader("Cookie", "escidocCookie=" + userHandle);
    // Execute the method with HttpClient.
    HttpClient client = new HttpClient();
    client.executeMethod(method);
    String response = method.getResponseBodyAsString();
    XmlTransformingBean ctransforming = new XmlTransformingBean();
    return ctransforming.transformUploadResponseToFileURL(response);
}

From source file:com.zimbra.cs.dav.client.WebDavClient.java

public HttpInputStream sendPut(String href, byte[] buf, String contentType, String etag,
        Collection<Pair<String, String>> headers) throws IOException {
    boolean done = false;
    PutMethod put = null;
    while (!done) {
        put = new PutMethod(mBaseUrl + href);
        put.setRequestEntity(new ByteArrayRequestEntity(buf, contentType));
        if (mDebugEnabled && contentType.startsWith("text"))
            ZimbraLog.dav.debug("PUT payload: \n" + new String(buf, "UTF-8"));
        if (etag != null)
            put.setRequestHeader(DavProtocol.HEADER_IF_MATCH, etag);
        if (headers != null)
            for (Pair<String, String> h : headers)
                put.addRequestHeader(h.getFirst(), h.getSecond());
        executeMethod(put, Depth.zero);//w ww . j  av  a2  s .  com
        int ret = put.getStatusCode();
        if (ret == HttpStatus.SC_MOVED_PERMANENTLY || ret == HttpStatus.SC_MOVED_TEMPORARILY) {
            Header newLocation = put.getResponseHeader("Location");
            if (newLocation != null) {
                href = newLocation.getValue();
                ZimbraLog.dav.debug("redirect to new url = " + href);
                put.releaseConnection();
                continue;
            }
        }
        done = true;
    }
    return new HttpInputStream(put);
}

From source file:io.fabric8.quickstarts.fabric.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/>/*from  w  w w .  j a v a  2s.  c  om*/
 * On the server side, it matches the CustomerService's updateCustomer() method
 *
 * @throws Exception
 */
@Test
public void putCustomerTest() 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 Fabric8 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:com.zimbra.cs.service.UserServlet.java

public static Pair<Header[], HttpInputStream> putRemoteResource(ZAuthToken authToken, String url,
        InputStream req, Header[] headers) throws ServiceException, IOException {
    StringBuilder u = new StringBuilder(url);
    u.append("?").append(QP_AUTH).append('=').append(AUTH_COOKIE);
    PutMethod method = new PutMethod(u.toString());
    String contentType = "application/octet-stream";
    if (headers != null) {
        for (Header hdr : headers) {
            String name = hdr.getName();
            method.addRequestHeader(hdr);
            if (name.equals("Content-Type"))
                contentType = hdr.getValue();
        }//from  www.j  ava 2 s .  com
    }
    method.setRequestEntity(new InputStreamRequestEntity(req, contentType));
    Pair<Header[], HttpMethod> pair = doHttpOp(authToken, method);
    return new Pair<Header[], HttpInputStream>(pair.getFirst(), new HttpInputStream(pair.getSecond()));
}

From source file:au.edu.usq.fascinator.harvester.fedora.restclient.FedoraRestClient.java

public void modifyDatastream(String pid, String dsId, String content) throws IOException {
    StringBuilder uri = new StringBuilder(getBaseUrl());
    uri.append("/objects/");
    uri.append(pid);//w ww.j a  v a2  s.  co  m
    uri.append("/datastreams/");
    uri.append(dsId);
    PutMethod method = new PutMethod(uri.toString());
    method.setRequestEntity(new StringRequestEntity(content, "text/xml", "UTF-8"));
    executeMethod(method);
    method.releaseConnection();
}

From source file:com.example.listsync.WebDavRepository.java

private void doUpload(String file, List<String> content) throws IOException {
    LOGGER.info("uploading {}", file);
    LOGGER.info("uploading {} -> {}", file, content);
    PutMethod putMethod = new PutMethod(config.getBaseUrl() + config.getWatchpath() + file);
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    IOUtils.writeLines(content, IOUtils.LINE_SEPARATOR_UNIX, output);
    putMethod.setRequestEntity(new ByteArrayRequestEntity(output.toByteArray()));
    int code = client.executeMethod(putMethod);
    LOGGER.info("upload resultcode: {}", code);
}

From source file:com.simonellistonball.nifi.processors.OpenScoringProcessor.OpenScoringProcessor.java

private String postModel(String openScoringUrl, String pmml) throws HttpException, IOException {
    id.set(UUID.randomUUID().toString());
    StringBuilder urlBuilder = new StringBuilder(openScoringUrl).append("/model/").append(id);
    String url = urlBuilder.toString();
    PutMethod put = new PutMethod(url);
    getLogger().warn(String.format("Posting model to %s", url));
    put.setRequestHeader("Content-Type", "text/xml");
    RequestEntity requestEntity = new StringRequestEntity(pmml, "text/xml", "utf-8");
    put.setRequestEntity(requestEntity);
    httpClient.executeMethod(put);/*from   w  ww . j ava 2  s  .c o m*/
    return id.get();
}

From source file:com.wandisco.s3hdfs.rewrite.redirect.VersionRedirect.java

/**
 * Places a new .v file in the default version directory.
 *
 * @param nnHostAddress//from   w w w  .ja v a2  s. c  o m
 * @param userName
 * @throws IOException
 */
public String createVersion(String nnHostAddress, String userName) throws IOException {
    String[] nnHost = nnHostAddress.split(":");

    String uri = (path != null) ? path.getFullHdfsObjPath() : request.getPathInfo();

    String versionpath = replaceUri(uri, OBJECT_FILE_NAME, VERSION_FILE_NAME);

    PutMethod httpPut = (PutMethod) getHttpMethod(request.getScheme(), nnHost[0], Integer.decode(nnHost[1]),
            "CREATE&overwrite=true", userName, versionpath, PUT);
    String version = UUID.randomUUID().toString();
    httpPut.setRequestEntity(new ByteArrayRequestEntity(version.getBytes(DEFAULT_CHARSET)));

    httpPut.setRequestHeader(S3_HEADER_NAME, S3_HEADER_VALUE);

    httpClient.executeMethod(httpPut);

    Header locationHeader = httpPut.getResponseHeader("Location");
    LOG.debug("1st response: " + httpPut.getStatusLine().toString());
    boolean containsRedirect = (locationHeader != null);
    httpPut.releaseConnection();

    if (!containsRedirect) {
        LOG.debug("1st response did not contain redirect. " + "No version will be created.");
        return null;
    }

    // Handle redirect header transition
    assert httpPut.getStatusCode() == 307;

    // Consume response and re-allocate connection for redirect
    httpPut.setURI(new URI(locationHeader.getValue(), true));

    httpClient.executeMethod(httpPut);

    LOG.debug("2nd response: " + httpPut.getStatusLine().toString());

    if (httpPut.getStatusCode() != 200) {
        LOG.debug("Response not 200: " + httpPut.getResponseBodyAsString());
        return null;
    }

    assert httpPut.getStatusCode() == 200;
    httpPut.releaseConnection();

    return version;
}

From source file:eu.learnpad.core.impl.qm.XwikiBridgeInterfaceRestResource.java

@Override
public void importModelSet(String modelSetId, ModelSetType type, InputStream modelContent)
        throws LpRestExceptionXWikiImpl {
    // Notify QM about a new model set imported
    HttpClient httpClient = this.getClient();
    String uri = String.format("%s/learnpad/qm/bridge/importmodel/%s", DefaultRestResource.REST_URI,
            modelSetId);/* www.j  a  v  a 2s  .c om*/
    PutMethod putMethod = new PutMethod(uri);
    putMethod.addRequestHeader("Accept", "application/xml");

    NameValuePair[] queryString = new NameValuePair[1];
    queryString[0] = new NameValuePair("type", type.toString());
    putMethod.setQueryString(queryString);

    RequestEntity requestEntity = new InputStreamRequestEntity(modelContent);
    putMethod.setRequestEntity(requestEntity);

    try {
        httpClient.executeMethod(putMethod);
    } catch (IOException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e);
    }

}