List of usage examples for org.apache.http.entity ContentType APPLICATION_JSON
ContentType APPLICATION_JSON
To view the source code for org.apache.http.entity ContentType APPLICATION_JSON.
Click Source Link
From source file:com.appdirect.sdk.feature.CanValidateCustomerDataIntegrationTest.java
@Test public void validateCustomerAccount() throws Exception { Map<String, String> dataMap = new HashMap<>(); dataMap.put("tenantId", "3379191"); dataMap.put("tenantDomain", "test.org"); dataMap.put("externalVendorId", UUID.randomUUID().toString()); dataMap.put("customerName", "Test Org"); String jsonData = objectMapper.writeValueAsString(dataMap); HttpResponse response = fakeAppmarket.sendSignedPostRequestTo( baseConnectorUrl() + CUSTOMER_ACCOUNT_API_END_POINT, new StringEntity(jsonData, ContentType.APPLICATION_JSON)); assertThat(response.getStatusLine().getStatusCode()).isEqualTo(HttpStatus.SC_OK); assertThat(EntityUtils.toString(response.getEntity())).isEqualTo( "{\"success\":false,\"errorCode\":\"CONFIGURATION_ERROR\",\"message\":\"Customer account validation is not supported.\"}"); }
From source file:org.elasticsearch.backwards.IndexingIT.java
private void createIndex(String name, Settings settings) throws IOException { assertOK(client().performRequest("PUT", name, Collections.emptyMap(), new StringEntity( "{ \"settings\": " + Strings.toString(settings) + " }", ContentType.APPLICATION_JSON))); }
From source file:nebula.plugin.metrics.dispatcher.RestMetricsDispatcher.java
protected void postPayload(String payload) { checkNotNull(payload);/*from www .j av a2 s. co m*/ try { Request postReq = Request.Post(extension.getRestUri()); postReq.bodyString(payload, ContentType.APPLICATION_JSON); addHeaders(postReq); postReq.execute(); } catch (IOException e) { throw new RuntimeException("Unable to POST to " + extension.getRestUri(), e); } }
From source file:brooklyn.entity.mesos.MesosUtils.java
public static final Optional<String> httpPost(Entity framework, String subUrl, String dataUrl, Map<String, Object> substitutions) { String targetUrl = Urls.mergePaths(framework.sensors().get(MesosFramework.FRAMEWORK_URL), subUrl); String templateContents = ResourceUtils.create().getResourceAsString(dataUrl); String processedJson = TemplateProcessor.processTemplateContents(templateContents, substitutions); LOG.debug("Posting JSON to {}: {}", targetUrl, processedJson); URI postUri = URI.create(targetUrl); HttpToolResponse response = HttpTool .httpPost(MesosUtils.buildClient(framework), postUri, MutableMap.of(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType(), HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType()), processedJson.getBytes()); LOG.debug("Response: " + response.getContentAsString()); if (!HttpTool.isStatusCodeHealthy(response.getResponseCode())) { LOG.warn("Invalid response code {}: {}", response.getResponseCode(), response.getReasonPhrase()); return Optional.absent(); } else {//from w ww. jav a 2 s .c om LOG.debug("Successfull call to {}: {}", targetUrl); return Optional.of(response.getContentAsString()); } }
From source file:org.megam.deccanplato.provider.box.BoxAdapterAccess.java
@Override public <T extends Object> DataMap<T> authenticate(DataMap<T> access) throws AdapterAccessException { Map<String, T> accessMap = access.map(); System.out.print("OAUTH MAP" + accessMap.toString()); Map<String, String> headerMap = new HashMap<String, String>(); headerMap.put("Authorization", "BoxAuth api_key=" + (String) accessMap.get(API_KEY)); Map<String, String> boxList = new HashMap<String, String>(); boxList.put("email", (String) accessMap.get(EMAIL)); TransportTools tools = new TransportTools(BOX_OAUTH2_URL, null, headerMap); Gson obj = new GsonBuilder().setPrettyPrinting().create(); System.out.println(obj.toJson(boxList)); tools.setContentType(ContentType.APPLICATION_JSON, obj.toJson(boxList)); String responseBody = null;//from w w w .ja v a 2 s. c om TransportResponse response = null; try { response = TransportMachinery.post(tools); responseBody = response.entityToString(); success = true; System.out.println("OUTPUT:" + responseBody); } catch (ClientProtocolException ce) { throw new AdapterAccessException("An error occurred during post operation.", ce); } catch (IOException ioe) { throw new AdapterAccessException("An error occurred during post operation.", ioe); } DataMap<T> accessMap1 = new DefaultDataMap<>(); accessMap1.map().put(OUTPUT, (T) accessMap.get(API_KEY)); return accessMap1; /* * Old Box code written by Thomas Alrin */ /*BOX_OAUTH2_URL = BOX_OAUTH2_URL + accessMap.get("api_key"); TransportTools tools = new TransportTools(BOX_OAUTH2_URL, null); String responseBody = null; TransportResponse response = null; try { try { response = TransportMachinery.get(tools); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } responseBody = response.entityToString(); } catch (ClientProtocolException ce) { throw new AdapterAccessException( "An error occurred during post operation.", ce); } catch (IOException ioe) { throw new AdapterAccessException( "An error occurred during post operation.", ioe); } DocumentBuilder db = null; try { db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); } InputSource is = new InputSource(); is.setCharacterStream(new StringReader(responseBody)); Document doc = null; try { doc = (Document) db.parse(is); } catch (SAXException | IOException e) { e.printStackTrace(); } NodeList nodes = ((Node) doc).getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node element = nodes.item(i); NodeList child = element.getChildNodes(); for (int j = 0; j < child.getLength(); j++) { Node ele = child.item(j); if (ele.getNodeName().equals("ticket")) { Ticket = ele.getTextContent(); } } } BoxAuthToken((String) accessMap.get("api_key"),Ticket); return null; } public void BoxAuthToken(String api, String tick) throws AdapterAccessException { String url = "https://www.box.com/api/1.0/rest?action=get_auth_token&api_key="+api+"&ticket="+tick; TransportTools tools = new TransportTools(url, null); String responseBody = null; TransportResponse response = null; try { try { response = TransportMachinery.get(tools); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } responseBody = response.entityToString(); } catch (ClientProtocolException ce) { throw new AdapterAccessException( "An error occurred during post operation.", ce); } catch (IOException ioe) { throw new AdapterAccessException( "An error occurred during post operation.", ioe); }*/ }
From source file:com.joyent.manta.http.MantaHttpHeadersTest.java
public void canExportApacheHeaders() { MantaHttpHeaders headers = new MantaHttpHeaders(); headers.setDurabilityLevel(3);/*from ww w . ja v a 2 s . com*/ headers.setContentType(ContentType.APPLICATION_JSON.withCharset(StandardCharsets.UTF_8).toString()); headers.put("X-Multi-Header", Arrays.asList("value 1", "value 2")); Header[] apacheHeaders = headers.asApacheHttpHeaders(); Header durability = findHeader(MantaHttpHeaders.HTTP_DURABILITY_LEVEL, apacheHeaders); Header contentType = findHeader(HttpHeaders.CONTENT_TYPE, apacheHeaders); Header multiHeader = findHeader("x-multi-header", apacheHeaders); Assert.assertEquals(headers.getDurabilityLevel().toString(), durability.getValue()); Assert.assertEquals(headers.getContentType(), contentType.getValue()); @SuppressWarnings("unchecked") Collection<String> multiHeaderValues = (Collection<String>) headers.get("x-multi-header"); Assert.assertEquals(StringUtils.join(multiHeaderValues, ", "), multiHeader.getValue()); }
From source file:org.talend.dataprep.api.service.command.preparation.PreviewAbstract.java
private HttpRequestBase onExecute() { final String uri = this.transformationServiceUrl + "/transform/preview"; HttpPost transformationCall = new HttpPost(uri); final String paramsAsJson; try {//from w w w. ja v a2s . c om paramsAsJson = objectMapper.writer().writeValueAsString(parameters); } catch (JsonProcessingException e) { throw new TDPException(TransformationErrorCodes.UNABLE_TO_PERFORM_PREVIEW, e); } HttpEntity reqEntity = new StringEntity(paramsAsJson, ContentType.APPLICATION_JSON); transformationCall.setEntity(reqEntity); return transformationCall; }
From source file:org.elasticsearch.packaging.util.ServerUtils.java
public static void runElasticsearchTests() throws IOException { makeRequest(Request.Post("http://localhost:9200/library/book/1?refresh=true&pretty") .bodyString("{ \"title\": \"Book #1\", \"pages\": 123 }", ContentType.APPLICATION_JSON)); makeRequest(Request.Post("http://localhost:9200/library/book/2?refresh=true&pretty") .bodyString("{ \"title\": \"Book #2\", \"pages\": 456 }", ContentType.APPLICATION_JSON)); String count = makeRequest(Request.Get("http://localhost:9200/_count?pretty")); assertThat(count, containsString("\"count\" : 2")); makeRequest(Request.Delete("http://localhost:9200/_all")); }
From source file:org.talend.dataprep.api.service.command.aggregation.Aggregate.java
/** * Call the transformation service with the export parameters in json the request body. * * @param parameters the aggregate parameters. * @return the http request to execute./*from w w w . java 2 s. c o m*/ */ private HttpRequestBase onExecute(AggregationParameters parameters) { // must work on either a dataset or a preparation, if both parameters are set, an error is thrown if (StringUtils.isNotBlank(parameters.getDatasetId()) && StringUtils.isNotBlank(parameters.getPreparationId())) { LOG.error("Cannot aggregate on both dataset id & preparation id : {}", parameters); throw new TDPException(CommonErrorCodes.BAD_AGGREGATION_PARAMETERS); } String uri = transformationServiceUrl + "/aggregate"; //$NON-NLS-1$ HttpPost aggregateCall = new HttpPost(uri); try { String paramsAsJson = objectMapper.writer().writeValueAsString(parameters); aggregateCall.setEntity(new StringEntity(paramsAsJson, ContentType.APPLICATION_JSON)); } catch (JsonProcessingException e) { throw new TDPException(CommonErrorCodes.UNABLE_TO_AGGREGATE, e); } return aggregateCall; }
From source file:com.joyent.manta.client.MantaObjectDepthComparatorTest.java
private static List<MantaObject> fileObjects(final MantaObject dirObject, final int number) { List<MantaObject> objects = new ArrayList<>(); for (int i = 0; i < number; i++) { final MantaObject object = mock(MantaObject.class); final int segmentChar = (number + i) % 26; String path = dirObject.getPath() + SEPARATOR + StringUtils.repeat(((char) (97 + segmentChar)), 4) + ".json"; when(object.getPath()).thenReturn(path); when(object.getType()).thenReturn(MantaObject.MANTA_OBJECT_TYPE_OBJECT); when(object.getContentType()).thenReturn(ContentType.APPLICATION_JSON.toString()); when(object.toString()).thenReturn("[F] " + path); objects.add(object);/* w w w.jav a2 s . com*/ } return objects; }