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:edu.indiana.dlib.avalon.HydrantWorkflowListener.java

private void pingHydrant(String pid, long workflowId) {
    logger.trace("Starting to ping Hydrant: " + pid + " " + workflowId);
    try {//from  w  w w  .j a v  a2 s .  co  m
        String url = UrlSupport.concat(new String[] { hydrantUrl, "master_files", pid });
        MultiThreadedHttpConnectionManager mgr = new MultiThreadedHttpConnectionManager();
        HttpClient client = new HttpClient(mgr);

        PutMethod put = new PutMethod(url);

        Part[] parts = { new StringPart("workflow_id", String.valueOf(workflowId)), };
        put.setRequestEntity(new MultipartRequestEntity(parts, put.getParams()));
        logger.trace("About to ping Hydrant");
        int status = client.executeMethod(put);
        logger.debug("Got status: " + status);
        logger.trace("Got response body: " + put.getResponseBodyAsString());
    } catch (Exception e) {
        logger.debug("Exception pinging Hydrant: " + e.getCause(), e);
    }
}

From source file:com.zimbra.cs.service.UserServlet.java

public static Pair<Header[], HttpInputStream> putMailItem(ZAuthToken authToken, String url, MailItem item)
        throws ServiceException, IOException {
    if (item instanceof Document) {
        Document doc = (Document) item;
        StringBuilder u = new StringBuilder(url);
        u.append("?").append(QP_AUTH).append('=').append(AUTH_COOKIE);
        if (doc.getType() == MailItem.Type.WIKI) {
            u.append("&fmt=wiki");
        }//from   w w  w .j  a  v a  2 s.c o  m
        PutMethod method = new PutMethod(u.toString());
        String contentType = doc.getContentType();
        method.addRequestHeader("Content-Type", contentType);
        method.setRequestEntity(
                new InputStreamRequestEntity(doc.getContentStream(), doc.getSize(), contentType));
        method = HttpClientUtil.addInputStreamToHttpMethod(method, doc.getContentStream(), doc.getSize(),
                contentType);
        method.addRequestHeader("X-Zimbra-Description", doc.getDescription());
        method.setRequestEntity(
                new InputStreamRequestEntity(doc.getContentStream(), doc.getSize(), contentType));
        Pair<Header[], HttpMethod> pair = doHttpOp(authToken, method);
        return new Pair<Header[], HttpInputStream>(pair.getFirst(), new HttpInputStream(pair.getSecond()));
    }
    return putRemoteResource(authToken, url, item.getContentStream(), null);
}

From source file:com.assemblade.client.AbstractClient.java

protected <T> T update(String path, T object, TypeReference<T> type) throws ClientException {
    PutMethod put = new PutMethod(baseUrl + path);
    try {/*from   ww  w. jav a2  s. co m*/
        try {
            put.setRequestEntity(
                    new StringRequestEntity(mapper.writeValueAsString(object), "application/json", null));
        } catch (IOException e) {
            throw new CallFailedException("Failed to serialize a request object", e);
        }
        int statusCode = executeMethod(put);
        if (statusCode == 200) {
            try {
                return mapper.readValue(put.getResponseBodyAsStream(), type);
            } catch (IOException e) {
                throw new CallFailedException("Failed to deserialize a response object", e);
            }
        } else {
            throw new InvalidStatusException(200, statusCode);
        }
    } finally {
        put.releaseConnection();
    }
}

From source file:eu.impact_project.resultsrepository.DavHandlerTest.java

@Test
public void testRetrieveTextFile() throws HttpException, IOException {
    DavHandler dav = new DavHandler(folders);

    InputStream stream = new ByteArrayInputStream("some text".getBytes());
    PutMethod putMethod = new PutMethod("http://localhost:9002/parent/child/textToRetrieve.txt");
    putMethod.setRequestEntity(new InputStreamRequestEntity(stream));
    HttpClient client = new HttpClient();
    client.executeMethod(putMethod);//from   www. j  av a 2 s  .c o  m
    stream.close();
    putMethod.releaseConnection();

    String retrieved = dav.retrieveTextFile("http://localhost:9002/parent/child/textToRetrieve.txt");
    assertEquals("some text", retrieved);
}

From source file:com.thoughtworks.go.remote.work.RemoteConsoleAppender.java

public void append(String content) throws IOException {
    PutMethod putMethod = new PutMethod(consoleUri);
    try {//from w  w  w  .java  2s .co m
        HttpClient httpClient = httpService.httpClient();
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Appending console to URL -> " + consoleUri);
        }
        putMethod.setRequestEntity(new StringRequestEntity(content));

        HttpClientParams clientParams = new HttpClientParams();
        clientParams.setParameter("agentId", agentIdentifier.getUuid());
        HttpService.setSizeHeader(putMethod, content.getBytes().length);
        putMethod.setParams(clientParams);
        httpClient.executeMethod(putMethod);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Got " + putMethod.getStatusCode());
        }
    } finally {
        putMethod.releaseConnection();
    }
}

From source file:com.linkedin.pinot.common.utils.webhdfs.WebHdfsV1Client.java

public synchronized boolean uploadSegment(String webHdfsPath, String localFilePath) {
    // Step 1: Submit a HTTP PUT request without automatically following
    // redirects and without sending the file data.
    String firstPutReqString = String.format(WEB_HDFS_UPLOAD_PATH_TEMPLATE, _protocol, _host, _port,
            webHdfsPath, _overwrite, _permission);
    HttpMethod firstPutReq = new PutMethod(firstPutReqString);
    try {//from  ww  w  .ja v  a2  s  .com
        LOGGER.info("Trying to send request: {}.", firstPutReqString);
        int firstResponseCode = _httpClient.executeMethod(firstPutReq);
        if (firstResponseCode != 307) {
            LOGGER.error(String.format(
                    "Failed to execute the first PUT request to upload segment to webhdfs: %s. "
                            + "Expected response code 307, but get %s. Response body: %s",
                    firstPutReqString, firstResponseCode, firstPutReq.getResponseBodyAsString()));
            return false;
        }
    } catch (Exception e) {
        LOGGER.error(String.format("Failed to execute the first request to upload segment to webhdfs: %s.",
                firstPutReqString), e);
        return false;
    } finally {
        firstPutReq.releaseConnection();
    }
    // Step 2: Submit another HTTP PUT request using the URL in the Location
    // header with the file data to be written.
    String redirectedReqString = firstPutReq.getResponseHeader(LOCATION).getValue();
    PutMethod redirectedReq = new PutMethod(redirectedReqString);
    File localFile = new File(localFilePath);
    RequestEntity requestEntity = new FileRequestEntity(localFile, "application/binary");
    redirectedReq.setRequestEntity(requestEntity);

    try {
        LOGGER.info("Trying to send request: {}.", redirectedReqString);
        int redirectedResponseCode = _httpClient.executeMethod(redirectedReq);
        if (redirectedResponseCode != 201) {
            LOGGER.error(String.format(
                    "Failed to execute the redirected PUT request to upload segment to webhdfs: %s. "
                            + "Expected response code 201, but get %s. Response: %s",
                    redirectedReqString, redirectedResponseCode, redirectedReq.getResponseBodyAsString()));
        }
        return true;
    } catch (IOException e) {
        LOGGER.error(String.format("Failed to execute the redirected request to upload segment to webhdfs: %s.",
                redirectedReqString), e);
        return false;
    } finally {
        redirectedReq.releaseConnection();
    }
}

From source file:de.mpg.escidoc.services.edoc.PubManImport.java

private String createItem(String itemXml) throws Exception {
    HttpClient httpClient = new HttpClient();

    // Create//from  w w w  . j a va2s.  c om
    PutMethod method = new PutMethod(CORESERVICES_URL + "/ir/item");

    method.addRequestHeader("Cookie", "escidocCookie=" + userHandle);

    method.setRequestEntity(new StringRequestEntity(itemXml));
    ProxyHelper.executeMethod(httpClient, method);

    String response = method.getResponseBodyAsString();

    if (method.getStatusCode() != 200) {
        throw new RuntimeException(response);
    }

    return response;
}

From source file:com.moss.bdbadmin.client.service.BdbClient.java

public void put(IdProof assertion, String path, BdbResourceHandle handle) throws ServiceException {
    try {//ww w  . j  a v  a2  s .  co m
        PutMethod method = new PutMethod(baseUrl + "/" + path);
        method.setRequestHeader(AuthenticationHeader.HEADER_NAME, AuthenticationHeader.encode(assertion));
        method.setRequestEntity(new InputStreamRequestEntity(handle.read()));

        int result = httpClient.executeMethod(method);
        if (result != 200) {
            throw new ServiceException(result);
        }
    } catch (IOException ex) {
        throw new ServiceFailure(ex);
    }
}

From source file:demo.jaxrs.client.Client.java

public void updateCustomerInfo(String name, String password) throws Exception {

    System.out.println("HTTP PUT to update customer info, user : " + name + ", password : " + password);
    PutMethod put = new PutMethod("http://localhost:9002/customerservice/customers/123");
    setMethodHeaders(put, name, password);
    RequestEntity entity = new InputStreamRequestEntity(
            this.getClass().getClassLoader().getResourceAsStream("update_customer.xml"));
    put.setRequestEntity(entity);

    handleHttpMethod(put);//from  w  ww.j  av  a2 s.c o  m
}

From source file:com.mirth.connect.connectors.http.HttpMessageDispatcher.java

private HttpMethod buildHttpRequest(String address, MessageObject mo) throws Exception {
    String method = connector.getDispatcherMethod();
    String content = replacer.replaceValues(connector.getDispatcherContent(), mo);
    String contentType = connector.getDispatcherContentType();
    String charset = connector.getDispatcherCharset();
    boolean isMultipart = connector.isDispatcherMultipart();
    Map<String, String> headers = replacer.replaceValuesInMap(connector.getDispatcherHeaders(), mo);
    Map<String, String> parameters = replacer.replaceValuesInMap(connector.getDispatcherParameters(), mo);

    HttpMethod httpMethod = null;/*  w ww .j ava2 s .c o  m*/

    // populate the query parameters
    NameValuePair[] queryParameters = new NameValuePair[parameters.size()];
    int index = 0;

    for (Entry<String, String> parameterEntry : parameters.entrySet()) {
        queryParameters[index] = new NameValuePair(parameterEntry.getKey(), parameterEntry.getValue());
        index++;
        logger.debug("setting query parameter: [" + parameterEntry.getKey() + ", " + parameterEntry.getValue()
                + "]");
    }

    // create the method
    if ("GET".equalsIgnoreCase(method)) {
        httpMethod = new GetMethod(address);
        httpMethod.setQueryString(queryParameters);
    } else if ("POST".equalsIgnoreCase(method)) {
        PostMethod postMethod = new PostMethod(address);

        if (isMultipart) {
            logger.debug("setting multipart file content");
            File tempFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
            FileUtils.writeStringToFile(tempFile, content, charset);
            Part[] parts = new Part[] { new FilePart(tempFile.getName(), tempFile, contentType, charset) };
            postMethod.setQueryString(queryParameters);
            postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
        } else if (StringUtils.equals(contentType, "application/x-www-form-urlencoded")) {
            postMethod.setRequestBody(queryParameters);
        } else {
            postMethod.setQueryString(queryParameters);
            postMethod.setRequestEntity(new StringRequestEntity(content, contentType, charset));
        }

        httpMethod = postMethod;
    } else if ("PUT".equalsIgnoreCase(method)) {
        PutMethod putMethod = new PutMethod(address);
        putMethod.setRequestEntity(new StringRequestEntity(content, contentType, charset));
        putMethod.setQueryString(queryParameters);
        httpMethod = putMethod;
    } else if ("DELETE".equalsIgnoreCase(method)) {
        httpMethod = new DeleteMethod(address);
        httpMethod.setQueryString(queryParameters);
    }

    // set the headers
    for (Entry<String, String> headerEntry : headers.entrySet()) {
        httpMethod.setRequestHeader(new Header(headerEntry.getKey(), headerEntry.getValue()));
        logger.debug("setting method header: [" + headerEntry.getKey() + ", " + headerEntry.getValue() + "]");
    }

    return httpMethod;
}