Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Copyright (C) 2012-2014 the original author or authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
 
 
 package ninja.jaxy;
 
 import java.net.URL;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
 import ninja.Router;
 
 
Implementation of a JAX-RS style route builder.

Author(s):
James Moger
 
 public class JaxyRoutes implements ApplicationRoutes {
 
     final static Logger logger = LoggerFactory.getLogger(JaxyRoutes.class);
 
 
     final NinjaMode runtimeMode;
 
     @Inject
     public JaxyRoutes(NinjaProperties ninjaProperties) {
         this. = ninjaProperties;
 
         if (ninjaProperties.isDev()) {
              = .;
         } else if (ninjaProperties.isTest()) {
              = .;
         } else {
              = .;
         }
 
     }

    
Scans, identifies, and registers annotated controller methods for the current runtime settings.

Parameters:
router
 
     @Override
     public void init(Router router) {
 
         ConfigurationBuilder builder = new ConfigurationBuilder();
 
         Set<URLpackagesToScan = getPackagesToScanForRoutes();
         builder.addUrls(packagesToScan);
 
         builder.addScanners(new MethodAnnotationsScanner());
         Reflections reflections = new Reflections(builder);
 
         // collect the allowed annotated methods
         Map<Class<?>, Set<String>> controllers = Maps.newHashMap();
         List<Methodmethods = Lists.newArrayList();
         for (Method method : reflections.getMethodsAnnotatedWith(Path.class)) {
 
            if (allowMethod(method)) {
                // add the method to our todo list
                methods.add(method);
                // generate the paths for the controller class
                final Class<?> controllerClass = method.getDeclaringClass();
                if (!controllers.containsKey(controllerClass)) {
                    Set<Stringpaths = collectPaths(controllerClass);
                    if (paths.isEmpty()) {
                        controllers.put(controllerClassnew HashSet<String>());
                    } else {
                        controllers.put(controllerClasspaths);
                    }
                }
            }
        }
        if (methods.isEmpty()) {
            // nothing to do
            return;
        }
        // Sort the methods into registration order
        Collections.sort(methodsnew Comparator<Method>() {
            @Override
            public int compare(Method m1Method m2) {
                int o1 = .;
                if (m1.isAnnotationPresent(Order.class)) {
                    Order order = m1.getAnnotation(Order.class);
                    o1 = order.value();
                }
                int o2 = .;
                if (m2.isAnnotationPresent(Order.class)) {
                    Order order = m2.getAnnotation(Order.class);
                    o2 = order.value();
                }
                if (o1 == o2) {
                    // same or unsorted, compare controller+method
                    String s1 = m1.getDeclaringClass().getName() + "."
                            + m1.getName();
                    String s2 = m2.getDeclaringClass().getName() + "."
                            + m2.getName();
                    return s1.compareTo(s2);
                }
                if (o1 < o2) {
                    return -1;
                } else {
                    return 1;
                }
            }
        });
        // register routes for all the methods
        for (Method method : methods) {
            final Class<?> controllerClass = method.getDeclaringClass();
            final Path methodPath = method.getAnnotation(Path.class);
            final Set<StringcontrollerPaths = controllers
                    .get(controllerClass);
            for (String controllerPath : controllerPaths) {
                for (String methodPathSpec : methodPath.value()) {
                    final String httpMethod = getHttpMethod(method);
                    final String fullPath = controllerPath + methodPathSpec;
                    final String methodName = method.getName();
                    router.METHOD(httpMethod).route(fullPath)
                            .with(controllerClassmethodName);
                }
            }
        }
    }

    
Recursively builds the paths for the controller class.

Parameters:
controllerClass
Returns:
the paths for the controller
    private Set<StringcollectPaths(Class<?> controllerClass) {
        Set<StringparentPaths = Collections.emptySet();
        if (controllerClass.getSuperclass() != null) {
            parentPaths = collectPaths(controllerClass.getSuperclass());
        }
        Set<Stringpaths = Sets.newLinkedHashSet();
        Path controllerPath = controllerClass.getAnnotation(Path.class);
        if (controllerPath != null) {
            if (parentPaths.isEmpty()) {
                // add all controller paths
                paths.addAll(Arrays.asList(controllerPath.value()));
            } else {
                // create controller paths based on the parent paths
                for (String parentPath : parentPaths) {
                    for (String path : controllerPath.value()) {
                        paths.add(parentPath + path);
                    }
                }
            }
        } else {
            // add all parent paths
            paths.addAll(parentPaths);
        }
        return paths;
    }

    
Returns the set of packages to scan for annotated controller methods.

Returns:
the set of packages to scan
    private Set<URLgetPackagesToScanForRoutes() {
        Set<URLpackagesToScanForRoutes = Sets.newHashSet();
        packagesToScanForRoutes.addAll(ClasspathHelper
                .forPackage(.));
        return packagesToScanForRoutes;
    }

    
Determines if this method may be registered as a route. Ninja properties are considered as well as runtime modes.

Parameters:
method
Returns:
true if the method can be registered as a route
    private boolean allowMethod(Method method) {
        // NinjaProperties-based route exclusions/inclusions
        if (method.isAnnotationPresent(Requires.class)) {
            String key = method.getAnnotation(Requires.class).value();
            String value = .get(key);
            if (value == null) {
                return false;
            }
        }
        // NinjaMode-based route exclusions/inclusions
        Set<NinjaModemodes = Sets.newTreeSet();
        for (Annotation annotation : method.getAnnotations()) {
            Class<? extends AnnotationannotationClass = annotation
                    .annotationType();
            if (annotationClass.isAnnotationPresent(RuntimeMode.class)) {
                RuntimeMode mode = annotationClass
                        .getAnnotation(RuntimeMode.class);
                modes.add(mode.value());
            }
        }
        return modes.isEmpty() || modes.contains();
    }

    
Returns the HTTP method for the controller method. Defaults to GET if unspecified.

Parameters:
method
Returns:
the http method for this controller method
    private String getHttpMethod(Method method) {
        for (Annotation annotation : method.getAnnotations()) {
            Class<? extends AnnotationannotationClass = annotation
                    .annotationType();
            if (annotationClass.isAnnotationPresent(HttpMethod.class)) {
                HttpMethod httpMethod = annotationClass
                        .getAnnotation(HttpMethod.class);
                return httpMethod.value();
            }
        }
        // default to GET
        .info(String
                .format("%s.%s does not specify an HTTP method annotation! Defaulting to GET.",
                        method.getClass().getName(), method.getName()));
        return .;
    }
New to GrepCode? Check out our FAQ X