Search in sources :

Example 11 with ContentType

use of org.apache.http.entity.ContentType in project uPortal by Jasig.

the class PortletResourceResponseContextImpl method handleResourceHeader.

/**
     * Handles resource response specific headers. Returns true if the header was consumed by this
     * method and requires no further processing
     *
     * @return
     */
protected boolean handleResourceHeader(String key, String value) {
    if (ResourceResponse.HTTP_STATUS_CODE.equals(key)) {
        this.portletResourceOutputHandler.setStatus(Integer.parseInt(value));
        return true;
    }
    if ("Content-Type".equals(key)) {
        final ContentType contentType = ContentType.parse(value);
        final Charset charset = contentType.getCharset();
        if (charset != null) {
            this.portletResourceOutputHandler.setCharacterEncoding(charset.name());
        }
        this.portletResourceOutputHandler.setContentType(contentType.getMimeType());
        return true;
    }
    if ("Content-Length".equals(key)) {
        this.portletResourceOutputHandler.setContentLength(Integer.parseInt(value));
        return true;
    }
    if ("Content-Language".equals(key)) {
        final HeaderElement[] parts = BasicHeaderValueParser.parseElements(value, null);
        if (parts.length > 0) {
            final String localeStr = parts[0].getValue();
            final Locale locale = LocaleUtils.toLocale(localeStr);
            this.portletResourceOutputHandler.setLocale(locale);
            return true;
        }
    }
    return false;
}
Also used : Locale(java.util.Locale) ContentType(org.apache.http.entity.ContentType) HeaderElement(org.apache.http.HeaderElement) Charset(java.nio.charset.Charset)

Example 12 with ContentType

use of org.apache.http.entity.ContentType in project elasticsearch by elastic.

the class RequestLogger method buildTraceResponse.

/**
     * Creates curl output for given response
     */
static String buildTraceResponse(HttpResponse httpResponse) throws IOException {
    String responseLine = "# " + httpResponse.getStatusLine().toString();
    for (Header header : httpResponse.getAllHeaders()) {
        responseLine += "\n# " + header.getName() + ": " + header.getValue();
    }
    responseLine += "\n#";
    HttpEntity entity = httpResponse.getEntity();
    if (entity != null) {
        if (entity.isRepeatable() == false) {
            entity = new BufferedHttpEntity(entity);
        }
        httpResponse.setEntity(entity);
        ContentType contentType = ContentType.get(entity);
        Charset charset = StandardCharsets.UTF_8;
        if (contentType != null && contentType.getCharset() != null) {
            charset = contentType.getCharset();
        }
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), charset))) {
            String line;
            while ((line = reader.readLine()) != null) {
                responseLine += "\n# " + line;
            }
        }
    }
    return responseLine;
}
Also used : Header(org.apache.http.Header) HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) ContentType(org.apache.http.entity.ContentType) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) Charset(java.nio.charset.Charset)

Example 13 with ContentType

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);
}
Also used : ContentType(org.apache.http.entity.ContentType) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ODataApplicationException(org.apache.olingo.odata2.api.exception.ODataApplicationException) BasicStatusLine(org.apache.http.message.BasicStatusLine) Olingo2BatchQueryRequest(org.apache.camel.component.olingo2.api.batch.Olingo2BatchQueryRequest) StringEntity(org.apache.http.entity.StringEntity) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) Olingo2BatchResponse(org.apache.camel.component.olingo2.api.batch.Olingo2BatchResponse) ByteArrayInputStream(java.io.ByteArrayInputStream) Map(java.util.Map) HashMap(java.util.HashMap)

Example 14 with ContentType

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);
    }
}
Also used : ContentType(org.apache.http.entity.ContentType) HttpStatusCodes(org.apache.olingo.odata2.api.commons.HttpStatusCodes) Olingo2BatchRequest(org.apache.camel.component.olingo2.api.batch.Olingo2BatchRequest) URISyntaxException(java.net.URISyntaxException) BatchException(org.apache.olingo.odata2.api.batch.BatchException) Olingo2BatchResponse(org.apache.camel.component.olingo2.api.batch.Olingo2BatchResponse) Iterator(java.util.Iterator) Olingo2BatchChangeRequest(org.apache.camel.component.olingo2.api.batch.Olingo2BatchChangeRequest) List(java.util.List) ArrayList(java.util.ArrayList) EdmEntitySet(org.apache.olingo.odata2.api.edm.EdmEntitySet) EdmProperty(org.apache.olingo.odata2.api.edm.EdmProperty) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) BatchSingleResponse(org.apache.olingo.odata2.api.client.batch.BatchSingleResponse) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpResponse(org.apache.http.HttpResponse) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) ODataApplicationException(org.apache.olingo.odata2.api.exception.ODataApplicationException) URISyntaxException(java.net.URISyntaxException) ODataApplicationException(org.apache.olingo.odata2.api.exception.ODataApplicationException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) EntityProviderException(org.apache.olingo.odata2.api.ep.EntityProviderException) EdmException(org.apache.olingo.odata2.api.edm.EdmException) ODataException(org.apache.olingo.odata2.api.exception.ODataException) IOException(java.io.IOException) BatchException(org.apache.olingo.odata2.api.batch.BatchException) InputStreamEntity(org.apache.http.entity.InputStreamEntity) EntityProviderException(org.apache.olingo.odata2.api.ep.EntityProviderException) ODataException(org.apache.olingo.odata2.api.exception.ODataException) Header(org.apache.http.Header) ODataResponse(org.apache.olingo.odata2.api.processor.ODataResponse) Map(java.util.Map) HashMap(java.util.HashMap)

Example 15 with ContentType

use of org.apache.http.entity.ContentType in project camel by apache.

the class HttpProducer method createRequestEntity.

/**
     * Creates a holder object for the data to send to the remote server.
     *
     * @param exchange the exchange with the IN message with data to send
     * @return the data holder
     * @throws CamelExchangeException is thrown if error creating RequestEntity
     */
protected HttpEntity createRequestEntity(Exchange exchange) throws CamelExchangeException {
    Message in = exchange.getIn();
    if (in.getBody() == null) {
        return null;
    }
    HttpEntity answer = in.getBody(HttpEntity.class);
    if (answer == null) {
        try {
            Object data = in.getBody();
            if (data != null) {
                String contentTypeString = ExchangeHelper.getContentType(exchange);
                ContentType contentType = null;
                //it removes "boundary" from Content-Type; I have to use contentType.create method.
                if (contentTypeString != null) {
                    // using ContentType.parser for charset
                    if (contentTypeString.indexOf("charset") > 0) {
                        contentType = ContentType.parse(contentTypeString);
                    } else {
                        contentType = ContentType.create(contentTypeString);
                    }
                }
                if (contentTypeString != null && HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT.equals(contentTypeString)) {
                    if (!getEndpoint().getComponent().isAllowJavaSerializedObject()) {
                        throw new CamelExchangeException("Content-type " + org.apache.camel.http.common.HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT + " is not allowed", exchange);
                    }
                    // serialized java object
                    Serializable obj = in.getMandatoryBody(Serializable.class);
                    // write object to output stream
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    HttpHelper.writeObjectToStream(bos, obj);
                    ByteArrayEntity entity = new ByteArrayEntity(bos.toByteArray());
                    entity.setContentType(HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT);
                    IOHelper.close(bos);
                    answer = entity;
                } else if (data instanceof File || data instanceof GenericFile) {
                    // file based (could potentially also be a FTP file etc)
                    File file = in.getBody(File.class);
                    if (file != null) {
                        if (contentType != null) {
                            answer = new FileEntity(file, contentType);
                        } else {
                            answer = new FileEntity(file);
                        }
                    }
                } else if (data instanceof String) {
                    // be a bit careful with String as any type can most likely be converted to String
                    // so we only do an instanceof check and accept String if the body is really a String
                    // do not fallback to use the default charset as it can influence the request
                    // (for example application/x-www-form-urlencoded forms being sent)
                    String charset = IOHelper.getCharsetName(exchange, false);
                    if (charset == null && contentType != null) {
                        // okay try to get the charset from the content-type
                        Charset cs = contentType.getCharset();
                        if (cs != null) {
                            charset = cs.name();
                        }
                    }
                    StringEntity entity = new StringEntity((String) data, charset);
                    if (contentType != null) {
                        entity.setContentType(contentType.toString());
                    }
                    answer = entity;
                }
                // fallback as input stream
                if (answer == null) {
                    // force the body as an input stream since this is the fallback
                    InputStream is = in.getMandatoryBody(InputStream.class);
                    String length = in.getHeader(Exchange.CONTENT_LENGTH, String.class);
                    InputStreamEntity entity = null;
                    if (ObjectHelper.isEmpty(length)) {
                        entity = new InputStreamEntity(is, -1);
                    } else {
                        entity = new InputStreamEntity(is, Long.parseLong(length));
                    }
                    if (contentType != null) {
                        entity.setContentType(contentType.toString());
                    }
                    answer = entity;
                }
            }
        } catch (UnsupportedEncodingException e) {
            throw new CamelExchangeException("Error creating RequestEntity from message body", exchange, e);
        } catch (IOException e) {
            throw new CamelExchangeException("Error serializing message body", exchange, e);
        }
    }
    return answer;
}
Also used : CamelExchangeException(org.apache.camel.CamelExchangeException) Serializable(java.io.Serializable) FileEntity(org.apache.http.entity.FileEntity) Message(org.apache.camel.Message) HttpEntity(org.apache.http.HttpEntity) ContentType(org.apache.http.entity.ContentType) InputStream(java.io.InputStream) Charset(java.nio.charset.Charset) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) InputStreamEntity(org.apache.http.entity.InputStreamEntity) StringEntity(org.apache.http.entity.StringEntity) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) GenericFile(org.apache.camel.component.file.GenericFile) File(java.io.File) GenericFile(org.apache.camel.component.file.GenericFile)

Aggregations

ContentType (org.apache.http.entity.ContentType)23 IOException (java.io.IOException)9 StringEntity (org.apache.http.entity.StringEntity)9 HttpEntity (org.apache.http.HttpEntity)8 Charset (java.nio.charset.Charset)6 HttpResponse (org.apache.http.HttpResponse)5 HttpPost (org.apache.http.client.methods.HttpPost)5 InputStreamReader (java.io.InputStreamReader)4 HttpGet (org.apache.http.client.methods.HttpGet)4 ByteArrayEntity (org.apache.http.entity.ByteArrayEntity)4 InputStream (java.io.InputStream)3 Reader (java.io.Reader)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 Header (org.apache.http.Header)3 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)3 XContentType (org.elasticsearch.common.xcontent.XContentType)3 SuccessUserResponse (com.bwssystems.HABridge.api.SuccessUserResponse)2 UserCreateRequest (com.bwssystems.HABridge.api.UserCreateRequest)2