Search in sources :

Example 1 with MediaType

use of org.restlet.data.MediaType in project camel by apache.

the class DefaultRestletBinding method populateRestletRequestFromExchange.

public void populateRestletRequestFromExchange(Request request, Exchange exchange) {
    request.setReferrerRef("camel-restlet");
    final Method method = request.getMethod();
    MediaType mediaType = exchange.getIn().getHeader(Exchange.CONTENT_TYPE, MediaType.class);
    if (mediaType == null) {
        mediaType = MediaType.APPLICATION_WWW_FORM;
    }
    Form form = null;
    // Use forms only for PUT, POST and x-www-form-urlencoded
    if ((Method.PUT == method || Method.POST == method) && MediaType.APPLICATION_WWW_FORM.equals(mediaType, true)) {
        form = new Form();
        if (exchange.getIn().getBody() instanceof Map) {
            //Body is key value pairs
            try {
                Map pairs = exchange.getIn().getBody(Map.class);
                for (Object key : pairs.keySet()) {
                    Object value = pairs.get(key);
                    form.add(key.toString(), value != null ? value.toString() : null);
                }
            } catch (Exception e) {
                throw new RuntimeCamelException("body for " + MediaType.APPLICATION_WWW_FORM + " request must be Map<String,String> or string format like name=bob&password=secRet", e);
            }
        } else {
            // use string based for forms
            String body = exchange.getIn().getBody(String.class);
            if (body != null) {
                List<NameValuePair> pairs = URLEncodedUtils.parse(body, Charset.forName(IOHelper.getCharsetName(exchange, true)));
                for (NameValuePair p : pairs) {
                    form.add(p.getName(), p.getValue());
                }
            }
        }
    }
    // get outgoing custom http headers from the exchange if they exists
    Series<Header> restletHeaders = exchange.getIn().getHeader(HeaderConstants.ATTRIBUTE_HEADERS, Series.class);
    if (restletHeaders == null) {
        restletHeaders = new Series<Header>(Header.class);
        request.getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, restletHeaders);
    } else {
        // if the restlet headers already exists on the exchange, we need to filter them
        for (String name : restletHeaders.getNames()) {
            if (headerFilterStrategy.applyFilterToCamelHeaders(name, restletHeaders.getValues(name), exchange)) {
                restletHeaders.removeAll(name);
            }
        }
        request.getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, restletHeaders);
        // since the restlet headers already exists remove them from the exchange so they don't get added again below
        // we will get a new set of restlet headers on the response
        exchange.getIn().removeHeader(HeaderConstants.ATTRIBUTE_HEADERS);
    }
    // login and password are filtered by header filter strategy
    String login = exchange.getIn().getHeader(RestletConstants.RESTLET_LOGIN, String.class);
    String password = exchange.getIn().getHeader(RestletConstants.RESTLET_PASSWORD, String.class);
    if (login != null && password != null) {
        ChallengeResponse authentication = new ChallengeResponse(ChallengeScheme.HTTP_BASIC, login, password);
        request.setChallengeResponse(authentication);
        LOG.debug("Basic HTTP Authentication has been applied");
    }
    for (Map.Entry<String, Object> entry : exchange.getIn().getHeaders().entrySet()) {
        String key = entry.getKey();
        Object value = entry.getValue();
        if (!headerFilterStrategy.applyFilterToCamelHeaders(key, value, exchange)) {
            // Use forms only for PUT, POST and x-www-form-urlencoded
            if (form != null) {
                if (key.startsWith("org.restlet.")) {
                    // put the org.restlet headers in attributes
                    request.getAttributes().put(key, value);
                } else {
                    // put the user stuff in the form
                    if (value instanceof Collection) {
                        for (Object v : (Collection<?>) value) {
                            form.add(key, v.toString());
                            if (!headerFilterStrategy.applyFilterToCamelHeaders(key, value, exchange)) {
                                restletHeaders.set(key, value.toString());
                            }
                        }
                    } else {
                        //Add headers to headers and to body
                        form.add(key, value.toString());
                        if (!headerFilterStrategy.applyFilterToCamelHeaders(key, value, exchange)) {
                            restletHeaders.set(key, value.toString());
                        }
                    }
                }
            } else {
                // For non-form post put all the headers in custom headers
                if (!headerFilterStrategy.applyFilterToCamelHeaders(key, value, exchange)) {
                    restletHeaders.set(key, value.toString());
                }
            }
            LOG.debug("Populate Restlet request from exchange header: {} value: {}", key, value);
        }
    }
    if (form != null) {
        request.setEntity(form.getWebRepresentation());
        LOG.debug("Populate Restlet {} request from exchange body as form using media type {}", method, mediaType);
    } else {
        // include body if PUT or POST
        if (request.getMethod() == Method.PUT || request.getMethod() == Method.POST) {
            Representation body = createRepresentationFromBody(exchange, mediaType);
            request.setEntity(body);
            LOG.debug("Populate Restlet {} request from exchange body: {} using media type {}", method, body, mediaType);
        } else {
            // no body
            LOG.debug("Populate Restlet {} request from exchange using media type {}", method, mediaType);
            request.setEntity(new EmptyRepresentation());
        }
    }
    // accept
    String accept = exchange.getIn().getHeader("Accept", String.class);
    final ClientInfo clientInfo = request.getClientInfo();
    final List<Preference<MediaType>> acceptedMediaTypesList = clientInfo.getAcceptedMediaTypes();
    if (accept != null) {
        final MediaType[] acceptedMediaTypes = exchange.getContext().getTypeConverter().tryConvertTo(MediaType[].class, exchange, accept);
        for (final MediaType acceptedMediaType : acceptedMediaTypes) {
            acceptedMediaTypesList.add(new Preference<MediaType>(acceptedMediaType));
        }
    }
    final MediaType[] acceptedMediaTypes = exchange.getIn().getHeader(Exchange.ACCEPT_CONTENT_TYPE, MediaType[].class);
    if (acceptedMediaTypes != null) {
        for (final MediaType acceptedMediaType : acceptedMediaTypes) {
            acceptedMediaTypesList.add(new Preference<MediaType>(acceptedMediaType));
        }
    }
}
Also used : NameValuePair(org.apache.http.NameValuePair) Form(org.restlet.data.Form) EmptyRepresentation(org.restlet.representation.EmptyRepresentation) StringRepresentation(org.restlet.representation.StringRepresentation) InputRepresentation(org.restlet.representation.InputRepresentation) ByteArrayRepresentation(org.restlet.representation.ByteArrayRepresentation) FileRepresentation(org.restlet.representation.FileRepresentation) StreamRepresentation(org.restlet.representation.StreamRepresentation) Representation(org.restlet.representation.Representation) DecodeRepresentation(org.restlet.engine.application.DecodeRepresentation) Method(org.restlet.data.Method) ParseException(java.text.ParseException) RuntimeCamelException(org.apache.camel.RuntimeCamelException) ChallengeResponse(org.restlet.data.ChallengeResponse) Header(org.restlet.data.Header) EmptyRepresentation(org.restlet.representation.EmptyRepresentation) Preference(org.restlet.data.Preference) MediaType(org.restlet.data.MediaType) Collection(java.util.Collection) RuntimeCamelException(org.apache.camel.RuntimeCamelException) ClientInfo(org.restlet.data.ClientInfo) Map(java.util.Map)

Example 2 with MediaType

use of org.restlet.data.MediaType in project camel by apache.

the class DefaultRestletBinding method populateRestletResponseFromExchange.

public void populateRestletResponseFromExchange(Exchange exchange, Response response) throws Exception {
    Message out;
    if (exchange.isFailed()) {
        // 500 for internal server error which can be overridden by response code in header
        response.setStatus(Status.valueOf(500));
        Message msg = exchange.hasOut() ? exchange.getOut() : exchange.getIn();
        if (msg.isFault()) {
            out = msg;
        } else {
            // print exception as message and stacktrace
            Exception t = exchange.getException();
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            t.printStackTrace(pw);
            response.setEntity(sw.toString(), MediaType.TEXT_PLAIN);
            return;
        }
    } else {
        out = exchange.hasOut() ? exchange.getOut() : exchange.getIn();
    }
    // get content type
    MediaType mediaType = out.getHeader(Exchange.CONTENT_TYPE, MediaType.class);
    if (mediaType == null) {
        Object body = out.getBody();
        mediaType = MediaType.TEXT_PLAIN;
        if (body instanceof String) {
            mediaType = MediaType.TEXT_PLAIN;
        } else if (body instanceof StringSource || body instanceof DOMSource) {
            mediaType = MediaType.TEXT_XML;
        }
    }
    // get response code
    Integer responseCode = out.getHeader(Exchange.HTTP_RESPONSE_CODE, Integer.class);
    if (responseCode != null) {
        response.setStatus(Status.valueOf(responseCode));
    }
    // set response body according to the message body
    Object body = out.getBody();
    if (body instanceof WrappedFile) {
        // grab body from generic file holder
        GenericFile<?> gf = (GenericFile<?>) body;
        body = gf.getBody();
    }
    if (body == null) {
        // empty response
        response.setEntity("", MediaType.TEXT_PLAIN);
    } else if (body instanceof Response) {
        // its already a restlet response, so dont do anything
        LOG.debug("Using existing Restlet Response from exchange body: {}", body);
    } else if (body instanceof Representation) {
        response.setEntity(out.getBody(Representation.class));
    } else if (body instanceof InputStream) {
        response.setEntity(new InputRepresentation(out.getBody(InputStream.class), mediaType));
    } else if (body instanceof File) {
        response.setEntity(new FileRepresentation(out.getBody(File.class), mediaType));
    } else if (body instanceof byte[]) {
        byte[] bytes = out.getBody(byte[].class);
        response.setEntity(new ByteArrayRepresentation(bytes, mediaType, bytes.length));
    } else {
        // fallback and use string
        String text = out.getBody(String.class);
        response.setEntity(text, mediaType);
    }
    LOG.debug("Populate Restlet response from exchange body: {}", body);
    if (exchange.getProperty(Exchange.CHARSET_NAME) != null) {
        CharacterSet cs = CharacterSet.valueOf(exchange.getProperty(Exchange.CHARSET_NAME, String.class));
        response.getEntity().setCharacterSet(cs);
    }
    // set headers at the end, as the entity must be set first
    // NOTE: setting HTTP headers on restlet is cumbersome and its API is "weird" and has some flaws
    // so we need to headers two times, and the 2nd time we add the non-internal headers once more
    Series<Header> series = new Series<Header>(Header.class);
    for (Map.Entry<String, Object> entry : out.getHeaders().entrySet()) {
        String key = entry.getKey();
        Object value = entry.getValue();
        if (!headerFilterStrategy.applyFilterToCamelHeaders(key, value, exchange)) {
            boolean added = setResponseHeader(exchange, response, key, value);
            if (!added) {
                // we only want non internal headers
                if (!key.startsWith("Camel") && !key.startsWith("org.restlet")) {
                    String text = exchange.getContext().getTypeConverter().tryConvertTo(String.class, exchange, value);
                    if (text != null) {
                        series.add(key, text);
                    }
                }
            }
        }
    }
    // set HTTP headers so we return these in the response
    if (!series.isEmpty()) {
        response.getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, series);
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) Message(org.apache.camel.Message) StringWriter(java.io.StringWriter) WrappedFile(org.apache.camel.WrappedFile) MediaType(org.restlet.data.MediaType) CharacterSet(org.restlet.data.CharacterSet) PrintWriter(java.io.PrintWriter) InputRepresentation(org.restlet.representation.InputRepresentation) InputStream(java.io.InputStream) EmptyRepresentation(org.restlet.representation.EmptyRepresentation) StringRepresentation(org.restlet.representation.StringRepresentation) InputRepresentation(org.restlet.representation.InputRepresentation) ByteArrayRepresentation(org.restlet.representation.ByteArrayRepresentation) FileRepresentation(org.restlet.representation.FileRepresentation) StreamRepresentation(org.restlet.representation.StreamRepresentation) Representation(org.restlet.representation.Representation) DecodeRepresentation(org.restlet.engine.application.DecodeRepresentation) ParseException(java.text.ParseException) RuntimeCamelException(org.apache.camel.RuntimeCamelException) ChallengeResponse(org.restlet.data.ChallengeResponse) Response(org.restlet.Response) Series(org.restlet.util.Series) Header(org.restlet.data.Header) FileRepresentation(org.restlet.representation.FileRepresentation) ByteArrayRepresentation(org.restlet.representation.ByteArrayRepresentation) StringSource(org.apache.camel.StringSource) WrappedFile(org.apache.camel.WrappedFile) GenericFile(org.apache.camel.component.file.GenericFile) File(java.io.File) Map(java.util.Map) GenericFile(org.apache.camel.component.file.GenericFile)

Example 3 with MediaType

use of org.restlet.data.MediaType in project camel by apache.

the class DefaultRestletBinding method setResponseHeader.

@SuppressWarnings("unchecked")
protected boolean setResponseHeader(Exchange exchange, org.restlet.Response message, String header, Object value) {
    // there must be a value going forward
    if (value == null) {
        return true;
    }
    // must put to attributes
    message.getAttributes().put(header, value);
    // special for certain headers
    if (message.getEntity() != null) {
        // arfg darn restlet you make using your api harder for end users with all this trick just to set those ACL headers
        if (header.equalsIgnoreCase(HeaderConstants.HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS)) {
            Boolean bool = exchange.getContext().getTypeConverter().tryConvertTo(Boolean.class, value);
            if (bool != null) {
                message.setAccessControlAllowCredentials(bool);
            }
            return true;
        }
        if (header.equalsIgnoreCase(HeaderConstants.HEADER_ACCESS_CONTROL_ALLOW_HEADERS)) {
            Set<String> set = convertToStringSet(value, exchange.getContext().getTypeConverter());
            message.setAccessControlAllowHeaders(set);
            return true;
        }
        if (header.equalsIgnoreCase(HeaderConstants.HEADER_ACCESS_CONTROL_ALLOW_METHODS)) {
            Set<Method> set = convertToMethodSet(value, exchange.getContext().getTypeConverter());
            message.setAccessControlAllowMethods(set);
            return true;
        }
        if (header.equalsIgnoreCase(HeaderConstants.HEADER_ACCESS_CONTROL_ALLOW_ORIGIN)) {
            String text = exchange.getContext().getTypeConverter().tryConvertTo(String.class, value);
            if (text != null) {
                message.setAccessControlAllowOrigin(text);
            }
            return true;
        }
        if (header.equalsIgnoreCase(HeaderConstants.HEADER_ACCESS_CONTROL_EXPOSE_HEADERS)) {
            Set<String> set = convertToStringSet(value, exchange.getContext().getTypeConverter());
            message.setAccessControlExposeHeaders(set);
            return true;
        }
        if (header.equalsIgnoreCase(HeaderConstants.HEADER_CACHE_CONTROL)) {
            if (value instanceof List) {
                message.setCacheDirectives((List<CacheDirective>) value);
            }
            if (value instanceof String) {
                List<CacheDirective> list = new ArrayList<CacheDirective>();
                // set the cache control value directive
                list.add(new CacheDirective((String) value));
                message.setCacheDirectives(list);
            }
            return true;
        }
        if (header.equalsIgnoreCase(HeaderConstants.HEADER_LOCATION)) {
            String text = exchange.getContext().getTypeConverter().tryConvertTo(String.class, value);
            if (text != null) {
                message.setLocationRef(text);
            }
            return true;
        }
        if (header.equalsIgnoreCase(HeaderConstants.HEADER_EXPIRES)) {
            if (value instanceof Calendar) {
                message.getEntity().setExpirationDate(((Calendar) value).getTime());
            } else if (value instanceof Date) {
                message.getEntity().setExpirationDate((Date) value);
            } else if (value instanceof String) {
                SimpleDateFormat format = new SimpleDateFormat(RFC_2822_DATE_PATTERN, Locale.ENGLISH);
                try {
                    Date date = format.parse((String) value);
                    message.getEntity().setExpirationDate(date);
                } catch (ParseException e) {
                    LOG.debug("Header {} with value {} cannot be converted as a Date. The value will be ignored.", HeaderConstants.HEADER_EXPIRES, value);
                }
            }
            return true;
        }
        if (header.equalsIgnoreCase(HeaderConstants.HEADER_LAST_MODIFIED)) {
            if (value instanceof Calendar) {
                message.getEntity().setModificationDate(((Calendar) value).getTime());
            } else if (value instanceof Date) {
                message.getEntity().setModificationDate((Date) value);
            } else if (value instanceof String) {
                SimpleDateFormat format = new SimpleDateFormat(RFC_2822_DATE_PATTERN, Locale.ENGLISH);
                try {
                    Date date = format.parse((String) value);
                    message.getEntity().setModificationDate(date);
                } catch (ParseException e) {
                    LOG.debug("Header {} with value {} cannot be converted as a Date. The value will be ignored.", HeaderConstants.HEADER_LAST_MODIFIED, value);
                }
            }
            return true;
        }
        if (header.equalsIgnoreCase(HeaderConstants.HEADER_CONTENT_LENGTH)) {
            if (value instanceof Long) {
                message.getEntity().setSize((Long) value);
            } else if (value instanceof Integer) {
                message.getEntity().setSize((Integer) value);
            } else {
                Long num = exchange.getContext().getTypeConverter().tryConvertTo(Long.class, value);
                if (num != null) {
                    message.getEntity().setSize(num);
                } else {
                    LOG.debug("Header {} with value {} cannot be converted as a Long. The value will be ignored.", HeaderConstants.HEADER_CONTENT_LENGTH, value);
                }
            }
            return true;
        }
        if (header.equalsIgnoreCase(HeaderConstants.HEADER_CONTENT_TYPE)) {
            if (value instanceof MediaType) {
                message.getEntity().setMediaType((MediaType) value);
            } else {
                String type = value.toString();
                MediaType media = MediaType.valueOf(type);
                if (media != null) {
                    message.getEntity().setMediaType(media);
                } else {
                    LOG.debug("Header {} with value {} cannot be converted as a MediaType. The value will be ignored.", HeaderConstants.HEADER_CONTENT_TYPE, value);
                }
            }
            return true;
        }
    }
    return false;
}
Also used : Calendar(java.util.Calendar) ArrayList(java.util.ArrayList) Method(org.restlet.data.Method) Date(java.util.Date) CacheDirective(org.restlet.data.CacheDirective) MediaType(org.restlet.data.MediaType) List(java.util.List) ArrayList(java.util.ArrayList) ParseException(java.text.ParseException) SimpleDateFormat(java.text.SimpleDateFormat)

Example 4 with MediaType

use of org.restlet.data.MediaType in project GeoGig by boundlessgeo.

the class CommandResource method resolveFormat.

private MediaType resolveFormat(Form options, Variant variant) {
    MediaType retval = variant.getMediaType();
    String requested = options.getFirstValue("output_format");
    if (requested != null) {
        if (requested.equalsIgnoreCase("xml")) {
            retval = MediaType.APPLICATION_XML;
        } else if (requested.equalsIgnoreCase("json")) {
            retval = MediaType.APPLICATION_JSON;
        } else if (requested.equalsIgnoreCase("csv")) {
            retval = CSV_MEDIA_TYPE;
        } else {
            throw new RestletException("Invalid output_format '" + requested + "'", org.restlet.data.Status.CLIENT_ERROR_BAD_REQUEST);
        }
    }
    return retval;
}
Also used : RestletException(org.locationtech.geogig.rest.RestletException) MediaType(org.restlet.data.MediaType)

Example 5 with MediaType

use of org.restlet.data.MediaType in project GeoGig by boundlessgeo.

the class TaskStatusResource method getRepresentation.

@Override
public Representation getRepresentation(Variant variant) {
    final Request request = getRequest();
    final String taskId = getStringAttribute(request, "taskId");
    final boolean prune = Boolean.valueOf(getRequest().getResourceRef().getQueryAsForm().getFirstValue("prune"));
    final boolean cancel = Boolean.valueOf(getRequest().getResourceRef().getQueryAsForm().getFirstValue("cancel"));
    final AsyncContext asyncContext = AsyncContext.get();
    MediaType mediaType = variant.getMediaType();
    final String rootPath = request.getRootRef().toString();
    if (Strings.isNullOrEmpty(taskId)) {
        Iterable<AsyncCommand<? extends Object>> all = asyncContext.getAll();
        return new TaskListResource(mediaType, rootPath, all);
    }
    Optional<AsyncCommand<?>> cmd;
    if (prune) {
        cmd = asyncContext.getAndPruneIfFinished(taskId);
    } else {
        cmd = asyncContext.get(taskId);
    }
    if (!cmd.isPresent()) {
        throw new RestletException("Task not found: " + taskId, Status.CLIENT_ERROR_NOT_FOUND);
    }
    AsyncCommand<?> command = cmd.get();
    if (cancel) {
        command.tryCancel();
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
        // ignore
        }
        if (prune) {
            asyncContext.getAndPruneIfFinished(taskId);
        }
    }
    return Representations.newRepresentation(command, mediaType, rootPath);
}
Also used : AsyncCommand(org.locationtech.geogig.rest.AsyncContext.AsyncCommand) Request(org.restlet.data.Request) MediaType(org.restlet.data.MediaType)

Aggregations

MediaType (org.restlet.data.MediaType)29 StringRepresentation (org.restlet.representation.StringRepresentation)11 Representation (org.restlet.representation.Representation)10 IOException (java.io.IOException)9 Map (java.util.Map)7 WriterRepresentation (org.restlet.representation.WriterRepresentation)7 Writer (java.io.Writer)6 TemplateException (freemarker.template.TemplateException)5 HashMap (java.util.HashMap)5 Form (org.restlet.data.Form)5 ArrayList (java.util.ArrayList)4 Preference (org.restlet.data.Preference)4 EmptyRepresentation (org.restlet.representation.EmptyRepresentation)4 ResourceException (org.restlet.resource.ResourceException)4 Template (freemarker.template.Template)3 InputStream (java.io.InputStream)3 URL (java.net.URL)3 ParseException (java.text.ParseException)3 InputRepresentation (org.restlet.representation.InputRepresentation)3 Representation (org.restlet.resource.Representation)3