List of usage examples for org.apache.http.entity ContentType toString
public String toString()
From source file:com.kolich.aws.services.s3.impl.KolichS3Client.java
@Override public Either<HttpFailure, PutObjectResult> putObject(final String bucketName, final boolean rrs, final ContentType type, final InputStream input, final long contentLength, final String... path) { return new AwsS3HttpClosure<PutObjectResult>(client_, SC_OK, bucketName) { @Override//from w w w . ja v a2 s . com public void validate() throws Exception { checkNotNull(bucketName, "Bucket name cannot be null."); checkState(isValidBucketName(bucketName), "Invalid bucket name, " + "did not match expected bucket name pattern."); } @Override public void prepare(final AwsHttpRequest request) throws Exception { final HttpRequestBase base = request.getRequestBase(); if (rrs) { base.setHeader(STORAGE_CLASS, S3_REDUCED_REDUNDANCY); } // Although InputStreamEntity lets you specify a Content-Type, // we're intentionally forcing the issue here. It seems that // setting the content type on the request through a vanilla // InputStreamEntity does not actually do the right thing. if (type != null) { base.setHeader(CONTENT_TYPE, type.toString()); } ((HttpPut) base).setEntity(new InputStreamEntity(input, contentLength)); } @Override public PutObjectResult success(final HttpSuccess success) throws Exception { final PutObjectResult result = new PutObjectResult(); result.setETag(success.getETag()); result.setVersionId(success.getFirstHeader(S3_VERSION_ID)); return result; } }.put(path); }
From source file:edu.lternet.pasta.client.DataPackageManagerClient.java
/** * Executes the 'readDataEntityNames' web service method. * //from www . java2 s . c o m * @param scope * the scope value, e.g. "knb-lter-lno" * @param identifier * the identifier value, e.g. 10 * @param revision * the revision value, e.g. "1" * * @return a list of data entity identifiers and their corresponding entity names, * one entity per line with id and name separated by a comma. Note that * many entity names themselves contain commas, so when parsing the return * value, split the string only up to the first occurrence of a comma. */ public String readDataEntityNames(String scope, Integer identifier, String revision) throws Exception { CloseableHttpClient httpClient = HttpClientBuilder.create().build(); String urlTail = makeUrlTail(scope, identifier.toString(), revision, null); String url = BASE_URL + "/name/eml" + urlTail; HttpGet httpGet = new HttpGet(url); String entityString = null; // Set header content if (this.token != null) { httpGet.setHeader("Cookie", "auth-token=" + this.token); } try { HttpResponse httpResponse = httpClient.execute(httpGet); int statusCode = httpResponse.getStatusLine().getStatusCode(); HttpEntity httpEntity = httpResponse.getEntity(); entityString = EntityUtils.toString(httpEntity); ContentType contentType = ContentType.getOrDefault(httpEntity); this.contentType = contentType.toString(); if (statusCode != HttpStatus.SC_OK) { handleStatusCode(statusCode, entityString); } } finally { closeHttpClient(httpClient); } return entityString; }
From source file:edu.lternet.pasta.client.DataPackageManagerClient.java
/** * Executes the 'readDataEntitySizes' web service method. * //from w w w.ja v a 2 s . com * @param scope * the scope value, e.g. "knb-lter-lno" * @param identifier * the identifier value, e.g. 10 * @param revision * the revision value, e.g. "1" * * @return a list of data entities and their corresponding entity sizes in bytes */ public String readDataEntitySizes(String scope, Integer identifier, String revision) throws Exception { CloseableHttpClient httpClient = HttpClientBuilder.create().build(); String urlTail = makeUrlTail(scope, identifier.toString(), revision, null); String url = BASE_URL + "/data/size/eml" + urlTail; HttpGet httpGet = new HttpGet(url); String entityString = null; // Set header content if (this.token != null) { httpGet.setHeader("Cookie", "auth-token=" + this.token); } try { HttpResponse httpResponse = httpClient.execute(httpGet); int statusCode = httpResponse.getStatusLine().getStatusCode(); HttpEntity httpEntity = httpResponse.getEntity(); entityString = EntityUtils.toString(httpEntity); ContentType contentType = ContentType.getOrDefault(httpEntity); this.contentType = contentType.toString(); if (statusCode != HttpStatus.SC_OK) { handleStatusCode(statusCode, entityString); } } finally { closeHttpClient(httpClient); } return entityString; }
From source file:edu.lternet.pasta.client.DataPackageManagerClient.java
/** * Executes the 'readDataEntityName' web service method. * //from w w w . ja va2s .c om * @param scope * the scope value, e.g. "knb-lter-lno" * @param identifier * the identifier value, e.g. 10 * @param revision * the revision value, e.g. "1" * @param entityId * the entity identifier string, e.g. "NoneSuchBugCount" * @return the data entity name * @see <a target="top" * href="http://package.lternet.edu/package/docs/api">Data Package * Manager web service API</a> */ public String readDataEntityName(String scope, Integer identifier, String revision, String entityId) throws Exception { // Re-encode "%" to its character reference value of %25 to mitigate // an issue with the HttpGet call that performs the decoding - this is // a kludge to deal with encoding nonsense. entityId = entityId.replace("%", "%25"); CloseableHttpClient httpClient = HttpClientBuilder.create().build(); String urlTail = makeUrlTail(scope, identifier.toString(), revision, entityId); String url = BASE_URL + "/name/eml" + urlTail; HttpGet httpGet = new HttpGet(url); String entityString = null; // Set header content if (this.token != null) { httpGet.setHeader("Cookie", "auth-token=" + this.token); } try { HttpResponse httpResponse = httpClient.execute(httpGet); int statusCode = httpResponse.getStatusLine().getStatusCode(); HttpEntity httpEntity = httpResponse.getEntity(); entityString = EntityUtils.toString(httpEntity); ContentType contentType = ContentType.getOrDefault(httpEntity); this.contentType = contentType.toString(); if (statusCode != HttpStatus.SC_OK) { handleStatusCode(statusCode, entityString); } } finally { closeHttpClient(httpClient); } return entityString; }
From source file:edu.lternet.pasta.client.DataPackageManagerClient.java
/** * Executes the 'readDataEntitySize' web service method. * /* w ww.ja va 2 s .co m*/ * @param scope * the scope value, e.g. "knb-lter-lno" * @param identifier * the identifier value, e.g. 10 * @param revision * the revision value, e.g. "1" * @param entityId * the entity identifier string, e.g. "NoneSuchBugCount" * @return the size of the data entity resource in bytes * @see <a target="top" * href="http://package.lternet.edu/package/docs/api">Data Package * Manager web service API</a> */ public Long readDataEntitySize(String scope, Integer identifier, String revision, String entityId) throws Exception { // Re-encode "%" to its character reference value of %25 to mitigate // an issue with the HttpGet call that performs the decoding - this is // a kludge to deal with encoding nonsense. entityId = entityId.replace("%", "%25"); CloseableHttpClient httpClient = HttpClientBuilder.create().build(); String urlTail = makeUrlTail(scope, identifier.toString(), revision, entityId); String url = BASE_URL + "/data/size/eml" + urlTail; HttpGet httpGet = new HttpGet(url); Long entitySize = null; // Set header content if (this.token != null) { httpGet.setHeader("Cookie", "auth-token=" + this.token); } try { HttpResponse httpResponse = httpClient.execute(httpGet); int statusCode = httpResponse.getStatusLine().getStatusCode(); HttpEntity httpEntity = httpResponse.getEntity(); String entityString = EntityUtils.toString(httpEntity); if (entityString != null) { try { entitySize = new Long(entityString); } catch (NumberFormatException e) { logger.error("Unable to determine entity size of entity: " + entityId); } } ContentType contentType = ContentType.getOrDefault(httpEntity); this.contentType = contentType.toString(); if (statusCode != HttpStatus.SC_OK) { handleStatusCode(statusCode, entityString); } } finally { closeHttpClient(httpClient); } return entitySize; }
From source file:fr.ippon.wip.http.hc.TransformerResponseInterceptor.java
/** * If httpResponse must be transformed, creates an instance of * WIPTransformer, executes WIPTransformer#transform on the response content * and updates the response entity accordingly. * /*from w ww . j av a 2s .c o m*/ * @param httpResponse * @param context * @throws HttpException * @throws IOException */ public void process(HttpResponse httpResponse, HttpContext context) throws HttpException, IOException { PortletRequest portletRequest = HttpClientResourceManager.getInstance().getCurrentPortletRequest(); PortletResponse portletResponse = HttpClientResourceManager.getInstance().getCurrentPortletResponse(); WIPConfiguration config = WIPUtil.getConfiguration(portletRequest); RequestBuilder request = HttpClientResourceManager.getInstance().getCurrentRequest(); if (httpResponse == null) { // No response -> no transformation LOG.warning("No response to transform."); return; } HttpEntity entity = httpResponse.getEntity(); if (entity == null) { // No entity -> no transformation return; } ContentType contentType = ContentType.getOrDefault(entity); String mimeType = contentType.getMimeType(); String actualURL; RedirectLocations redirectLocations = (RedirectLocations) context .getAttribute("http.protocol.redirect-locations"); if (redirectLocations != null) actualURL = Iterables.getLast(redirectLocations.getAll()).toString(); else if (context.getAttribute(CachingHttpClient.CACHE_RESPONSE_STATUS) == CacheResponseStatus.CACHE_HIT) { actualURL = request.getRequestedURL(); } else { HttpRequest actualRequest = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost actualHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); actualURL = actualHost.toURI() + actualRequest.getRequestLine().getUri(); } // Check if actual URI must be transformed if (!config.isProxyURI(actualURL)) return; // a builder for creating a WIPTransformer instance TransformerBuilder transformerBuilder = new TransformerBuilder().setActualURL(actualURL) .setMimeType(mimeType).setPortletRequest(portletRequest).setPortletResponse(portletResponse) .setResourceType(request.getResourceType()).setXmlReaderPool(xmlReaderPool); // Creates an instance of Transformer depending on ResourceType and // MimeType int status = transformerBuilder.build(); if (status == TransformerBuilder.STATUS_NO_TRANSFORMATION) return; WIPTransformer transformer = transformerBuilder.getTransformer(); // Call WIPTransformer#transform method and update the response Entity // object try { String content = EntityUtils.toString(entity); String transformedContent = ((AbstractTransformer) transformer).transform(content); StringEntity transformedEntity; if (contentType.getCharset() != null) { transformedEntity = new StringEntity(transformedContent, contentType); } else { transformedEntity = new StringEntity(transformedContent); } transformedEntity.setContentType(contentType.toString()); httpResponse.setEntity(transformedEntity); } catch (SAXException e) { LOG.log(Level.SEVERE, "Could not transform HTML", e); throw new IllegalArgumentException(e); } catch (TransformerException e) { LOG.log(Level.SEVERE, "Could not transform HTML", e); throw new IllegalArgumentException(e); } }
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 w w . java 2 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.joyent.manta.client.MantaClient.java
/** * Copies the supplied {@link String} to a remote Manta object at the specified * path using the supplied {@link Charset}. * * @param path The fully qualified path of the object. i.e. /user/stor/foo/bar/baz * @param string string to copy//from ww w .ja v a 2s .com * @param charset character set to encode string as * @return Manta response object * @throws IOException when there is a problem sending the object over the network */ public MantaObjectResponse put(final String path, final String string, final Charset charset) throws IOException { ContentType contentType = ContentType.TEXT_PLAIN.withCharset(charset); MantaHttpHeaders headers = new MantaHttpHeaders(); headers.setContentType(contentType.toString()); return put(path, string, headers, null); }