use of org.apache.http.entity.ContentType in project feign by OpenFeign.
the class ApacheHttpClient method toHttpUriRequest.
HttpUriRequest toHttpUriRequest(Request request, Request.Options options) throws UnsupportedEncodingException, MalformedURLException, URISyntaxException {
RequestBuilder requestBuilder = RequestBuilder.create(request.method());
//per request timeouts
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(options.connectTimeoutMillis()).setSocketTimeout(options.readTimeoutMillis()).build();
requestBuilder.setConfig(requestConfig);
URI uri = new URIBuilder(request.url()).build();
requestBuilder.setUri(uri.getScheme() + "://" + uri.getAuthority() + uri.getRawPath());
//request query params
List<NameValuePair> queryParams = URLEncodedUtils.parse(uri, requestBuilder.getCharset().name());
for (NameValuePair queryParam : queryParams) {
requestBuilder.addParameter(queryParam);
}
//request headers
boolean hasAcceptHeader = false;
for (Map.Entry<String, Collection<String>> headerEntry : request.headers().entrySet()) {
String headerName = headerEntry.getKey();
if (headerName.equalsIgnoreCase(ACCEPT_HEADER_NAME)) {
hasAcceptHeader = true;
}
if (headerName.equalsIgnoreCase(Util.CONTENT_LENGTH)) {
// doesn't like us to set it as well.
continue;
}
for (String headerValue : headerEntry.getValue()) {
requestBuilder.addHeader(headerName, headerValue);
}
}
//some servers choke on the default accept string, so we'll set it to anything
if (!hasAcceptHeader) {
requestBuilder.addHeader(ACCEPT_HEADER_NAME, "*/*");
}
//request body
if (request.body() != null) {
HttpEntity entity = null;
if (request.charset() != null) {
ContentType contentType = getContentType(request);
String content = new String(request.body(), request.charset());
entity = new StringEntity(content, contentType);
} else {
entity = new ByteArrayEntity(request.body());
}
requestBuilder.setEntity(entity);
}
return requestBuilder.build();
}
use of org.apache.http.entity.ContentType in project libresonic by Libresonic.
the class PodcastService method getCoverArtSuffix.
private String getCoverArtSuffix(HttpResponse response) {
String result = null;
Header contentTypeHeader = response.getEntity().getContentType();
if (contentTypeHeader != null && contentTypeHeader.getValue() != null) {
ContentType contentType = ContentType.parse(contentTypeHeader.getValue());
String mimeType = contentType.getMimeType();
result = StringUtil.getSuffix(mimeType);
}
return result == null ? "jpeg" : result;
}
use of org.apache.http.entity.ContentType in project camel by apache.
the class Olingo2AppImpl method parseResponse.
private Olingo2BatchResponse parseResponse(Edm edm, Map<String, String> contentIdLocationMap, Olingo2BatchRequest request, BatchSingleResponse response) throws EntityProviderException, ODataApplicationException {
// validate HTTP status
final int statusCode = Integer.parseInt(response.getStatusCode());
final String statusInfo = response.getStatusInfo();
final BasicHttpResponse httpResponse = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, statusCode, statusInfo));
final Map<String, String> headers = response.getHeaders();
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpResponse.setHeader(entry.getKey(), entry.getValue());
}
ByteArrayInputStream content = null;
try {
if (response.getBody() != null) {
final ContentType partContentType = receiveWithCharsetParameter(ContentType.parse(headers.get(HttpHeaders.CONTENT_TYPE)), Consts.UTF_8);
final String charset = partContentType.getCharset().toString();
final String body = response.getBody();
content = body != null ? new ByteArrayInputStream(body.getBytes(charset)) : null;
httpResponse.setEntity(new StringEntity(body, charset));
}
AbstractFutureCallback.checkStatus(httpResponse);
} catch (ODataApplicationException e) {
return new Olingo2BatchResponse(statusCode, statusInfo, response.getContentId(), response.getHeaders(), e);
} catch (UnsupportedEncodingException e) {
return new Olingo2BatchResponse(statusCode, statusInfo, response.getContentId(), response.getHeaders(), e);
}
// resolve resource path and query params and parse batch part uri
final String resourcePath = request.getResourcePath();
final String resolvedResourcePath;
if (resourcePath.startsWith("$") && !(METADATA.equals(resourcePath) || BATCH.equals(resourcePath))) {
resolvedResourcePath = findLocation(resourcePath, contentIdLocationMap);
} else {
final String resourceLocation = response.getHeader(HttpHeaders.LOCATION);
resolvedResourcePath = resourceLocation != null ? resourceLocation.substring(serviceUri.length()) : resourcePath;
}
final Map<String, String> resolvedQueryParams = request instanceof Olingo2BatchQueryRequest ? ((Olingo2BatchQueryRequest) request).getQueryParams() : null;
final UriInfoWithType uriInfo = parseUri(edm, resolvedResourcePath, resolvedQueryParams);
// resolve response content
final Object resolvedContent = content != null ? readContent(uriInfo, content) : null;
return new Olingo2BatchResponse(statusCode, statusInfo, response.getContentId(), response.getHeaders(), resolvedContent);
}
use of org.apache.http.entity.ContentType in project camel by apache.
the class Olingo2AppImpl method writeContent.
private <T> void writeContent(final Edm edm, HttpEntityEnclosingRequestBase httpEntityRequest, final UriInfoWithType uriInfo, final Object content, final Olingo2ResponseHandler<T> responseHandler) {
try {
// 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);
}
}
use of org.apache.http.entity.ContentType in project stanbol by apache.
the class ContentItemWriter method writeTo.
@Override
public void writeTo(ContentItem ci, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
//(0) handle default dataType
Map<String, Object> reqProp = ContentItemHelper.getRequestPropertiesContentPart(ci);
boolean omitMetadata = isOmitMetadata(reqProp);
if (!MULTIPART.isCompatible(mediaType)) {
//two possible cases
if (!omitMetadata) {
// (1) just return the RDF data
//(1.a) Backward support for default dataType if no Accept header is set
StringBuilder ctb = new StringBuilder();
if (mediaType.isWildcardType() || TEXT_PLAIN_TYPE.isCompatible(mediaType) || APPLICATION_OCTET_STREAM_TYPE.isCompatible(mediaType)) {
ctb.append(APPLICATION_LD_JSON);
} else {
ctb.append(mediaType.getType()).append('/').append(mediaType.getSubtype());
}
ctb.append(";charset=").append(UTF8.name());
String contentType = ctb.toString();
httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, contentType);
try {
serializer.serialize(entityStream, ci.getMetadata(), contentType);
} catch (UnsupportedSerializationFormatException e) {
throw new WebApplicationException("The enhancement results " + "cannot be serialized in the requested media type: " + mediaType.toString(), Response.Status.NOT_ACCEPTABLE);
}
} else {
// (2) return a single content part
Entry<IRI, Blob> contentPart = getBlob(ci, Collections.singleton(mediaType.toString()));
if (contentPart == null) {
//no alternate content with the requeste media type
throw new WebApplicationException("The requested enhancement chain has not created an " + "version of the parsed content in the reuqest media type " + mediaType.toString(), Response.Status.UNSUPPORTED_MEDIA_TYPE);
} else {
//found -> stream the content to the client
//NOTE: This assumes that the presence of a charset
// implies reading/writing character streams
String requestedCharset = mediaType.getParameters().get("charset");
String blobCharset = contentPart.getValue().getParameter().get("charset");
Charset readerCharset = blobCharset == null ? UTF8 : Charset.forName(blobCharset);
Charset writerCharset = requestedCharset == null ? null : Charset.forName(requestedCharset);
if (writerCharset != null && !writerCharset.equals(readerCharset)) {
//we need to transcode
Reader reader = new InputStreamReader(contentPart.getValue().getStream(), readerCharset);
Writer writer = new OutputStreamWriter(entityStream, writerCharset);
IOUtils.copy(reader, writer);
IOUtils.closeQuietly(reader);
} else {
//no transcoding
if (requestedCharset == null && blobCharset != null) {
httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, mediaType.toString() + "; charset=" + blobCharset);
}
InputStream in = contentPart.getValue().getStream();
IOUtils.copy(in, entityStream);
IOUtils.closeQuietly(in);
}
}
}
} else {
// multipart mime requested!
final String charsetName = mediaType.getParameters().get("charset");
final Charset charset = charsetName != null ? Charset.forName(charsetName) : UTF8;
MediaType rdfFormat;
String rdfFormatString = getRdfFormat(reqProp);
if (rdfFormatString == null || rdfFormatString.isEmpty()) {
rdfFormat = DEFAULT_RDF_FORMAT;
} else {
try {
rdfFormat = MediaType.valueOf(rdfFormatString);
if (rdfFormat.getParameters().get("charset") == null) {
//use the charset of the default RDF format
rdfFormat = new MediaType(rdfFormat.getType(), rdfFormat.getSubtype(), DEFAULT_RDF_FORMAT.getParameters());
}
} catch (IllegalArgumentException e) {
throw new WebApplicationException("The specified RDF format '" + rdfFormatString + "' (used to serialize all RDF parts of " + "multipart MIME responses) is not a well formated MIME type", Response.Status.BAD_REQUEST);
}
}
//(1) setting the correct header
String contentType = String.format("%s/%s; charset=%s; boundary=%s", mediaType.getType(), mediaType.getSubtype(), charset.toString(), CONTENT_ITEM_BOUNDARY);
httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, contentType);
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setBoundary(CONTENT_ITEM_BOUNDARY);
//(2) serialising the metadata
if (!isOmitMetadata(reqProp)) {
entityBuilder.addPart("metadata", new ClerezzaContentBody(ci.getUri().getUnicodeString(), ci.getMetadata(), rdfFormat));
// entity.addBodyPart(new FormBodyPart("metadata", new ClerezzaContentBody(
// ci.getUri().getUnicodeString(), ci.getMetadata(),
// rdfFormat)));
}
//(3) serialising the Content (Bloby)
//(3.a) Filter based on parameter
List<Entry<IRI, Blob>> includedBlobs = filterBlobs(ci, reqProp);
//(3.b) Serialise the filtered
if (!includedBlobs.isEmpty()) {
Map<String, ContentBody> contentParts = new LinkedHashMap<String, ContentBody>();
for (Entry<IRI, Blob> entry : includedBlobs) {
Blob blob = entry.getValue();
ContentType ct = ContentType.create(blob.getMimeType());
String cs = blob.getParameter().get("charset");
if (StringUtils.isNotBlank(cs)) {
ct = ct.withCharset(cs);
}
contentParts.put(entry.getKey().getUnicodeString(), new InputStreamBody(blob.getStream(), ct));
}
//add all the blobs
entityBuilder.addPart("content", new MultipartContentBody(contentParts, CONTENT_PARTS_BOUNDERY, MULTIPART_ALTERNATE));
}
//else no content to include
Set<String> includeContentParts = getIncludedContentPartURIs(reqProp);
if (includeContentParts != null) {
//(4) serialise the Request Properties
if (includeContentParts.isEmpty() || includeContentParts.contains(REQUEST_PROPERTIES_URI.getUnicodeString())) {
JSONObject object;
try {
object = toJson(reqProp);
} catch (JSONException e) {
String message = "Unable to convert Request Properties " + "to JSON (values : " + reqProp + ")!";
log.error(message, e);
throw new WebApplicationException(message, Response.Status.INTERNAL_SERVER_ERROR);
}
entityBuilder.addTextBody(REQUEST_PROPERTIES_URI.getUnicodeString(), object.toString(), ContentType.APPLICATION_JSON.withCharset(UTF8));
}
//(5) additional RDF metadata stored in contentParts
for (Entry<IRI, Graph> entry : getContentParts(ci, Graph.class).entrySet()) {
if (includeContentParts.isEmpty() || includeContentParts.contains(entry.getKey())) {
entityBuilder.addPart(entry.getKey().getUnicodeString(), new //no file name
ClerezzaContentBody(//no file name
null, entry.getValue(), rdfFormat));
}
// else ignore this content part
}
}
entityBuilder.build().writeTo(entityStream);
}
}
Aggregations