Search in sources :

Example 1 with Method

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

the class RestletComponent method attachUriPatternToRestlet.

private void attachUriPatternToRestlet(String offsetPath, String uriPattern, RestletEndpoint endpoint, Restlet target) throws Exception {
    uriPattern = decodePattern(uriPattern);
    MethodBasedRouter router = getMethodRouter(uriPattern, true);
    Map<String, String> realm = endpoint.getRestletRealm();
    if (realm != null && realm.size() > 0) {
        ChallengeAuthenticator guard = new ChallengeAuthenticator(component.getContext().createChildContext(), ChallengeScheme.HTTP_BASIC, "Camel-Restlet Endpoint Realm");
        MapVerifier verifier = new MapVerifier();
        for (Map.Entry<String, String> entry : realm.entrySet()) {
            verifier.getLocalSecrets().put(entry.getKey(), entry.getValue().toCharArray());
        }
        guard.setVerifier(verifier);
        guard.setNext(target);
        target = guard;
        LOG.debug("Target has been set to guard: {}", guard);
    }
    if (endpoint.getRestletMethods() != null) {
        Method[] methods = endpoint.getRestletMethods();
        for (Method method : methods) {
            router.addRoute(method, target);
            LOG.debug("Attached restlet uriPattern: {} method: {}", uriPattern, method);
        }
    } else {
        Method method = endpoint.getRestletMethod();
        router.addRoute(method, target);
        LOG.debug("Attached restlet uriPattern: {} method: {}", uriPattern, method);
    }
    if (!router.hasBeenAttached()) {
        component.getDefaultHost().attach(offsetPath == null ? uriPattern : offsetPath + uriPattern, router);
        LOG.debug("Attached methodRouter uriPattern: {}", uriPattern);
    }
    if (!router.isStarted()) {
        router.start();
        LOG.debug("Started methodRouter uriPattern: {}", uriPattern);
    }
}
Also used : ChallengeAuthenticator(org.restlet.security.ChallengeAuthenticator) MapVerifier(org.restlet.security.MapVerifier) Method(org.restlet.data.Method) HashMap(java.util.HashMap) Map(java.util.Map)

Example 2 with Method

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

the class RestletEndpoint method updateEndpointUri.

// Update the endpointUri with the restlet method information
protected void updateEndpointUri() {
    String endpointUri = getEndpointUri();
    CollectionStringBuffer methods = new CollectionStringBuffer(",");
    if (getRestletMethods() != null && getRestletMethods().length > 0) {
        // list the method(s) as a comma seperated list
        for (Method method : getRestletMethods()) {
            methods.append(method.getName());
        }
    } else {
        // otherwise consider the single method we own
        methods.append(getRestletMethod());
    }
    // update the uri
    endpointUri = endpointUri + "?restletMethods=" + methods;
    setEndpointUri(endpointUri);
}
Also used : CollectionStringBuffer(org.apache.camel.util.CollectionStringBuffer) Method(org.restlet.data.Method)

Example 3 with Method

use of org.restlet.data.Method 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 4 with Method

use of org.restlet.data.Method 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 5 with Method

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

the class DefaultRestletBinding method convertToMethodSet.

@SuppressWarnings("unchecked")
private Set<Method> convertToMethodSet(Object value, TypeConverter typeConverter) {
    if (value instanceof Set) {
        return (Set<Method>) value;
    }
    Set<Method> set = new LinkedHashSet<>();
    Iterator it = ObjectHelper.createIterator(value);
    while (it.hasNext()) {
        Object next = it.next();
        String text = typeConverter.tryConvertTo(String.class, next);
        if (text != null) {
            // creates new instance only if no matching instance exists
            Method method = Method.valueOf(text.trim());
            set.add(method);
        }
    }
    return set;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Set(java.util.Set) LinkedHashSet(java.util.LinkedHashSet) CharacterSet(org.restlet.data.CharacterSet) Iterator(java.util.Iterator) Method(org.restlet.data.Method)

Aggregations

Method (org.restlet.data.Method)8 ParseException (java.text.ParseException)2 ArrayList (java.util.ArrayList)2 Map (java.util.Map)2 MediaType (org.restlet.data.MediaType)2 SimpleDateFormat (java.text.SimpleDateFormat)1 Calendar (java.util.Calendar)1 Collection (java.util.Collection)1 Date (java.util.Date)1 HashMap (java.util.HashMap)1 Iterator (java.util.Iterator)1 LinkedHashSet (java.util.LinkedHashSet)1 List (java.util.List)1 Set (java.util.Set)1 RuntimeCamelException (org.apache.camel.RuntimeCamelException)1 CollectionStringBuffer (org.apache.camel.util.CollectionStringBuffer)1 NameValuePair (org.apache.http.NameValuePair)1 Restlet (org.restlet.Restlet)1 CacheDirective (org.restlet.data.CacheDirective)1 ChallengeResponse (org.restlet.data.ChallengeResponse)1