Example usage for org.springframework.core.annotation AnnotationAwareOrderComparator sort

List of usage examples for org.springframework.core.annotation AnnotationAwareOrderComparator sort

Introduction

In this page you can find the example usage for org.springframework.core.annotation AnnotationAwareOrderComparator sort.

Prototype

public static void sort(Object[] array) 

Source Link

Document

Sort the given array with a default AnnotationAwareOrderComparator.

Usage

From source file:org.springframework.test.context.support.AbstractContextLoader.java

@SuppressWarnings("unchecked")
private void invokeApplicationContextInitializers(ConfigurableApplicationContext context,
        MergedContextConfiguration mergedConfig) {

    Set<Class<? extends ApplicationContextInitializer<?>>> initializerClasses = mergedConfig
            .getContextInitializerClasses();
    if (initializerClasses.isEmpty()) {
        // no ApplicationContextInitializers have been declared -> nothing to do
        return;/*from  w  w  w  .  j  av  a  2 s .  co m*/
    }

    List<ApplicationContextInitializer<ConfigurableApplicationContext>> initializerInstances = new ArrayList<>();
    Class<?> contextClass = context.getClass();

    for (Class<? extends ApplicationContextInitializer<?>> initializerClass : initializerClasses) {
        Class<?> initializerContextClass = GenericTypeResolver.resolveTypeArgument(initializerClass,
                ApplicationContextInitializer.class);
        if (initializerContextClass != null && !initializerContextClass.isInstance(context)) {
            throw new ApplicationContextException(String.format(
                    "Could not apply context initializer [%s] since its generic parameter [%s] "
                            + "is not assignable from the type of application context used by this "
                            + "context loader: [%s]",
                    initializerClass.getName(), initializerContextClass.getName(), contextClass.getName()));
        }
        initializerInstances.add((ApplicationContextInitializer<ConfigurableApplicationContext>) BeanUtils
                .instantiateClass(initializerClass));
    }

    AnnotationAwareOrderComparator.sort(initializerInstances);
    for (ApplicationContextInitializer<ConfigurableApplicationContext> initializer : initializerInstances) {
        initializer.initialize(context);
    }
}

From source file:org.springframework.test.context.support.AbstractTestContextBootstrapper.java

@Override
public final List<TestExecutionListener> getTestExecutionListeners() {
    Class<?> clazz = getBootstrapContext().getTestClass();
    Class<TestExecutionListeners> annotationType = TestExecutionListeners.class;
    List<Class<? extends TestExecutionListener>> classesList = new ArrayList<>();
    boolean usingDefaults = false;

    AnnotationDescriptor<TestExecutionListeners> descriptor = MetaAnnotationUtils
            .findAnnotationDescriptor(clazz, annotationType);

    // Use defaults?
    if (descriptor == null) {
        if (logger.isDebugEnabled()) {
            logger.debug(String.format("@TestExecutionListeners is not present for class [%s]: using defaults.",
                    clazz.getName()));/*  w w  w . j ava2s.c  o m*/
        }
        usingDefaults = true;
        classesList.addAll(getDefaultTestExecutionListenerClasses());
    } else {
        // Traverse the class hierarchy...
        while (descriptor != null) {
            Class<?> declaringClass = descriptor.getDeclaringClass();
            TestExecutionListeners testExecutionListeners = descriptor.synthesizeAnnotation();
            if (logger.isTraceEnabled()) {
                logger.trace(String.format("Retrieved @TestExecutionListeners [%s] for declaring class [%s].",
                        testExecutionListeners, declaringClass.getName()));
            }

            boolean inheritListeners = testExecutionListeners.inheritListeners();
            AnnotationDescriptor<TestExecutionListeners> superDescriptor = MetaAnnotationUtils
                    .findAnnotationDescriptor(descriptor.getRootDeclaringClass().getSuperclass(),
                            annotationType);

            // If there are no listeners to inherit, we might need to merge the
            // locally declared listeners with the defaults.
            if ((!inheritListeners || superDescriptor == null)
                    && testExecutionListeners.mergeMode() == MergeMode.MERGE_WITH_DEFAULTS) {
                if (logger.isDebugEnabled()) {
                    logger.debug(String.format(
                            "Merging default listeners with listeners configured via "
                                    + "@TestExecutionListeners for class [%s].",
                            descriptor.getRootDeclaringClass().getName()));
                }
                usingDefaults = true;
                classesList.addAll(getDefaultTestExecutionListenerClasses());
            }

            classesList.addAll(0, Arrays.asList(testExecutionListeners.listeners()));

            descriptor = (inheritListeners ? superDescriptor : null);
        }
    }

    Collection<Class<? extends TestExecutionListener>> classesToUse = classesList;
    // Remove possible duplicates if we loaded default listeners.
    if (usingDefaults) {
        classesToUse = new LinkedHashSet<>(classesList);
    }

    List<TestExecutionListener> listeners = instantiateListeners(classesToUse);
    // Sort by Ordered/@Order if we loaded default listeners.
    if (usingDefaults) {
        AnnotationAwareOrderComparator.sort(listeners);
    }

    if (logger.isInfoEnabled()) {
        logger.info("Using TestExecutionListeners: " + listeners);
    }
    return listeners;
}

From source file:org.springframework.transaction.reactive.TransactionSynchronizationManager.java

/**
 * Return an unmodifiable snapshot list of all registered synchronizations
 * for the current context.//from w  w w. ja  v  a 2s.c  om
 * @return unmodifiable List of TransactionSynchronization instances
 * @throws IllegalStateException if synchronization is not active
 * @see TransactionSynchronization
 */
public List<TransactionSynchronization> getSynchronizations() throws IllegalStateException {
    Set<TransactionSynchronization> synchs = this.transactionContext.getSynchronizations();
    if (synchs == null) {
        throw new IllegalStateException("Transaction synchronization is not active");
    }
    // Return unmodifiable snapshot, to avoid ConcurrentModificationExceptions
    // while iterating and invoking synchronization callbacks that in turn
    // might register further synchronizations.
    if (synchs.isEmpty()) {
        return Collections.emptyList();
    } else {
        // Sort lazily here, not in registerSynchronization.
        List<TransactionSynchronization> sortedSynchs = new ArrayList<>(synchs);
        AnnotationAwareOrderComparator.sort(sortedSynchs);
        return Collections.unmodifiableList(sortedSynchs);
    }
}

From source file:org.springframework.transaction.support.TransactionSynchronizationManager.java

/**
 * Return an unmodifiable snapshot list of all registered synchronizations
 * for the current thread./*from  w w w.j  a  v a  2 s  .  c o m*/
 * @return unmodifiable List of TransactionSynchronization instances
 * @throws IllegalStateException if synchronization is not active
 * @see TransactionSynchronization
 */
public static List<TransactionSynchronization> getSynchronizations() throws IllegalStateException {
    Set<TransactionSynchronization> synchs = synchronizations.get();
    if (synchs == null) {
        throw new IllegalStateException("Transaction synchronization is not active");
    }
    // Return unmodifiable snapshot, to avoid ConcurrentModificationExceptions
    // while iterating and invoking synchronization callbacks that in turn
    // might register further synchronizations.
    if (synchs.isEmpty()) {
        return Collections.emptyList();
    } else {
        // Sort lazily here, not in registerSynchronization.
        List<TransactionSynchronization> sortedSynchs = new ArrayList<>(synchs);
        AnnotationAwareOrderComparator.sort(sortedSynchs);
        return Collections.unmodifiableList(sortedSynchs);
    }
}

From source file:org.springframework.web.context.ContextLoader.java

/**
 * Customize the {@link ConfigurableWebApplicationContext} created by this
 * ContextLoader after config locations have been supplied to the context
 * but before the context is <em>refreshed</em>.
 * <p>The default implementation {@linkplain #determineContextInitializerClasses(ServletContext)
 * determines} what (if any) context initializer classes have been specified through
 * {@linkplain #CONTEXT_INITIALIZER_CLASSES_PARAM context init parameters} and
 * {@linkplain ApplicationContextInitializer#initialize invokes each} with the
 * given web application context./* w  ww  . j  a  v  a2s.  c o  m*/
 * <p>Any {@code ApplicationContextInitializers} implementing
 * {@link org.springframework.core.Ordered Ordered} or marked with @{@link
 * org.springframework.core.annotation.Order Order} will be sorted appropriately.
 * @param sc the current servlet context
 * @param wac the newly created application context
 * @see #CONTEXT_INITIALIZER_CLASSES_PARAM
 * @see ApplicationContextInitializer#initialize(ConfigurableApplicationContext)
 */
protected void customizeContext(ServletContext sc, ConfigurableWebApplicationContext wac) {
    List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>> initializerClasses = determineContextInitializerClasses(
            sc);

    for (Class<ApplicationContextInitializer<ConfigurableApplicationContext>> initializerClass : initializerClasses) {
        Class<?> initializerContextClass = GenericTypeResolver.resolveTypeArgument(initializerClass,
                ApplicationContextInitializer.class);
        if (initializerContextClass != null && !initializerContextClass.isInstance(wac)) {
            throw new ApplicationContextException(String.format(
                    "Could not apply context initializer [%s] since its generic parameter [%s] "
                            + "is not assignable from the type of application context used by this "
                            + "context loader: [%s]",
                    initializerClass.getName(), initializerContextClass.getName(), wac.getClass().getName()));
        }
        this.contextInitializers.add(BeanUtils.instantiateClass(initializerClass));
    }

    AnnotationAwareOrderComparator.sort(this.contextInitializers);
    for (ApplicationContextInitializer<ConfigurableApplicationContext> initializer : this.contextInitializers) {
        initializer.initialize(wac);
    }
}

From source file:org.springframework.web.reactive.DispatcherHandler.java

protected void initStrategies(ApplicationContext context) {
    Map<String, HandlerMapping> mappingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(context,
            HandlerMapping.class, true, false);

    ArrayList<HandlerMapping> mappings = new ArrayList<>(mappingBeans.values());
    AnnotationAwareOrderComparator.sort(mappings);
    this.handlerMappings = Collections.unmodifiableList(mappings);

    Map<String, HandlerAdapter> adapterBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(context,
            HandlerAdapter.class, true, false);

    this.handlerAdapters = new ArrayList<>(adapterBeans.values());
    AnnotationAwareOrderComparator.sort(this.handlerAdapters);

    Map<String, HandlerResultHandler> beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(context,
            HandlerResultHandler.class, true, false);

    this.resultHandlers = new ArrayList<>(beans.values());
    AnnotationAwareOrderComparator.sort(this.resultHandlers);
}

From source file:org.springframework.web.reactive.resource.ResourceUrlProvider.java

private void detectResourceHandlers(ApplicationContext context) {
    logger.debug("Looking for resource handler mappings");

    Map<String, SimpleUrlHandlerMapping> beans = context.getBeansOfType(SimpleUrlHandlerMapping.class);
    List<SimpleUrlHandlerMapping> mappings = new ArrayList<>(beans.values());
    AnnotationAwareOrderComparator.sort(mappings);

    mappings.forEach(mapping -> {//from   www  .  jav a 2 s  . co m
        mapping.getHandlerMap().forEach((pattern, handler) -> {
            if (handler instanceof ResourceWebHandler) {
                ResourceWebHandler resourceHandler = (ResourceWebHandler) handler;
                if (logger.isDebugEnabled()) {
                    logger.debug("Found resource handler mapping: URL pattern=\"" + pattern + "\", "
                            + "locations=" + resourceHandler.getLocations() + ", " + "resolvers="
                            + resourceHandler.getResourceResolvers());
                }
                this.handlerMap.put(pattern, resourceHandler);
            }
        });
    });
}

From source file:org.springframework.web.reactive.result.method.annotation.ControllerMethodResolver.java

private void initControllerAdviceCaches(@Nullable ApplicationContext applicationContext) {
    if (applicationContext == null) {
        return;/*from  w ww .  j  a  v  a 2s.  c  om*/
    }
    if (logger.isInfoEnabled()) {
        logger.info("Looking for @ControllerAdvice: " + applicationContext);
    }

    List<ControllerAdviceBean> beans = ControllerAdviceBean.findAnnotatedBeans(applicationContext);
    AnnotationAwareOrderComparator.sort(beans);

    for (ControllerAdviceBean bean : beans) {
        Class<?> beanType = bean.getBeanType();
        if (beanType != null) {
            Set<Method> attrMethods = selectMethods(beanType, ATTRIBUTE_METHODS);
            if (!attrMethods.isEmpty()) {
                this.modelAttributeAdviceCache.put(bean, attrMethods);
                if (logger.isInfoEnabled()) {
                    logger.info("Detected @ModelAttribute methods in " + bean);
                }
            }
            Set<Method> binderMethods = selectMethods(beanType, BINDER_METHODS);
            if (!binderMethods.isEmpty()) {
                this.initBinderAdviceCache.put(bean, binderMethods);
                if (logger.isInfoEnabled()) {
                    logger.info("Detected @InitBinder methods in " + bean);
                }
            }
            ExceptionHandlerMethodResolver resolver = new ExceptionHandlerMethodResolver(beanType);
            if (resolver.hasExceptionMappings()) {
                this.exceptionHandlerAdviceCache.put(bean, resolver);
                if (logger.isInfoEnabled()) {
                    logger.info("Detected @ExceptionHandler methods in " + bean);
                }
            }
        }
    }
}

From source file:org.springframework.web.servlet.DispatcherServlet.java

/**
 * Initialize the HandlerMappings used by this class.
 * <p>If no HandlerMapping beans are defined in the BeanFactory for this namespace,
 * we default to BeanNameUrlHandlerMapping.
 *///w ww . j a v  a2  s .c o  m
private void initHandlerMappings(ApplicationContext context) {
    this.handlerMappings = null;

    if (this.detectAllHandlerMappings) {
        // Find all HandlerMappings in the ApplicationContext, including ancestor contexts.
        Map<String, HandlerMapping> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(context,
                HandlerMapping.class, true, false);
        if (!matchingBeans.isEmpty()) {
            this.handlerMappings = new ArrayList<>(matchingBeans.values());
            // We keep HandlerMappings in sorted order.
            AnnotationAwareOrderComparator.sort(this.handlerMappings);
        }
    } else {
        try {
            HandlerMapping hm = context.getBean(HANDLER_MAPPING_BEAN_NAME, HandlerMapping.class);
            this.handlerMappings = Collections.singletonList(hm);
        } catch (NoSuchBeanDefinitionException ex) {
            // Ignore, we'll add a default HandlerMapping later.
        }
    }

    // Ensure we have at least one HandlerMapping, by registering
    // a default HandlerMapping if no other mappings are found.
    if (this.handlerMappings == null) {
        this.handlerMappings = getDefaultStrategies(context, HandlerMapping.class);
        if (logger.isDebugEnabled()) {
            logger.debug("No HandlerMappings found in servlet '" + getServletName() + "': using default");
        }
    }
}

From source file:org.springframework.web.servlet.DispatcherServlet.java

/**
 * Initialize the HandlerAdapters used by this class.
 * <p>If no HandlerAdapter beans are defined in the BeanFactory for this namespace,
 * we default to SimpleControllerHandlerAdapter.
 *//*from   w ww  . j  a v a2 s. c  o  m*/
private void initHandlerAdapters(ApplicationContext context) {
    this.handlerAdapters = null;

    if (this.detectAllHandlerAdapters) {
        // Find all HandlerAdapters in the ApplicationContext, including ancestor contexts.
        Map<String, HandlerAdapter> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(context,
                HandlerAdapter.class, true, false);
        if (!matchingBeans.isEmpty()) {
            this.handlerAdapters = new ArrayList<>(matchingBeans.values());
            // We keep HandlerAdapters in sorted order.
            AnnotationAwareOrderComparator.sort(this.handlerAdapters);
        }
    } else {
        try {
            HandlerAdapter ha = context.getBean(HANDLER_ADAPTER_BEAN_NAME, HandlerAdapter.class);
            this.handlerAdapters = Collections.singletonList(ha);
        } catch (NoSuchBeanDefinitionException ex) {
            // Ignore, we'll add a default HandlerAdapter later.
        }
    }

    // Ensure we have at least some HandlerAdapters, by registering
    // default HandlerAdapters if no other adapters are found.
    if (this.handlerAdapters == null) {
        this.handlerAdapters = getDefaultStrategies(context, HandlerAdapter.class);
        if (logger.isDebugEnabled()) {
            logger.debug("No HandlerAdapters found in servlet '" + getServletName() + "': using default");
        }
    }
}