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:io.kyligence.benchmark.loadtest.client.RestClient.java

private boolean setCache(boolean flag) throws IOException {
    String url = baseUrl + "/admin/config";
    HttpPut put = newPut(url);
    HashMap<String, String> paraMap = new HashMap<String, String>();
    paraMap.put("key", "kylin.query.cache-enabled");
    paraMap.put("value", flag + "");
    put.setEntity(new StringEntity(new ObjectMapper().writeValueAsString(paraMap), "UTF-8"));
    HttpResponse response = client.execute(put);
    EntityUtils.consume(response.getEntity());
    if (response.getStatusLine().getStatusCode() != 200) {
        return false;
    } else {// w  ww.jav a2  s. c  o  m
        return true;
    }
}

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

@Test
public void testPutConsumer() throws Exception {
    HttpPut put = new HttpPut("http://localhost:" + CXT + "/rest/customerservice/customers");
    StringEntity entity = new StringEntity(PUT_REQUEST, "ISO-8859-1");
    entity.setContentType("text/xml; charset=ISO-8859-1");
    put.addHeader("test", "header1;header2");
    put.setEntity(entity);
    HttpClient httpclient = new DefaultHttpClient();

    try {/*from  w ww  .j  av a 2  s  .c o m*/
        HttpResponse response = httpclient.execute(put);
        assertEquals(200, response.getStatusLine().getStatusCode());
        assertEquals("", EntityUtils.toString(response.getEntity()));
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.apache.cloudstack.cloudian.client.CloudianClient.java

private HttpResponse put(final String path, final Object item) throws IOException {
    final ObjectMapper mapper = new ObjectMapper();
    final String json = mapper.writeValueAsString(item);
    final StringEntity entity = new StringEntity(json);
    final HttpPut request = new HttpPut(adminApiUrl + path);
    request.setHeader("Content-type", "application/json");
    request.setEntity(entity);
    final HttpResponse response = httpClient.execute(request, httpContext);
    checkAuthFailure(response);//from   w  w w  . j  ava  2s . c  o m
    return response;
}

From source file:com.couchbase.lite.performance.Test7_PullReplication.java

private void pushDocumentToSyncGateway(String docId, final String docJson) throws MalformedURLException {
    // push a document to server
    URL replicationUrlTrailingDoc1 = new URL(
            String.format("%s/%s", getReplicationURL().toExternalForm(), docId));
    final URL pathToDoc1 = new URL(replicationUrlTrailingDoc1, docId);
    Log.d(TAG, "Send http request to " + pathToDoc1);

    final CountDownLatch httpRequestDoneSignal = new CountDownLatch(1);
    BackgroundTask getDocTask = new BackgroundTask() {

        @Override//from   ww w .j  a va 2s  .c o m
        public void run() {

            HttpClient httpclient = new DefaultHttpClient();

            HttpResponse response;
            String responseString = null;
            try {
                HttpPut post = new HttpPut(pathToDoc1.toExternalForm());
                StringEntity se = new StringEntity(docJson.toString());
                se.setContentType(new BasicHeader("content_type", "application/json"));
                post.setEntity(se);
                response = httpclient.execute(post);
                StatusLine statusLine = response.getStatusLine();
                Log.d(TAG, "Got response: " + statusLine);
                assertTrue(statusLine.getStatusCode() == HttpStatus.SC_CREATED);
            } catch (ClientProtocolException e) {
                assertNull("Got ClientProtocolException: " + e.getLocalizedMessage(), e);
            } catch (IOException e) {
                assertNull("Got IOException: " + e.getLocalizedMessage(), e);
            }

            httpRequestDoneSignal.countDown();
        }

    };
    getDocTask.execute();

    Log.d(TAG, "Waiting for http request to finish");
    try {
        httpRequestDoneSignal.await(300, TimeUnit.SECONDS);
        Log.d(TAG, "http request finished");
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:io.fabric8.itests.paxexam.basic.FabricMavenProxyTest.java

@Test
public void testUpload() throws Exception {
    String featureLocation = System.getProperty("feature.location");
    System.out.println("Testing with feature from:" + featureLocation);
    System.out.println(executeCommand("fabric:create -n --wait-for-provisioning"));
    //System.out.println(executeCommand("shell:info"));
    //System.out.println(executeCommand("fabric:info"));
    //System.out.println(executeCommand("fabric:profile-list"));

    ServiceProxy<FabricService> fabricProxy = ServiceProxy.createServiceProxy(bundleContext,
            FabricService.class);
    try {//www . j  av a2 s  .  co m
        Set<ContainerProxy> containers = ContainerBuilder.create(fabricProxy, 2).withName("maven")
                .withProfiles("fabric").assertProvisioningResult().build();
        try {
            List<String> uploadUrls = new ArrayList<String>();
            ServiceProxy<CuratorFramework> curatorProxy = ServiceProxy.createServiceProxy(bundleContext,
                    CuratorFramework.class);
            try {
                CuratorFramework curator = curatorProxy.getService();
                List<String> children = ZooKeeperUtils.getChildren(curator,
                        ZkPath.MAVEN_PROXY.getPath("upload"));
                for (String child : children) {
                    String uploadeUrl = ZooKeeperUtils.getSubstitutedPath(curator,
                            ZkPath.MAVEN_PROXY.getPath("upload") + "/" + child);
                    uploadUrls.add(uploadeUrl);
                }
            } finally {
                curatorProxy.close();
            }
            //Pick a random maven proxy from the list.
            Random random = new Random();
            int index = random.nextInt(uploadUrls.size());
            String targetUrl = uploadUrls.get(index);

            String uploadUrl = targetUrl + "itest/itest/1.0/itest-1.0-features.xml";
            System.out.println("Using URI: " + uploadUrl);
            DefaultHttpClient client = new DefaultHttpClient();
            HttpPut put = new HttpPut(uploadUrl);
            client.getCredentialsProvider().setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials("admin", "admin"));

            FileNIOEntity entity = new FileNIOEntity(new File(featureLocation), "text/xml");
            put.setEntity(entity);
            HttpResponse response = client.execute(put);
            System.out.println("Response:" + response.getStatusLine());
            Assert.assertTrue(response.getStatusLine().getStatusCode() == 200
                    || response.getStatusLine().getStatusCode() == 202);

            System.out.println(executeCommand(
                    "fabric:profile-edit --repositories mvn:itest/itest/1.0/xml/features default"));
            System.out.println(executeCommand("fabric:profile-edit --features example-cbr default"));
            Provision.containerStatus(containers, PROVISION_TIMEOUT);
        } finally {
            ContainerBuilder.destroy(containers);
        }
    } finally {
        fabricProxy.close();
    }
}

From source file:org.flowable.rest.service.api.runtime.ProcessInstanceVariableResourceTest.java

/**
 * Test updating a single process variable, including "not found" check.
 * /*  ww w  .  ja  v a  2s .  c om*/
 * PUT runtime/process-instances/{processInstanceId}/variables/{variableName}
 */
@Deployment(resources = {
        "org/flowable/rest/service/api/runtime/ProcessInstanceVariableResourceTest.testProcess.bpmn20.xml" })
public void testUpdateProcessVariable() throws Exception {
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess",
            Collections.singletonMap("overlappingVariable", (Object) "processValue"));
    runtimeService.setVariable(processInstance.getId(), "myVar", "value");

    // Update variable
    ObjectNode requestNode = objectMapper.createObjectNode();
    requestNode.put("name", "myVar");
    requestNode.put("value", "updatedValue");
    requestNode.put("type", "string");

    HttpPut httpPut = new HttpPut(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(
            RestUrls.URL_PROCESS_INSTANCE_VARIABLE, processInstance.getId(), "myVar"));
    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("updatedValue", responseNode.get("value").asText());

    // Try updating with mismatch between URL and body variableName
    requestNode.put("name", "unexistingVariable");
    httpPut.setEntity(new StringEntity(requestNode.toString()));
    closeResponse(executeRequest(httpPut, HttpStatus.SC_BAD_REQUEST));

    // Try updating unexisting property
    requestNode.put("name", "unexistingVariable");
    httpPut = new HttpPut(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(
            RestUrls.URL_PROCESS_INSTANCE_VARIABLE, processInstance.getId(), "unexistingVariable"));
    httpPut.setEntity(new StringEntity(requestNode.toString()));
    closeResponse(executeRequest(httpPut, HttpStatus.SC_NOT_FOUND));
}

From source file:com.urbancode.ud.client.ComponentClient.java

public void updateSourceConfigProperty(String componentParam, String name, String value, String description,
        Boolean secure) throws IOException, JSONException {
    JSONObject propJson = createNewPropertyJSON(name, value, secure);
    propJson.put("description", description);

    String uri = url + "/rest/deploy/component/" + encodePath(componentParam) + "/updateSourceConfigProperties/"
            + encodePath(name);//  w  w  w.  j  a v a2  s  .  c o  m
    HttpPut method = new HttpPut(uri);
    method.setEntity(getStringEntity(propJson));
    invokeMethod(method);
}

From source file:org.sahli.asciidoc.confluence.publisher.client.http.HttpRequestFactory.java

HttpPut updatePageRequest(String contentId, String ancestorId, String title, String content, int newVersion) {
    assertMandatoryParameter(isNotBlank(contentId), "contentId");
    assertMandatoryParameter(isNotBlank(ancestorId), "ancestorId");
    assertMandatoryParameter(isNotBlank(title), "title");

    PagePayload pagePayload = pagePayloadBuilder().ancestorId(ancestorId).title(title).content(content)
            .version(newVersion).build();

    String jsonPayload = toJsonString(pagePayload);
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(new ByteArrayInputStream(jsonPayload.getBytes()));

    HttpPut updatePageRequest = new HttpPut(this.confluenceRestApiEndpoint + "/content/" + contentId);
    updatePageRequest.setEntity(entity);
    updatePageRequest.addHeader(APPLICATION_JSON_UTF8_HEADER);

    return updatePageRequest;
}

From source file:com.bigdata.rockstor.console.UploadServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    if (!ServletFileUpload.isMultipartContent(req)) {
        LOG.error("It is not a MultipartContent, return error.");
        resp.sendError(500, "It is not a MultipartContent, return error.");
        return;//w  w  w. j  a  v  a2 s . com
    }

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(1024 * 1024 * 512);
    List<FileItem> fileItems = null;
    try {
        fileItems = upload.parseRequest(req);
        LOG.info("parse requeset success : items num : " + fileItems.size());
    } catch (FileUploadException e) {
        LOG.error("parse requeset failed !");
        resp.sendError(500, "parse requeset failed !");
        return;
    }

    HashMap<String, String> headMap = new HashMap<String, String>();
    FileItem theFile = null;
    long size = -1;
    URI uri = null;

    Iterator<FileItem> iter = fileItems.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        if (item.isFormField()) {
            String name = item.getFieldName();
            String value = null;
            try {
                value = item.getString("UTF-8").trim();
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }
            LOG.info("Parse head info : " + name + " -- " + value);
            if (name.equals("ObjName")) {
                try {
                    uri = new URI(value);
                } catch (URISyntaxException e) {
                    LOG.info("Parse uri info error : " + value);
                    uri = null;
                }
            } else if (name.equals("ObjSize")) {
                try {
                    size = Long.parseLong(value);
                } catch (Exception e) {
                    LOG.error("Parse objSize error : " + value);
                }
            } else {
                headMap.put(name, value);
            }
        } else {
            theFile = item;
        }
    }

    if (size == -1 || uri == null || theFile == null || headMap.size() == 0) {
        LOG.error("Parse upload info error : size==-1 || uri == null || theFile == null || headMap.size()==0");
        resp.sendError(500,
                "Parse upload info error : size==-1 || uri == null || theFile == null || headMap.size()==0");
        return;
    }

    HttpPut put = new HttpPut();
    put.setURI(uri);
    for (Map.Entry<String, String> e : headMap.entrySet()) {
        if ("Filename".equals(e.getKey()))
            continue;
        put.setHeader(e.getKey(), e.getValue());
    }
    put.setEntity(new InputStreamEntity(theFile.getInputStream(), size));
    DefaultHttpClient client = new DefaultHttpClient();
    HttpResponse response = client.execute(put);
    if (200 != response.getStatusLine().getStatusCode()) {
        LOG.error("Put object error : " + response.getStatusLine().getStatusCode() + " : "
                + response.getStatusLine().getReasonPhrase());
        resp.sendError(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase());
        return;
    }
    LOG.info("Put object OK : " + uri);
    response.setStatusCode(200);
}