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:test.portlet.service.impl.MolgenisAPIRequestLocalServiceImpl.java

public void testAPIUpdate() {
    String url = "http://catalogue.rd-connect.eu/apiv1/update";
    System.out.println("-- API Update Test: " + url);
    try {/*www.  java2s  .com*/
        HttpClient c = HttpClientBuilder.create().build();

        HttpPost p = new HttpPost(url);
        BASE64Encoder base = new BASE64Encoder();
        String encoding = base.encode("jud@patientcrossroads.com:rdc2016".getBytes());
        p.addHeader("Authorization", "Basic " + encoding);
        p.setHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());
        System.out.println("Authorization:" + encoding);

        String entry = "[{\"/update-portlet.idcard/diseasematrix\": {\"url\": \"https://connect.patientcrossroads.org/?org=algsa\",\"diseasname\": \"Alagille Syndrome 1\",\"patientcount\": \"\",\"gene\": \"JAG1\",\"orphanumber\": \"ORPHA52\",\"icd10\": \"Q44.7\",\"omim\": \"#610205\",\"synonym\": \"ALGS1\"}}]";
        p.setEntity(new StringEntity(entry, ContentType.APPLICATION_JSON));

        HttpResponse r = c.execute(p);

        BufferedReader rd = new BufferedReader(new InputStreamReader(r.getEntity().getContent()));
        String line = "";
        while ((line = rd.readLine()) != null) {
            // Parse our JSON response
            System.out.println(line);
        }

    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:com.sugarcrm.candybean.webservices.WSSystemTest.java

License:asdf

@Test
public void testPutRequest() {
    try {//  w w w. ja  va2s . c o  m
        response = WS.request(WS.OP.PUT, uri + "/put", headers, "Hello World", ContentType.APPLICATION_JSON);
    } catch (Exception e) {
        Assert.fail(e.toString());
    }
    Assert.assertTrue(response != null);
    // The field data will contain what ever we sent it
    Assert.assertEquals("Hello World", response.get("data"));
}

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

public void testDeleteStoredScript() throws Exception {
    final StoredScriptSource scriptSource = new StoredScriptSource("painless",
            "Math.log(_score * 2) + params.my_modifier",
            Collections.singletonMap(Script.CONTENT_TYPE_OPTION, XContentType.JSON.mediaType()));

    final String script = Strings.toString(scriptSource.toXContent(jsonBuilder(), ToXContent.EMPTY_PARAMS));
    // TODO: change to HighLevel PutStoredScriptRequest when it will be ready
    // so far - using low-level REST API
    Response putResponse = adminClient().performRequest("PUT", "/_scripts/" + id, emptyMap(),
            new StringEntity("{\"script\":" + script + "}", ContentType.APPLICATION_JSON));
    assertEquals(putResponse.getStatusLine().getReasonPhrase(), 200,
            putResponse.getStatusLine().getStatusCode());
    assertEquals("{\"acknowledged\":true}", EntityUtils.toString(putResponse.getEntity()));

    DeleteStoredScriptRequest deleteRequest = new DeleteStoredScriptRequest(id);
    deleteRequest.masterNodeTimeout("50s");
    deleteRequest.timeout("50s");

    DeleteStoredScriptResponse deleteResponse = execute(deleteRequest, highLevelClient()::deleteScript,
            highLevelClient()::deleteScriptAsync);

    assertThat(deleteResponse.isAcknowledged(), equalTo(true));

    GetStoredScriptRequest getRequest = new GetStoredScriptRequest(id);

    final ElasticsearchStatusException statusException = expectThrows(ElasticsearchStatusException.class,
            () -> execute(getRequest, highLevelClient()::getScript, highLevelClient()::getScriptAsync));
    assertThat(statusException.status(), equalTo(RestStatus.NOT_FOUND));
}

From source file:org.sourcepit.docker.watcher.ConsulForwarder.java

private void register(ConsulService service) {

    final HttpPut put = new HttpPut(uri + "/v1/agent/service/register");
    put.setEntity(new StringEntity(service.toString(), ContentType.APPLICATION_JSON));
    try {/*  ww  w.  ja v  a  2  s.c  o  m*/
        HttpResponse response = client.execute(put);
        closeQuietly(response);
    } catch (IOException e) {
        e.printStackTrace();
    }

    final TtlCheck check = new TtlCheck();
    check.serviceId = id(service);
    check.name = getTtlCheckName(service);
    check.id = getTtlCheckName(service);
    check.ttl = "90s";

    final HttpPut put2 = new HttpPut(uri + "/v1/agent/check/register");
    put2.setEntity(new StringEntity(check.toString(), ContentType.APPLICATION_JSON));
    try {
        HttpResponse response = client.execute(put2);
        closeQuietly(response);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.ibm.streamsx.topology.internal.streaminganalytics.RestUtils.java

/**
 * Submit an application bundle to execute as a job.
 *//*from   w w w  . j a  v  a  2  s.c o m*/
public static JsonObject postJob(CloseableHttpClient httpClient, JsonObject service, File bundle,
        JsonObject jobConfigOverlay) throws ClientProtocolException, IOException {

    final String serviceName = jstring(service, "name");
    final JsonObject credentials = service.getAsJsonObject("credentials");

    String url = getJobSubmitURL(credentials, bundle);

    HttpPost postJobWithConfig = new HttpPost(url);
    postJobWithConfig.addHeader("accept", ContentType.APPLICATION_JSON.getMimeType());
    postJobWithConfig.addHeader(AUTH.WWW_AUTH_RESP, getAPIKey(credentials));
    FileBody bundleBody = new FileBody(bundle, ContentType.APPLICATION_OCTET_STREAM);
    StringBody configBody = new StringBody(jobConfigOverlay.toString(), ContentType.APPLICATION_JSON);

    HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("sab", bundleBody)
            .addPart(DeployKeys.JOB_CONFIG_OVERLAYS, configBody).build();

    postJobWithConfig.setEntity(reqEntity);

    JsonObject jsonResponse = getGsonResponse(httpClient, postJobWithConfig);

    RemoteContext.REMOTE_LOGGER.info("Streaming Analytics service (" + serviceName + "): submit job response:"
            + jsonResponse.toString());

    return jsonResponse;
}

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

/**
 * this method creates a user in salesforce.com and returns that user id.
 * This method gets input from a MAP(contains json data) and returns a MAp.
 * @param outMap /* w w  w  .  ja va  2 s . co  m*/
 */
private Map<String, String> create() {
    Map<String, String> outMap = new HashMap<String, String>();
    final String SALESFORCE_CREATE_USER_URL = args.get(INSTANCE_URL) + SALESFORCE_USER_URL;
    Map<String, String> header = new HashMap<String, String>();
    header.put(S_AUTHORIZATION, S_OAUTH + args.get(ACCESS_TOKEN));

    Map<String, Object> userAttrMap = new HashMap<String, Object>();
    userAttrMap.put(S_USERNAME, args.get(USERNAME));
    userAttrMap.put(S_FIRSTNAME, args.get(FIRSTNAME));
    userAttrMap.put(S_EMAIL, args.get(EMAIL));
    userAttrMap.put(S_ALIAS, args.get(ALIAS));
    userAttrMap.put(S_PROFILEID, args.get(PROFILEID));
    userAttrMap.put(S_LASTNAME, args.get(LASTNAME));
    userAttrMap.put(S_TIMEZONESIDKEY, args.get(TIMEZONESIDKEY));
    userAttrMap.put(S_LOCALESIDKEY, args.get(LOCALESIDKEY));
    userAttrMap.put(S_EMAILENCODINGKEY, args.get(EMAILENCODINGKEY));
    userAttrMap.put(S_LANGUAGELOCALEYKEY, args.get(LANGUAGELOCALEKEY));

    TransportTools tst = new TransportTools(SALESFORCE_CREATE_USER_URL, null, header);
    Gson obj = new GsonBuilder().setPrettyPrinting().create();
    tst.setContentType(ContentType.APPLICATION_JSON, obj.toJson(userAttrMap));
    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.vmware.photon.controller.nsxclient.RestClientTest.java

@Test
public void testPerformPost() {
    String payload = "{name: DUMMY}";
    ArgumentCaptor<HttpUriRequest> argumentCaptor = setup(RestClient.Method.POST,
            new StringEntity(payload, ContentType.APPLICATION_JSON));

    HttpUriRequest request = argumentCaptor.getValue();
    assertNotNull(request);/*from  www  .  jav a 2  s.c o m*/
    assertTrue(request.getMethod().equalsIgnoreCase(RestClient.Method.POST.toString()));
    assertEquals(request.getURI().toString(), target + path);

    HttpEntityEnclosingRequest httpEntityEnclosingRequest = (HttpEntityEnclosingRequest) request;
    String actualPayload = null;
    try {
        actualPayload = IOUtils.toString(httpEntityEnclosingRequest.getEntity().getContent());
    } catch (IOException e) {
        fail(e.getMessage());
    }

    assertEquals(actualPayload, payload);
}

From source file:cf.spring.servicebroker.ServiceBrokerErrorHandlingTest.java

@Test
public void handlesUnexpectedException() throws Exception {
    final ServiceBrokerHandler.BindBody bindBody = new ServiceBrokerHandler.BindBody(BROKER_ID, PLAN_ID,
            UUID.randomUUID());//from  ww  w  .j  a v a 2  s .c o  m
    final HttpUriRequest bindRequest = RequestBuilder.put()
            .setUri("http://localhost:8080/v2/service_instances/" + UUID.randomUUID() + "/service_bindings/"
                    + UUID.randomUUID())
            .setEntity(new StringEntity(mapper.writeValueAsString(bindBody), ContentType.APPLICATION_JSON))
            .build();
    final CloseableHttpResponse bindResponse = client.execute(bindRequest);
    assertEquals(bindResponse.getStatusLine().getStatusCode(), 500);
    final JsonNode responseJson = mapper.readTree(bindResponse.getEntity().getContent());

    assertTrue(responseJson.has("description"));
    assertEquals(responseJson.get("description").asText(), BINDING_ERROR);
}

From source file:de.neofonie.aiko.yaml.ResponseDefinition.java

private boolean isBodyIncorrect(final ClientResponse response, final Context context) throws IOException {
    final String contentType = response.getHeaders().getFirst(HttpHeaders.CONTENT_TYPE);

    if (contentType != null && contentType.contains(ContentType.APPLICATION_JSON.getMimeType())) {
        return isJsonIncorrect(response, context);
    } else {//w w  w .jav  a  2  s  .  c  o m
        return isByteContentIncorrect(response, context);
    }
}

From source file:com.arcbees.vcs.github.GitHubApi.java

@Override
public Comment postComment(Integer pullRequestId, String comment) throws IOException {
    String requestUrl = apiPaths.addComment(repositoryOwner, repositoryName, pullRequestId);

    HttpPost request = new HttpPost(requestUrl);
    request.setHeader(new BasicHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()));
    request.setEntity(/*w ww  . j  a  v a  2 s  .  c o m*/
            new ByteArrayEntity(gson.toJson(new GitHubCreateComment(comment)).getBytes(Charsets.UTF_8)));

    return processResponse(httpClient, request, credentials, gson, GitHubComment.class);
}