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:br.com.jbugbrasil.bot.telegram.api.message.sender.MessageSender.java

/**
 * Prepara a request e envia a mensagem para a API do telegram para o grupo ou chat destinatrio da mensagem.
 * Parmetros necessrios para efetuar a request:
 *  - chat_id = chat ou grupo/*from  www . ja va2  s. co  m*/
 *  - parse_mode = default HTML, markdown h muitos problemas de formatao nos diversos clients disponveis.
 *  - reply_to_message_id = Id de uma mensagem enviada, se presente a mensagem ser respondida ao seu remetente original
 *  - disable_web_page_preview = desabilita pr vizualizao de links.
 * @param message Mensagem a ser enviada
 */
private void send(Message message) {
    ObjectMapper objectMapper = new ObjectMapper();
    try {
        String url = String.format(TELEGRAM_API_SENDER_ENDPOINT, botTokenId);
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("charset", StandardCharsets.UTF_8.name());
        httpPost.addHeader("content-type", "application/json");
        Map<String, String> body = new HashMap<>();
        body.put("chat_id", message.getChat().getId() + "");
        body.put("parse_mode", "HTML");
        body.put("reply_to_message_id", message.getMessageId() + "");
        body.put("text", message.getText());
        body.put("disable_web_page_preview", "true");
        httpPost.setEntity(
                new StringEntity(objectMapper.writeValueAsString(body), ContentType.APPLICATION_JSON));
        try (CloseableHttpResponse response = httpClient.get().execute(httpPost)) {
            HttpEntity responseEntity = response.getEntity();
            BufferedHttpEntity buf = new BufferedHttpEntity(responseEntity);
            String responseContent = EntityUtils.toString(buf, StandardCharsets.UTF_8);
            log.fine("Telegram API response: [" + responseContent + "]");
        } catch (final Exception e) {
            e.printStackTrace();
            log.warning("Erro encontrado " + e.getMessage());
        }
    } catch (final Exception e) {
        e.printStackTrace();
        log.warning("Erro encontrado " + e.getMessage());
    }
}

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

/**
 * this method creates an event in salesforce.com and returns that event id.
 * This method gets input from a MAP(contains json data) and returns a MAp.
 * @param outMap /*w w w  . ja  va 2 s.  c  o m*/
 */
private Map<String, String> create() {

    final String SALESFORCE_CREATE_EVENT_URL = args.get(INSTANCE_URL) + SALESFORCE_EVENT_URL;
    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_SUBJECT, args.get(SUBJECT));
    userAttrMap.put(S_STARTDATETIME, datetime.parse(args.get(START_DATE)));
    userAttrMap.put(S_ENDDATETIME, datetime.parse(args.get(END_DATE)));

    GsonBuilder gson = new GsonBuilder();
    gson.registerTypeAdapter(DateTime.class, new DateTimeTypeConverter());
    Gson obj = gson.setPrettyPrinting().create();
    TransportTools tst = new TransportTools(SALESFORCE_CREATE_EVENT_URL, null, header);
    tst.setContentType(ContentType.APPLICATION_JSON, obj.toJson(userAttrMap));
    TransportResponse response = null;
    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.kiji.checkin.CheckinClient.java

/**
 * Performs a POST of the given entity and returns the response.
 *
 * @param entityToPost is the entity to send.
 * @return the response from the POST//from   ww w  .  ja v a2 s.  co m
 * @throws IOException if there is an error.
 */
private String genericPost(JsonBeanInterface entityToPost) throws IOException {
    // Create a POST request to send to the update server.
    HttpPost postRequest = new HttpPost(mCheckinServerURI);
    // Create an Entity for the message body with the proper content type and content taken
    // from the provided checkin message.
    HttpEntity postRequestEntity = new StringEntity(entityToPost.toJSON(), ContentType.APPLICATION_JSON);
    postRequest.setEntity(postRequestEntity);

    // Execute the request.
    HttpResponse response = mHttpClient.execute(postRequest);
    try {
        HttpEntity responseEntity = response.getEntity();
        String responseBody = EntityUtils.toString(responseEntity);
        // The response body should contain JSON that can be used to create an upgrade response.
        return responseBody;
    } finally {
        postRequest.releaseConnection();
    }
}

From source file:org.elasticsearch.integration.AbstractPrivilegeTestCase.java

private static HttpEntity entityOrNull(String body) {
    HttpEntity entity = null;/*  w  ww .  j  ava  2  s.c  om*/
    if (body != null) {
        entity = new StringEntity(body, ContentType.APPLICATION_JSON);
    }
    return entity;
}

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

public void generateToken() {
    GetToken gett = new GetToken();
    Auth auth = new Auth();
    PasswordCredentials pass = new PasswordCredentials();
    pass.setPassword(openstackPassword);
    pass.setUsername(openstackUser);/*from w  w  w. j a  v a 2  s  .c  o m*/
    auth.setPasswordCredentials(pass);
    auth.setTenantName(openstackTenantName);
    gett.setAuth(auth);
    try {
        String body = JsonBuilder.createJson(gett);

        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) {
                throw new OsCiPluginException("Invalid OpenStack server response " + status);
            }
            this.entryPoints = JsonParser.parseGetTokenAndEntryPoints(response);
        } 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:com.epam.reportportal.service.ReportPortalErrorHandler.java

private boolean isNotJson(Response<ByteSource> rs) {

    boolean result = true;

    Collection<String> contentTypes = rs.getHeaders().get(HttpHeaders.CONTENT_TYPE);

    for (String contentType : contentTypes) {

        boolean isJson = contentType.contains(ContentType.APPLICATION_JSON.getMimeType());
        if (isJson) {
            result = false;/*from   ww  w  .  jav a  2  s .c o m*/
            break;
        }
    }

    return result;
}

From source file:org.osiam.tests.stress.AggregatorJob.java

public void execute(JobExecutionContext context) throws JobExecutionException {
    jobName = context.getJobDetail().getKey().getName();
    osiamConnector = OsiamContext.getInstance().getConnector(jobName);
    accessToken = OsiamContext.getInstance().getValidAccessToken();

    try {//from   w w  w.  ja  v  a  2 s . c  o  m
        SimpleDateFormat dateFormatter = new SimpleDateFormat("dd.MM.yyyy-HH:mm:ss:SSS");
        String dateOut = dateFormatter.format(new Date());
        System.out.println(dateOut + "; Retrieving metrics data");

        WebTarget targetEndpoint = client.target(OsiamContext.getInstance().getResourceEndpointAddress());

        Response response = targetEndpoint.path("/Metrics").request(MediaType.APPLICATION_JSON)
                .header("Authorization", BEARER + accessToken.getToken())
                .header("Accept", ContentType.APPLICATION_JSON.getMimeType()).get();

        StatusType status = response.getStatusInfo();
        String content = response.readEntity(String.class);
        if (status.getStatusCode() != SC_OK) {
            logError(content);
        }

        int mb = 1024 * 1024;
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.readTree(content);
        String memoryUsage = ""
                + (rootNode.get("gauges").get("jvm.memory.total.used").get("value").asInt() / mb);
        String totalUser = getTotalUsers();

        DataStorage.storeData(memoryUsage, totalUser);
    } catch (Throwable e) {
        logError(e);
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        logger.error(jobName + ": " + sw.toString());
    }
}

From source file:org.elasticsearch.xpack.qa.sql.rest.RestSqlTestCase.java

public void testNextPage() throws IOException {
    Request request = new Request("POST", "/test/test/_bulk");
    request.addParameter("refresh", "true");
    String mode = randomMode();//  w  w w.  j  av  a  2s.co m
    StringBuilder bulk = new StringBuilder();
    for (int i = 0; i < 20; i++) {
        bulk.append("{\"index\":{\"_id\":\"" + i + "\"}}\n");
        bulk.append("{\"text\":\"text" + i + "\", \"number\":" + i + "}\n");
    }
    request.setJsonEntity(bulk.toString());
    client().performRequest(request);

    String sqlRequest = "{\"query\":\"" + "   SELECT text, number, SQRT(number) AS s, SCORE()"
            + "     FROM test" + " ORDER BY number, SCORE()\", " + "\"mode\":\"" + mode + "\", "
            + "\"fetch_size\":2}";

    String cursor = null;
    for (int i = 0; i < 20; i += 2) {
        Map<String, Object> response;
        if (i == 0) {
            response = runSql(mode, new StringEntity(sqlRequest, ContentType.APPLICATION_JSON));
        } else {
            response = runSql(mode,
                    new StringEntity("{\"cursor\":\"" + cursor + "\"}", ContentType.APPLICATION_JSON));
        }

        Map<String, Object> expected = new HashMap<>();
        if (i == 0) {
            expected.put("columns",
                    Arrays.asList(columnInfo(mode, "text", "text", JDBCType.VARCHAR, 0),
                            columnInfo(mode, "number", "long", JDBCType.BIGINT, 20),
                            columnInfo(mode, "s", "double", JDBCType.DOUBLE, 25),
                            columnInfo(mode, "SCORE()", "float", JDBCType.REAL, 15)));
        }
        expected.put("rows", Arrays.asList(Arrays.asList("text" + i, i, Math.sqrt(i), 1.0),
                Arrays.asList("text" + (i + 1), i + 1, Math.sqrt(i + 1), 1.0)));
        cursor = (String) response.remove("cursor");
        assertResponse(expected, response);
        assertNotNull(cursor);
    }
    Map<String, Object> expected = new HashMap<>();
    expected.put("rows", emptyList());
    assertResponse(expected,
            runSql(mode, new StringEntity("{ \"cursor\":\"" + cursor + "\"}", ContentType.APPLICATION_JSON)));
}

From source file:org.biokoframework.system.services.push.impl.AbstractPushNotificationService.java

@Override
public void addPushReceiver(String userToken, String deviceToken, boolean pushStatus)
        throws NotificationFailureException {
    try {//from  w w  w.j  av  a2 s .  co m

        Fields fields = new Fields();
        fields.put(APP_TOKEN, fAppToken);
        fields.put(DEVICE_TOKEN, deviceToken);
        fields.put(DEVICE_TYPE, IOS_TYPE);
        fields.put(DEVICE_VERSION, "6");
        fields.put(USER_TOKEN, userToken);
        fields.put(PUSH_STATUS, pushStatus);

        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(fPusherdrilloUrl + REGISTER_DEVICE);
        post.setEntity(new StringEntity(fields.toJSONString(), ContentType.APPLICATION_JSON));

        post.completed();

        HttpResponse response = client.execute(post);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new NotificationFailureException(EntityUtils.toString(response.getEntity()));
        }

    } catch (NotificationFailureException exception) {
        throw exception;
    } catch (Exception exception) {
        throw new NotificationFailureException(exception);
    }
}

From source file:com.hp.octane.integrations.services.pipelines.PipelineContextServiceImpl.java

@Override
public PipelineContextList getJobConfiguration(String serverIdentity, String jobName) throws IOException {
    String url = getConfigurationUrl(serverIdentity, jobName);

    OctaneRestClient octaneRestClient = restService.obtainOctaneRestClient();
    Map<String, String> headers = new HashMap<>();
    headers.put(ACCEPT_HEADER, ContentType.APPLICATION_JSON.getMimeType());

    OctaneRequest request = dtoFactory.newDTO(OctaneRequest.class).setMethod(HttpMethod.GET).setUrl(url)
            .setHeaders(headers);//w  w  w  . j  a  va 2s  .c  o  m
    OctaneResponse response = octaneRestClient.execute(request);
    validateResponse(HttpStatus.SC_OK, response);

    PipelineContextList result = dtoFactory.dtoFromJson(response.getBody(), PipelineContextList.class);
    return result;
}