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:org.artifactory.post.services.CallHomeService.java

/**
 * Serializes {@link CallHomeRequest} to {@link org.apache.http.entity.StringEntity}
 *
 * @param request {@link CallHomeRequest}
 *
 * @return {@link org.apache.http.entity.StringEntity}
 * @throws IOException happens if serialization fails
 *///from   w  ww  .j  a  v  a2  s. c om
private StringEntity serializeToStringEntity(CallHomeRequest request) throws IOException {
    String serialized = JacksonWriter.serialize(request, true);
    return new StringEntity(serialized, ContentType.APPLICATION_JSON);
}

From source file:com.tremolosecurity.proxy.myvd.inserts.restful.OpenUnisonRestful.java

@Override
public void bind(BindInterceptorChain chain, DistinguishedName dn, Password pwd, LDAPConstraints constraints)
        throws LDAPException {
    String localBindDN = this.getRemoteMappedDN(dn.getDN()).toString();

    HttpCon con;/* w  w w.jav a2  s . c  o  m*/
    try {
        con = this.createClient();
    } catch (Exception e) {
        throw new LDAPException(LDAPException.resultCodeToString(LDAPException.OPERATIONS_ERROR),
                LDAPException.OPERATIONS_ERROR, "Could not create connection", e);
    }

    try {
        LdapJsonBindRequest bindRequest = new LdapJsonBindRequest();
        bindRequest.setPassword(new String(pwd.getValue()));
        StringBuffer b = new StringBuffer();
        b.append(this.uriPath).append('/').append(URLEncoder.encode(localBindDN, "UTF-8"));

        StringBuffer urlBuffer = new StringBuffer();
        urlBuffer.append(this.urlBase);
        urlBuffer.append(b);

        HttpPost post = new HttpPost(urlBuffer.toString());

        this.addAuthorizationHeader(b.toString(), post);

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

        HttpResponse resp = con.getHttp().execute(post);

        String json = EntityUtils.toString(resp.getEntity());
        LdapJsonError ldapResponse = gson.fromJson(json, LdapJsonError.class);
        if (ldapResponse.getResponseCode() != 0) {
            throw new LDAPException(LDAPException.resultCodeToString(ldapResponse.getResponseCode()),
                    ldapResponse.getResponseCode(), ldapResponse.getErrorMessage());
        }
    } catch (LDAPException e) {
        throw e;
    } catch (Exception e) {
        throw new LDAPException(LDAPException.resultCodeToString(LDAPException.OPERATIONS_ERROR),
                LDAPException.OPERATIONS_ERROR, "Could not create connection", e);
    } finally {
        if (con != null) {
            try {
                con.getHttp().close();
            } catch (IOException e) {
                //no point
            }
            con.getBcm().close();
        }

    }

}

From source file:biz.dfch.j.clickatell.ClickatellClient.java

public MessageResponse sendMessage(String recipient, String message, int maxCredits, int maxParts)
        throws IOException, HttpResponseException {
    class ClickatellMessage {
        public ArrayList<String> to = new ArrayList<String>();
        public String text;
        public String maxCredits;
        public String maxMessageParts;
    }/*from   w ww .  j a  va  2  s . co  m*/
    try {
        ClickatellMessage clickatellMessage = new ClickatellMessage();
        clickatellMessage.to.add(recipient);
        clickatellMessage.text = message;
        clickatellMessage.maxCredits = (0 == maxCredits) ? null : Integer.toString(maxCredits);
        clickatellMessage.maxMessageParts = (0 == maxParts) ? null : Integer.toString(maxParts);

        ObjectMapper om = new ObjectMapper();
        om.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        om.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
        String request = om.writeValueAsString(clickatellMessage);
        String response = Request.Post(uriMessage.toString()).setHeader(headerApiVersion)
                .setHeader(headerContentType).setHeader(headerAccept).setHeader("Authorization", bearerToken)
                .bodyString(request, ContentType.APPLICATION_JSON).execute().returnContent().asString();
        MessageResponse messageResponse = om.readValue(response, MessageResponse.class);
        return messageResponse;
    } catch (HttpResponseException ex) {
        int statusCode = ex.getStatusCode();
        switch (statusCode) {
        case 410:
            LOG.error(String.format("Sending message to '%s' FAILED with HTTP %d. No coverage of recipient.",
                    recipient, statusCode));
            break;
        default:
            break;
        }
        throw ex;
    }
}

From source file:org.jenkinsci.plugins.os_ci.repohandlers.OpenStackClient.java

public void renewToken() {
    GetToken getToken = new GetToken();
    Auth auth = new Auth();
    PasswordCredentials pass = new PasswordCredentials();
    pass.setPassword(openstackPassword);
    pass.setUsername(openstackUser);/*w  ww. j  a  va 2s.  c om*/
    auth.setPasswordCredentials(pass);
    auth.setTenantName(openstackTenantName);
    getToken.setAuth(auth);
    String token = null;
    try {
        String body = JsonBuilder.createJson(getToken);

        URI uri = new URIBuilder().setScheme("http").setHost(openstackHost).setPort(openstackPort)
                .setPath(openstackPath).build();
        HttpPost httpPost = new HttpPost(uri);
        httpPost.addHeader("Accept", "application/json");
        final StringEntity entity = new StringEntity(body, ContentType.APPLICATION_JSON);
        httpPost.setEntity(entity);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            int status = response.getStatusLine().getStatusCode();
            if (status != 200) {
                LogUtils.log(listener,
                        "Request body: " + body + "\nResponse: " + JsonParser.readResponseBody(response));
                throw new OsCiPluginException("Invalid OpenStack server response " + status);
            }
            token = JsonParser.parseRenewToken(response);
            this.entryPoints.setToken(token);
        } finally {
            response.close();
        }
    } catch (IOException e) {
        throw new OsCiPluginException("IOException in getToken " + e.getMessage());
    } catch (URISyntaxException e) {
        throw new OsCiPluginException("URISyntaxException in getToken " + e.getMessage());
    } catch (Exception e) {
        throw new OsCiPluginException("IOException in getToken " + e.getMessage());
    }
}

From source file:org.apache.solr.cloud.CreateRoutedAliasTest.java

@Test
public void testV2() throws Exception {
    // note we don't use TZ in this test, thus it's UTC
    final String aliasName = getTestName();

    String createNode = cluster.getRandomJetty(random()).getNodeName();

    final String baseUrl = cluster.getRandomJetty(random()).getBaseUrl().toString();
    //TODO fix Solr test infra so that this /____v2/ becomes /api/
    HttpPost post = new HttpPost(baseUrl + "/____v2/c");
    post.setEntity(new StringEntity("{\n" + "  \"create-alias\" : {\n" + "    \"name\": \"" + aliasName
            + "\",\n" + "    \"router\" : {\n" + "      \"name\": \"time\",\n"
            + "      \"field\": \"evt_dt\",\n" + "      \"start\":\"NOW/DAY\",\n" + // small window for test failure once a day.
            "      \"interval\":\"+2HOUR\",\n" + "      \"maxFutureMs\":\"14400000\"\n" + "    },\n" +
            //TODO should we use "NOW=" param?  Won't work with v2 and is kinda a hack any way since intended for distrib
            "    \"create-collection\" : {\n" + "      \"router\": {\n" + "        \"name\":\"implicit\",\n"
            + "        \"field\":\"foo_s\"\n" + "      },\n" + "      \"shards\":\"foo,bar\",\n"
            + "      \"config\":\"_default\",\n" + "      \"tlogReplicas\":1,\n" + "      \"pullReplicas\":1,\n"
            + "      \"maxShardsPerNode\":4,\n" + // note: we also expect the 'policy' to work fine
            "      \"nodeSet\": ['" + createNode + "'],\n" + "      \"properties\" : {\n"
            + "        \"foobar\":\"bazbam\",\n" + "        \"foobar2\":\"bazbam2\"\n" + "      }\n" + "    }\n"
            + "  }\n" + "}", ContentType.APPLICATION_JSON));
    assertSuccess(post);/*w w w.j  a  v a 2s .  co m*/

    Date startDate = DateMathParser.parseMath(new Date(), "NOW/DAY");
    String initialCollectionName = TimeRoutedAlias.formatCollectionNameFromInstant(aliasName,
            startDate.toInstant());
    // small chance could fail due to "NOW"; see above
    assertCollectionExists(initialCollectionName);

    // Test created collection:
    final DocCollection coll = solrClient.getClusterStateProvider().getState(initialCollectionName).get();
    //System.err.println(coll);
    //TODO how do we assert the configSet ?
    assertEquals(ImplicitDocRouter.class, coll.getRouter().getClass());
    assertEquals("foo_s", ((Map) coll.get("router")).get("field"));
    assertEquals(2, coll.getSlices().size()); // numShards
    assertEquals(4, coll.getSlices().stream().mapToInt(s -> s.getReplicas().size()).sum()); // num replicas
    // we didn't ask for any NRT replicas
    assertEquals(0, coll.getSlices().stream()
            .mapToInt(s -> s.getReplicas(r -> r.getType() == Replica.Type.NRT).size()).sum());
    //assertEquals(1, coll.getNumNrtReplicas().intValue()); // TODO seems to be erroneous; I figured 'null'
    assertEquals(1, coll.getNumTlogReplicas().intValue()); // per-shard
    assertEquals(1, coll.getNumPullReplicas().intValue()); // per-shard
    assertEquals(4, coll.getMaxShardsPerNode());
    //TODO SOLR-11877 assertEquals(2, coll.getStateFormat());
    assertTrue("nodeSet didn't work?", coll.getSlices().stream().flatMap(s -> s.getReplicas().stream())
            .map(Replica::getNodeName).allMatch(createNode::equals));

    // Test Alias metadata:
    Aliases aliases = cluster.getSolrClient().getZkStateReader().getAliases();
    Map<String, String> collectionAliasMap = aliases.getCollectionAliasMap();
    assertEquals(initialCollectionName, collectionAliasMap.get(aliasName));
    Map<String, String> meta = aliases.getCollectionAliasProperties(aliasName);
    //System.err.println(new TreeMap(meta));
    assertEquals("evt_dt", meta.get("router.field"));
    assertEquals("_default", meta.get("create-collection.collection.configName"));
    assertEquals("foo_s", meta.get("create-collection.router.field"));
    assertEquals("bazbam", meta.get("create-collection.property.foobar"));
    assertEquals("bazbam2", meta.get("create-collection.property.foobar2"));
    assertEquals(createNode, meta.get("create-collection.createNodeSet"));
}

From source file:com.github.lindenb.jvarkit.tools.ensembl.VcfEnsemblVepRest.java

private Object generic_vep(List<VariantContext> contexts, boolean xml_answer) throws IOException {
    LOG.info("Running VEP " + contexts.size());
    InputStream response = null;/*  ww w  .  j a va 2s  . com*/
    javax.xml.transform.Source inputSource = null;
    HttpPost httpPost = null;
    try {
        if (this.lastMillisec != -1L && this.lastMillisec + 5000 < System.currentTimeMillis()) {
            try {
                Thread.sleep(1000);
            } catch (Exception err) {
            }
        }

        httpPost = new HttpPost(this.server + this.extension);

        StringBuilder queryb = new StringBuilder();
        queryb.append("{ \"variants\" : [");
        for (int i = 0; i < contexts.size(); ++i) {
            VariantContext ctx = contexts.get(i);
            if (i > 0)
                queryb.append(",");
            queryb.append("\"").append(createInputContext(ctx)).append("\"");
        }
        queryb.append("]");
        for (String s : new String[] { "canonical", "ccds", "domains", "hgvs", "numbers", "protein",
                "xref_refseq" }) {
            queryb.append(",\"").append(s).append("\":1");
        }
        queryb.append("}");
        byte postBody[] = queryb.toString().getBytes();

        httpPost.setHeader("Content-Type", ContentType.APPLICATION_JSON.getMimeType());
        httpPost.setHeader("Accept", ContentType.TEXT_XML.getMimeType());
        //httpPost.setHeader("Content-Length", Integer.toString(postBody.length));
        httpPost.setEntity(new ByteArrayEntity(postBody, ContentType.APPLICATION_JSON));

        final CloseableHttpResponse httpResponse = httpClient.execute(httpPost);

        int responseCode = httpResponse.getStatusLine().getStatusCode();

        if (responseCode != 200) {
            throw new RuntimeException("Response code was not 200. Detected response was " + responseCode);
        }

        //response = new TeeInputStream( httpConnection.getInputStream(),System.err,false);
        response = httpResponse.getEntity().getContent();
        if (this.teeResponse) {
            stderr().println(queryb);
            response = new TeeInputStream(response, stderr(), false);
        }

        if (xml_answer) {
            return documentBuilder.parse(response);
        } else {
            inputSource = new StreamSource(response);
            return unmarshaller.unmarshal(inputSource, Opt.class).getValue();
        }

    } catch (Exception e) {
        throw new IOException(e);
    } finally {
        CloserUtil.close(response);
        if (httpPost != null)
            httpPost.releaseConnection();
        this.lastMillisec = System.currentTimeMillis();
    }
}

From source file:com.nextdoor.bender.ipc.http.HttpTransportTest.java

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

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

    try {//from  w w w . j a v a  2s  . c om
        transport.sendBatch("foo".getBytes());
    } catch (Exception e) {
        assertEquals("http transport call failed because \"expected failure\" payload response \"resp\"",
                e.getCause().getMessage());
        throw e;
    }
}

From source file:com.omertron.slackbot.utils.HttpTools.java

/**
 * POST content to the URL with the specified body
 *
 * @param url URL to use in the request/*from   ww w  .j  a v a2 s.c  o  m*/
 * @param jsonBody Body to use in the request
 * @return String content
 * @throws ApiException
 */
public String postRequest(final URL url, final String jsonBody) throws ApiException {
    try {
        HttpPost httpPost = new HttpPost(url.toURI());
        httpPost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
        httpPost.addHeader(HttpHeaders.ACCEPT, APPLICATION_JSON);
        StringEntity params = new StringEntity(jsonBody, ContentType.APPLICATION_JSON);
        httpPost.setEntity(params);

        return validateResponse(DigestedResponseReader.postContent(httpClient, httpPost, CHARSET), url);
    } catch (URISyntaxException | IOException ex) {
        throw new ApiException(ApiExceptionType.CONNECTION_ERROR, null, url, ex);
    }
}

From source file:com.ibm.streamsx.topology.internal.context.AnalyticsServiceStreamsContext.java

private JSONObject getJsonResponse(CloseableHttpClient httpClient, HttpRequestBase request)
        throws IOException, ClientProtocolException {
    request.addHeader("accept", ContentType.APPLICATION_JSON.getMimeType());

    CloseableHttpResponse response = httpClient.execute(request);
    JSONObject jsonResponse;/* ww w.j ava2s  .co m*/
    try {
        HttpEntity entity = response.getEntity();
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            final String errorInfo;
            if (entity != null)
                errorInfo = " -- " + EntityUtils.toString(entity);
            else
                errorInfo = "";
            throw new IllegalStateException(
                    "Unexpected HTTP resource from service:" + response.getStatusLine().getStatusCode() + ":"
                            + response.getStatusLine().getReasonPhrase() + errorInfo);
        }

        if (entity == null)
            throw new IllegalStateException("No HTTP resource from service");

        jsonResponse = JSONObject.parse(new BufferedInputStream(entity.getContent()));
        EntityUtils.consume(entity);
    } finally {
        response.close();
    }
    return jsonResponse;
}

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

/**
 * This method updates a case in salesforce.com and returns a success message with updated case id.
 * This method gets input from a MAP(contains json data) and returns a MAp.
 * @param outMap /*from   ww  w  .ja  va  2  s . co  m*/
 */
private Map<String, String> update() {
    Map<String, String> outMap = new HashMap<>();
    final String SALESFORCE_UPDATE_CASE_URL = args.get(INSTANCE_URL) + SALESFORCE_CASE_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_CASE_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;
}