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.blacklocus.jres.http.HttpMethods.java

static HttpEntity createEntity(final Object payload) throws IOException {
    final HttpEntity entity;
    if (payload instanceof InputStream) {

        if (LOG.isDebugEnabled()) {
            String stream = IOUtils.toString((InputStream) payload);
            LOG.debug(stream);/*  w  w w .j  av  a  2 s .  co  m*/
            entity = new StringEntity(stream, ContentType.APPLICATION_JSON);
        } else {
            entity = new InputStreamEntity((InputStream) payload, ContentType.APPLICATION_JSON);
        }

    } else if (payload instanceof String) {

        LOG.debug((String) payload);
        entity = new StringEntity((String) payload, ContentType.APPLICATION_JSON);

    } else { // anything else will be serialized with Jackson

        if (LOG.isDebugEnabled()) {
            String json = ObjectMappers.toJson(payload);
            LOG.debug(json);
            entity = new StringEntity(json, ContentType.APPLICATION_JSON);

        } else {
            final PipedOutputStream pipedOutputStream = new PipedOutputStream();
            final PipedInputStream pipedInputStream = new PipedInputStream(pipedOutputStream);
            PIPER.submit(new ExceptingRunnable() {
                @Override
                protected void go() throws Exception {
                    try {
                        ObjectMappers.NORMAL.writeValue(pipedOutputStream, payload);
                        pipedOutputStream.flush();
                    } finally {
                        IOUtils.closeQuietly(pipedOutputStream);
                    }
                }
            });
            entity = new InputStreamEntity(pipedInputStream, ContentType.APPLICATION_JSON);
        }

    }
    return entity;
}

From source file:com.ctrip.infosec.rule.resource.DataProxy.java

/**
 *
 * @param key tag?/*w  w  w  .  j a v a2 s  .  c om*/
 * @param values tag??tag?map example:key:uid-123
 * values:RECENT_IP-112.23.32.36 RECENT_IPAREA-
 * -------------------------------------
 *
 * ? temp = new
 * HashMap();temp.put("RECENT_IP","112.23.32.36");temp.put("RECENT_IPAREA","");
 * addTagData("123",temp)
 * @return ?true?false
 */
public static boolean addTagData(String key, Map<String, String> values) {
    boolean flag = false;
    check();
    beforeInvoke("DataProxy.addTagData");
    try {
        List<DataProxyRequest> requests = new ArrayList<>();
        DataProxyRequest request = new DataProxyRequest();
        request.setServiceName("CommonService");
        request.setOperationName("addData");

        Map params = new HashMap<String, String>();
        params.put("tableName", "UserProfileInfo");
        params.put("pkValue", key.trim());
        params.put("storageType", "1");
        params.put("values", values);
        request.setParams(params);
        requests.add(request);
        String requestText = JSON.toPrettyJSONString(requests);
        String responseText = Request.Post(urlPrefix + "/rest/dataproxy/dataprocess")
                .bodyString(requestText, ContentType.APPLICATION_JSON).execute().returnContent().asString();
        Map result = JSON.parseObject(responseText, Map.class);
        if (result.get("rtnCode").equals("0")) {
            flag = true;
        } else {
            flag = false;
            logger.warn("?:" + JSON.toPrettyJSONString(values) + "\t" + "userProfile!");
        }
    } catch (Exception ex) {
        fault("DataProxy.addTagData");
        logger.error(Contexts.getLogPrefix() + "invoke DataProxy.addTagData fault.", ex);
    } finally {
        afterInvoke("DataProxy.addTagData");
    }
    return flag;
}

From source file:com.wso2telco.saa.service.PushServiceAPI.java

/**
 * OutBound to Push Service*//  w w w .ja  va 2  s  .  co  m
 *
 * @param pushMessageData Message details to pass to the fcm
 * @param msisdn          msisdn of the client user
 * @return successful message
 */
@POST
@Path("client/{" + MSISDN + "}/send")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response sendPushNotification(@PathParam(MSISDN) String msisdn, String pushMessageData) {

    //// TODO: 3/6/17 Remove Success or Failure variables and keep one variable- status
    JSONObject pushMessageObj = new JSONObject(pushMessageData);
    JSONObject messageData = pushMessageObj.getJSONObject(DATA);
    JSONObject pushMessageResponse = new JSONObject();
    int[] success_failure;

    try {
        dbConnection = DBConnection.getInstance();
        ClientDetails clientDetails = dbConnection.getClientDetails(msisdn);
        if (clientDetails != null) {
            String pushToken = clientDetails.getPushToken();
            String message = messageData.getString(MESSAGE);
            String applicationName = messageData.getString(APPLICATION_NAME);
            String referenceId = messageData.getString(REFERENCE);
            String acr = messageData.getString(ACR);
            String spImageUrl = messageData.getString(SP_LOGO_URL);

            AuthenticationMessageDetail data = new AuthenticationMessageDetail();
            data.setMsg(message);
            data.setSp(applicationName);
            data.setRef(referenceId);
            data.setAcr(acr);
            data.setSp_url(spImageUrl);

            FirebaseCloudMessageDetails firebaseCloudMessageDetails = new FirebaseCloudMessageDetails();
            firebaseCloudMessageDetails.setTo(pushToken);
            firebaseCloudMessageDetails.setData(data);

            DefaultHttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(FCM_URL);

            post.setHeader("Authorization", FCM_KEY);
            post.setHeader("Content-Type", MediaType.APPLICATION_JSON);

            StringEntity requestEntity = new StringEntity(new Gson().toJson(firebaseCloudMessageDetails),
                    ContentType.APPLICATION_JSON);
            post.setEntity(requestEntity);

            HttpResponse httpResponse = client.execute(post);
            success_failure = getJsonObject(httpResponse);

            pushMessageResponse.put(SUCCESS, success_failure[0]);
            pushMessageResponse.put(FAILURE, success_failure[1]);

        } else {
            pushMessageResponse.put(SUCCESS, 0);
            pushMessageResponse.put(FAILURE, 1);
        }
    } catch (SQLException | IOException | DBUtilException | EmptyResultSetException
            | ClassNotFoundException e) {
        log.error(
                "Error occurred in sending message through Firebase Cloud Messaging Service for the client with MSISDN:"
                        + msisdn + "error:" + e.getMessage());
        pushMessageResponse.put(SUCCESS, 0);
        pushMessageResponse.put(FAILURE, 1);
    }
    return Response.ok(pushMessageResponse.toString(), MediaType.APPLICATION_JSON).build();
}

From source file:com.mywork.framework.util.RemoteHttpUtil.java

/**
 * ???json?post?/*from   w ww . j a  va  2 s .  c  om*/
 *
 * @throws IOException
 *
 */
public static String fetchJsonHttpResponse(String contentUrl, Map<String, String> headerMap, String jsonBody)
        throws IOException {
    Executor executor = Executor.newInstance(httpClient);
    Request request = Request.Post(contentUrl);
    if (headerMap != null && !headerMap.isEmpty()) {
        for (Map.Entry<String, String> m : headerMap.entrySet()) {
            request.addHeader(m.getKey(), m.getValue());
        }
    }
    if (jsonBody != null) {
        request.bodyString(jsonBody, ContentType.APPLICATION_JSON);
    }
    long start = System.currentTimeMillis();
    String response = executor.execute(request).returnContent().asString();
    logger.info("url = " + contentUrl + " request spend time = " + (System.currentTimeMillis() - start));
    return response;
}

From source file:com.qwazr.graph.test.FullTest.java

@Test
public void test110PutVisitNodes() throws IOException {
    for (int i = 0; i < VISIT_NUMBER; i += 100) {
        Map<String, GraphNode> nodeMap = new LinkedHashMap<String, GraphNode>();
        for (int k = 0; k < 100; k++) {
            GraphNode node = new GraphNode();
            node.properties = new HashMap<String, Object>();
            node.properties.put("type", "visit");
            node.properties.put("user", "user" + RandomUtils.nextInt(0, 100));
            node.properties.put("date", "201501" + RandomUtils.nextInt(10, 31));
            node.edges = new HashMap<String, Set<Object>>();
            int seePages = RandomUtils.nextInt(3, 12);
            Set<Object> set = new TreeSet<Object>();
            for (int j = 0; j < seePages; j++)
                set.add("p" + RandomUtils.nextInt(0, PRODUCT_NUMBER / 2));
            node.edges.put("see", set);
            if (RandomUtils.nextInt(0, 10) == 0) {
                int buyItems = RandomUtils.nextInt(1, 5);
                set = new TreeSet<Object>();
                for (int j = 0; j < buyItems; j++)
                    set.add("p" + RandomUtils.nextInt(0, PRODUCT_NUMBER / 2));
                node.edges.put("buy", set);
            }//from   w  w w . j  a v  a  2s.c  o m
            nodeMap.put("v" + (i + k), node);
        }
        HttpResponse response = Request.Post(BASE_URL + '/' + TEST_BASE + "/node")
                .bodyString(JsonMapper.MAPPER.writeValueAsString(nodeMap), ContentType.APPLICATION_JSON)
                .connectTimeout(60000).socketTimeout(60000).execute().returnResponse();
        Assert.assertEquals(200, response.getStatusLine().getStatusCode());
    }
}

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

private int indexDocs(String index, final int idStart, final int numDocs) throws IOException {
    for (int i = 0; i < numDocs; i++) {
        final int id = idStart + i;
        assertOK(client().performRequest("PUT", index + "/test/" + id, emptyMap(), new StringEntity(
                "{\"test\": \"test_" + randomAsciiOfLength(2) + "\"}", ContentType.APPLICATION_JSON)));
    }//from  w ww  .  j  ava 2s.  co  m
    return numDocs;
}

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

/**
 * Delete all documents of certain type from the index.
 *
 * @return response from server/* w ww  .  ja  v a 2 s  . c  o m*/
 */
public String deleteType() throws IOException {
    String query = "{\n" + "  \"query\": {\n" + "    \"match_all\": {}\n" + "  }\n" + "}";
    HttpEntity entity = new NStringEntity(query, ContentType.APPLICATION_JSON);
    Response indexResponse = restClient.performRequest("POST",
            "/" + this.getIndex() + "/" + this.getType() + "/_delete_by_query",
            Collections.<String, String>emptyMap(), entity);
    return indexResponse.toString();
}

From source file:org.apache.reef.runtime.hdinsight.client.yarnrest.HDInsightInstance.java

/**
 * Submits an application for execution.
 *
 * @param applicationSubmission/*  w ww. j a  v a 2  s  . co m*/
 * @throws IOException
 */
public void submitApplication(final ApplicationSubmission applicationSubmission) throws IOException {
    final String url = "ws/v1/cluster/apps";
    final HttpPost post = preparePost(url);

    final StringWriter writer = new StringWriter();
    try {
        this.objectMapper.writeValue(writer, applicationSubmission);
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
    final String message = writer.toString();
    LOG.log(Level.FINE, "Sending:\n{0}", message.replace("\n", "\n\t"));
    post.setEntity(new StringEntity(message, ContentType.APPLICATION_JSON));

    try (final CloseableHttpResponse response = this.httpClient.execute(post, this.httpClientContext)) {
        final String responseMessage = IOUtils.toString(response.getEntity().getContent());
        LOG.log(Level.FINE, "Response: {0}", responseMessage.replace("\n", "\n\t"));
    }
}

From source file:org.ambraproject.wombat.service.remote.AbstractRestfulJsonApi.java

private <R extends HttpUriRequest & HttpEntityEnclosingRequest> HttpResponse uploadObject(ApiAddress address,
        Object object, Function<URI, R> requestConstructor) throws IOException {
    R request = buildRequest(address, requestConstructor);

    ContentType contentType = ContentType.APPLICATION_JSON;
    if (object != null) {
        String json = jsonService.serialize(object);
        request.setEntity(new StringEntity(json, contentType));
    }//from   ww w  .  ja  v  a 2s. co m

    request.addHeader(HttpHeaders.CONTENT_TYPE, contentType.toString());

    try (CloseableHttpResponse response = cachedRemoteReader.getResponse(request)) {
        //return closed response
        return response;
    }
}

From source file:org.megam.deccanplato.provider.box.handler.FileImpl.java

/**
 * @return//  w  w  w  .  j a  va  2  s  . c om
 */
private Map<String, String> share() {

    Map<String, String> outMap = new HashMap<>();
    final String BOX_UPLOAD = "/files/" + args.get(FILE_ID);

    Map<String, String> headerMap = new HashMap<String, String>();
    headerMap.put("Authorization", "BoxAuth api_key=" + args.get(API_KEY) + "&auth_token=" + args.get(TOKEN));

    Map<String, String> access = new HashMap<>();
    access.put("access", "open");
    access.put("unshared_at", "2013-02-28T12:07:46.981+05:30");
    Map<String, String> pAccess = new HashMap<>();
    pAccess.put("can_download ", "Company");
    pAccess.put(" can_preview ", "Company");
    Map<String, Map<String, String>> links = new HashMap<>();
    links.put("shared_link", access);
    links.put("permissions", pAccess);

    TransportTools tools = new TransportTools(BOX_URI + BOX_UPLOAD, null, headerMap);
    GsonBuilder gson = new GsonBuilder();
    gson.registerTypeAdapter(DateTime.class, new DateTimeTypeConverter());
    Gson obj = gson.setPrettyPrinting().create();
    System.out.println(obj.toJson(links));
    tools.setContentType(ContentType.APPLICATION_JSON, obj.toJson(links));
    String responseBody = "";
    TransportResponse response = null;
    try {
        response = TransportMachinery.put(tools);
        responseBody = response.entityToString();
        System.out.println("OUTPUT:" + responseBody);
    } catch (ClientProtocolException ce) {
        ce.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    outMap.put(OUTPUT, responseBody);
    return outMap;
}