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.michaeljones.httpclient.apache.ApacheMethodClient.java

@Override
public int PutFile(String url, String filePath, List<Pair<String, String>> queryParams, StringBuilder redirect)
        throws FileNotFoundException {
    try {/*from   w  ww . j av a 2  s  . c  o m*/
        URIBuilder fileUri = new URIBuilder(url);

        if (queryParams != null) {
            // Query params are optional. In the case of a redirect the url will contain
            // all the params.
            for (Pair<String, String> queryParam : queryParams) {
                fileUri.addParameter(queryParam.getFirst(), queryParam.getSecond());
            }
        }

        HttpPut httpPut = new HttpPut(fileUri.build());
        InputStream fileInStream = new FileInputStream(filePath);
        InputStreamEntity chunkedStream = new InputStreamEntity(fileInStream, -1,
                ContentType.APPLICATION_OCTET_STREAM);
        chunkedStream.setChunked(true);

        httpPut.setEntity(chunkedStream);

        CloseableHttpResponse response = clientImpl.execute(httpPut);
        try {
            Header[] hdrs = response.getHeaders("Location");
            if (redirect != null && hdrs.length > 0) {
                String redirectLocation = hdrs[0].getValue();

                redirect.append(redirectLocation);
                LOGGER.debug("Redirect to: " + redirectLocation);
            }

            return response.getStatusLine().getStatusCode();
        } finally {
            // I believe this releases the connection to the client pool, but does not
            // close the connection.
            response.close();
        }
    } catch (IOException | URISyntaxException ex) {
        throw new RuntimeException("Apache method putQuery: " + ex.getMessage());
    }
}

From source file:com.prey.net.PreyRestHttpClient.java

public PreyHttpResponse put(String url, Map<String, String> params, PreyConfig preyConfig) throws IOException {
    HttpPut method = new HttpPut(url);
    method.setHeader("Accept", "*/*");
    method.setEntity(new UrlEncodedFormEntity(getHttpParamsFromMap(params), HTTP.UTF_8));
    // method.setParams(getHttpParamsFromMap(params));
    PreyLogger.d("Sending using 'PUT' - URI: " + url + " - parameters: " + params.toString());
    HttpResponse httpResponse = httpclient.execute(method);
    PreyHttpResponse response = new PreyHttpResponse(httpResponse);
    //PreyLogger.d("Response from server: " + response.toString());
    return response;
}

From source file:org.activiti.rest.service.api.identity.UserInfoResourceTest.java

/**
 * Test update the info for an unexisting user.
 *//*from www  .  ja v a2  s .c o m*/
public void testUpdateInfoForUnexistingUser() throws Exception {
    ObjectNode requestNode = objectMapper.createObjectNode();
    requestNode.put("value", "Updated value");

    HttpPut httpPut = new HttpPut(SERVER_URL_PREFIX
            + RestUrls.createRelativeResourceUrl(RestUrls.URL_USER_INFO, "unexisting", "key1"));
    httpPut.setEntity(new StringEntity(requestNode.toString()));
    closeResponse(executeRequest(httpPut, HttpStatus.SC_NOT_FOUND));
}

From source file:net.ravendb.client.RavenDBAwareTests.java

protected void createDb(String dbName, int i) {
    HttpPut put = null;
    try {//from  ww w.j  a  v  a 2 s .c  om
        put = new HttpPut(getServerUrl(i) + "/admin/databases/" + UrlUtils.escapeDataString(dbName));
        put.setEntity(new StringEntity(getCreateDbDocument(dbName, getDefaultServerPort(i)),
                ContentType.APPLICATION_JSON));
        HttpResponse httpResponse = client.execute(put);
        if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw new IllegalStateException(
                    "Invalid response on put:" + httpResponse.getStatusLine().getStatusCode());
        }
    } catch (IOException e) {
        throw new IllegalStateException("Unable to create DB", e);
    } finally {
        if (put != null) {
            put.releaseConnection();
        }
    }
}

From source file:org.activiti.rest.service.api.repository.ModelResourceTest.java

@Deployment(resources = { "org/activiti/rest/service/api/repository/oneTaskProcess.bpmn20.xml" })
public void testUpdateModel() throws Exception {

    Model model = null;//w  w w .ja va2 s.c  o m
    try {
        Calendar createTime = Calendar.getInstance();
        createTime.set(Calendar.MILLISECOND, 0);
        processEngineConfiguration.getClock().setCurrentTime(createTime.getTime());

        model = repositoryService.newModel();
        model.setCategory("Model category");
        model.setKey("Model key");
        model.setMetaInfo("Model metainfo");
        model.setName("Model name");
        model.setVersion(2);
        repositoryService.saveModel(model);

        Calendar updateTime = Calendar.getInstance();
        updateTime.set(Calendar.MILLISECOND, 0);
        updateTime.add(Calendar.HOUR, 1);
        processEngineConfiguration.getClock().setCurrentTime(updateTime.getTime());

        // Create update request
        ObjectNode requestNode = objectMapper.createObjectNode();
        requestNode.put("name", "Updated name");
        requestNode.put("category", "Updated category");
        requestNode.put("key", "Updated key");
        requestNode.put("metaInfo", "Updated metainfo");
        requestNode.put("deploymentId", deploymentId);
        requestNode.put("version", 3);
        requestNode.put("tenantId", "myTenant");

        HttpPut httpPut = new HttpPut(
                SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_MODEL, model.getId()));
        httpPut.setEntity(new StringEntity(requestNode.toString()));
        CloseableHttpResponse response = executeRequest(httpPut, HttpStatus.SC_OK);

        JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
        closeResponse(response);
        assertNotNull(responseNode);
        assertEquals("Updated name", responseNode.get("name").textValue());
        assertEquals("Updated key", responseNode.get("key").textValue());
        assertEquals("Updated category", responseNode.get("category").textValue());
        assertEquals(3, responseNode.get("version").intValue());
        assertEquals("Updated metainfo", responseNode.get("metaInfo").textValue());
        assertEquals(deploymentId, responseNode.get("deploymentId").textValue());
        assertEquals(model.getId(), responseNode.get("id").textValue());
        assertEquals("myTenant", responseNode.get("tenantId").textValue());

        assertEquals(createTime.getTime().getTime(),
                getDateFromISOString(responseNode.get("createTime").textValue()).getTime());
        assertEquals(updateTime.getTime().getTime(),
                getDateFromISOString(responseNode.get("lastUpdateTime").textValue()).getTime());

        assertTrue(responseNode.get("url").textValue()
                .endsWith(RestUrls.createRelativeResourceUrl(RestUrls.URL_MODEL, model.getId())));
        assertTrue(responseNode.get("deploymentUrl").textValue()
                .endsWith(RestUrls.createRelativeResourceUrl(RestUrls.URL_DEPLOYMENT, deploymentId)));

    } finally {
        try {
            repositoryService.deleteModel(model.getId());
        } catch (Throwable ignore) {
            // Ignore, model might not be created
        }
    }
}

From source file:org.flowable.rest.service.api.repository.ModelResourceTest.java

@Deployment(resources = { "org/flowable/rest/service/api/repository/oneTaskProcess.bpmn20.xml" })
public void testUpdateModel() throws Exception {

    Model model = null;//  www .  jav a 2 s  .c  o  m
    try {
        Calendar createTime = Calendar.getInstance();
        createTime.set(Calendar.MILLISECOND, 0);
        processEngineConfiguration.getClock().setCurrentTime(createTime.getTime());

        model = repositoryService.newModel();
        model.setCategory("Model category");
        model.setKey("Model key");
        model.setMetaInfo("Model metainfo");
        model.setName("Model name");
        model.setVersion(2);
        repositoryService.saveModel(model);

        Calendar updateTime = Calendar.getInstance();
        updateTime.set(Calendar.MILLISECOND, 0);
        updateTime.add(Calendar.HOUR, 1);
        processEngineConfiguration.getClock().setCurrentTime(updateTime.getTime());

        // Create update request
        ObjectNode requestNode = objectMapper.createObjectNode();
        requestNode.put("name", "Updated name");
        requestNode.put("category", "Updated category");
        requestNode.put("key", "Updated key");
        requestNode.put("metaInfo", "Updated metainfo");
        requestNode.put("deploymentId", deploymentId);
        requestNode.put("version", 3);
        requestNode.put("tenantId", "myTenant");

        HttpPut httpPut = new HttpPut(
                SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_MODEL, model.getId()));
        httpPut.setEntity(new StringEntity(requestNode.toString()));
        CloseableHttpResponse response = executeRequest(httpPut, HttpStatus.SC_OK);

        JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
        closeResponse(response);
        assertNotNull(responseNode);
        assertEquals("Updated name", responseNode.get("name").textValue());
        assertEquals("Updated key", responseNode.get("key").textValue());
        assertEquals("Updated category", responseNode.get("category").textValue());
        assertEquals(3, responseNode.get("version").intValue());
        assertEquals("Updated metainfo", responseNode.get("metaInfo").textValue());
        assertEquals(deploymentId, responseNode.get("deploymentId").textValue());
        assertEquals(model.getId(), responseNode.get("id").textValue());
        assertEquals("myTenant", responseNode.get("tenantId").textValue());

        assertEquals(createTime.getTime().getTime(),
                getDateFromISOString(responseNode.get("createTime").textValue()).getTime());
        assertEquals(updateTime.getTime().getTime(),
                getDateFromISOString(responseNode.get("lastUpdateTime").textValue()).getTime());

        assertTrue(responseNode.get("url").textValue()
                .endsWith(RestUrls.createRelativeResourceUrl(RestUrls.URL_MODEL, model.getId())));
        assertTrue(responseNode.get("deploymentUrl").textValue()
                .endsWith(RestUrls.createRelativeResourceUrl(RestUrls.URL_DEPLOYMENT, deploymentId)));

    } finally {
        try {
            repositoryService.deleteModel(model.getId());
        } catch (Throwable ignore) {
            // Ignore, model might not be created
        }
    }
}

From source file:co.cask.cdap.client.rest.RestStreamClient.java

@Override
public void setTTL(String stream, long ttl) throws IOException {
    HttpPut putRequest = new HttpPut(restClient.getBaseURL()
            .resolve(String.format("/%s/streams/%s/config", restClient.getVersion(), stream)));
    StringEntity entity = new StringEntity(GSON.toJson(ImmutableMap.of(TTL_ATTRIBUTE_NAME, ttl)));
    entity.setContentType(MediaType.APPLICATION_JSON);
    putRequest.setEntity(entity);
    CloseableHttpResponse httpResponse = restClient.execute(putRequest);
    try {//from  ww w.  j av a2  s . com
        int responseCode = httpResponse.getStatusLine().getStatusCode();
        LOG.debug("Set TTL Response Code : {}", responseCode);
        RestClient.responseCodeAnalysis(httpResponse);
    } finally {
        httpResponse.close();
    }
}

From source file:org.apache.camel.component.cxf.jaxrs.simplebinding.CxfRsConsumerSimpleBindingTest.java

@Test
public void testUpdateCustomerBodyAndHeaders() throws Exception {
    HttpPut put = new HttpPut("http://localhost:" + PORT_PATH + "/rest/customerservice/customers/123");
    StringWriter sw = new StringWriter();
    jaxb.createMarshaller().marshal(new Customer(123, "Raul"), sw);
    put.setEntity(new StringEntity(sw.toString()));
    put.addHeader("Content-Type", "text/xml");
    put.addHeader("Accept", "text/xml");
    HttpResponse response = httpclient.execute(put);
    assertEquals(200, response.getStatusLine().getStatusCode());
}

From source file:com.hoccer.api.Linccer.java

public void submitEnvironment() throws UpdateException, ClientProtocolException, IOException {
    HttpResponse response;/* w w  w .j av  a 2s. c om*/
    long startTime = 0;
    String uri = mConfig.getClientUri() + "/environment";
    try {
        HttpPut request = new HttpPut(sign(uri));
        request.setEntity(new StringEntity(mEnvironment.toJson().toString(), HTTP.UTF_8));
        startTime = System.currentTimeMillis();
        LOG.finest("submit environment uri = " + uri);
        LOG.finest("submit environment = " + mEnvironment.toJson().toString());
        response = getHttpClient().execute(request);
    } catch (JSONException e) {
        mEnvironmentStatus = null;
        throw new UpdateException(
                "could not update gps measurement for " + mConfig.getClientUri() + " because of " + e);
    } catch (UnsupportedEncodingException e) {
        mEnvironmentStatus = null;
        throw new UpdateException(
                "could not update gps measurement for " + mConfig.getClientUri() + " because of " + e);
    }

    if (response.getStatusLine().getStatusCode() != 201) {
        try {
            mEnvironmentStatus = null;
            throw new UpdateException("could not update environment because server " + uri + " responded with "
                    + response.getStatusLine().getStatusCode() + ": "
                    + convertResponseToString(response, true));
        } catch (ParseException e) {
        } catch (IOException e) {
        }
        throw new UpdateException("could not update environment because server " + uri + " responded with "
                + response.getStatusLine().getStatusCode() + " and an unparsable body");
    }

    try {
        mEnvironmentStatus = new EnvironmentStatus(convertResponseToJsonObject(response));
    } catch (Exception e) {
        mEnvironmentStatus = null;
        throw new UpdateException("could not update environment because server responded with "
                + response.getStatusLine().getStatusCode() + " and an ill formed body: " + e.getMessage());
    }
    int latency = (int) (System.currentTimeMillis() - startTime);

    mEnvironment.setNetworkLatency(latency);
}