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:org.jenkinsci.test.acceptance.update_center.MockUpdateCenter.java
public void ensureRunning() { if (original != null) { return;// w w w . ja v a2s .co m } // TODO this will likely not work on arbitrary controllers, so perhaps limit to the default WinstoneController Jenkins jenkins = injector.getInstance(Jenkins.class); List<String> sites = new UpdateCenter(jenkins).getJson("tree=sites[url]").findValuesAsText("url"); if (sites.size() != 1) { // TODO ideally it would rather delegate to all of them, but that implies deprecating CachedUpdateCenterMetadataLoader.url and using whatever site(s) Jenkins itself specifies LOGGER.log(Level.WARNING, "found an unexpected number of update sites: {0}", sites); return; } UpdateCenterMetadata ucm; try { ucm = ucmd.get(jenkins); } catch (IOException x) { LOGGER.log(Level.WARNING, "cannot load data for mock update center", x); return; } JSONObject all; try { all = new JSONObject(ucm.originalJSON); all.remove("signature"); JSONObject plugins = all.getJSONObject("plugins"); LOGGER.info(() -> "editing JSON with " + plugins.length() + " plugins to reflect " + ucm.plugins.size() + " possible overrides"); for (PluginMetadata meta : ucm.plugins.values()) { String name = meta.getName(); String version = meta.getVersion(); JSONObject plugin = plugins.optJSONObject(name); if (plugin == null) { LOGGER.log(Level.INFO, "adding plugin {0}", name); plugin = new JSONObject().accumulate("name", name); plugins.put(name, plugin); } plugin.put("url", name + ".hpi"); updating(plugin, "version", version); updating(plugin, "gav", meta.gav); updating(plugin, "requiredCore", meta.requiredCore().toString()); updating(plugin, "dependencies", new JSONArray(meta.getDependencies().stream().map(d -> { try { return new JSONObject().accumulate("name", d.name).accumulate("version", d.version) .accumulate("optional", d.optional); } catch (JSONException x) { throw new AssertionError(x); } }).collect(Collectors.toList()))); plugin.remove("sha1"); } } catch (JSONException x) { LOGGER.log(Level.WARNING, "cannot prepare mock update center", x); return; } HttpProcessor proc = HttpProcessorBuilder.create().add(new ResponseServer("MockUpdateCenter")) .add(new ResponseContent()).add(new RequestConnControl()).build(); UriHttpRequestHandlerMapper handlerMapper = new UriHttpRequestHandlerMapper(); String json = "updateCenter.post(\n" + all + "\n);"; handlerMapper.register("/update-center.json", (HttpRequest request, HttpResponse response, HttpContext context) -> { response.setStatusCode(HttpStatus.SC_OK); response.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON)); }); handlerMapper.register("*.hpi", (HttpRequest request, HttpResponse response, HttpContext context) -> { String plugin = request.getRequestLine().getUri().replaceFirst("^/(.+)[.]hpi$", "$1"); PluginMetadata meta = ucm.plugins.get(plugin); if (meta == null) { LOGGER.log(Level.WARNING, "no such plugin {0}", plugin); response.setStatusCode(HttpStatus.SC_NOT_FOUND); return; } File local = meta.resolve(injector, meta.getVersion()); LOGGER.log(Level.INFO, "serving {0}", local); response.setStatusCode(HttpStatus.SC_OK); response.setEntity(new FileEntity(local)); }); handlerMapper.register("*", (HttpRequest request, HttpResponse response, HttpContext context) -> { String location = original.replace("/update-center.json", request.getRequestLine().getUri()); LOGGER.log(Level.INFO, "redirect to {0}", location); /* TODO for some reason DownloadService.loadJSONHTML does not seem to process the redirect, despite calling setInstanceFollowRedirects(true): response.setStatusCode(HttpStatus.SC_MOVED_TEMPORARILY); response.setHeader("Location", location); */ HttpURLConnection uc = (HttpURLConnection) new URL(location).openConnection(); uc.setInstanceFollowRedirects(true); // TODO consider caching these downloads locally like CachedUpdateCenterMetadataLoader does for the main update-center.json byte[] data = IOUtils.toByteArray(uc); String contentType = uc.getContentType(); response.setStatusCode(HttpStatus.SC_OK); response.setEntity(new ByteArrayEntity(data, ContentType.create(contentType))); }); server = ServerBootstrap.bootstrap(). // could setLocalAddress if using a JenkinsController that requires it setHttpProcessor(proc).setHandlerMapper(handlerMapper).setExceptionLogger(serverExceptionHandler()) .create(); try { server.start(); } catch (IOException x) { LOGGER.log(Level.WARNING, "cannot start mock update center", x); return; } original = sites.get(0); // TODO figure out how to deal with Docker-based controllers which would need to have an IP address for the host String override = "http://" + server.getInetAddress().getHostAddress() + ":" + server.getLocalPort() + "/update-center.json"; LOGGER.log(Level.INFO, "replacing update site {0} with {1}", new Object[] { original, override }); jenkins.runScript( "DownloadService.signatureCheck = false; Jenkins.instance.updateCenter.sites.replaceBy([new UpdateSite(UpdateCenter.ID_DEFAULT, '%s')])", override); }
From source file:com.qwazr.graph.test.FullTest.java
@Test public void test200PutRandomEdges() throws IOException { for (int i = 0; i < VISIT_NUMBER / 100; i++) { int visitNodeId = RandomUtils.nextInt(VISIT_NUMBER / 2, VISIT_NUMBER); if (!nodeExists(visitNodeId)) continue; int productNodeId = RandomUtils.nextInt(PRODUCT_NUMBER / 2, PRODUCT_NUMBER); HttpResponse response = Request .Post(BASE_URL + '/' + TEST_BASE + "/node/v" + visitNodeId + "/edge/see/p" + productNodeId) .connectTimeout(60000).socketTimeout(60000).execute().returnResponse(); if (response.getStatusLine().getStatusCode() == 500) System.out.println(IOUtils.toString(response.getEntity().getContent())); Assert.assertThat(response.getStatusLine().getStatusCode(), AnyOf.anyOf(Is.is(200), Is.is(404))); Assert.assertThat(response.getEntity().getContentType().getValue(), Is.is(ContentType.APPLICATION_JSON.toString())); }/*from ww w . j av a 2s. c o m*/ }
From source file:com.graphaware.test.util.TestHttpClient.java
/** * Issue an HTTP PUT and assert the response status code. * * @param url to POST to. * @param json request body. * @param headers request headers as map. * @param expectedStatusCode expected status code. * @return the body of the response./*from ww w . java 2 s . c o m*/ */ public String put(String url, String json, Map<String, String> headers, final int expectedStatusCode) { HttpPut put = new HttpPut(url); if (json != null) { put.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON)); } setHeaders(put, headers); return method(put, expectedStatusCode); }
From source file:org.megam.deccanplato.provider.salesforce.crm.handler.EventImpl.java
/** * This method updates a event in salesforce.com and returns a success message with event contract id. * This method gets input from a MAP(contains json data) and returns a MAp. * @param outMap //from w ww .j ava 2 s . com */ private Map<String, String> update() { final String SALESFORCE_UPDATE_EVENT_URL = args.get(INSTANCE_URL) + SALESFORCE_EVENT_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_SUBJECT, args.get(SUBJECT)); TransportTools tst = new TransportTools(SALESFORCE_UPDATE_EVENT_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.samebug.clients.search.api.client.SamebugClient.java
public void trace(@NotNull final TrackEvent event) throws SamebugClientException { if (config.isTrackingEnabled) { HttpPost post = new HttpPost(config.trackingRoot); post.addHeader("Content-Type", "application/json"); final String json = gson.toJson(event.fields); post.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON)); rawClient.executeTracking(post); }// ww w .j a va 2 s. c om }
From source file:org.jboss.as.test.integration.domain.AbstractSSLMasterSlaveTestCase.java
private static ModelNode executeOverHttp(URI mgmtURI, String operation) throws IOException { CloseableHttpClient httpClient = createHttpClient(mgmtURI); HttpEntity operationEntity = new StringEntity(operation, ContentType.APPLICATION_JSON); HttpPost httpPost = new HttpPost(mgmtURI); httpPost.setEntity(operationEntity); HttpResponse response;/*from www .ja v a2 s . c o m*/ ModelNode responseNode; try { response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { return null; } HttpEntity entity = response.getEntity(); if (entity == null) { return null; } responseNode = ModelNode.fromJSONStream(response.getEntity().getContent()); EntityUtils.consume(entity); } finally { httpClient.close(); } return responseNode; }
From source file:org.elasticsearch.client.RestHighLevelClientTests.java
public void testInfo() throws IOException { Header[] headers = RestClientTestUtil.randomHeaders(random(), "Header"); Response response = mock(Response.class); MainResponse testInfo = new MainResponse("nodeName", Version.CURRENT, new ClusterName("clusterName"), "clusterUuid", Build.CURRENT, true); when(response.getEntity()).thenReturn(new StringEntity( toXContent(testInfo, XContentType.JSON, false).utf8ToString(), ContentType.APPLICATION_JSON)); when(restClient.performRequest(anyString(), anyString(), anyMapOf(String.class, String.class), anyObject(), anyVararg())).thenReturn(response); MainResponse receivedInfo = restHighLevelClient.info(headers); assertEquals(testInfo, receivedInfo); verify(restClient).performRequest(eq("GET"), eq("/"), eq(Collections.emptyMap()), Matchers.isNull(HttpEntity.class), argThat(new HeadersVarargMatcher(headers))); }
From source file:com.hp.octane.integrations.services.pipelines.PipelineContextServiceImpl.java
@Override public PipelineContext createPipeline(String serverIdentity, String jobName, PipelineContext pipelineContext) throws IOException { String url = getConfigurationUrl(serverIdentity, jobName); validateRelease(pipelineContext);// w w w . ja v a 2 s .com OctaneRestClient octaneRestClient = restService.obtainOctaneRestClient(); Map<String, String> headers = new HashMap<>(); headers.put(ACCEPT_HEADER, ContentType.APPLICATION_JSON.getMimeType()); headers.put(CONTENT_TYPE_HEADER, ContentType.APPLICATION_JSON.getMimeType()); String jsonData = dtoFactory.dtoToJson(pipelineContext); OctaneRequest request = dtoFactory.newDTO(OctaneRequest.class).setMethod(HttpMethod.POST).setUrl(url) .setBody(jsonData).setHeaders(headers); OctaneResponse response = octaneRestClient.execute(request); validateResponse(HttpStatus.SC_CREATED, response); PipelineContextList list = dtoFactory.dtoFromJson(response.getBody(), PipelineContextList.class); //we might receive several pipeline context from other workspaces. //find updated context by workspace id PipelineContext result = list.getData().stream() .filter(p -> p.getWorkspaceId() == pipelineContext.getWorkspaceId()).findFirst().get(); return result; }
From source file:org.apache.cloudstack.storage.datastore.util.NexentaNmsClient.java
public NmsResponse execute(Class responseClass, String object, String method, Object... params) { StringBuilder sb = new StringBuilder(); NmsRequest nmsRequest = new NmsRequest(object, method, params); if (logger.isDebugEnabled()) { logger.debug(nmsRequest);//from w ww . j a v a 2 s . c om } final Gson gson = new Gson(); String jsonRequest = gson.toJson(nmsRequest); StringEntity input = new StringEntity(jsonRequest, ContentType.APPLICATION_JSON); HttpPost postRequest = new HttpPost(nmsUrl.toString()); postRequest.setEntity(input); DefaultHttpClient httpClient = getClient(); try { HttpResponse response = httpClient.execute(postRequest); final int status = response.getStatusLine().getStatusCode(); if (!isSuccess(status)) { throw new CloudRuntimeException("Failed on JSON-RPC API call. HTTP error code = " + status); } try (BufferedReader buffer = new BufferedReader( new InputStreamReader(response.getEntity().getContent()));) { String tmp; while ((tmp = buffer.readLine()) != null) { sb.append(tmp); } } catch (IOException ex) { throw new CloudRuntimeException(ex.getMessage()); } } catch (ClientProtocolException ex) { throw new CloudRuntimeException(ex.getMessage()); } catch (IOException ex) { throw new CloudRuntimeException(ex.getMessage()); } finally { if (httpClient != null) { try { httpClient.getConnectionManager().shutdown(); } catch (Exception t) { logger.debug(t.getMessage()); } } } String responseString = sb.toString(); if (logger.isDebugEnabled()) { logger.debug("NexentaStor Appliance response: " + responseString); } NmsResponse nmsResponse = (NmsResponse) gson.fromJson(responseString, responseClass); if (nmsResponse.getError() != null) { throw new CloudRuntimeException(nmsResponse.getError().getMesssage()); } return nmsResponse; }