Search in sources :

Example 1 with CacheDirective

use of org.restlet.data.CacheDirective 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 2 with CacheDirective

use of org.restlet.data.CacheDirective in project vcell by virtualcell.

the class AccessTokenServerResource method get_json.

@Override
public AccessTokenRepresentation get_json() {
    VCellApiApplication application = ((VCellApiApplication) getApplication());
    String clientId = getQueryValue(PARAM_CLIENT_ID);
    String userId = getQueryValue(PARAM_USER_ID);
    String userPassword = getQueryValue(PARAM_USER_PASSWORD);
    try {
        ApiClient apiClient = application.getUserVerifier().getApiClient(clientId);
        if (apiClient == null) {
            throw new RuntimeException("client not found");
        }
        User authenticatedUser = application.getUserVerifier().authenticateUser(userId, userPassword.toCharArray());
        if (authenticatedUser == null) {
            throw new RuntimeException("unable to authenticate user");
        }
        ApiAccessToken apiAccessToken = application.getUserVerifier().generateApiAccessToken(apiClient.getKey(), authenticatedUser);
        AccessTokenRepresentation tokenRep = new AccessTokenRepresentation(apiAccessToken);
        // 
        // indicate no caching of response.
        // 
        ArrayList<CacheDirective> cacheDirectives = new ArrayList<CacheDirective>();
        cacheDirectives.add(CacheDirective.noCache());
        getResponse().setCacheDirectives(cacheDirectives);
        return tokenRep;
    } catch (Exception e) {
        e.printStackTrace(System.out);
        throw new RuntimeException(e.getMessage(), e);
    }
}
Also used : User(org.vcell.util.document.User) CacheDirective(org.restlet.data.CacheDirective) ApiAccessToken(cbit.vcell.modeldb.ApiAccessToken) ArrayList(java.util.ArrayList) VCellApiApplication(org.vcell.rest.VCellApiApplication) ApiClient(cbit.vcell.modeldb.ApiClient) AccessTokenRepresentation(org.vcell.rest.common.AccessTokenRepresentation) ResourceException(org.restlet.resource.ResourceException)

Example 3 with CacheDirective

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

the class RestletResponseTest method createRouteBuilder.

@Override
protected RouteBuilder createRouteBuilder() {
    return new RouteBuilder() {

        @Override
        public void configure() throws Exception {
            from("restlet:http://localhost:" + portNum + "/users/{username}?restletMethod=POST").process(new Processor() {

                public void process(Exchange exchange) throws Exception {
                    String userName = exchange.getIn().getHeader("username", String.class);
                    assertNotNull("userName should not be null", userName);
                    exchange.getOut().setBody("{" + userName + "}");
                    exchange.getOut().setHeader(Exchange.HTTP_RESPONSE_CODE, "417");
                    exchange.getOut().setHeader(Exchange.CONTENT_TYPE, "application/JSON");
                    // set the cache control with String
                    exchange.getOut().setHeader(HeaderConstants.HEADER_CACHE_CONTROL, "max-age=20");
                }
            });
            from("restlet:http://localhost:" + portNum + "/cached/{username}?restletMethod=POST").process(new Processor() {

                public void process(Exchange exchange) throws Exception {
                    String userName = exchange.getIn().getHeader("username", String.class);
                    assertNotNull("userName should not be null", userName);
                    exchange.getOut().setBody("{" + userName + "}");
                    exchange.getOut().setHeader(Exchange.HTTP_RESPONSE_CODE, "417");
                    exchange.getOut().setHeader(Exchange.CONTENT_TYPE, "application/JSON");
                    // set cache control with cacheDirectives
                    List<CacheDirective> cacheDirectives = new ArrayList<CacheDirective>();
                    cacheDirectives.add(CacheDirective.maxAge(20));
                    exchange.getOut().setHeader(HeaderConstants.HEADER_CACHE_CONTROL, cacheDirectives);
                }
            });
        }
    };
}
Also used : Exchange(org.apache.camel.Exchange) Processor(org.apache.camel.Processor) RouteBuilder(org.apache.camel.builder.RouteBuilder) CacheDirective(org.restlet.data.CacheDirective) ArrayList(java.util.ArrayList) List(java.util.List) CamelExecutionException(org.apache.camel.CamelExecutionException)

Example 4 with CacheDirective

use of org.restlet.data.CacheDirective in project vcell by virtualcell.

the class AuthenticationTokenRestlet method handle.

@Override
public void handle(Request req, Response response) {
    if (req.getMethod().equals(Method.GET)) {
        try {
            VCellApiApplication application = ((VCellApiApplication) getApplication());
            HttpRequest request = (HttpRequest) req;
            Form form = request.getResourceRef().getQueryAsForm();
            String userId = form.getFirstValue(PARAM_USER_ID, false);
            if (userId == null) {
                throw new RuntimeException("expecting " + PARAM_USER_ID + " query parameter");
            }
            String clientId = form.getFirstValue(PARAM_CLIENT_ID, false);
            if (clientId == null) {
                throw new RuntimeException("expecting " + PARAM_CLIENT_ID + " query parameter");
            }
            String userPassword = form.getFirstValue(PARAM_USER_PASSWORD, false);
            if (userPassword == null) {
                throw new RuntimeException("expecting " + PARAM_USER_PASSWORD + " query parameter");
            }
            ApiClient apiClient = application.getUserVerifier().getApiClient(clientId);
            if (apiClient == null) {
                if (lg.isWarnEnabled())
                    lg.warn("client not found");
                response.setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
                response.setEntity("authentication error, unknown client", MediaType.TEXT_PLAIN);
                return;
            }
            User authenticatedUser = application.getUserVerifier().authenticateUser(userId, userPassword.toCharArray());
            if (authenticatedUser == null) {
                if (lg.isWarnEnabled())
                    lg.warn("unable to authenticate user");
                response.setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
                response.setEntity("authentication error, either userid or password is incorrect", MediaType.TEXT_PLAIN);
                return;
            }
            ApiAccessToken apiAccessToken = application.getUserVerifier().generateApiAccessToken(apiClient.getKey(), authenticatedUser);
            AccessTokenRepresentation tokenRep = new AccessTokenRepresentation(apiAccessToken);
            // 
            // indicate no caching of response.
            // 
            ArrayList<CacheDirective> cacheDirectives = new ArrayList<CacheDirective>();
            cacheDirectives.add(CacheDirective.noCache());
            response.setCacheDirectives(cacheDirectives);
            Gson gson = new Gson();
            String tokenRepJSON = gson.toJson(tokenRep);
            response.setStatus(Status.SUCCESS_OK, "authentication token returned");
            response.setEntity(new JsonRepresentation(tokenRepJSON));
        } catch (Exception e) {
            lg.error(e.getMessage(), e);
            response.setStatus(Status.SERVER_ERROR_INTERNAL);
            response.setEntity("internal error returning authentication token: " + e.getMessage(), MediaType.TEXT_PLAIN);
        }
    }
}
Also used : HttpRequest(org.restlet.engine.adapter.HttpRequest) User(org.vcell.util.document.User) Form(org.restlet.data.Form) ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) ApiClient(cbit.vcell.modeldb.ApiClient) CacheDirective(org.restlet.data.CacheDirective) ApiAccessToken(cbit.vcell.modeldb.ApiAccessToken) VCellApiApplication(org.vcell.rest.VCellApiApplication) JsonRepresentation(org.restlet.ext.json.JsonRepresentation) AccessTokenRepresentation(org.vcell.rest.common.AccessTokenRepresentation)

Aggregations

ArrayList (java.util.ArrayList)4 CacheDirective (org.restlet.data.CacheDirective)4 ApiAccessToken (cbit.vcell.modeldb.ApiAccessToken)2 ApiClient (cbit.vcell.modeldb.ApiClient)2 List (java.util.List)2 VCellApiApplication (org.vcell.rest.VCellApiApplication)2 AccessTokenRepresentation (org.vcell.rest.common.AccessTokenRepresentation)2 User (org.vcell.util.document.User)2 Gson (com.google.gson.Gson)1 ParseException (java.text.ParseException)1 SimpleDateFormat (java.text.SimpleDateFormat)1 Calendar (java.util.Calendar)1 Date (java.util.Date)1 CamelExecutionException (org.apache.camel.CamelExecutionException)1 Exchange (org.apache.camel.Exchange)1 Processor (org.apache.camel.Processor)1 RouteBuilder (org.apache.camel.builder.RouteBuilder)1 Form (org.restlet.data.Form)1 MediaType (org.restlet.data.MediaType)1 Method (org.restlet.data.Method)1