List of usage examples for org.apache.http.entity ContentType parse
public static ContentType parse(String str) throws ParseException, UnsupportedCharsetException
From source file:org.apache.sling.etcd.client.impl.EtcdClientImplTest.java
@Test public void testPostRequestFormat() throws Exception { HttpServlet servlet = new HttpServlet() { @Override//from w w w .j av a2 s .co m protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { ContentType contentType = ContentType.parse(req.getContentType()); if (!contentType.getMimeType().equals(EtcdClientImpl.FORM_URLENCODED.getMimeType())) { throw new IllegalArgumentException("wrong mime type"); } if (!contentType.getCharset().equals(EtcdClientImpl.FORM_URLENCODED.getCharset())) { throw new IllegalArgumentException("wrong content charset"); } String value = req.getParameter("value"); if (value == null) { throw new IllegalArgumentException("missing value parameter"); } String ttl = req.getParameter("ttl"); if (!"10".equals(ttl)) { throw new IllegalArgumentException("missing ttl parameter"); } res.setStatus(201); res.getWriter().write(IOUtils.toString(getClass().getResourceAsStream("/action-3.json"))); } }; server1 = startServer(servlet, "/v2/keys/post/test"); buildEtcdClient(serverPort(server1)); KeyResponse response = etcdClient.postKey("/post/test", "test-data", Collections.singletonMap("ttl", "10")); Assert.assertNotNull(response); Assert.assertTrue(response.isAction()); }
From source file:de.tudarmstadt.ukp.shibhttpclient.ShibHttpClient.java
/** * Checks whether the HttpResponse is a SAML SOAP message * @param res the HttpResponse to check//from w w w . j a v a 2s .c o m * @return true if the HttpResponse is a SAML SOAP message, false if not */ protected boolean isSamlSoapResponse(HttpResponse res) { boolean isSamlSoap = false; if (res.getFirstHeader(HttpHeaders.CONTENT_TYPE) != null) { ContentType contentType = ContentType.parse(res.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue()); isSamlSoap = MIME_TYPE_PAOS.equals(contentType.getMimeType()); } return isSamlSoap; }
From source file:org.apache.camel.component.olingo2.api.impl.Olingo2AppImpl.java
private <T> void writeContent(final Edm edm, HttpEntityEnclosingRequestBase httpEntityRequest, final UriInfoWithType uriInfo, final Object content, final Olingo2ResponseHandler<T> responseHandler) { try {//from w w w . j av a2 s . c o m // process resource by UriType final ODataResponse response = writeContent(edm, uriInfo, content); // copy all response headers for (String header : response.getHeaderNames()) { httpEntityRequest.setHeader(header, response.getHeader(header)); } // get (http) entity which is for default Olingo2 implementation an InputStream if (response.getEntity() instanceof InputStream) { httpEntityRequest.setEntity(new InputStreamEntity((InputStream) response.getEntity())); /* // avoid sending it without a header field set if (!httpEntityRequest.containsHeader(HttpHeaders.CONTENT_TYPE)) { httpEntityRequest.addHeader(HttpHeaders.CONTENT_TYPE, getContentType()); } */ } // execute HTTP request final Header requestContentTypeHeader = httpEntityRequest.getFirstHeader(HttpHeaders.CONTENT_TYPE); final ContentType requestContentType = requestContentTypeHeader != null ? ContentType.parse(requestContentTypeHeader.getValue()) : contentType; execute(httpEntityRequest, requestContentType, new AbstractFutureCallback<T>(responseHandler) { @SuppressWarnings("unchecked") @Override public void onCompleted(HttpResponse result) throws IOException, EntityProviderException, BatchException, ODataApplicationException { // if a entity is created (via POST request) the response body contains the new created entity HttpStatusCodes statusCode = HttpStatusCodes .fromStatusCode(result.getStatusLine().getStatusCode()); // look for no content, or no response body!!! final boolean noEntity = result.getEntity() == null || result.getEntity().getContentLength() == 0; if (statusCode == HttpStatusCodes.NO_CONTENT || noEntity) { responseHandler.onResponse( (T) HttpStatusCodes.fromStatusCode(result.getStatusLine().getStatusCode())); } else { switch (uriInfo.getUriType()) { case URI9: // $batch final List<BatchSingleResponse> singleResponses = EntityProvider.parseBatchResponse( result.getEntity().getContent(), result.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue()); // parse batch response bodies final List<Olingo2BatchResponse> responses = new ArrayList<Olingo2BatchResponse>(); Map<String, String> contentIdLocationMap = new HashMap<String, String>(); final List<Olingo2BatchRequest> batchRequests = (List<Olingo2BatchRequest>) content; final Iterator<Olingo2BatchRequest> iterator = batchRequests.iterator(); for (BatchSingleResponse response : singleResponses) { final Olingo2BatchRequest request = iterator.next(); if (request instanceof Olingo2BatchChangeRequest && ((Olingo2BatchChangeRequest) request).getContentId() != null) { contentIdLocationMap.put( "$" + ((Olingo2BatchChangeRequest) request).getContentId(), response.getHeader(HttpHeaders.LOCATION)); } try { responses.add(parseResponse(edm, contentIdLocationMap, request, response)); } catch (Exception e) { // report any parsing errors as error response responses.add(new Olingo2BatchResponse( Integer.parseInt(response.getStatusCode()), response.getStatusInfo(), response.getContentId(), response.getHeaders(), new ODataApplicationException( "Error parsing response for " + request + ": " + e.getMessage(), Locale.ENGLISH, e))); } } responseHandler.onResponse((T) responses); break; case URI4: case URI5: // simple property // get the response content as Object for $value or Map<String, Object> otherwise final List<EdmProperty> simplePropertyPath = uriInfo.getPropertyPath(); final EdmProperty simpleProperty = simplePropertyPath .get(simplePropertyPath.size() - 1); if (uriInfo.isValue()) { responseHandler.onResponse((T) EntityProvider.readPropertyValue(simpleProperty, result.getEntity().getContent())); } else { responseHandler.onResponse((T) EntityProvider.readProperty(getContentType(), simpleProperty, result.getEntity().getContent(), EntityProviderReadProperties.init().build())); } break; case URI3: // complex property // get the response content as Map<String, Object> final List<EdmProperty> complexPropertyPath = uriInfo.getPropertyPath(); final EdmProperty complexProperty = complexPropertyPath .get(complexPropertyPath.size() - 1); responseHandler.onResponse((T) EntityProvider.readProperty(getContentType(), complexProperty, result.getEntity().getContent(), EntityProviderReadProperties.init().build())); break; case URI7A: // $links with 0..1 cardinality property // get the response content as String final EdmEntitySet targetLinkEntitySet = uriInfo.getTargetEntitySet(); responseHandler.onResponse((T) EntityProvider.readLink(getContentType(), targetLinkEntitySet, result.getEntity().getContent())); break; case URI7B: // $links with * cardinality property // get the response content as java.util.List<String> final EdmEntitySet targetLinksEntitySet = uriInfo.getTargetEntitySet(); responseHandler.onResponse((T) EntityProvider.readLinks(getContentType(), targetLinksEntitySet, result.getEntity().getContent())); break; case URI1: case URI2: case URI6A: case URI6B: // Entity // get the response content as an ODataEntry object responseHandler.onResponse((T) EntityProvider.readEntry(response.getContentHeader(), uriInfo.getTargetEntitySet(), result.getEntity().getContent(), EntityProviderReadProperties.init().build())); break; default: throw new ODataApplicationException( "Unsupported resource type " + uriInfo.getTargetType(), Locale.ENGLISH); } } } }); } catch (ODataException e) { responseHandler.onException(e); } catch (URISyntaxException e) { responseHandler.onException(e); } catch (UnsupportedEncodingException e) { responseHandler.onException(e); } catch (IOException e) { responseHandler.onException(e); } }
From source file:com.basistech.rosette.api.HttpRosetteAPI.java
private void setupMultipartRequest(final Request request, final ObjectWriter finalWriter, HttpPost post) throws IOException { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMimeSubtype("mixed"); builder.setMode(HttpMultipartMode.STRICT); FormBodyPartBuilder partBuilder = FormBodyPartBuilder.create("request", // Make sure we're not mislead by someone who puts a charset into the mime type. new AbstractContentBody(ContentType.parse(ContentType.APPLICATION_JSON.getMimeType())) { @Override/*from w w w . j a va 2 s. com*/ public String getFilename() { return null; } @Override public void writeTo(OutputStream out) throws IOException { finalWriter.writeValue(out, request); } @Override public String getTransferEncoding() { return MIME.ENC_BINARY; } @Override public long getContentLength() { return -1; } }); // Either one of 'name=' or 'Content-ID' would be enough. partBuilder.setField(MIME.CONTENT_DISPOSITION, "inline;name=\"request\""); partBuilder.setField("Content-ID", "request"); builder.addPart(partBuilder.build()); AbstractContentBody insBody; if (request instanceof DocumentRequest) { DocumentRequest docReq = (DocumentRequest) request; insBody = new InputStreamBody(docReq.getContentBytes(), ContentType.parse(docReq.getContentType())); } else if (request instanceof AdmRequest) { //TODO: smile? AdmRequest admReq = (AdmRequest) request; ObjectWriter writer = mapper.writer().without(JsonGenerator.Feature.AUTO_CLOSE_TARGET); byte[] json = writer.writeValueAsBytes(admReq.getText()); insBody = new ByteArrayBody(json, ContentType.parse(AdmRequest.ADM_CONTENT_TYPE), null); } else { throw new UnsupportedOperationException("Unsupported request type for multipart processing"); } partBuilder = FormBodyPartBuilder.create("content", insBody); partBuilder.setField(MIME.CONTENT_DISPOSITION, "inline;name=\"content\""); partBuilder.setField("Content-ID", "content"); builder.addPart(partBuilder.build()); builder.setCharset(StandardCharsets.UTF_8); HttpEntity entity = builder.build(); post.setEntity(entity); }
From source file:com.nkang.kxmoment.util.SolrUtils.HttpSolrServer.java
public NamedList<Object> request(final SolrRequest request, final ResponseParser processor) throws SolrServerException, IOException { HttpRequestBase method = null;// w w w . j a v a2 s . c om InputStream is = null; SolrParams params = request.getParams(); Collection<ContentStream> streams = requestWriter.getContentStreams(request); String path = requestWriter.getPath(request); if (path == null || !path.startsWith("/")) { path = DEFAULT_PATH; } ResponseParser parser = request.getResponseParser(); if (parser == null) { parser = this.parser; } // The parser 'wt=' and 'version=' params are used instead of the original // params ModifiableSolrParams wparams = new ModifiableSolrParams(params); if (parser != null) { wparams.set(CommonParams.WT, parser.getWriterType()); wparams.set(CommonParams.VERSION, parser.getVersion()); } if (invariantParams != null) { wparams.add(invariantParams); } int tries = maxRetries + 1; try { while (tries-- > 0) { // Note: since we aren't do intermittent time keeping // ourselves, the potential non-timeout latency could be as // much as tries-times (plus scheduling effects) the given // timeAllowed. try { if (SolrRequest.METHOD.GET == request.getMethod()) { if (streams != null) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!"); } method = new HttpGet(baseUrl + path + ClientUtils.toQueryString(wparams, false)); } else if (SolrRequest.METHOD.POST == request.getMethod()) { String url = baseUrl + path; boolean hasNullStreamName = false; if (streams != null) { for (ContentStream cs : streams) { if (cs.getName() == null) { hasNullStreamName = true; break; } } } boolean isMultipart = (this.useMultiPartPost || (streams != null && streams.size() > 1)) && !hasNullStreamName; // only send this list of params as query string params ModifiableSolrParams queryParams = new ModifiableSolrParams(); for (String param : this.queryParams) { String[] value = wparams.getParams(param); if (value != null) { for (String v : value) { queryParams.add(param, v); } wparams.remove(param); } } LinkedList<NameValuePair> postParams = new LinkedList<NameValuePair>(); if (streams == null || isMultipart) { HttpPost post = new HttpPost(url + ClientUtils.toQueryString(queryParams, false)); post.setHeader("Content-Charset", "UTF-8"); if (!isMultipart) { post.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); } List<FormBodyPart> parts = new LinkedList<FormBodyPart>(); Iterator<String> iter = wparams.getParameterNamesIterator(); while (iter.hasNext()) { String p = iter.next(); String[] vals = wparams.getParams(p); if (vals != null) { for (String v : vals) { if (isMultipart) { parts.add(new FormBodyPart(p, new StringBody(v, Charset.forName("UTF-8")))); } else { postParams.add(new BasicNameValuePair(p, v)); } } } } if (isMultipart && streams != null) { for (ContentStream content : streams) { String contentType = content.getContentType(); if (contentType == null) { contentType = BinaryResponseParser.BINARY_CONTENT_TYPE; // default } String name = content.getName(); if (name == null) { name = ""; } parts.add(new FormBodyPart(name, new InputStreamBody(content.getStream(), contentType, content.getName()))); } } if (parts.size() > 0) { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT); for (FormBodyPart p : parts) { entity.addPart(p); } post.setEntity(entity); } else { //not using multipart post.setEntity(new UrlEncodedFormEntity(postParams, "UTF-8")); } method = post; } // It is has one stream, it is the post body, put the params in the URL else { String pstr = ClientUtils.toQueryString(wparams, false); HttpPost post = new HttpPost(url + pstr); // Single stream as body // Using a loop just to get the first one final ContentStream[] contentStream = new ContentStream[1]; for (ContentStream content : streams) { contentStream[0] = content; break; } if (contentStream[0] instanceof RequestWriter.LazyContentStream) { post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) { @Override public Header getContentType() { return new BasicHeader("Content-Type", contentStream[0].getContentType()); } @Override public boolean isRepeatable() { return false; } }); } else { post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) { @Override public Header getContentType() { return new BasicHeader("Content-Type", contentStream[0].getContentType()); } @Override public boolean isRepeatable() { return false; } }); } method = post; } } else { throw new SolrServerException("Unsupported method: " + request.getMethod()); } } catch (NoHttpResponseException r) { method = null; if (is != null) { is.close(); } // If out of tries then just rethrow (as normal error). if (tries < 1) { throw r; } } } } catch (IOException ex) { throw new SolrServerException("error reading streams", ex); } // client already has this set, is this needed method.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, followRedirects); method.addHeader("User-Agent", AGENT); // add jauth information //String username = WebServiceLoaderUtils.getWebServiceProperty(Constants.SECURITY_USERNAME).toString(); //String password = WebServiceLoaderUtils.getWebServiceProperty(Constants.SECURITY_PASSWORD).toString(); ResourceBundle bundle = ResourceBundle.getBundle("solrconfig"); String username; String password; username = bundle.getString("wsUsername.url"); password = bundle.getString("wsPassword.url"); method.addHeader("username", username); method.addHeader("password", password); InputStream respBody = null; boolean shouldClose = true; boolean success = false; try { // Execute the method. final HttpResponse response = httpClient.execute(method); int httpStatus = response.getStatusLine().getStatusCode(); // Read the contents respBody = response.getEntity().getContent(); Header ctHeader = response.getLastHeader("content-type"); String contentType; if (ctHeader != null) { contentType = ctHeader.getValue(); } else { contentType = ""; } // handle some http level checks before trying to parse the response switch (httpStatus) { case HttpStatus.SC_OK: case HttpStatus.SC_BAD_REQUEST: case HttpStatus.SC_CONFLICT: // 409 break; case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_MOVED_TEMPORARILY: if (!followRedirects) { throw new SolrServerException( "Server at " + getBaseURL() + " sent back a redirect (" + httpStatus + ")."); } break; default: if (processor == null) { throw new RemoteSolrException(httpStatus, "Server at " + getBaseURL() + " returned non ok status:" + httpStatus + ", message:" + response.getStatusLine().getReasonPhrase(), null); } } if (processor == null) { // no processor specified, return raw stream NamedList<Object> rsp = new NamedList<Object>(); rsp.add("stream", respBody); // Only case where stream should not be closed shouldClose = false; success = true; return rsp; } String procCt = processor.getContentType(); if (procCt != null) { String procMimeType = ContentType.parse(procCt).getMimeType().trim().toLowerCase(Locale.ROOT); String mimeType = ContentType.parse(contentType).getMimeType().trim().toLowerCase(Locale.ROOT); if (!procMimeType.equals(mimeType)) { // unexpected mime type String msg = "Expected mime type " + procMimeType + " but got " + mimeType + "."; Header encodingHeader = response.getEntity().getContentEncoding(); String encoding; if (encodingHeader != null) { encoding = encodingHeader.getValue(); } else { encoding = "UTF-8"; // try UTF-8 } try { msg = msg + " " + IOUtils.toString(respBody, encoding); } catch (IOException e) { throw new RemoteSolrException(httpStatus, "Could not parse response with encoding " + encoding, e); } RemoteSolrException e = new RemoteSolrException(httpStatus, msg, null); throw e; } } // if(true) { // ByteArrayOutputStream copy = new ByteArrayOutputStream(); // IOUtils.copy(respBody, copy); // String val = new String(copy.toByteArray()); // System.out.println(">RESPONSE>"+val+"<"+val.length()); // respBody = new ByteArrayInputStream(copy.toByteArray()); // } NamedList<Object> rsp = null; String charset = EntityUtils.getContentCharSet(response.getEntity()); try { rsp = processor.processResponse(respBody, charset); } catch (Exception e) { throw new RemoteSolrException(httpStatus, e.getMessage(), e); } if (httpStatus != HttpStatus.SC_OK) { String reason = null; try { NamedList<?> err = (NamedList<?>) rsp.get("error"); if (err != null) { reason = (String) err.get("msg"); // TODO? get the trace? } } catch (Exception ex) { } if (reason == null) { StringBuilder msg = new StringBuilder(); msg.append(response.getStatusLine().getReasonPhrase()); msg.append("\n\n"); msg.append("request: " + method.getURI()); reason = java.net.URLDecoder.decode(msg.toString(), UTF_8); } throw new RemoteSolrException(httpStatus, reason, null); } success = true; return rsp; } catch (ConnectException e) { throw new SolrServerException("Server refused connection at: " + getBaseURL(), e); } catch (SocketTimeoutException e) { throw new SolrServerException("Timeout occured while waiting response from server at: " + getBaseURL(), e); } catch (IOException e) { throw new SolrServerException("IOException occured when talking to server at: " + getBaseURL(), e); } finally { if (respBody != null && shouldClose) { try { respBody.close(); } catch (IOException e) { //log.error("", e); } finally { if (!success) { method.abort(); } } } } }
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 ww w . ja va 2 s . c o m @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.mirth.connect.connectors.http.HttpReceiver.java
private void sendResponse(Request baseRequest, HttpServletResponse servletResponse, DispatchResult dispatchResult) throws Exception { ContentType contentType = ContentType .parse(replaceValues(connectorProperties.getResponseContentType(), dispatchResult)); if (!connectorProperties.isResponseDataTypeBinary() && contentType.getCharset() == null) { /*/*from ww w . ja v a2 s . c o m*/ * If text mode is used and a specific charset isn't already defined, use the one from * the connector properties. We can't use ContentType.withCharset here because it * doesn't preserve other parameters, like boundary definitions */ contentType = ContentType.parse(contentType.toString() + "; charset=" + CharsetUtils.getEncoding(connectorProperties.getCharset())); } servletResponse.setContentType(contentType.toString()); // set the response headers for (Entry<String, List<String>> entry : connectorProperties.getResponseHeaders().entrySet()) { for (String headerValue : entry.getValue()) { servletResponse.addHeader(entry.getKey(), replaceValues(headerValue, dispatchResult)); } } // set the status code int statusCode = NumberUtils .toInt(replaceValues(connectorProperties.getResponseStatusCode(), dispatchResult), -1); /* * set the response body and status code (if we choose a response from the drop-down) */ if (dispatchResult != null && dispatchResult.getSelectedResponse() != null) { dispatchResult.setAttemptedResponse(true); Response selectedResponse = dispatchResult.getSelectedResponse(); Status newMessageStatus = selectedResponse.getStatus(); /* * If the status code is custom, use the entered/replaced string If is is not a * variable, use the status of the destination's response (success = 200, failure = 500) * Otherwise, return 200 */ if (statusCode != -1) { servletResponse.setStatus(statusCode); } else if (newMessageStatus != null && newMessageStatus.equals(Status.ERROR)) { servletResponse.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); } else { servletResponse.setStatus(HttpStatus.SC_OK); } String message = selectedResponse.getMessage(); if (message != null) { OutputStream responseOutputStream = servletResponse.getOutputStream(); byte[] responseBytes; if (connectorProperties.isResponseDataTypeBinary()) { responseBytes = Base64Util.decodeBase64(message.getBytes("US-ASCII")); } else { responseBytes = message.getBytes(CharsetUtils.getEncoding(connectorProperties.getCharset())); } // If the client accepts GZIP compression, compress the content boolean gzipResponse = false; for (Enumeration<String> en = baseRequest.getHeaders("Accept-Encoding"); en.hasMoreElements();) { String acceptEncoding = en.nextElement(); if (acceptEncoding != null && acceptEncoding.contains("gzip")) { gzipResponse = true; break; } } if (gzipResponse) { servletResponse.setHeader(HTTP.CONTENT_ENCODING, "gzip"); GZIPOutputStream gzipOutputStream = new GZIPOutputStream(responseOutputStream); gzipOutputStream.write(responseBytes); gzipOutputStream.finish(); } else { responseOutputStream.write(responseBytes); } // TODO include full HTTP payload in sentResponse } } else { /* * If the status code is custom, use the entered/replaced string Otherwise, return 200 */ if (statusCode != -1) { servletResponse.setStatus(statusCode); } else { servletResponse.setStatus(HttpStatus.SC_OK); } } }
From source file:sk.datalan.solr.impl.HttpSolrServer.java
protected NamedList<Object> executeMethod(HttpRequestBase method, final ResponseParser processor) throws SolrServerException { // // XXX client already has this set, is this needed? // method.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, // followRedirects); method.addHeader("User-Agent", AGENT); InputStream respBody = null;/*ww w .ja v a 2 s .c om*/ boolean shouldClose = true; boolean success = false; try { // Execute the method. final HttpResponse response = httpClient.execute(method); int httpStatus = response.getStatusLine().getStatusCode(); // Read the contents respBody = response.getEntity().getContent(); Header ctHeader = response.getLastHeader("content-type"); String contentType; if (ctHeader != null) { contentType = ctHeader.getValue(); } else { contentType = ""; } // handle some http level checks before trying to parse the response switch (httpStatus) { case HttpStatus.SC_OK: case HttpStatus.SC_BAD_REQUEST: case HttpStatus.SC_CONFLICT: // 409 break; case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_MOVED_TEMPORARILY: if (!followRedirects) { throw new SolrServerException( "Server at " + getBaseURL() + " sent back a redirect (" + httpStatus + ")."); } break; default: if (processor == null) { throw new RemoteSolrException(httpStatus, "Server at " + getBaseURL() + " returned non ok status:" + httpStatus + ", message:" + response.getStatusLine().getReasonPhrase(), null); } } if (processor == null) { // no processor specified, return raw stream NamedList<Object> rsp = new NamedList<>(); rsp.add("stream", respBody); // Only case where stream should not be closed shouldClose = false; success = true; return rsp; } String procCt = processor.getContentType(); if (procCt != null) { String procMimeType = ContentType.parse(procCt).getMimeType().trim().toLowerCase(Locale.ROOT); String mimeType = ContentType.parse(contentType).getMimeType().trim().toLowerCase(Locale.ROOT); if (!procMimeType.equals(mimeType)) { // unexpected mime type String msg = "Expected mime type " + procMimeType + " but got " + mimeType + "."; Header encodingHeader = response.getEntity().getContentEncoding(); String encoding; if (encodingHeader != null) { encoding = encodingHeader.getValue(); } else { encoding = "UTF-8"; // try UTF-8 } try { msg = msg + " " + IOUtils.toString(respBody, encoding); } catch (IOException e) { throw new RemoteSolrException(httpStatus, "Could not parse response with encoding " + encoding, e); } RemoteSolrException e = new RemoteSolrException(httpStatus, msg, null); throw e; } } // if(true) { // ByteArrayOutputStream copy = new ByteArrayOutputStream(); // IOUtils.copy(respBody, copy); // String val = new String(copy.toByteArray()); // System.out.println(">RESPONSE>"+val+"<"+val.length()); // respBody = new ByteArrayInputStream(copy.toByteArray()); // } NamedList<Object> rsp = null; ContentType ct = ContentType.getOrDefault(response.getEntity()); try { rsp = processor.processResponse(respBody, ct.getCharset().toString()); } catch (Exception e) { throw new RemoteSolrException(httpStatus, e.getMessage(), e); } if (httpStatus != HttpStatus.SC_OK) { String reason = null; try { NamedList err = (NamedList) rsp.get("error"); if (err != null) { reason = (String) err.get("msg"); if (reason == null) { reason = (String) err.get("trace"); } } } catch (Exception ex) { } if (reason == null) { StringBuilder msg = new StringBuilder(); msg.append(response.getStatusLine().getReasonPhrase()); msg.append("\n\n"); msg.append("request: ").append(method.getURI()); reason = java.net.URLDecoder.decode(msg.toString(), UTF_8); } throw new RemoteSolrException(httpStatus, reason, null); } success = true; return rsp; } catch (ConnectException e) { throw new SolrServerException("Server refused connection at: " + getBaseURL(), e); } catch (SocketTimeoutException e) { throw new SolrServerException("Timeout occured while waiting response from server at: " + getBaseURL(), e); } catch (IOException e) { throw new SolrServerException("IOException occured when talking to server at: " + getBaseURL(), e); } finally { if (respBody != null && shouldClose) { try { respBody.close(); } catch (IOException e) { log.error("", e); } finally { if (!success) { method.abort(); } } } } }