Example usage for org.apache.http.entity ContentType APPLICATION_JSON

List of usage examples for org.apache.http.entity ContentType APPLICATION_JSON

Introduction

In this page you can find the example usage for org.apache.http.entity ContentType APPLICATION_JSON.

Prototype

ContentType APPLICATION_JSON

To view the source code for org.apache.http.entity ContentType APPLICATION_JSON.

Click Source Link

Usage

From source file:com.foundationdb.server.service.security.SecurityServiceIT.java

@Test
public void restAddDropUser() throws Exception {
    SecurityService securityService = securityService();
    assertNull(securityService.getUser("user3"));
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(getRestURL("/security/users", null, "akiban:topsecret"));
    post.setEntity(new StringEntity(ADD_USER, ContentType.APPLICATION_JSON));
    HttpResponse response = client.execute(post);
    int code = response.getStatusLine().getStatusCode();
    String content = EntityUtils.toString(response.getEntity());
    assertEquals(HttpStatus.SC_OK, code);
    assertNotNull(securityService.getUser("user3"));

    // Check returned id
    JsonNode idNode = readTree(content).get("id");
    assertNotNull("Has id field", idNode);
    assertEquals("id is integer", true, idNode.isInt());

    HttpDelete delete = new HttpDelete(getRestURL("/security/users/user3", null, "akiban:topsecret"));
    response = client.execute(delete);/* www  . jav a2s .  c  om*/
    code = response.getStatusLine().getStatusCode();
    EntityUtils.consume(response.getEntity());
    client.getConnectionManager().shutdown();
    assertEquals(HttpStatus.SC_OK, code);
    assertNull(securityService.getUser("user3"));
}

From source file:org.elasticsearch.client.documentation.RestClientDocumentation.java

@SuppressWarnings("unused")
public void testUsage() throws IOException, InterruptedException {

    //tag::rest-client-init
    RestClient restClient = RestClient//from ww w  .ja  v a  2  s .  c  o  m
            .builder(new HttpHost("localhost", 9200, "http"), new HttpHost("localhost", 9201, "http")).build();
    //end::rest-client-init

    //tag::rest-client-close
    restClient.close();
    //end::rest-client-close

    {
        //tag::rest-client-init-default-headers
        RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
        Header[] defaultHeaders = new Header[] { new BasicHeader("header", "value") };
        builder.setDefaultHeaders(defaultHeaders); // <1>
        //end::rest-client-init-default-headers
    }
    {
        //tag::rest-client-init-max-retry-timeout
        RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
        builder.setMaxRetryTimeoutMillis(10000); // <1>
        //end::rest-client-init-max-retry-timeout
    }
    {
        //tag::rest-client-init-failure-listener
        RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
        builder.setFailureListener(new RestClient.FailureListener() {
            @Override
            public void onFailure(HttpHost host) {
                // <1>
            }
        });
        //end::rest-client-init-failure-listener
    }
    {
        //tag::rest-client-init-request-config-callback
        RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
        builder.setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
            @Override
            public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder requestConfigBuilder) {
                return requestConfigBuilder.setSocketTimeout(10000); // <1>
            }
        });
        //end::rest-client-init-request-config-callback
    }
    {
        //tag::rest-client-init-client-config-callback
        RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
        builder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
            @Override
            public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                return httpClientBuilder.setProxy(new HttpHost("proxy", 9000, "http")); // <1>
            }
        });
        //end::rest-client-init-client-config-callback
    }

    {
        //tag::rest-client-sync
        Request request = new Request("GET", // <1>
                "/"); // <2>
        Response response = restClient.performRequest(request);
        //end::rest-client-sync
    }
    {
        //tag::rest-client-async
        Request request = new Request("GET", // <1>
                "/"); // <2>
        restClient.performRequestAsync(request, new ResponseListener() {
            @Override
            public void onSuccess(Response response) {
                // <3>
            }

            @Override
            public void onFailure(Exception exception) {
                // <4>
            }
        });
        //end::rest-client-async
    }
    {
        Request request = new Request("GET", "/");
        //tag::rest-client-parameters
        request.addParameter("pretty", "true");
        //end::rest-client-parameters
        //tag::rest-client-body
        request.setEntity(new NStringEntity("{\"json\":\"text\"}", ContentType.APPLICATION_JSON));
        //end::rest-client-body
        //tag::rest-client-body-shorter
        request.setJsonEntity("{\"json\":\"text\"}");
        //end::rest-client-body-shorter
        {
            //tag::rest-client-headers
            RequestOptions.Builder options = request.getOptions().toBuilder();
            options.addHeader("Accept", "text/plain");
            options.addHeader("Cache-Control", "no-cache");
            request.setOptions(options);
            //end::rest-client-headers
        }
        {
            //tag::rest-client-response-consumer
            RequestOptions.Builder options = request.getOptions().toBuilder();
            options.setHttpAsyncResponseConsumerFactory(
                    new HttpAsyncResponseConsumerFactory.HeapBufferedResponseConsumerFactory(30 * 1024 * 1024));
            request.setOptions(options);
            //end::rest-client-response-consumer
        }
    }
    {
        HttpEntity[] documents = new HttpEntity[10];
        //tag::rest-client-async-example
        final CountDownLatch latch = new CountDownLatch(documents.length);
        for (int i = 0; i < documents.length; i++) {
            Request request = new Request("PUT", "/posts/doc/" + i);
            //let's assume that the documents are stored in an HttpEntity array
            request.setEntity(documents[i]);
            restClient.performRequestAsync(request, new ResponseListener() {
                @Override
                public void onSuccess(Response response) {
                    // <1>
                    latch.countDown();
                }

                @Override
                public void onFailure(Exception exception) {
                    // <2>
                    latch.countDown();
                }
            });
        }
        latch.await();
        //end::rest-client-async-example
    }
    {
        //tag::rest-client-response2
        Response response = restClient.performRequest("GET", "/");
        RequestLine requestLine = response.getRequestLine(); // <1>
        HttpHost host = response.getHost(); // <2>
        int statusCode = response.getStatusLine().getStatusCode(); // <3>
        Header[] headers = response.getHeaders(); // <4>
        String responseBody = EntityUtils.toString(response.getEntity()); // <5>
        //end::rest-client-response2
    }
}

From source file:com.linkedin.pinot.common.utils.FileUploadDownloadClient.java

private static HttpUriRequest getSendSegmentJsonRequest(URI uri, String jsonString,
        @Nullable List<Header> headers, @Nullable List<NameValuePair> parameters, int socketTimeoutMs) {
    RequestBuilder requestBuilder = RequestBuilder.post(uri).setVersion(HttpVersion.HTTP_1_1)
            .setHeader(CustomHeaders.UPLOAD_TYPE, FileUploadType.JSON.toString())
            .setEntity(new StringEntity(jsonString, ContentType.APPLICATION_JSON));
    addHeadersAndParameters(requestBuilder, headers, parameters);
    setTimeout(requestBuilder, socketTimeoutMs);
    return requestBuilder.build();
}

From source file:org.elasticsearch.xpack.ml.integration.MlBasicMultiNodeIT.java

public void testMiniFarequoteWithDatafeeder() throws Exception {
    String mappings = "{" + "  \"mappings\": {" + "    \"response\": {" + "      \"properties\": {"
            + "        \"time\": { \"type\":\"date\"}," + "        \"airline\": { \"type\":\"keyword\"},"
            + "        \"responsetime\": { \"type\":\"float\"}" + "      }" + "    }" + "  }" + "}";
    client().performRequest("put", "airline-data", Collections.emptyMap(),
            new StringEntity(mappings, ContentType.APPLICATION_JSON));
    client().performRequest("put", "airline-data/response/1", Collections.emptyMap(),
            new StringEntity("{\"time\":\"2016-06-01T00:00:00Z\",\"airline\":\"AAA\",\"responsetime\":135.22}",
                    ContentType.APPLICATION_JSON));
    client().performRequest("put", "airline-data/response/2", Collections.emptyMap(),
            new StringEntity("{\"time\":\"2016-06-01T01:59:00Z\",\"airline\":\"AAA\",\"responsetime\":541.76}",
                    ContentType.APPLICATION_JSON));

    // Ensure all data is searchable
    client().performRequest("post", "_refresh");

    String jobId = "mini-farequote-with-data-feeder-job";
    createFarequoteJob(jobId);//  w w w  .j  a v a 2 s.c om
    String datafeedId = "bar";
    createDatafeed(datafeedId, jobId);

    Response response = client().performRequest("post",
            MachineLearning.BASE_PATH + "anomaly_detectors/" + jobId + "/_open");
    assertEquals(200, response.getStatusLine().getStatusCode());
    assertEquals(Collections.singletonMap("opened", true), responseEntityToMap(response));

    response = client().performRequest("post",
            MachineLearning.BASE_PATH + "datafeeds/" + datafeedId + "/_start",
            Collections.singletonMap("start", "0"));
    assertEquals(200, response.getStatusLine().getStatusCode());
    assertEquals(Collections.singletonMap("started", true), responseEntityToMap(response));

    assertBusy(() -> {
        try {
            Response statsResponse = client().performRequest("get",
                    MachineLearning.BASE_PATH + "anomaly_detectors/" + jobId + "/_stats");
            assertEquals(200, statsResponse.getStatusLine().getStatusCode());
            @SuppressWarnings("unchecked")
            Map<String, Object> dataCountsDoc = (Map<String, Object>) ((Map) ((List) responseEntityToMap(
                    statsResponse).get("jobs")).get(0)).get("data_counts");
            assertEquals(2, dataCountsDoc.get("input_record_count"));
            assertEquals(2, dataCountsDoc.get("processed_record_count"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    });

    response = client().performRequest("post",
            MachineLearning.BASE_PATH + "datafeeds/" + datafeedId + "/_stop");
    assertEquals(200, response.getStatusLine().getStatusCode());
    assertEquals(Collections.singletonMap("stopped", true), responseEntityToMap(response));

    response = client().performRequest("post",
            MachineLearning.BASE_PATH + "anomaly_detectors/" + jobId + "/_close",
            Collections.singletonMap("timeout", "20s"));
    assertEquals(200, response.getStatusLine().getStatusCode());
    assertEquals(Collections.singletonMap("closed", true), responseEntityToMap(response));

    response = client().performRequest("delete", MachineLearning.BASE_PATH + "datafeeds/" + datafeedId);
    assertEquals(200, response.getStatusLine().getStatusCode());

    response = client().performRequest("delete", MachineLearning.BASE_PATH + "anomaly_detectors/" + jobId);
    assertEquals(200, response.getStatusLine().getStatusCode());
}

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

protected static void startServerWithOAuth(int port) {
    HttpPut put = null;// ww w  .j a v a  2s.c o  m
    try {
        put = new HttpPut(DEFAULT_SERVER_RUNNER_URL);
        put.setEntity(new StringEntity(getCreateServerDocumentWithApiKey(port), 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(e);
    } finally {
        if (put != null) {
            put.releaseConnection();
        }
    }
}

From source file:org.megam.deccanplato.provider.salesforce.crm.handler.PartnerImpl.java

/**
 * this method creates an account in salesforce.com and returns that account id.
 * This method gets input from a MAP(contains json data) and returns a MAp.
 * @param outMap //from   www  .ja va  2 s  .co  m
 */
private Map<String, String> create() {
    Map<String, String> outMap = new HashMap<>();
    final String SALESFORCE_CREATE_PARTNER_URL = args.get(INSTANCE_URL) + SALESFORCE_PARTNER_URL;
    Map<String, String> header = new HashMap<String, String>();
    header.put(S_AUTHORIZATION, S_OAUTH + args.get(ACCESS_TOKEN));
    Map<String, Object> partnerAttrMap = new HashMap<String, Object>();
    partnerAttrMap.put(S_ACCOUNTFROMIDE, args.get(ACCOUNT_FROM_ID));
    partnerAttrMap.put(S_ACCOUNTTOID, args.get(ACCOUNT_TO_ID));
    partnerAttrMap.put(S_ISPRIMARY, Boolean.parseBoolean(args.get(ISPRIMARY)));
    partnerAttrMap.put(S_OPPORTUNITYID, args.get(OPPORTUNITY_ID));
    partnerAttrMap.put(S_ROLE, args.get(ROLE));

    TransportTools tst = new TransportTools(SALESFORCE_CREATE_PARTNER_URL, null, header);
    Gson obj = new GsonBuilder().setPrettyPrinting().create();
    tst.setContentType(ContentType.APPLICATION_JSON, obj.toJson(partnerAttrMap));
    try {
        String responseBody = TransportMachinery.post(tst).entityToString();
        outMap.put(OUTPUT, responseBody);

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return outMap;
}

From source file:com.nextdoor.bender.ipc.es.ElasticSearchTransporterTest.java

@Test
public void testUncompressedContentType() {
    ElasticSearchTransport transport = new ElasticSearchTransport(null, false);
    assertEquals(ContentType.APPLICATION_JSON, transport.getUncompressedContentType());
}

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

protected void createDbAtPort(String dbName, int port) {
    HttpPut put = null;//from w  ww. j a v  a2s  . co  m
    try {
        put = new HttpPut("http://" + getHostName() + ":" + port + "/admin/databases/"
                + UrlUtils.escapeDataString(dbName));
        put.setEntity(new StringEntity(getCreateDbDocument(dbName, port), 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(e);
    } finally {
        if (put != null) {
            put.releaseConnection();
        }
    }
}

From source file:sonata.kernel.vimadaptor.wrapper.openstack.javastackclient.JavaStackCore.java

public synchronized HttpResponse createStack(String template, String stackName) throws IOException {

    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpResponseFactory factory = new DefaultHttpResponseFactory();
    HttpPost createStack = null;/*from w ww .ja v  a2s. c  om*/
    HttpResponse response = null;

    String jsonTemplate = JavaStackUtils.convertYamlToJson(template);
    JSONObject modifiedObject = new JSONObject();
    modifiedObject.put("stack_name", stackName);
    modifiedObject.put("template", new JSONObject(jsonTemplate));

    if (this.isAuthenticated) {
        StringBuilder buildUrl = new StringBuilder();
        buildUrl.append("http://");
        buildUrl.append(this.endpoint);
        buildUrl.append(":");
        buildUrl.append(Constants.HEAT_PORT.toString());
        buildUrl.append(String.format("/%s/%s/stacks", Constants.HEAT_VERSION.toString(), tenant_id));

        // Logger.debug(buildUrl.toString());
        createStack = new HttpPost(buildUrl.toString());
        createStack.setEntity(new StringEntity(modifiedObject.toString(), ContentType.APPLICATION_JSON));
        // Logger.debug(this.token_id);
        createStack.addHeader(Constants.AUTHTOKEN_HEADER.toString(), this.token_id);

        Logger.debug("Request: " + createStack.toString());
        Logger.debug("Request body: " + modifiedObject.toString());

        response = httpClient.execute(createStack);
        int statusCode = response.getStatusLine().getStatusCode();
        String responsePhrase = response.getStatusLine().getReasonPhrase();

        Logger.debug("Response: " + response.toString());
        Logger.debug("Response body:");

        if (statusCode != 201) {
            BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String line = null;

            while ((line = in.readLine()) != null)
                Logger.debug(line);
        }

        return (statusCode == 201) ? response
                : factory.newHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, statusCode,
                        responsePhrase + ". Create Failed with Status: " + statusCode), null);
    } else {
        throw new IOException("You must Authenticate before issuing this request, please re-authenticate. ");
    }
}

From source file:com.tremolosecurity.provisioning.customTasks.CallRemoteWorkflow.java

@Override
public boolean doTask(User user, Map<String, Object> request) throws ProvisioningException {

    HashMap<String, Object> newRequest = new HashMap<String, Object>();
    for (String name : this.fromRequest) {
        newRequest.put(name, request.get(name));
    }//w  ww .  ja  va  2  s. c o m

    for (String key : this.staticRequest.keySet()) {
        newRequest.put(key, this.staticRequest.get(key));
    }

    WFCall wfCall = new WFCall();
    wfCall.setName(this.workflowName);
    wfCall.setRequestParams(newRequest);
    wfCall.setUser(new TremoloUser());
    wfCall.getUser().setUid(user.getUserID());
    wfCall.getUser().setUserPassword(user.getPassword());
    wfCall.getUser().setGroups(user.getGroups());
    wfCall.getUser().setAttributes(new ArrayList<Attribute>());
    wfCall.getUser().getAttributes().addAll(user.getAttribs().values());
    wfCall.setUidAttributeName(uidAttributeName);
    wfCall.setReason(task.getWorkflow().getUser().getRequestReason());
    if (task.getWorkflow().getRequester() != null) {
        wfCall.setRequestor(task.getWorkflow().getRequester().getUserID());
    } else {
        wfCall.setRequestor(this.lastMileUser);
    }

    DateTime notBefore = new DateTime();
    notBefore = notBefore.minusSeconds(timeSkew);
    DateTime notAfter = new DateTime();
    notAfter = notAfter.plusSeconds(timeSkew);

    com.tremolosecurity.lastmile.LastMile lastmile = null;

    try {
        lastmile = new com.tremolosecurity.lastmile.LastMile(this.uri, notBefore, notAfter, 0, "oauth2");

    } catch (URISyntaxException e) {
        throw new ProvisioningException("Could not generate lastmile", e);
    }

    Attribute attrib = new Attribute(this.lastMileUid, this.lastMileUser);
    lastmile.getAttributes().add(attrib);
    String encryptedXML = null;

    try {
        encryptedXML = lastmile
                .generateLastMileToken(this.task.getConfigManager().getSecretKey(this.lastmileKeyName));
    } catch (Exception e) {
        throw new ProvisioningException("Could not generate lastmile", e);
    }

    StringBuffer header = new StringBuffer();
    header.append("Bearer ").append(encryptedXML);

    BasicHttpClientConnectionManager bhcm = null;
    CloseableHttpClient http = null;

    try {
        bhcm = new BasicHttpClientConnectionManager(this.task.getConfigManager().getHttpClientSocketRegistry());

        RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).setRedirectsEnabled(false)
                .build();

        http = HttpClients.custom().setConnectionManager(bhcm).setDefaultRequestConfig(rc).build();

        HttpPost post = new HttpPost(this.url);
        post.addHeader(new BasicHeader("Authorization", header.toString()));

        Gson gson = new Gson();
        StringEntity str = new StringEntity(gson.toJson(wfCall), ContentType.APPLICATION_JSON);
        post.setEntity(str);

        HttpResponse resp = http.execute(post);
        if (resp.getStatusLine().getStatusCode() != 200) {
            throw new ProvisioningException("Call failed");
        }

    } catch (IOException e) {
        throw new ProvisioningException("Could not make call", e);
    } finally {
        if (http != null) {
            try {
                http.close();
            } catch (IOException e) {
                logger.warn(e);
            }
        }

        if (bhcm != null) {
            bhcm.close();
        }

    }

    return true;
}