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:net.ravendb.client.RavenDBAwareTests.java

protected void createDb(String dbName, int i) {
    HttpPut put = null;//from w  w  w  . ja  va2  s  .  c o  m
    try {
        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.megam.deccanplato.provider.salesforce.crm.handler.ContactImpl.java

/**
 * This method updates a contact in salesforce.com and returns a success message with updated contact id.
 * This method gets input from a MAP(contains json data) and returns a MAp.
 * @param outMap /*from  w w  w. ja v  a  2 s  .  c o  m*/
 */
private Map<String, String> update() {
    final String SALESFORCE_UPDATE_CONTACT_URL = args.get(INSTANCE_URL) + SALESFORCE_CONTACT_URL + args.get(ID);
    Map<String, String> outMap = new HashMap<>();
    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_LASTNAME, args.get(LASTNAME));

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

    try {
        TransportMachinery.patch(tst);
        outMap.put(OUTPUT, UPDATE_STRING + args.get(ID));
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return outMap;
}

From source file:org.phenotips.vocabulary.internal.RemoteGeneNomenclature.java

@Override
public VocabularyTerm getTerm(String id) {
    VocabularyTerm result = this.cache.get(id);
    String safeID;// w  w w. j  av  a2s .com
    if (result == null) {
        try {
            safeID = URLEncoder.encode(id, Consts.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            safeID = id.replaceAll("\\s", "");
            this.logger.warn("Could not find the encoding: {}", Consts.UTF_8.name());
        }
        HttpGet method = new HttpGet(this.fetchServiceURL + "symbol/" + safeID);
        method.setHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType());
        try (CloseableHttpResponse httpResponse = this.client.execute(method)) {
            String response = IOUtils.toString(httpResponse.getEntity().getContent(), Consts.UTF_8);
            JSONObject responseJSON = new JSONObject(response);
            JSONArray docs = responseJSON.getJSONObject(RESPONSE_KEY).getJSONArray(DATA_KEY);
            if (docs.length() == 1) {
                result = new JSONOntologyTerm(docs.getJSONObject(0), this);
                this.cache.set(id, result);
            } else {
                this.cache.set(id, EMPTY_MARKER);
            }
        } catch (IOException | JSONException ex) {
            this.logger.warn("Failed to fetch gene definition: {}", ex.getMessage());
        }
    }
    return (result == EMPTY_MARKER) ? null : result;
}

From source file:org.kitodo.data.elasticsearch.index.IndexRestClient.java

/**
 * Enable sorting by text field./*from ww  w  .  j  a v a 2  s .  c  o m*/
 *
 * @param type
 *            as String
 * @param field
 *            as String
 */
public void enableSortingByTextField(String type, String field) throws IOException, CustomResponseException {
    String query = "{\n \"properties\": {\n\"" + field + "\": {\n" + "      \"type\": \"text\",\n"
            + "      \"fielddata\": true,\n" + "      \"fields\": {\n" + "        \"raw\": {\n"
            + "          \"type\":  \"text\",\n" + "          \"index\": false}\n" + "    }\n" + "  }}}";
    HttpEntity entity = new NStringEntity(query, ContentType.APPLICATION_JSON);
    Response indexResponse = client.performRequest(HttpMethod.PUT,
            "/" + this.getIndex() + "/_mapping/" + type + "?update_all_types", Collections.emptyMap(), entity);
    processStatusCode(indexResponse.getStatusLine());
}

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

/**
 * This method updates a Campaign in salesforce.com and returns a success message with updated campaign id.
 * This method gets input from a MAP(contains json data) and returns a MAp.
 * @param outMap //from   ww w . j a v a2s .  co  m
 */
private Map<String, String> update() {
    final String SALESFORCE_UPDATE_CAMPAIGN_URL = args.get(INSTANCE_URL) + SALESFORCE_CAMPAIGN_URL
            + args.get(ID);
    Map<String, String> outMap = new HashMap<>();
    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_NAME, args.get(NAME));

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

    try {
        TransportMachinery.patch(tst);
        outMap.put(OUTPUT, UPDATE_STRING + args.get(ID));

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

    return outMap;
}

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

@Test(expected = TransportException.class)
public void testRetries() throws Exception {
    byte[] respPayload = getResponse().getBytes(StandardCharsets.UTF_8);

    HttpClient client = getMockClientWithResponse(respPayload, ContentType.APPLICATION_JSON, HttpStatus.SC_OK);
    ElasticSearchTransport transport = new ElasticSearchTransport(client, "", false, 3, 10);

    try {//from w  ww  .  j a v  a  2s . c  o  m
        transport.sendBatch("foo".getBytes());
    } catch (Exception e) {
        assertEquals("es index failure count is 1", e.getCause().getMessage());
        throw e;
    }
}

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

/**
 * This method updates a solution in salesforce.com and returns a success message with solution id.
 * This method gets input from a MAP(contains json data) and returns a MAp.
 * @param outMap /*from ww  w .j  a v a 2  s  .  c  o m*/
 */
private Map<String, String> update() {
    Map<String, String> outMap = new HashMap<>();
    final String SALESFORCE_UPDATE_SOLUTION_URL = args.get(INSTANCE_URL) + SALESFORCE_SOLUTION_URL
            + args.get(ID);

    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_SOLUTIONNAME, args.get(SOLUTION_NAME));

    TransportTools tst = new TransportTools(SALESFORCE_UPDATE_SOLUTION_URL, null, header);
    Gson obj = new GsonBuilder().setPrettyPrinting().create();
    tst.setContentType(ContentType.APPLICATION_JSON, obj.toJson(userAttrMap));
    try {
        TransportMachinery.patch(tst);
        outMap.put(OUTPUT, UPDATE_STRING + args.get(ID));

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

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

/**
 * This method updates a task in salesforce.com and returns a success message with task id.
 * This method gets input from a MAP(contains json data) and returns a MAp.
 * @param outMap /*  w w w .j  a v a2  s  .c  o m*/
 */
private Map<String, String> update() {
    Map<String, String> outMap = new HashMap<>();
    final String SALESFORCE_UPDATE_PRODUCT_URL = args.get(INSTANCE_URL) + SALESFORCE_TASK_URL + args.get(ID);

    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_SUBJECT, args.get(SUBJECT));

    TransportTools tst = new TransportTools(SALESFORCE_UPDATE_PRODUCT_URL, null, header);
    Gson obj = new GsonBuilder().setPrettyPrinting().create();
    tst.setContentType(ContentType.APPLICATION_JSON, obj.toJson(userAttrMap));
    try {
        TransportMachinery.patch(tst);
        outMap.put(OUTPUT, UPDATE_STRING + args.get(ID));

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

From source file:org.aludratest.service.gui.web.selenium.TAFMSSeleniumResourceService.java

@Override
public String acquire() {
    // prepare a JSON query to the given TAFMS server
    JSONObject query = new JSONObject();

    try {//from  w ww .  j  av a2 s .  co  m
        query.put("resourceType", "selenium");
        query.put("niceLevel", configuration.getIntValue("tafms.niceLevel", 0));
        String jobName = configuration.getStringValue("tafms.jobName");
        if (jobName != null && !"".equals(jobName)) {
            query.put("jobName", jobName);
        }
    } catch (JSONException e) {
    }

    // prepare authentication
    BasicCredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
            configuration.getStringValue("tafms.user"), configuration.getStringValue("tafms.password")));

    CloseableHttpClient client = HttpClientBuilder.create()
            .setConnectionReuseStrategy(new NoConnectionReuseStrategy()).disableConnectionState()
            .disableAutomaticRetries().setDefaultCredentialsProvider(provider).build();

    String message = null;
    try {
        boolean wait;

        // use preemptive authentication to avoid double connection count
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local auth cache
        BasicScheme basicAuth = new BasicScheme();
        URL url = new URL(getTafmsUrl());
        HttpHost host = new HttpHost(url.getHost(), url.getPort() == -1 ? url.getDefaultPort() : url.getPort(),
                url.getProtocol());
        authCache.put(host, basicAuth);

        // Add AuthCache to the execution context
        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache);

        do {
            // send a POST request to resource URL
            HttpPost request = new HttpPost(getTafmsUrl() + "resource");

            // attach query as JSON string data
            request.setEntity(new StringEntity(query.toString(), ContentType.APPLICATION_JSON));

            CloseableHttpResponse response = null;

            // fire request
            response = client.execute(request, localcontext);

            try {
                if (response.getStatusLine() == null) {
                    throw new ClientProtocolException("No HTTP status line transmitted");
                }

                message = extractMessage(response);
                if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                    LOG.error("Exception when querying TAFMS server for resource. HTTP Status: "
                            + response.getStatusLine().getStatusCode() + ", message: " + message);
                    return null;
                }

                JSONObject object = new JSONObject(message);
                if (object.has("errorMessage")) {
                    LOG.error("TAFMS server reported an error: " + object.get("errorMessage"));
                    return null;
                }

                // continue wait?
                if (object.has("waiting") && object.getBoolean("waiting")) {
                    wait = true;
                    query.put("requestId", object.getString("requestId"));
                } else {
                    JSONObject resource = object.optJSONObject("resource");
                    if (resource == null) {
                        LOG.error("TAFMS server response did not provide a resource. Message was: " + message);
                        return null;
                    }

                    String sUrl = resource.getString("url");
                    hostResourceIds.put(sUrl, object.getString("requestId"));

                    return sUrl;
                }
            } finally {
                IOUtils.closeQuietly(response);
            }
        } while (wait);

        // should never come here
        return null;
    } catch (ClientProtocolException e) {
        LOG.error("Exception in HTTP transmission", e);
        return null;
    } catch (IOException e) {
        LOG.error("Exception in communication with TAFMS server", e);
        return null;
    } catch (JSONException e) {
        LOG.error("Invalid JSON received from TAFMS server. JSON message was: " + message, e);
        return null;
    } finally {
        IOUtils.closeQuietly(client);
    }
}

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

/**
 * This method updates a contract in salesforce.com and returns a success message with updated contract id.
 * This method gets input from a MAP(contains json data) and returns a MAp.
 * @param outMap /*  www .j av  a  2s.c  om*/
 */
private Map<String, String> update() {
    final String SALESFORCE_UPDATE_CONTACT_URL = args.get(INSTANCE_URL) + SALESFORCE_CONTRACT_URL
            + args.get(ID);
    Map<String, String> outMap = new HashMap<>();
    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_BILLINGCITY, args.get(BILLING_CITY));

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

    try {
        TransportMachinery.patch(tst);
        outMap.put(OUTPUT, UPDATE_STRING + args.get(ID));

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