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.actelion.research.mapReduceExecSpark.executors.MapReduceExecutorSparkProxy.java

private void deployTask(String serUUID, int parallelism, String resultDir) throws IOException {
    int numCPUs = Math.min((int) (totalClusterCores * clusterUsage), coresPerJob * parallelism);

    String payload = "{" + "  \"action\": \"CreateSubmissionRequest\"," +

            "  \"mainClass\": \"com.actelion.research.mapReduceExecSpark.executors.MapReduceExecutorSparkExec\","
            + "  \"appArgs\": [ \"spark/MR-" + serUUID + ".ser\",\"" + resultDir + "\", \"" + this.smbUsername
            + "\",\"" + this.smbPassword + "\",\"" + this.smbDomain + "\",\"" + this.smbShare + "\" ],"
            + "  \"appResource\": \"" + fatJarName + "\"," +

            "  \"clientSparkVersion\": \"2.1.1\"," + "  \"environmentVariables\" : {"
            + "    \"SPARK_ENV_LOADED\" : \"1\"" + "    ,\"MESOS_SANDBOX\" : \"/mnt/mesos/sandbox\"" + "  },"
            + "  \"sparkProperties\": {" +
            //  "    \"spark.jars\": \"deps.jar\"," +    // does not work
            "    \"spark.app.name\": \"" + appName + "\"," + "    \"spark.driver.supervise\":\"false\","
            + "    \"spark.executor.memory\": \"" + memPerJobGB + "G\"," +
            //  "    \"spark.executor.cores\": \"10\"," +     //
            //  "    \"spark.executor.instances\": \"3\"," +   // not taken into account
            "    \"spark.cores.max\": \"" + numCPUs + "\"," + "    \"spark.task.cpus\": \"" + coresPerJob
            + "\"," +

            "    \"spark.driver.memory\": \"1G\"," + "    \"spark.driver.cores\": \"2\","
            + "    \"spark.default.parallelism\": \"" + parallelism + "\","
            + "    \"spark.submit.deployMode\":\"cluster\","
            + "    \"spark.mesos.executor.docker.image\": \"mesosphere/spark:2.1.0-2.2.1-1-hadoop-2.6\","
            + "    \"spark.mesos.executor.docker.volumes\": \"/arcite/orbit/:orbit:rw\"" + "  }" + "}";
    StringEntity entity = new StringEntity(payload, ContentType.APPLICATION_JSON);

    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpPost request = new HttpPost("http://" + host_port + "/v1/submissions/create");
    request.setEntity(entity);/*  w  w w .  j  a  v a2  s . c  o  m*/

    HttpResponse response = httpClient.execute(request);
    System.out.println("Status Code: " + response.getStatusLine().getStatusCode());
    String responseString = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
    System.out.println(responseString);

}

From source file:org.megam.deccanplato.provider.salesforce.crm.handler.AccountImpl.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   w  w  w  . j av  a 2 s  .c  o  m
 */
private Map<String, String> create() {
    Map<String, String> outMap = new HashMap<String, String>();
    final String SALESFORCE_CREATE_ACCOUNT_URL = args.get(INSTANCE_URL) + SALESFORCE_ACCOUNT_URL;
    Map<String, String> header = new HashMap<String, String>();
    header.put(S_AUTHORIZATION, S_OAUTH + args.get(ACCESS_TOKEN));
    Map<String, Object> accountAttrMap = new HashMap<String, Object>();
    accountAttrMap.put(S_NAME, args.get(NAME));

    TransportTools tst = new TransportTools(SALESFORCE_CREATE_ACCOUNT_URL, null, header);
    Gson obj = new GsonBuilder().setPrettyPrinting().create();
    tst.setContentType(ContentType.APPLICATION_JSON, obj.toJson(accountAttrMap));

    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:org.wso2.am.integration.tests.other.InvalidAuthTokenLargePayloadTestCase.java

@Test(groups = { "wso2.am" }, description = "Subscribe and invoke api", dependsOnMethods = "testApiCreation")
public void testApiInvocation() throws Exception {
    apiStore = new APIStoreRestClient(storeURLHttp);
    apiStore.login(user.getUserName(), String.valueOf(user.getPassword()));
    //add a application
    HttpResponse serviceResponse = apiStore.addApplication(APP_NAME, APIThrottlingTier.UNLIMITED.getState(), "",
            "this-is-test");
    verifyResponse(serviceResponse);/*from w ww  .  j  a v  a2s .co m*/

    //subscribe to the api
    SubscriptionRequest subscriptionRequest = new SubscriptionRequest(API_NAME, user.getUserName());
    subscriptionRequest.setApplicationName(APP_NAME);
    subscriptionRequest.setTier(APIMIntegrationConstants.API_TIER.GOLD);
    serviceResponse = apiStore.subscribe(subscriptionRequest);
    verifyResponse(serviceResponse);

    //invoke api
    requestHeaders.put(APIMIntegrationConstants.AUTHORIZATION_HEADER, "Bearer invalid_token_key");
    requestHeaders.put("Content-Type", ContentType.APPLICATION_JSON.toString());
    String invokeURL = getAPIInvocationURLHttp(API_CONTEXT, API_VERSION) + "/post";

    HttpResponse response;
    //first test for small payload
    try {
        response = uploadFile(invokeURL, new File(testFile1KBFilePath), requestHeaders);
        Assert.fail("Resource cannot be access with wrong access token");
    } catch (IOException e) {
        Assert.assertTrue(e.getMessage().contains(String.valueOf(HttpStatus.SC_UNAUTHORIZED)));
    }

    //test for medium payload
    try {
        response = uploadFile(invokeURL, new File(testFile100KBFilePath), requestHeaders);
        Assert.fail("Resource cannot be access with wrong access token");
    } catch (IOException e) {
        Assert.assertTrue(e.getMessage().contains(String.valueOf(HttpStatus.SC_UNAUTHORIZED)));
    }

    //test for large payload
    try {
        response = uploadFile(invokeURL, new File(testFile1MBFilePath), requestHeaders);
        Assert.fail("Resource cannot be access with wrong access token");
    } catch (IOException e) {
        Assert.assertTrue(e.getMessage().contains(String.valueOf(HttpStatus.SC_UNAUTHORIZED)));
    }
}

From source file:org.elasticsearch.upgrades.FullClusterRestartIT.java

public void testSearch() throws Exception {
    int count;//from   w w w  . ja  va2s  .  co  m
    if (runningAgainstOldCluster) {
        XContentBuilder mappingsAndSettings = jsonBuilder();
        mappingsAndSettings.startObject();
        {
            mappingsAndSettings.startObject("settings");
            mappingsAndSettings.field("number_of_shards", 1);
            mappingsAndSettings.field("number_of_replicas", 0);
            mappingsAndSettings.endObject();
        }
        {
            mappingsAndSettings.startObject("mappings");
            mappingsAndSettings.startObject("doc");
            mappingsAndSettings.startObject("properties");
            {
                mappingsAndSettings.startObject("string");
                mappingsAndSettings.field("type", "text");
                mappingsAndSettings.endObject();
            }
            {
                mappingsAndSettings.startObject("dots_in_field_names");
                mappingsAndSettings.field("type", "text");
                mappingsAndSettings.endObject();
            }
            {
                mappingsAndSettings.startObject("binary");
                mappingsAndSettings.field("type", "binary");
                mappingsAndSettings.field("store", "true");
                mappingsAndSettings.endObject();
            }
            mappingsAndSettings.endObject();
            mappingsAndSettings.endObject();
            mappingsAndSettings.endObject();
        }
        mappingsAndSettings.endObject();
        client().performRequest("PUT", "/" + index, Collections.emptyMap(),
                new StringEntity(Strings.toString(mappingsAndSettings), ContentType.APPLICATION_JSON));

        count = randomIntBetween(2000, 3000);
        byte[] randomByteArray = new byte[16];
        random().nextBytes(randomByteArray);
        indexRandomDocuments(count, true, true, i -> {
            return JsonXContent.contentBuilder().startObject().field("string", randomAlphaOfLength(10))
                    .field("int", randomInt(100)).field("float", randomFloat())
                    // be sure to create a "proper" boolean (True, False) for the first document so that automapping is correct
                    .field("bool", i > 0 && supportsLenientBooleans ? randomLenientBoolean() : randomBoolean())
                    .field("field.with.dots", randomAlphaOfLength(10))
                    .field("binary", Base64.getEncoder().encodeToString(randomByteArray)).endObject();
        });
        refresh();
    } else {
        count = countOfIndexedRandomDocuments();
    }

    Map<String, String> params = new HashMap<>();
    params.put("timeout", "2m");
    params.put("wait_for_status", "green");
    params.put("wait_for_no_relocating_shards", "true");
    params.put("wait_for_events", "languid");
    Map<String, Object> healthRsp = toMap(client().performRequest("GET", "/_cluster/health/" + index, params));
    logger.info("health api response: {}", healthRsp);
    assertEquals("green", healthRsp.get("status"));
    assertFalse((Boolean) healthRsp.get("timed_out"));

    assertBasicSearchWorks(count);
    assertAllSearchWorks(count);
    assertBasicAggregationWorks();
    assertRealtimeGetWorks();
    assertStoredBinaryFields(count);
}

From source file:org.commonjava.indy.metrics.zabbix.api.IndyZabbixApi.java

@Override
public JsonNode call(Request request) throws IOException {
    if (request.getAuth() == null) {
        request.setAuth(this.auth);
    }/*from   w w w  . j a  va2 s  .c om*/
    ObjectMapper mapper = new ObjectMapper();
    HttpUriRequest httpRequest = org.apache.http.client.methods.RequestBuilder.post().setUri(uri)
            .addHeader("Content-Type", "application/json")
            .setEntity(new StringEntity(mapper.writeValueAsString(request), ContentType.APPLICATION_JSON))
            .build();
    CloseableHttpResponse response = httpClient.execute(httpRequest);
    String result = EntityUtils.toString(response.getEntity());
    logger.info(result);
    return mapper.readTree(result);
}

From source file:com.mollie.api.MollieClient.java

/**
 * Perform a http call. This method is used by the resource specific classes.
 * Please use the payments() method to perform operations on payments.
 *
 * @param method the http method to use//from   ww  w . j av a  2s. co  m
 * @param apiMethod the api method to call
 * @param httpBody the contents to send to the server.
 * @return result of the http call
 * @throws MollieException when the api key is not set or when there is a
 * problem communicating with the mollie server.
 * @see #performHttpCall(String method, String apiMethod)
 */
public String performHttpCall(String method, String apiMethod, String httpBody) throws MollieException {
    URI uri = null;
    String result = null;

    if (_apiKey == null || _apiKey.trim().equals("")) {
        throw new MollieException("You have not set an api key. Please use setApiKey() to set the API key.");
    }

    try {
        URIBuilder ub = new URIBuilder(this._apiEndpoint + "/" + API_VERSION + "/" + apiMethod);
        uri = ub.build();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }

    if (uri != null) {
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        HttpRequestBase action = null;
        HttpResponse response = null;

        if (method.equals(HTTP_POST)) {
            action = new HttpPost(uri);
        } else if (method.equals(HTTP_DELETE)) {
            action = new HttpDelete(uri);
        } else {
            action = new HttpGet(uri);
        }

        if (httpBody != null && action instanceof HttpPost) {
            StringEntity entity = new StringEntity(httpBody, ContentType.APPLICATION_JSON);
            ((HttpPost) action).setEntity(entity);
        }

        action.setHeader("Authorization", "Bearer " + this._apiKey);
        action.setHeader("Accept", ContentType.APPLICATION_JSON.getMimeType());

        try {
            response = httpclient.execute(action);

            HttpEntity entity = response.getEntity();
            StringWriter sw = new StringWriter();

            IOUtils.copy(entity.getContent(), sw, "UTF-8");
            result = sw.toString();
            EntityUtils.consume(entity);
        } catch (Exception e) {
            throw new MollieException("Unable to communicate with Mollie");
        }

        try {
            httpclient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return result;
}

From source file:org.elasticsearch.upgrades.TokenBackwardsCompatibilityIT.java

public void testUpgradedCluster() throws Exception {
    assumeTrue("this test should only run against the mixed cluster", clusterType == CLUSTER_TYPE.UPGRADED);
    Response getResponse = client().performRequest("GET",
            "token_backwards_compatibility_it/doc/old_cluster_token2");
    assertOK(getResponse);/* ww w. j  ava  2 s . c  om*/
    Map<String, Object> source = (Map<String, Object>) entityAsMap(getResponse).get("_source");
    final String token = (String) source.get("token");

    // invalidate again since this may not have been invalidated in the mixed cluster
    final StringEntity body = new StringEntity("{\"token\": \"" + token + "\"}", ContentType.APPLICATION_JSON);
    Response invalidationResponse = client().performRequest("DELETE", "_xpack/security/oauth2/token",
            Collections.singletonMap("error_trace", "true"), body);
    assertOK(invalidationResponse);
    assertTokenDoesNotWork(token);

    getResponse = client().performRequest("GET", "token_backwards_compatibility_it/doc/old_cluster_token1");
    assertOK(getResponse);
    source = (Map<String, Object>) entityAsMap(getResponse).get("_source");
    final String workingToken = (String) source.get("token");
    assertTokenWorks(workingToken);

    final StringEntity tokenPostBody = new StringEntity("{\n" + "    \"username\": \"test_user\",\n"
            + "    \"password\": \"x-pack-test-password\",\n" + "    \"grant_type\": \"password\"\n" + "}",
            ContentType.APPLICATION_JSON);
    Response response = client().performRequest("POST", "_xpack/security/oauth2/token", Collections.emptyMap(),
            tokenPostBody);
    assertOK(response);
    Map<String, Object> responseMap = entityAsMap(response);
    String accessToken = (String) responseMap.get("access_token");
    String refreshToken = (String) responseMap.get("refresh_token");
    assertNotNull(accessToken);
    assertNotNull(refreshToken);
    assertTokenWorks(accessToken);

    final StringEntity tokenRefresh = new StringEntity("{\n" + "    \"refresh_token\": \"" + refreshToken
            + "\",\n" + "    \"grant_type\": \"refresh_token\"\n" + "}", ContentType.APPLICATION_JSON);
    response = client().performRequest("POST", "_xpack/security/oauth2/token", Collections.emptyMap(),
            tokenRefresh);
    assertOK(response);
    responseMap = entityAsMap(response);
    String updatedAccessToken = (String) responseMap.get("access_token");
    String updatedRefreshToken = (String) responseMap.get("refresh_token");
    assertNotNull(updatedAccessToken);
    assertNotNull(updatedRefreshToken);
    assertTokenWorks(updatedAccessToken);
    assertTokenWorks(accessToken);
    assertNotEquals(accessToken, updatedAccessToken);
    assertNotEquals(refreshToken, updatedRefreshToken);
}

From source file:org.megam.deccanplato.provider.salesforce.crm.handler.PriceBookImpl.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 //ww  w .ja  v  a 2s.  co m
 */
private Map<String, String> create() {
    Map<String, String> outMap = new HashMap<>();
    final String SALESFORCE_CREATE_PRICEBOOK_URL = args.get(INSTANCE_URL) + SALESFORCE_PRICEBOOK_URL;
    Map<String, String> header = new HashMap<String, String>();
    header.put(S_AUTHORIZATION, S_OAUTH + args.get(ACCESS_TOKEN));
    Map<String, Object> priceBookAttrMap = new HashMap<String, Object>();
    priceBookAttrMap.put(S_NAME, args.get(NAME));
    priceBookAttrMap.put(S_DESCRIPTION, args.get(DESCRIPTION));
    priceBookAttrMap.put(S_ISACTIVE, Boolean.parseBoolean(args.get(ISACTIVE)));

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

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

From source file:org.elasticsearch.client.CustomRestHighLevelClientTests.java

/**
 * Mocks the synchronous request execution like if it was executed by Elasticsearch.
 */// ww w  .  ja  v a 2  s.c  o  m
private Response mockPerformRequest(Request request) throws IOException {
    assertThat(request.getOptions().getHeaders(), hasSize(1));
    Header httpHeader = request.getOptions().getHeaders().get(0);
    final Response mockResponse = mock(Response.class);
    when(mockResponse.getHost()).thenReturn(new HttpHost("localhost", 9200));

    ProtocolVersion protocol = new ProtocolVersion("HTTP", 1, 1);
    when(mockResponse.getStatusLine()).thenReturn(new BasicStatusLine(protocol, 200, "OK"));

    MainResponse response = new MainResponse(httpHeader.getValue(), Version.CURRENT, ClusterName.DEFAULT, "_na",
            Build.CURRENT);
    BytesRef bytesRef = XContentHelper.toXContent(response, XContentType.JSON, false).toBytesRef();
    when(mockResponse.getEntity())
            .thenReturn(new ByteArrayEntity(bytesRef.bytes, ContentType.APPLICATION_JSON));

    RequestLine requestLine = new BasicRequestLine(HttpGet.METHOD_NAME, ENDPOINT, protocol);
    when(mockResponse.getRequestLine()).thenReturn(requestLine);

    return mockResponse;
}