Example usage for org.apache.http.client.methods HttpPut setEntity

List of usage examples for org.apache.http.client.methods HttpPut setEntity

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpPut setEntity.

Prototype

public void setEntity(final HttpEntity entity) 

Source Link

Usage

From source file:com.ibm.watson.app.common.util.rest.SimpleRestClient.java

public <T> T put(String endpoint, HttpEntity entity, ResponseHandler<? extends T> responseHandler)
        throws IOException {
    if (logger.isDebugEnabled()) {
        logger.debug("Making PUT request at endpoint '" + endpoint + "'");
        if (logger.isTraceEnabled()) {
            logger.trace("PUT request body:\n" + EntityUtils.toString(entity));
        }/*  w w w.j  a  v  a  2 s.  c om*/
    }

    HttpPut httppost = new HttpPut(url + endpoint);
    if (entity != null) {
        httppost.setEntity(entity);
    }
    return doPut(httppost, responseHandler);
}

From source file:se.inera.certificate.proxy.mappings.remote.RemoteDispatcher.java

private HttpResponse makePutRequest(HttpServletRequest request, HttpPut put) throws IOException {
    addHeaders(request, put);/*w  w  w  .j  a v  a  2 s  .  com*/
    put.setEntity(new InputStreamEntity(request.getInputStream(), -1));
    return makeRequest(put);
}

From source file:org.apache.hyracks.tests.integration.ApplicationDeploymentAPIIntegrationTest.java

protected void deployApplicationFile(int dataSize, String fileName) throws URISyntaxException, IOException {
    final String deployid = "testApp";

    String path = "/applications/" + deployid + "&" + fileName;
    URI uri = uri(path);/*w w w . ja v a2s .  co  m*/

    byte[] data = new byte[dataSize];
    for (int i = 0; i < data.length; ++i) {
        data[i] = (byte) i;
    }

    HttpClient client = HttpClients.createMinimal();

    // Put the data

    HttpPut put = new HttpPut(uri);
    HttpEntity entity = new ByteArrayEntity(data, ContentType.APPLICATION_OCTET_STREAM);
    put.setEntity(entity);
    client.execute(put);

    // Get it back

    HttpGet get = new HttpGet(uri);
    HttpResponse response = client.execute(get);
    HttpEntity respEntity = response.getEntity();
    Header contentType = respEntity.getContentType();

    // compare results

    Assert.assertEquals(ContentType.APPLICATION_OCTET_STREAM.getMimeType(), contentType.getValue());
    InputStream is = respEntity.getContent();

    for (int i = 0; i < dataSize; ++i) {
        Assert.assertEquals(data[i], (byte) is.read());
    }
    Assert.assertEquals(-1, is.read());
    is.close();
}

From source file:edu.uci.ics.hyracks.api.client.HyracksConnection.java

@Override
public DeploymentId deployBinary(List<String> jars) throws Exception {
    /** generate a deployment id */
    DeploymentId deploymentId = new DeploymentId(UUID.randomUUID().toString());
    List<URL> binaryURLs = new ArrayList<URL>();
    if (jars != null && jars.size() > 0) {
        HttpClient hc = new DefaultHttpClient();
        /** upload jars through a http client one-by-one to the CC server */
        for (String jar : jars) {
            int slashIndex = jar.lastIndexOf('/');
            String fileName = jar.substring(slashIndex + 1);
            String url = "http://" + ccHost + ":" + ccInfo.getWebPort() + "/applications/"
                    + deploymentId.toString() + "&" + fileName;
            HttpPut put = new HttpPut(url);
            put.setEntity(new FileEntity(new File(jar), "application/octet-stream"));
            HttpResponse response = hc.execute(put);
            if (response != null) {
                response.getEntity().consumeContent();
            }//from   ww  w . ja  v a  2s .c om
            if (response.getStatusLine().getStatusCode() != 200) {
                hci.unDeployBinary(deploymentId);
                throw new HyracksException(response.getStatusLine().toString());
            }
            /** add the uploaded URL address into the URLs of jars to be deployed at NCs */
            binaryURLs.add(new URL(url));
        }
    }
    /** deploy the URLs to the CC and NCs */
    hci.deployBinary(binaryURLs, deploymentId);
    return deploymentId;
}

From source file:org.opendaylight.alto.manager.AltoManager.java

protected boolean httpPut(String url, String data) throws IOException {
    HttpPut httpPut = new HttpPut(url);
    httpPut.setHeader(HTTP.CONTENT_TYPE, AltoManagerConstants.JSON_CONTENT_TYPE);
    httpPut.setEntity(new StringEntity(data));
    logHttpRequest("HTTP PUT:", url, data);
    HttpResponse response = httpClient.execute(httpPut);
    return handleResponse(response);
}

From source file:org.metaeffekt.dcc.agent.DccAgentEndpoint.java

private HttpPut createPutRequest(String command, String deploymentId, String packageId, String unitId,
        byte[] payload) {
    StringBuilder sb = new StringBuilder("/");
    sb.append(deploymentId).append("/");
    if (!"clean".equals(command)) {
        sb.append("packages").append("/").append(packageId).append("/");
        sb.append("units").append("/").append(unitId != null ? unitId + "/" : "");
    }/*from  w ww . j av a  2 s . c o m*/
    String paramsPart = sb.toString();

    URIBuilder uriBuilder = getUriBuilder();
    String path = String.format("/%s%s%s", PATH_ROOT, paramsPart, command);
    uriBuilder.setPath(path);
    URI uri;
    try {
        uri = uriBuilder.build();
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
    HttpPut put = new HttpPut(uri);
    if (payload != null && payload.length > 0) {
        put.setEntity(new ByteArrayEntity(payload));
    }
    if (requestConfig != null) {
        put.setConfig(requestConfig);
    }
    return put;
}

From source file:com.microsoft.live.UploadRequest.java

@Override
public JSONObject execute() throws LiveOperationException {
    UriBuilder uploadRequestUri;/*from w w w .jav  a 2s  .  c o  m*/

    // if the path was relative, we have to retrieve the upload location, because if we don't,
    // we will proxy the upload request, which is a waste of resources.
    if (this.pathUri.isRelative()) {
        JSONObject response = this.getUploadLocation();

        // We could of tried to get the upload location on an invalid path.
        // If we did, just return that response.
        // If the user passes in a path that does contain an upload location, then
        // we need to throw an error.
        if (response.has(ERROR_KEY)) {
            return response;
        } else if (!response.has(UPLOAD_LOCATION_KEY)) {
            throw new LiveOperationException(ErrorMessages.MISSING_UPLOAD_LOCATION);
        }

        // once we have the file object, get the upload location
        String uploadLocation;
        try {
            uploadLocation = response.getString(UPLOAD_LOCATION_KEY);
        } catch (JSONException e) {
            throw new LiveOperationException(ErrorMessages.SERVER_ERROR, e);
        }

        uploadRequestUri = UriBuilder.newInstance(Uri.parse(uploadLocation));

        // The original path might have query parameters that were sent to the 
        // the upload location request, and those same query parameters will need
        // to be sent to the HttpPut upload request too. Also, the returned upload_location
        // *could* have query parameters on it. We want to keep those intact and in front of the
        // the client's query parameters.
        uploadRequestUri.appendQueryString(this.pathUri.getQuery());
    } else {
        uploadRequestUri = this.requestUri;
    }

    if (!this.isFileUpload) {
        // if it is not a file upload it is a folder upload and we must
        // add the file name to the upload location
        // and don't forget to set the overwrite query parameter
        uploadRequestUri.appendToPath(this.filename);
        this.overwrite.appendQueryParameterOnTo(uploadRequestUri);
    }

    HttpPut uploadRequest = new HttpPut(uploadRequestUri.toString());
    uploadRequest.setEntity(this.entity);

    this.currentRequest = uploadRequest;

    return super.execute();
}

From source file:org.fcrepo.integration.SanityCheckIT.java

@Test
public void testConstraintLink() throws Exception {
    // Create a resource
    final HttpPost post = new HttpPost(serverAddress + "rest/");
    final HttpResponse postResponse = executeAndVerify(post, SC_CREATED);

    final String location = postResponse.getFirstHeader("Location").getValue();
    logger.debug("new resource location: {}", location);

    // GET the new resource
    final HttpGet get = new HttpGet(location);
    final HttpResponse getResponse = executeAndVerify(get, SC_OK);

    final String body = EntityUtils.toString(getResponse.getEntity());
    logger.debug("new resource body: {}", body);

    // PUT the exact body back to the new resource... successfully
    final HttpPut put = new HttpPut(location);
    put.setEntity(new StringEntity(body));
    put.setHeader(CONTENT_TYPE, "text/turtle");
    executeAndVerify(put, SC_NO_CONTENT);

    // Update a server managed property in the resource body... not allowed!
    final String body2 = body.replaceFirst("fedora:created \"2\\d\\d\\d", "fedora:created \"1999");

    // PUT the erroneous body back to the new resource... unsuccessfully
    final HttpPut put2 = new HttpPut(location);
    put2.setEntity(new StringEntity(body2));
    put2.setHeader(CONTENT_TYPE, "text/turtle");
    final HttpResponse put2Response = executeAndVerify(put2, SC_CONFLICT);

    // Verify the returned LINK header
    final String linkHeader = put2Response.getFirstHeader(LINK).getValue();
    final Link link = Link.valueOf(linkHeader);
    logger.debug("constraint linkHeader: {}", linkHeader);

    // Verify the LINK rel
    final String linkRel = link.getRel();
    assertEquals(CONSTRAINED_BY.getURI(), linkRel);

    // Verify the LINK URI by fetching it
    final URI linkURI = link.getUri();
    logger.debug("constraint linkURI: {}", linkURI);

    final HttpGet getLink = new HttpGet(linkURI);
    executeAndVerify(getLink, SC_OK);/*w  w w.jav  a  2 s  .  c om*/
}

From source file:com.sepgil.ral.CreateNodeTask.java

@Override
public HttpRequestBase getHttpRequest(String url) {
    HttpPut put = new HttpPut(url);

    try {/*from  ww  w. ja  v a2  s.co m*/
        StringEntity enity = new StringEntity(mNode.getJSON());
        put.setEntity(enity);
    } catch (JSONException e) {
        mListener.onError(ErrorState.ERROR_PARSE);
    } catch (UnsupportedEncodingException e) {
        mListener.onError(ErrorState.ERROR_PARSE);
    }
    return put;
}

From source file:org.opentravel.otm.forum2016.am.UpdateAPIOperation.java

/**
 * @see org.opentravel.otm.forum2016.am.RESTClientOperation#execute()
 *//*  ww w .j a  va2s.  c o m*/
@Override
public APIDetails execute() throws IOException {
    HttpPut request = new HttpPut(APIPublisherConfig.getWSO2PublisherApiBaseUrl() + "/" + api.getId());

    request.setHeader("Content-Type", "application/json");
    request.setEntity(new StringEntity(new Gson().toJson(api.toJson())));
    return execute(request);
}