List of usage examples for org.apache.http.entity ContentType APPLICATION_XML
ContentType APPLICATION_XML
To view the source code for org.apache.http.entity ContentType APPLICATION_XML.
Click Source Link
From source file:com.cloud.network.brocade.BrocadeVcsApi.java
protected Output executeRetreiveStatus(String uri) throws BrocadeVcsApiException { if (_host == null || _host.isEmpty() || _adminuser == null || _adminuser.isEmpty() || _adminpass == null || _adminpass.isEmpty()) {/* w ww . ja v a 2 s . c o m*/ throw new BrocadeVcsApiException("Hostname/credentials are null or empty"); } String readLine = null; StringBuffer sb = null; HttpPost pm = (HttpPost) createMethod("post", uri); pm.setHeader("Accept", "application/vnd.operational-state.resource+xml"); pm.setEntity(new StringEntity("<show-vcs></show-vcs>", ContentType.APPLICATION_XML)); HttpResponse response = executeMethod(pm); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { String errorMessage; try { errorMessage = responseToErrorMessage(response); } catch (IOException e) { s_logger.error("Failed to retreive status : " + e.getMessage()); throw new BrocadeVcsApiException("Failed to retreive status : " + e.getMessage()); } pm.releaseConnection(); s_logger.error("Failed to retreive status : " + errorMessage); throw new BrocadeVcsApiException("Failed to retreive status : " + errorMessage); } try (BufferedReader br = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), Charset.forName("UTF-8")))) { sb = new StringBuffer(); while (((readLine = br.readLine()) != null)) { s_logger.debug(readLine); sb.append(readLine); } } catch (Exception e) { s_logger.error("Failed to retreive status : " + e.getMessage()); throw new BrocadeVcsApiException("Failed to retreive status : " + e.getMessage()); } pm.releaseConnection(); return convertToXML(sb.toString()); }
From source file:org.geowebcache.jetty.RestIntegrationTest.java
@Test public void testCreateUpdateDelete() throws Exception { final String layerName = "testLayer"; final String url1 = "http://example.com/wms1?"; final String url2 = "http://example.com/wms2?"; final String layers = "remoteLayer"; // Create//from ww w . ja va2s .c o m { final HttpPut request = new HttpPut(jetty.getUri().resolve("rest/layers/").resolve(layerName + ".xml")); request.setEntity(new StringEntity( "<wmsLayer><name>" + layerName + "</name><wmsUrl><string>" + url1 + "</string></wmsUrl><wmsLayers>" + layers + "</wmsLayers></wmsLayer>", ContentType.APPLICATION_XML)); try (CloseableHttpResponse response = admin.getClient().execute(request)) { assertThat(response.getStatusLine(), hasProperty("statusCode", equalTo(200))); } doGetXML("rest/layers.xml", admin.getClient(), equalTo(200), doc -> { assertThat(doc, hasXPath("/layers/layer[name/text()='" + layerName + "']/atom:link/@href", equalTo( jetty.getUri().resolve("/geowebcache/rest/layers/" + layerName + ".xml").toString()))); }); doGetXML("rest/layers/" + layerName + ".xml", admin.getClient(), equalTo(200), doc -> { assertThat(doc, hasXPath("/wmsLayer/name", equalTo(layerName))); assertThat(doc, hasXPath("/wmsLayer/wmsUrl/string", equalTo(url1))); assertThat(doc, hasXPath("/wmsLayer/wmsLayers", equalTo(layers))); }); } // Update { final HttpPost request = new HttpPost( jetty.getUri().resolve("rest/layers/").resolve(layerName + ".xml")); request.setEntity(new StringEntity( "<wmsLayer><name>" + layerName + "</name><wmsUrl><string>" + url2 + "</string></wmsUrl><wmsLayers>" + layers + "</wmsLayers></wmsLayer>", ContentType.APPLICATION_XML)); try (CloseableHttpResponse response = admin.getClient().execute(request)) { assertThat(response.getStatusLine(), hasProperty("statusCode", equalTo(200))); } doGetXML("rest/layers/" + layerName + ".xml", admin.getClient(), equalTo(200), doc -> { assertThat(doc, hasXPath("/wmsLayer/name", equalTo(layerName))); assertThat(doc, hasXPath("/wmsLayer/wmsUrl/string", equalTo(url2))); assertThat(doc, hasXPath("/wmsLayer/wmsLayers", equalTo(layers))); }); } // GetCap { doGetXML("service/wmts?REQUEST=getcapabilities", anonymous.getClient(), equalTo(200), doc -> { assertThat(doc, hasXPath( "/wmts:Capabilities/wmts:Contents/wmts:Layer/ows:Title[text()='" + layerName + "']")); }); } // Delete { final HttpDelete request = new HttpDelete( jetty.getUri().resolve("rest/layers/").resolve(layerName + ".xml")); try (CloseableHttpResponse response = admin.getClient().execute(request)) { assertThat(response.getStatusLine(), hasProperty("statusCode", equalTo(200))); } doGetXML("rest/layers.xml", admin.getClient(), equalTo(200), doc -> { assertThat(doc, not(hasXPath("/layers/layer[name/text()='" + layerName + "']"))); }); final HttpGet request2 = new HttpGet( jetty.getUri().resolve("rest/layers/").resolve(layerName + ".xml")); try (CloseableHttpResponse response = admin.getClient().execute(request2)) { assertThat(response.getStatusLine(), hasProperty("statusCode", equalTo(404))); } } // GetCap { doGetXML("service/wmts?REQUEST=getcapabilities", anonymous.getClient(), equalTo(200), doc -> { assertThat(doc, not(hasXPath( "/wmts:Capabilities/wmts:Contents/wmts:Layer/ows:Title[text()='" + layerName + "']"))); }); } }
From source file:org.wuspba.ctams.ws.ITPersonController.java
private static void add(Person person) throws Exception { CTAMSDocument doc = new CTAMSDocument(); doc.getPeople().add(person);//w w w. ja v a2 s.com CloseableHttpClient httpclient = HttpClients.createDefault(); String xml = XMLUtils.marshal(doc); URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build(); HttpPost httpPost = new HttpPost(uri); StringEntity xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML); CloseableHttpResponse response = null; try { httpPost.setEntity(xmlEntity); response = httpclient.execute(httpPost); assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString()); HttpEntity responseEntity = response.getEntity(); doc = IntegrationTestUtils.convertEntity(responseEntity); for (Person p : doc.getPeople()) { if (p.getFirstName().equals(TestFixture.INSTANCE.andy.getFirstName())) { TestFixture.INSTANCE.andy.setId(p.getId()); } else if (p.getFirstName().equals(TestFixture.INSTANCE.bob.getFirstName())) { TestFixture.INSTANCE.bob.setId(p.getId()); } else if (p.getFirstName().equals(TestFixture.INSTANCE.elaine.getFirstName())) { TestFixture.INSTANCE.elaine.setId(p.getId()); } else if (p.getFirstName().equals(TestFixture.INSTANCE.eoin.getFirstName())) { TestFixture.INSTANCE.eoin.setId(p.getId()); } else if (p.getFirstName().equals(TestFixture.INSTANCE.jamie.getFirstName())) { TestFixture.INSTANCE.jamie.setId(p.getId()); } } EntityUtils.consume(responseEntity); } catch (UnsupportedEncodingException ex) { LOG.error("Unsupported coding", ex); } catch (IOException ioex) { LOG.error("IOException", ioex); } finally { if (response != null) { try { response.close(); } catch (IOException ex) { LOG.error("Could not close response", ex); } } } }
From source file:org.wuspba.ctams.ws.ITRosterController.java
private static void add(Roster roster) throws Exception { CTAMSDocument doc = new CTAMSDocument(); doc.getRosters().add(roster);/*from w w w.j a v a 2 s .c om*/ String xml = XMLUtils.marshal(doc); CloseableHttpClient httpclient = HttpClients.createDefault(); URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build(); HttpPost httpPost = new HttpPost(uri); StringEntity xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML); CloseableHttpResponse response = null; try { httpPost.setEntity(xmlEntity); response = httpclient.execute(httpPost); assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString()); HttpEntity responseEntity = response.getEntity(); doc = IntegrationTestUtils.convertEntity(responseEntity); roster.setId(doc.getRosters().get(0).getId()); EntityUtils.consume(responseEntity); } catch (UnsupportedEncodingException ex) { LOG.error("Unsupported coding", ex); } catch (IOException ioex) { LOG.error("IOException", ioex); } finally { if (response != null) { try { response.close(); } catch (IOException ex) { LOG.error("Could not close response", ex); } } } }
From source file:org.apache.openaz.xacml.rest.XACMLPdpServlet.java
/** * POST - We expect XACML requests to be posted by PEP applications. They can be in the form of XML or * JSON according to the XACML 3.0 Specifications for both. * * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) *//*from w w w. j ava 2 s. com*/ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // // no point in doing any work if we know from the get-go that we cannot do anything with the request // if (status.getLoadedRootPolicies().size() == 0) { logger.warn("Request from PEP at " + request.getRequestURI() + " for service when PDP has No Root Policies loaded"); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); return; } XACMLRest.dumpRequest(request); // // Set our no-cache header // response.setHeader("Cache-Control", "no-cache"); // // They must send a Content-Type // if (request.getContentType() == null) { logger.warn("Must specify a Content-Type"); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "no content-type given"); return; } // // Limit the Content-Length to something reasonable // if (request.getContentLength() > Integer .parseInt(XACMLProperties.getProperty("MAX_CONTENT_LENGTH", "32767"))) { String message = "Content-Length larger than server will accept."; logger.info(message); response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); return; } if (request.getContentLength() <= 0) { String message = "Content-Length is negative"; logger.info(message); response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); return; } ContentType contentType = null; try { contentType = ContentType.parse(request.getContentType()); } catch (Exception e) { String message = "Parsing Content-Type: " + request.getContentType() + ", error=" + e.getMessage(); logger.error(message, e); response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); return; } // // What exactly did they send us? // String incomingRequestString = null; Request pdpRequest = null; if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType()) || contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType()) || contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) { // // Read in the string // StringBuilder buffer = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()))) { String line; while ((line = reader.readLine()) != null) { buffer.append(line); } incomingRequestString = buffer.toString(); } logger.info(incomingRequestString); // // Parse into a request // try { if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) { pdpRequest = JSONRequest.load(incomingRequestString); } else if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType()) || contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) { pdpRequest = DOMRequest.load(incomingRequestString); } } catch (Exception e) { logger.error("Could not parse request", e); response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); return; } } else { String message = "unsupported content type" + request.getContentType(); logger.error(message); response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); return; } // // Did we successfully get and parse a request? // if (pdpRequest == null || pdpRequest.getRequestAttributes() == null || pdpRequest.getRequestAttributes().size() <= 0) { String message = "Zero Attributes found in the request"; logger.error(message); response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); return; } // // Run it // try { // // Get the pointer to the PDP Engine // PDPEngine myEngine = null; synchronized (pdpEngineLock) { myEngine = this.pdpEngine; } if (myEngine == null) { String message = "No engine loaded."; logger.error(message); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); return; } // // Send the request and save the response // long lTimeStart, lTimeEnd; Response pdpResponse = null; // TODO - Make this unnecessary // TODO It seems that the PDP Engine is not thread-safe, so when a configuration change occurs in // the middle of processing // TODO a PEP Request, that Request fails (it throws a NullPointerException in the decide() // method). // TODO Using synchronize will slow down processing of PEP requests, possibly by a significant // amount. // TODO Since configuration changes are rare, it would be A Very Good Thing if we could eliminate // this sychronized block. // TODO // TODO This problem was found by starting one PDP then // TODO RestLoadTest switching between 2 configurations, 1 second apart // TODO both configurations contain the datarouter policy // TODO both configurations already have all policies cached in the PDPs config directory // TODO RestLoadTest started with the Datarouter test requests, 5 threads, no interval // TODO With that configuration this code (without the synchronized) throws a NullPointerException // TODO within a few seconds. // synchronized (pdpEngineLock) { myEngine = this.pdpEngine; try { lTimeStart = System.currentTimeMillis(); pdpResponse = myEngine.decide(pdpRequest); lTimeEnd = System.currentTimeMillis(); } catch (PDPException e) { String message = "Exception during decide: " + e.getMessage(); logger.error(message); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); return; } } requestLogger.info(lTimeStart + "=" + incomingRequestString); if (logger.isDebugEnabled()) { logger.debug("Request time: " + (lTimeEnd - lTimeStart) + "ms"); } // // Convert Response to appropriate Content-Type // if (pdpResponse == null) { requestLogger.info(lTimeStart + "=" + "{}"); throw new Exception("Failed to get response from PDP engine."); } // // Set our content-type // response.setContentType(contentType.getMimeType()); // // Convert the PDP response object to a String to // return to our caller as well as dump to our loggers. // String outgoingResponseString = ""; if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) { // // Get it as a String. This is not very efficient but we need to log our // results for auditing. // outgoingResponseString = JSONResponse.toString(pdpResponse, logger.isDebugEnabled()); if (logger.isDebugEnabled()) { logger.debug(outgoingResponseString); // // Get rid of whitespace // outgoingResponseString = JSONResponse.toString(pdpResponse, false); } } else if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType()) || contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) { // // Get it as a String. This is not very efficient but we need to log our // results for auditing. // outgoingResponseString = DOMResponse.toString(pdpResponse, logger.isDebugEnabled()); if (logger.isDebugEnabled()) { logger.debug(outgoingResponseString); // // Get rid of whitespace // outgoingResponseString = DOMResponse.toString(pdpResponse, false); } } // // lTimeStart is used as an ID within the requestLogger to match up // request's with responses. // requestLogger.info(lTimeStart + "=" + outgoingResponseString); response.getWriter().print(outgoingResponseString); } catch (Exception e) { String message = "Exception executing request: " + e; logger.error(message, e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); return; } response.setStatus(HttpServletResponse.SC_OK); }
From source file:com.github.restdriver.clientdriver.integration.ClientDriverSuccessTest.java
@Test public void testPostWithBodyOverTwoExpectations() throws Exception { // bug fix//from w ww . j a va 2 s. c om String baseUrl = driver.getBaseUrl(); driver.addExpectation(onRequestTo("/foo"), giveResponse("___", "text/plain").withStatus(417)); driver.addExpectation(onRequestTo("/blah2").withBody("<eh/>", "application/xml").withMethod(POST), giveResponse("___", "text/plain").withStatus(418)); HttpClient postClient = new DefaultHttpClient(); HttpPost poster = new HttpPost(baseUrl + "/blah2"); poster.setEntity(new StringEntity("<eh/>", ContentType.APPLICATION_XML)); HttpResponse response = postClient.execute(poster); HttpClient getClient = new DefaultHttpClient(); HttpGet getter = new HttpGet(baseUrl + "/foo"); HttpResponse getResponse = getClient.execute(getter); assertThat(getResponse.getStatusLine().getStatusCode(), equalTo(417)); assertThat(response.getStatusLine().getStatusCode(), is(418)); assertThat(IOUtils.toString(response.getEntity().getContent()), equalTo("___")); }
From source file:org.apache.openaz.xacml.pdp.test.TestBase.java
/** * This makes an HTTP POST call to a running PDP RESTful servlet to get a decision. * * @param file/*from w w w . j a v a 2 s .com*/ * @return */ protected Response callRESTfulPDP(InputStream is) { Response response = null; HttpURLConnection connection = null; try { // // Open up the connection // connection = (HttpURLConnection) this.restURL.openConnection(); connection.setRequestProperty("Content-Type", "application/json"); // // Setup our method and headers // connection.setRequestMethod("POST"); connection.setUseCaches(false); // // Adding this in. It seems the HttpUrlConnection class does NOT // properly forward our headers for POST re-direction. It does so // for a GET re-direction. // // So we need to handle this ourselves. // connection.setInstanceFollowRedirects(false); connection.setDoOutput(true); connection.setDoInput(true); // // Send the request // try (OutputStream os = connection.getOutputStream()) { IOUtils.copy(is, os); } // // Do the connect // connection.connect(); if (connection.getResponseCode() == 200) { // // Read the response // ContentType contentType = null; try { contentType = ContentType.parse(connection.getContentType()); if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) { response = JSONResponse.load(connection.getInputStream()); } else if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType()) || contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) { response = DOMResponse.load(connection.getInputStream()); } else { logger.error("unknown content-type: " + contentType); } } catch (Exception e) { String message = "Parsing Content-Type: " + connection.getContentType() + ", error=" + e.getMessage(); logger.error(message, e); } } else { logger.error(connection.getResponseCode() + " " + connection.getResponseMessage()); } } catch (Exception e) { logger.error(e); } return response; }
From source file:com.hp.mqm.client.MqmRestClientImpl.java
private ByteArrayEntity createGZipEntity(InputStream inputStream) { try {//from ww w.java 2 s .co m ByteArrayOutputStream arr = new ByteArrayOutputStream(); OutputStream zipper = new GZIPOutputStream(arr); byte[] buffer = new byte[1024]; int len; while ((len = inputStream.read(buffer)) > 0) { zipper.write(buffer, 0, len); } try { inputStream.close(); } catch (IOException ioe) { logger.warning("failed to close silently input stream of tests result"); } try { zipper.close(); } catch (IOException ioe) { logger.warning("failed to close silently zip stream of tests result"); } return new ByteArrayEntity(arr.toByteArray(), ContentType.APPLICATION_XML); } catch (IOException ex) { throw new RequestErrorException("Failed to create GZip entity.", ex); } }
From source file:org.activiti.designer.eclipse.navigator.cloudrepo.ActivitiCloudEditorUtil.java
public static JsonNode importModel(String filename, byte[] content, boolean firstTry) { JsonNode modelNode = null;//from w w w . j av a2 s. c o m CloseableHttpClient client = getAuthenticatedClient(); try { HttpPost post = new HttpPost(PreferencesUtil.getStringPreference(Preferences.ACTIVITI_CLOUD_EDITOR_URL) + "/rest/app/rest/import-process-model"); HttpEntity entity = MultipartEntityBuilder.create() .addBinaryBody("file", content, ContentType.APPLICATION_XML, filename).build(); post.setEntity(entity); CloseableHttpResponse response = client.execute(post); try { int statusCode = response.getStatusLine().getStatusCode(); InputStream responseContent = response.getEntity().getContent(); if (statusCode >= 200 && statusCode < 300) { modelNode = objectMapper.readTree(responseContent); } else if (statusCode == 401 && firstTry) { String cookieString = PreferencesUtil .getStringPreference(Preferences.ACTIVITI_CLOUD_EDITOR_COOKIE); if (StringUtils.isNotEmpty(cookieString)) { PreferencesUtil.getActivitiDesignerPreferenceStore() .setValue(Preferences.ACTIVITI_CLOUD_EDITOR_COOKIE.getPreferenceId(), ""); InstanceScope.INSTANCE.getNode(ActivitiPlugin.PLUGIN_ID).flush(); return importModel(filename, content, false); } } else { JsonNode exceptionNode = null; String exceptionString = IOUtils.toString(responseContent); try { exceptionNode = objectMapper.readTree(exceptionString); } catch (Exception e) { throw new ActivitiCloudEditorException(exceptionString); } throw new ActivitiCloudEditorException(exceptionNode); } } finally { response.close(); } } catch (ActivitiCloudEditorException e) { throw e; } catch (Exception e) { Logger.logError("Error importing process model", e); } finally { try { client.close(); } catch (Exception e) { } } return modelNode; }