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.camel.component.olingo2.api.impl.Olingo2AppImpl.java
@Override public void setContentType(String contentType) { this.contentType = ContentType.parse(contentType); }
From source file:com.github.avarabyeu.restendpoint.http.HttpClientRestEndpoint.java
@Override public final <RS> Will<Response<RS>> post(String resource, MultiPartRequest request, Class<RS> clazz) throws RestEndpointIOException { HttpPost post = new HttpPost(spliceUrl(resource)); try {/*from w ww .ja v a2 s . com*/ MultipartEntityBuilder builder = MultipartEntityBuilder.create(); for (MultiPartRequest.MultiPartSerialized<?> serializedPart : request.getSerializedRQs()) { Serializer serializer = getSupportedSerializer(serializedPart); builder.addPart(serializedPart.getPartName(), new StringBody(new String(serializer.serialize(serializedPart.getRequest())), ContentType.parse(serializer.getMimeType()))); } for (MultiPartRequest.MultiPartBinary partBinaty : request.getBinaryRQs()) { builder.addPart(partBinaty.getPartName(), new ByteArrayBody(partBinaty.getData().read(), ContentType.parse(partBinaty.getContentType()), partBinaty.getFilename())); } /* Here is some dirty hack to avoid problem with MultipartEntity and asynchronous http client * Details can be found here: http://comments.gmane.org/gmane.comp.apache.httpclient.user/2426 * * The main idea is to replace MultipartEntity with NByteArrayEntity once first * doesn't support #getContent method * which is required for async client implementation. So, we are copying response * body as byte array to NByteArrayEntity to * leave it unmodified. * * Alse we need to add boundary value to content type header. Details are here: * http://en.wikipedia.org/wiki/Delimiter#Content_boundary * MultipartEntity generates correct header by yourself, but we need to put it * manually once we replaced entity type to NByteArrayEntity */ String boundary = "-------------" + UUID.randomUUID().toString(); builder.setBoundary(boundary); ByteArrayOutputStream baos = new ByteArrayOutputStream(); builder.build().writeTo(baos); post.setEntity(new NByteArrayEntity(baos.toByteArray(), ContentType.MULTIPART_FORM_DATA)); post.setHeader("Content-Type", "multipart/form-data;boundary=" + boundary); } catch (Exception e) { throw new RestEndpointIOException("Unable to build post multipart request", e); } return executeInternal(post, new ClassConverterCallback<RS>(serializers, clazz)); }
From source file:net.simondieterle.wns.server.Sender.java
/** * Asynchronously send a message with a context to be passed in the future result. * * @param message The message to send.//from w ww .j av a 2 s.c om * @param requestContext An opaque context to include the future result. * @return The future. */ public ListenableFuture<Result> send(final String url, final Message message, final Object requestContext) { if (accessToken == null) { System.out.println("sucks!!!!!!!!!!!!"); return null; } // not yet able to send return executor.getFutureWithRetry(new RetryCallable<ListenableFuture<Result>>() { @Override public ListenableFuture<Result> call(RetryContext context) throws Exception { SettableFuture<Result> future = SettableFuture.create(); HttpPost request = new HttpPost(url); request.setHeader("Authorization", "Bearer " + accessToken.access_token); request.setHeader("X-WNS-Type", message.getType().toString()); if (message.getCachePolicy() != null) request.setHeader("X-WNS-Cache-Policy", message.getCachePolicy().toString()); if (message.getRequestForStatus() != null) request.setHeader("X-WNS-RequestForStatus", message.getRequestForStatus().toString()); if (message.getTag() != null) request.setHeader("X-WNS-Tag", message.getTag().toString()); if (message.getTtl() != null) request.setHeader("X-WNS-TTL", message.getTtl().toString()); if (message.getSuppressPopup() != null) request.setHeader("X-WNS-SuppressPopup", message.getSuppressPopup().toString()); if (message.getGroup() != null) request.setHeader("X-WNS-Group", message.getGroup().toString()); if (message.getMatch() != null) request.setHeader("X-WNS-Match", message.getMatch().toString()); // set appropriate content types StringEntity entity; if (message.getType() == Message.Type.RAW) { entity = new StringEntity(message.serialize(), ContentType.parse("application/octet-stream")); } else { entity = new StringEntity(message.serialize(), ContentType.parse("text/xml")); } request.setEntity(entity); client.execute(request, new ResponseHandler(future, requestContext)); return future; } }); }
From source file:org.apache.hadoop.gateway.dispatch.DefaultDispatch.java
protected HttpEntity createRequestEntity(HttpServletRequest request) throws IOException { String contentType = request.getContentType(); int contentLength = request.getContentLength(); InputStream contentStream = request.getInputStream(); HttpEntity entity;//from w w w . ja v a 2 s. c o m if (contentType == null) { entity = new InputStreamEntity(contentStream, contentLength); } else { entity = new InputStreamEntity(contentStream, contentLength, ContentType.parse(contentType)); } GatewayConfig config = (GatewayConfig) request.getServletContext() .getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE); if (config != null && config.isHadoopKerberosSecured()) { //Check if delegation token is supplied in the request boolean delegationTokenPresent = false; String queryString = request.getQueryString(); if (queryString != null) { delegationTokenPresent = queryString.startsWith("delegation=") || queryString.contains("&delegation="); } if (replayBufferSize < 0) { replayBufferSize = config.getHttpServerRequestBuffer(); } if (!delegationTokenPresent && replayBufferSize > 0) { entity = new PartiallyRepeatableHttpEntity(entity, replayBufferSize); } } return entity; }
From source file:org.apache.sling.etcd.client.impl.EtcdClientImplTest.java
@Test public void testPutRequestFormat() throws Exception { HttpServlet servlet = new HttpServlet() { @Override/* ww w .j a v a2 s. com*/ 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.putKey("/post/test", "test-data", Collections.singletonMap("ttl", "10")); Assert.assertNotNull(response); Assert.assertTrue(response.isAction()); }
From source file:org.apache.hadoop.gateway.dispatch.HttpClientDispatch.java
protected HttpEntity createRequestEntity(HttpServletRequest request) throws IOException { String contentType = request.getContentType(); int contentLength = request.getContentLength(); InputStream contentStream = request.getInputStream(); HttpEntity entity;//from w w w . j a v a 2s . c om if (contentType == null) { entity = new InputStreamEntity(contentStream, contentLength); } else { entity = new InputStreamEntity(contentStream, contentLength, ContentType.parse(contentType)); } if ("true".equals(System.getProperty(GatewayConfig.HADOOP_KERBEROS_SECURED))) { //Check if delegation token is supplied in the request boolean delegationTokenPresent = false; String queryString = request.getQueryString(); if (queryString != null) { delegationTokenPresent = queryString.startsWith("delegation=") || queryString.contains("&delegation="); } if (!delegationTokenPresent && getReplayBufferSize() > 0) { entity = new CappedBufferHttpEntity(entity, getReplayBufferSize() * 1024); } } return entity; }
From source file:eu.scape_project.fcrepo.integration.IntellectualEntitiesIT.java
@Test public void testIngestAndRetrieveIntellectualEntityCollection() throws Exception { IntellectualEntity ie1 = TestUtil.createTestEntity("entity-8"); this.postEntity(ie1); IntellectualEntity ie2 = TestUtil.createTestEntity("entity-9"); this.postEntity(ie2); /* check the desc metadata of the entity */ HttpPost post = new HttpPost(SCAPE_URL + "/entity-list"); String uriList = FEDORA_URL + "/scape/entity/entity-8\n" + FEDORA_URL + "scape/entity/entity-9"; post.setEntity(new StringEntity(uriList, ContentType.parse("text/uri-list"))); HttpResponse resp = this.client.execute(post); assertEquals(200, resp.getStatusLine().getStatusCode()); IntellectualEntityCollection coll = this.marshaller.deserialize(IntellectualEntityCollection.class, resp.getEntity().getContent()); post.releaseConnection();/*from w ww . j av a 2 s.c o m*/ assertEquals(2, coll.getEntities().size()); }
From source file:com.digitalpebble.storm.crawler.bolt.JSoupParserBolt.java
private String getContentCharset(byte[] content, Metadata metadata) { String charset = null;/*from ww w . jav a2 s. c o m*/ // check if the server specified a charset String specifiedContentType = metadata.getFirstValue(HttpHeaders.CONTENT_TYPE); try { if (specifiedContentType != null) { ContentType parsedContentType = ContentType.parse(specifiedContentType); charset = parsedContentType.getCharset().name(); } } catch (Exception e) { charset = null; } // filter HTML tags CharsetDetector detector = new CharsetDetector(); detector.enableInputFilter(true); // give it a hint detector.setDeclaredEncoding(charset); detector.setText(content); try { CharsetMatch charsetMatch = detector.detect(); if (charsetMatch != null) { charset = charsetMatch.getName(); } } catch (Exception e) { // ignore and leave the charset as-is } return charset; }
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 . j a va2 s. 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); }
From source file:com.mirth.connect.connectors.http.HttpMessageConverter.java
/** * This method takes in a ContentType and returns an equivalent ContentType, only overriding the * charset. This is needed because ContentType.withCharset(charset) does not correctly handle * headers with multiple parameters. Parsing a ContentType from a String works, calling * toString() to get the correct header value works, but there's no way from ContentType itself * to update a specific parameter in-place. *///from ww w . j a v a 2 s .c om public static ContentType setCharset(ContentType contentType, Charset charset) throws ParseException, UnsupportedCharsetException { // Get the correct header value String contentTypeString = contentType.toString(); // Parse the header manually the same way ContentType does it CharArrayBuffer buffer = new CharArrayBuffer(contentTypeString.length()); buffer.append(contentTypeString); ParserCursor cursor = new ParserCursor(0, contentTypeString.length()); HeaderElement[] elements = BasicHeaderValueParser.INSTANCE.parseElements(buffer, cursor); if (ArrayUtils.isNotEmpty(elements)) { String mimeType = elements[0].getName(); NameValuePair[] params = elements[0].getParameters(); List<NameValuePair> paramsList = new ArrayList<NameValuePair>(); boolean charsetFound = false; // Iterate through each parameter and override the charset if present if (ArrayUtils.isNotEmpty(params)) { for (NameValuePair nvp : params) { if (nvp.getName().equalsIgnoreCase("charset")) { charsetFound = true; nvp = new BasicNameValuePair(nvp.getName(), charset.name()); } paramsList.add(nvp); } } // Add the charset at the end if it wasn't found before if (!charsetFound) { paramsList.add(new BasicNameValuePair("charset", charset.name())); } // Format the header the same way ContentType does it CharArrayBuffer newBuffer = new CharArrayBuffer(64); newBuffer.append(mimeType); newBuffer.append("; "); BasicHeaderValueFormatter.INSTANCE.formatParameters(newBuffer, paramsList.toArray(new NameValuePair[paramsList.size()]), false); // Once we have the correct string, let ContentType do the rest return ContentType.parse(newBuffer.toString()); } else { throw new ParseException("Invalid content type: " + contentTypeString); } }