List of usage examples for org.apache.http.entity ContentType getMimeType
public String getMimeType()
From source file:com.mirth.connect.connectors.http.HttpReceiver.java
@Override public boolean isBinaryContentType(ContentType contentType) { String mimeType = contentType.getMimeType(); if (connectorProperties.isBinaryMimeTypesRegex()) { return binaryMimeTypesRegex.matcher(mimeType).matches(); } else {// w w w.j a va 2 s . c om return StringUtils.startsWithAny(mimeType, binaryMimeTypesArray); } }
From source file:com.serphacker.serposcope.scraper.http.ScrapClient.java
public Charset getDetectedCharset() { ContentType contentType = null; try {/* w w w . j a v a 2 s .c o m*/ contentType = ContentType.get(response.getEntity()); } catch (Exception ex) { } Charset charset = null; if (contentType != null) { try { charset = contentType.getCharset(); } catch (final Exception ex) { } if (charset == null) { if (contentType.getMimeType().contains("text/html")) { charset = detectCharsetFromHtmlMeta(); } } } return charset; }
From source file:org.apache.camel.component.olingo2.api.impl.Olingo2AppImpl.java
private ContentType receiveWithCharsetParameter(ContentType contentType, Charset charset) { if (contentType.getCharset() != null) { return contentType; }/*from w w w.j av a 2s. c om*/ final String mimeType = contentType.getMimeType(); if (mimeType.equals(ContentType.TEXT_PLAIN.getMimeType()) || AbstractFutureCallback.ODATA_MIME_TYPE.matcher(mimeType).matches()) { return contentType.withCharset(charset); } return contentType; }
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 a2 s . c om*/ * @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:org.apache.camel.component.olingo2.api.impl.Olingo2AppImpl.java
/** * public for unit test, not to be used otherwise *//*w w w .ja va2 s. c o m*/ public void execute(HttpUriRequest httpUriRequest, ContentType contentType, FutureCallback<HttpResponse> callback) { // add accept header when its not a form or multipart final String contentTypeString = contentType.toString(); if (!ContentType.APPLICATION_FORM_URLENCODED.getMimeType().equals(contentType.getMimeType()) && !contentType.getMimeType().startsWith(MULTIPART_MIME_TYPE)) { // otherwise accept what is being sent httpUriRequest.addHeader(HttpHeaders.ACCEPT, contentTypeString); } // is something being sent? if (httpUriRequest instanceof HttpEntityEnclosingRequestBase && httpUriRequest.getFirstHeader(HttpHeaders.CONTENT_TYPE) == null) { httpUriRequest.addHeader(HttpHeaders.CONTENT_TYPE, contentTypeString); } // set user specified custom headers if (httpHeaders != null && !httpHeaders.isEmpty()) { for (Map.Entry<String, String> entry : httpHeaders.entrySet()) { httpUriRequest.setHeader(entry.getKey(), entry.getValue()); } } // add client protocol version if not specified if (!httpUriRequest.containsHeader(ODataHttpHeaders.DATASERVICEVERSION)) { httpUriRequest.addHeader(ODataHttpHeaders.DATASERVICEVERSION, ODataServiceVersion.V20); } if (!httpUriRequest.containsHeader(MAX_DATA_SERVICE_VERSION)) { httpUriRequest.addHeader(MAX_DATA_SERVICE_VERSION, ODataServiceVersion.V30); } // execute request client.execute(httpUriRequest, callback); }
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 .java 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.adobe.aem.demo.communities.Loader.java
private static String doThumbnail(String hostname, String port, String adminPassword, String csvfile, String filename) {/*from w w w .j ava 2 s. co m*/ String pathToFile = "/content/dam/communities/resource-thumbnails/" + filename; File attachment = new File(csvfile.substring(0, csvfile.indexOf(".csv")) + File.separator + filename); ContentType ct = ContentType.MULTIPART_FORM_DATA; if (filename.indexOf(".mp4") > 0) { ct = ContentType.create("video/mp4", MIME.UTF8_CHARSET); } else if (filename.indexOf(".jpg") > 0 || filename.indexOf(".jpeg") > 0) { ct = ContentType.create("image/jpeg", MIME.UTF8_CHARSET); } else if (filename.indexOf(".png") > 0) { ct = ContentType.create("image/png", MIME.UTF8_CHARSET); } MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setCharset(MIME.UTF8_CHARSET); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addBinaryBody("file", attachment, ct, attachment.getName()); builder.addTextBody("fileName", filename, ContentType.create("text/plain", MIME.UTF8_CHARSET)); logger.debug( "Adding file for thumbnails with name: " + attachment.getName() + " and type: " + ct.getMimeType()); Loader.doPost(hostname, port, pathToFile, "admin", adminPassword, builder.build(), null); logger.debug("Path to thumbnail: " + pathToFile); return pathToFile + "/file"; }
From source file:com.mirth.connect.connectors.http.HttpDispatcher.java
@Override public Response send(ConnectorProperties connectorProperties, ConnectorMessage connectorMessage) { HttpDispatcherProperties httpDispatcherProperties = (HttpDispatcherProperties) connectorProperties; eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(), getDestinationName(), ConnectionStatusEventType.WRITING)); String responseData = null;/*from w ww .ja v a 2s . c o m*/ String responseError = null; String responseStatusMessage = null; Status responseStatus = Status.QUEUED; boolean validateResponse = false; CloseableHttpClient client = null; HttpRequestBase httpMethod = null; CloseableHttpResponse httpResponse = null; File tempFile = null; int socketTimeout = NumberUtils.toInt(httpDispatcherProperties.getSocketTimeout(), 30000); try { configuration.configureDispatcher(this, httpDispatcherProperties); long dispatcherId = getDispatcherId(); client = clients.get(dispatcherId); if (client == null) { BasicHttpClientConnectionManager httpClientConnectionManager = new BasicHttpClientConnectionManager( socketFactoryRegistry.build()); httpClientConnectionManager .setSocketConfig(SocketConfig.custom().setSoTimeout(socketTimeout).build()); HttpClientBuilder clientBuilder = HttpClients.custom() .setConnectionManager(httpClientConnectionManager); HttpUtil.configureClientBuilder(clientBuilder); if (httpDispatcherProperties.isUseProxyServer()) { clientBuilder.setRoutePlanner(new DynamicProxyRoutePlanner()); } client = clientBuilder.build(); clients.put(dispatcherId, client); } URI hostURI = new URI(httpDispatcherProperties.getHost()); String host = hostURI.getHost(); String scheme = hostURI.getScheme(); int port = hostURI.getPort(); if (port == -1) { if (scheme.equalsIgnoreCase("https")) { port = 443; } else { port = 80; } } // Parse the content type field first, and then add the charset if needed ContentType contentType = ContentType.parse(httpDispatcherProperties.getContentType()); Charset charset = null; if (contentType.getCharset() == null) { charset = Charset.forName(CharsetUtils.getEncoding(httpDispatcherProperties.getCharset())); } else { charset = contentType.getCharset(); } if (httpDispatcherProperties.isMultipart()) { tempFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp"); } HttpHost target = new HttpHost(host, port, scheme); httpMethod = buildHttpRequest(hostURI, httpDispatcherProperties, connectorMessage, tempFile, contentType, charset); HttpClientContext context = HttpClientContext.create(); // authentication if (httpDispatcherProperties.isUseAuthentication()) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM); Credentials credentials = new UsernamePasswordCredentials(httpDispatcherProperties.getUsername(), httpDispatcherProperties.getPassword()); credsProvider.setCredentials(authScope, credentials); AuthCache authCache = new BasicAuthCache(); RegistryBuilder<AuthSchemeProvider> registryBuilder = RegistryBuilder.<AuthSchemeProvider>create(); if (AuthSchemes.DIGEST.equalsIgnoreCase(httpDispatcherProperties.getAuthenticationType())) { logger.debug("using Digest authentication"); registryBuilder.register(AuthSchemes.DIGEST, new DigestSchemeFactory(charset)); if (httpDispatcherProperties.isUsePreemptiveAuthentication()) { processDigestChallenge(authCache, target, credentials, httpMethod, context); } } else { logger.debug("using Basic authentication"); registryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory(charset)); if (httpDispatcherProperties.isUsePreemptiveAuthentication()) { authCache.put(target, new BasicScheme()); } } context.setCredentialsProvider(credsProvider); context.setAuthSchemeRegistry(registryBuilder.build()); context.setAuthCache(authCache); logger.debug("using authentication with credentials: " + credentials); } RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(socketTimeout) .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true).build(); context.setRequestConfig(requestConfig); // Set proxy information if (httpDispatcherProperties.isUseProxyServer()) { context.setAttribute(PROXY_CONTEXT_KEY, new HttpHost(httpDispatcherProperties.getProxyAddress(), Integer.parseInt(httpDispatcherProperties.getProxyPort()))); } // execute the method logger.debug( "executing method: type=" + httpMethod.getMethod() + ", uri=" + httpMethod.getURI().toString()); httpResponse = client.execute(target, httpMethod, context); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); logger.debug("received status code: " + statusCode); Map<String, List<String>> headers = new HashMap<String, List<String>>(); for (Header header : httpResponse.getAllHeaders()) { List<String> list = headers.get(header.getName()); if (list == null) { list = new ArrayList<String>(); headers.put(header.getName(), list); } list.add(header.getValue()); } connectorMessage.getConnectorMap().put("responseStatusLine", statusLine.toString()); connectorMessage.getConnectorMap().put("responseHeaders", new MessageHeaders(new CaseInsensitiveMap(headers))); ContentType responseContentType = ContentType.get(httpResponse.getEntity()); if (responseContentType == null) { responseContentType = ContentType.TEXT_PLAIN; } Charset responseCharset = charset; if (responseContentType.getCharset() != null) { responseCharset = responseContentType.getCharset(); } final String responseBinaryMimeTypes = httpDispatcherProperties.getResponseBinaryMimeTypes(); BinaryContentTypeResolver binaryContentTypeResolver = new BinaryContentTypeResolver() { @Override public boolean isBinaryContentType(ContentType contentType) { return HttpDispatcher.this.isBinaryContentType(responseBinaryMimeTypes, contentType); } }; /* * First parse out the body of the HTTP response. Depending on the connector settings, * this could end up being a string encoded with the response charset, a byte array * representing the raw response payload, or a MimeMultipart object. */ Object responseBody = ""; // The entity could be null in certain cases such as 204 responses if (httpResponse.getEntity() != null) { // Only parse multipart if XML Body is selected and Parse Multipart is enabled if (httpDispatcherProperties.isResponseXmlBody() && httpDispatcherProperties.isResponseParseMultipart() && responseContentType.getMimeType().startsWith(FileUploadBase.MULTIPART)) { responseBody = new MimeMultipart(new ByteArrayDataSource(httpResponse.getEntity().getContent(), responseContentType.toString())); } else if (binaryContentTypeResolver.isBinaryContentType(responseContentType)) { responseBody = IOUtils.toByteArray(httpResponse.getEntity().getContent()); } else { responseBody = IOUtils.toString(httpResponse.getEntity().getContent(), responseCharset); } } /* * Now that we have the response body, we need to create the actual Response message * data. Depending on the connector settings this could be our custom serialized XML, a * Base64 string encoded from the raw response payload, or a string encoded from the * payload with the request charset. */ if (httpDispatcherProperties.isResponseXmlBody()) { responseData = HttpMessageConverter.httpResponseToXml(statusLine.toString(), headers, responseBody, responseContentType, httpDispatcherProperties.isResponseParseMultipart(), httpDispatcherProperties.isResponseIncludeMetadata(), binaryContentTypeResolver); } else if (responseBody instanceof byte[]) { responseData = new String(Base64Util.encodeBase64((byte[]) responseBody), "US-ASCII"); } else { responseData = (String) responseBody; } validateResponse = httpDispatcherProperties.getDestinationConnectorProperties().isValidateResponse(); if (statusCode < HttpStatus.SC_BAD_REQUEST) { responseStatus = Status.SENT; } else { eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(), connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(), connectorProperties.getName(), "Received error response from HTTP server.", null)); responseStatusMessage = ErrorMessageBuilder .buildErrorResponse("Received error response from HTTP server.", null); responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(), responseData, null); } } catch (Exception e) { eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(), connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(), connectorProperties.getName(), "Error connecting to HTTP server.", e)); responseStatusMessage = ErrorMessageBuilder.buildErrorResponse("Error connecting to HTTP server", e); responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(), "Error connecting to HTTP server", e); } finally { try { HttpClientUtils.closeQuietly(httpResponse); // Delete temp files if we created them if (tempFile != null) { tempFile.delete(); tempFile = null; } } finally { eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(), getDestinationName(), ConnectionStatusEventType.IDLE)); } } return new Response(responseStatus, responseData, responseStatusMessage, responseError, validateResponse); }