javax.annotation.Priority Java Examples

The following examples show how to use javax.annotation.Priority. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DescendingPriorityComparator.java    From portals-pluto with Apache License 2.0 6 votes vote down vote up
@Override
public int compare(Object object1, Object object2) {
	Class<?> class1 = object1.getClass();
	Priority priority1 = class1.getAnnotation(Priority.class);
	Class<?> class2 = object2.getClass();
	Priority priority2 = class2.getAnnotation(Priority.class);

	if ((priority1 == null) && (priority2 == null)) {
		return 0;
	}
	else if (priority1 == null) {
		return Integer.compare(priority2.value(), _defaultPriority);
	}
	else if (priority2 == null) {
		return Integer.compare(_defaultPriority, priority1.value());
	}
	else {
		return Integer.compare(priority1.value(), priority2.value());
	}
}
 
Example #2
Source File: PropertyFilterComparator.java    From incubator-tamaya with Apache License 2.0 6 votes vote down vote up
/**
 * Compare 2 filters for ordering the filter chain.
 *
 * @param filter1 the first filter
 * @param filter2 the second filter
 * @return the comparison result
 */
private int comparePropertyFilters(PropertyFilter filter1, PropertyFilter filter2) {
    int ord1 = 0;
    int ord2 = 0;

    if(ServiceContext.PRIORITY_ANNOTATION_AVAILABLE) {
        Priority prio1 = filter1.getClass().getAnnotation(Priority.class);
        Priority prio2 = filter2.getClass().getAnnotation(Priority.class);
        if(prio1!=null) {
            ord1 = prio1.value();
        }
        if(prio2!=null) {
            ord2 = prio2.value();
        }
    }
    if (ord1 < ord2) {
        return -1;
    } else if (ord1 > ord2) {
        return 1;
    } else {
        return filter1.getClass().getName().compareTo(filter2.getClass().getName());
    }
}
 
Example #3
Source File: PriorityAwareServiceProvider.java    From jsr354-ri with Apache License 2.0 6 votes vote down vote up
public static int compareServices(Object o1, Object o2) {
    int prio1 = 0;
    int prio2 = 0;
    Priority prio1Annot = o1.getClass().getAnnotation(Priority.class);
    if (prio1Annot != null) {
        prio1 = prio1Annot.value();
    }
    Priority prio2Annot = o2.getClass().getAnnotation(Priority.class);
    if (prio2Annot != null) {
        prio2 = prio2Annot.value();
    }
    if (prio1 < prio2) {
        return 1;
    }
    if (prio2 < prio1) {
        return -1;
    }
    return o2.getClass().getSimpleName().compareTo(o1.getClass().getSimpleName());
}
 
Example #4
Source File: PriorityAwareServiceProvider.java    From javamoney-lib with Apache License 2.0 6 votes vote down vote up
public static int compareServices(Object o1, Object o2) {
    int prio1 = 0;
    int prio2 = 0;
    Priority prio1Annot = o1.getClass().getAnnotation(Priority.class);
    if (prio1Annot != null) {
        prio1 = prio1Annot.value();
    }
    Priority prio2Annot = o2.getClass().getAnnotation(Priority.class);
    if (prio2Annot != null) {
        prio2 = prio2Annot.value();
    }
    if (prio1 < prio2) {
        return 1;
    }
    if (prio2 < prio1) {
        return -1;
    }
    return o2.getClass().getSimpleName().compareTo(o1.getClass().getSimpleName());
}
 
Example #5
Source File: SmallRyeConfigBuilder.java    From smallrye-config with Apache License 2.0 6 votes vote down vote up
private InterceptorWithPriority(ConfigSourceInterceptor interceptor) {
    this(new ConfigSourceInterceptorFactory() {
        @Override
        public ConfigSourceInterceptor getInterceptor(final ConfigSourceInterceptorContext context) {
            return interceptor;
        }

        @Override
        public OptionalInt getPriority() {
            final OptionalInt priority = ConfigSourceInterceptorFactory.super.getPriority();
            if (priority.isPresent()) {
                return priority;
            }

            return Optional.ofNullable(interceptor.getClass().getAnnotation(Priority.class))
                    .map(priority1 -> OptionalInt.of(priority1.value()))
                    .orElse(OPTIONAL_DEFAULT_PRIORITY);
        }
    });
}
 
Example #6
Source File: SimpleScheduler.java    From quarkus with Apache License 2.0 5 votes vote down vote up
void start(@Observes @Priority(Interceptor.Priority.PLATFORM_BEFORE) StartupEvent event) {
    if (scheduledExecutor == null) {
        return;
    }
    // Try to compute the initial delay to execute the checks near to the whole second
    // Note that this does not guarantee anything, it's just best effort
    LocalDateTime now = LocalDateTime.now();
    LocalDateTime trunc = now.plusSeconds(1).truncatedTo(ChronoUnit.SECONDS);
    scheduledExecutor.scheduleAtFixedRate(this::checkTriggers, ChronoUnit.MILLIS.between(now, trunc), CHECK_PERIOD,
            TimeUnit.MILLISECONDS);
}
 
Example #7
Source File: OSGIServiceComparator.java    From incubator-tamaya with Apache License 2.0 5 votes vote down vote up
/**
 * Checks the given type optionally annotated with a @Priority. If present the annotation's createValue is evaluated.
 * If no such annotation is present, a default priority {@code 1} is returned.
 *
 * @param type the type, not {@code null}.
 * @return a priority, by default 1.
 */
public static int getPriority(Class<? extends Object> type) {
    int prio = 1;
    if(ServiceContext.PRIORITY_ANNOTATION_AVAILABLE) {
        Priority priority = type.getAnnotation(Priority.class);
        if (priority != null) {
            prio = priority.value();
        }
    }
    return prio;
}
 
Example #8
Source File: DefaultServiceContext.java    From incubator-tamaya with Apache License 2.0 5 votes vote down vote up
/**
 * Checks the given instance for a @Priority annotation. If present the annotation's createValue is evaluated. If no such
 * annotation is present, a default priority of {@code 1} is returned.
 * @param o the instance, not {@code null}.
 * @return a priority, by default 1.
 */
public static int getPriority(Object o){
    int prio = 1;
    if(ServiceContext.PRIORITY_ANNOTATION_AVAILABLE) {
        Priority priority = o.getClass().getAnnotation(Priority.class);
        if (priority != null) {
            prio = priority.value();
        }
    }
    return prio;
}
 
Example #9
Source File: PriorityServiceComparator.java    From incubator-tamaya with Apache License 2.0 5 votes vote down vote up
/**
 * Checks the given type optionally annotated with a @Priority. If present the annotation's createValue is evaluated.
 * If no such annotation is present, a default priority {@code 1} is returned.
 *
 * @param type the type, not {@code null}.
 * @return a priority, by default 1.
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static int getPriority(Class type) {
    int prio = 1;
    if(ServiceContext.PRIORITY_ANNOTATION_AVAILABLE) {
        Priority priority = (Priority) type.getAnnotation(Priority.class);
        if (priority != null) {
            prio = priority.value();
        }
    }
    return prio;
}
 
Example #10
Source File: ServiceContext.java    From incubator-tamaya with Apache License 2.0 5 votes vote down vote up
/**
 * Checks the given instance for a @Priority annotation. If present the annotation's value is evaluated. If no such
 * annotation is present, a default priority of {@code 1} is returned.
 * @param o the instance, not {@code null}.
 * @return a priority, by default 1.
 */
static int getPriority(Object o){
    int prio = 1;
    if(PRIORITY_ANNOTATION_AVAILABLE) {
        Priority priority = o.getClass().getAnnotation(Priority.class);
        if (priority != null) {
            prio = priority.value();
        }
    }
    return prio;
}
 
Example #11
Source File: SmallRyeFaultToleranceProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@BuildStep
AnnotationsTransformerBuildItem transformInterceptorPriority(BeanArchiveIndexBuildItem index) {
    return new AnnotationsTransformerBuildItem(new AnnotationsTransformer() {
        @Override
        public boolean appliesTo(Kind kind) {
            return kind == Kind.CLASS;
        }

        @Override
        public void transform(TransformationContext ctx) {
            if (ctx.isClass()) {
                if (!ctx.getTarget().asClass().name().toString()
                        .equals("io.smallrye.faulttolerance.FaultToleranceInterceptor")) {
                    return;
                }
                final Config config = ConfigProvider.getConfig();

                OptionalInt priority = config.getValue("mp.fault.tolerance.interceptor.priority", OptionalInt.class);
                if (priority.isPresent()) {
                    ctx.transform()
                            .remove(ann -> ann.name().toString().equals(Priority.class.getName()))
                            .add(Priority.class, AnnotationValue.createIntegerValue("value", priority.getAsInt()))
                            .done();
                }
            }
        }
    });
}
 
Example #12
Source File: QuartzScheduler.java    From quarkus with Apache License 2.0 5 votes vote down vote up
void start(@Observes @Priority(Interceptor.Priority.PLATFORM_BEFORE) StartupEvent startupEvent) {
    if (scheduler == null) {
        return;
    }
    try {
        scheduler.start();
    } catch (SchedulerException e) {
        throw new IllegalStateException("Unable to start Scheduler", e);
    }
}
 
Example #13
Source File: TestMediaTypeFilter.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Test
public void testAnnotations() {
  // Check that the class is correctly annotated
  assertNotNull("@PreMatching annotation is required to modify headers", MediaTypeFilter.class.getAnnotation(PreMatching.class));
  Priority priority = MediaTypeFilter.class.getAnnotation(Priority.class);
  assertNotNull("@Priority annotation is required to modify headers", priority);

  assertTrue("priority should be higher than HEADER_DECORATOR", priority.value() <= Priorities.HEADER_DECORATOR);
}
 
Example #14
Source File: QuarkusWorkerPoolRegistry.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public void terminate(
        @Observes(notifyObserver = Reception.IF_EXISTS) @Priority(100) @BeforeDestroyed(ApplicationScoped.class) Object event) {
    if (!workerExecutors.isEmpty()) {
        for (WorkerExecutor executor : workerExecutors.values()) {
            executor.close();
        }
    }
}
 
Example #15
Source File: SmallRyeReactiveMessagingLifecycle.java    From quarkus with Apache License 2.0 5 votes vote down vote up
void onApplicationStart(@Observes @Priority(javax.interceptor.Interceptor.Priority.LIBRARY_BEFORE) StartupEvent event) {
    try {
        mediatorManager.initializeAndRun();
    } catch (Exception e) {
        throw new DeploymentException(e);
    }
}
 
Example #16
Source File: Filter.java    From redkale with Apache License 2.0 5 votes vote down vote up
@Override
public int compareTo(Object o) {
    if (!(o instanceof Filter)) return 1;
    Priority p1 = this.getClass().getAnnotation(Priority.class);
    Priority p2 = o.getClass().getAnnotation(Priority.class);
    return (p2 == null ? 0 : p2.value()) - (p1 == null ? 0 : p1.value());
}
 
Example #17
Source File: OzarkCdiExtension.java    From ozark with Apache License 2.0 5 votes vote down vote up
/**
 * Search for {@link Controller} annotation and patch AnnotatedType.
 * Note: PLATFORM_AFTER is required so we execute AFTER the Hibernate Validator Extension
 */
public <T> void processAnnotatedType(
        @Observes @Priority(Interceptor.Priority.PLATFORM_AFTER) @WithAnnotations({Controller.class})
                ProcessAnnotatedType<T> pat) {

    AnnotatedType<T> replacement = annotatedTypeProcessor.getReplacement(pat.getAnnotatedType());
    if (replacement != null) {
        log.log(Level.FINE, "Replacing AnnotatedType of class: {0}", replacement.getJavaClass().getName());
        pat.setAnnotatedType(replacement);
    }

}
 
Example #18
Source File: LocaleResolverChain.java    From ozark with Apache License 2.0 5 votes vote down vote up
public Locale resolve(ContainerRequestContext requestContext) {

        // prepare context instance
        LocaleResolverContext context = new LocaleResolverContextImpl(configuration, requestContext);

        List<LocaleResolver> resolvers = CdiUtils.getApplicationBeans(LocaleResolver.class);

        // candidates as sorted list
        List<LocaleResolver> candidates = StreamSupport.stream(resolvers.spliterator(), false)
                .sorted((resolver1, resolver2) -> {
                    final Priority prio1 = getAnnotation(resolver1.getClass(), Priority.class);
                    final Priority prio2 = getAnnotation(resolver2.getClass(), Priority.class);
                    final int value1 = prio1 != null ? prio1.value() : 1000;
                    final int value2 = prio2 != null ? prio2.value() : 1000;
                    return value2 - value1;
                })
                .collect(Collectors.toList());

        // do the resolving
        for (LocaleResolver candidate : candidates) {
            Locale locale = candidate.resolveLocale(context);
            if (locale != null) {
                return locale;
            }
        }

        throw new IllegalStateException("Could not resolve locale with any of the " + candidates.size()
                + " resolver implementations");

    }
 
Example #19
Source File: ViewEngineFinder.java    From ozark with Apache License 2.0 5 votes vote down vote up
/**
 * Finds view engine for a viewable.
 *
 * @param viewable the viewable to be used.
 * @return selected view engine or {@code null} if none found.
 */
public ViewEngine find(Viewable viewable) {
    Optional<ViewEngine> engine;
    final String view = viewable.getView();

    // If engine specified in viewable, use it
    final Class<? extends ViewEngine> engineClass = viewable.getViewEngine();
    if (engineClass != null) {
        engine = Optional.of(cdiUtils.newBean(engineClass));
    } else {
        // Check cache first
        engine = Optional.ofNullable(cache.get(view));

        if (!engine.isPresent()) {
            List<ViewEngine> engines = CdiUtils.getApplicationBeans(ViewEngine.class);

            // Gather set of candidates
            final Set<ViewEngine> candidates = engines.stream()
                    .filter(e -> e.supports(view)).collect(toSet());

            // Find candidate with highest priority
            engine = candidates.stream().max(
                    (e1, e2) -> {
                        final Priority p1 = getAnnotation(e1.getClass(), Priority.class);
                        final int v1 = p1 != null ? p1.value() : ViewEngine.PRIORITY_APPLICATION;
                        final Priority p2 = getAnnotation(e2.getClass(), Priority.class);
                        final int v2 = p2 != null ? p2.value() : ViewEngine.PRIORITY_APPLICATION;
                        return v1 - v2;
                    });
            // Update cache
            if (engine.isPresent()) {
                cache.put(view, engine.get());
            }
        }
    }
    return engine.isPresent() ? engine.get() : null;
}
 
Example #20
Source File: KrazoCdiExtension.java    From krazo with Apache License 2.0 5 votes vote down vote up
/**
 * Search for {@link Controller} annotation and patch AnnotatedType.
 * Note: PLATFORM_AFTER is required so we execute AFTER the Hibernate Validator Extension
 */
public <T> void processAnnotatedType(
        @Observes @Priority(Interceptor.Priority.PLATFORM_AFTER) @WithAnnotations({Controller.class})
                ProcessAnnotatedType<T> pat) {

    AnnotatedType<T> replacement = annotatedTypeProcessor.getReplacement(pat.getAnnotatedType());
    if (replacement != null) {
        log.log(Level.FINE, "Replacing AnnotatedType of class: {0}", replacement.getJavaClass().getName());
        pat.setAnnotatedType(replacement);
    }

}
 
Example #21
Source File: TestDatawaveUserService.java    From datawave with Apache License 2.0 5 votes vote down vote up
protected List<String> readAccumuloAuthorizations() {
    try {
        Connector connector = accumuloConnectionFactory.getConnection(null, AccumuloConnectionFactory.Priority.ADMIN, new HashMap<>());
        Authorizations auths = connector.securityOperations().getUserAuthorizations(connector.whoami());
        return Arrays.asList(auths.toString().split("\\s*,\\s*"));
    } catch (Exception e) {
        throw new RuntimeException("Unable to acquire accumulo connector: " + e.getMessage(), e);
    }
}
 
Example #22
Source File: TestDatawaveUserService.java    From datawave with Apache License 2.0 5 votes vote down vote up
@PostConstruct
protected void init() {
    // @formatter:off
    Comparator<Bean<?>> beanComparator = Comparator.comparing(
        b -> b.getBeanClass().isAnnotationPresent(Priority.class)
           ? b.getBeanClass().getAnnotation(Priority.class).value()
           : Integer.MIN_VALUE);

    Bean<?> alternate = beanManager.getBeans(CachedDatawaveUserService.class).stream()
            .filter(b -> b.getBeanClass() != getClass())
            .sorted(beanComparator.reversed())
            .findFirst().orElse(null);

    Bean<?> basicAlternate = beanManager.getBeans(DatawaveUserService.class).stream()
            .filter(b -> b.getBeanClass() != getClass())
            .sorted(beanComparator.reversed())
            .findFirst().orElse(null);
    // @formatter:on
    
    if (alternate == null && basicAlternate == null) {
        throw new IllegalStateException("No delegate " + CachedDatawaveUserService.class + " or " + DatawaveUser.class + " was found.");
    } else if (alternate != null) {
        delegateContext = beanManager.createCreationalContext(alternate);
        delegateCachedService = (CachedDatawaveUserService) beanManager.getReference(alternate, alternate.getBeanClass(), delegateContext);
        delegateService = delegateCachedService;
    } else {
        delegateContext = beanManager.createCreationalContext(basicAlternate);
        delegateService = (DatawaveUserService) beanManager.getReference(basicAlternate, basicAlternate.getBeanClass(), delegateContext);
    }
    
    readTestUsers();
}
 
Example #23
Source File: OSGIServiceComparator.java    From jsr354-ri with Apache License 2.0 5 votes vote down vote up
/**
 * Checks the given type optionally annotated with a @Priority. If present the annotation's value is evaluated.
 * If no such annotation is present, a default priority {@code 1} is returned.
 *
 * @param type the type, not {@code null}.
 * @return a priority, by default 1.
 */
public static int getPriority(Class<?> type) {
    int prio = 1;
    Priority priority = type.getAnnotation(Priority.class);
    if (priority != null) {
        prio = priority.value();
    }
    return prio;
}
 
Example #24
Source File: FaultToleranceExtension.java    From smallrye-fault-tolerance with Apache License 2.0 5 votes vote down vote up
void changeInterceptorPriority(@Observes ProcessAnnotatedType<FaultToleranceInterceptor> event) {
    ConfigProvider.getConfig()
            .getOptionalValue("mp.fault.tolerance.interceptor.priority", Integer.class)
            .ifPresent(configuredInterceptorPriority -> {
                event.configureAnnotatedType()
                        .remove(ann -> ann instanceof Priority)
                        .add(new PriorityLiteral(configuredInterceptorPriority));
            });
}
 
Example #25
Source File: PriorityServiceComparator.java    From jsr354-ri with Apache License 2.0 5 votes vote down vote up
/**
   * Checks the given type optionally annotated with a @Priority. If present the annotation's value is evaluated.
   * If no such annotation is present, a default priority {@code 1} is returned.
   *
   * @param type the type, not {@code null}.
   * @return a priority, by default 1.
   */
  @SuppressWarnings({ "rawtypes", "unchecked" })
  public static int getPriority(Class type) {
      int prio = 1;
Priority priority = (Priority)type.getAnnotation(Priority.class);
      if (priority != null) {
          prio = priority.value();
      }
      return prio;
  }
 
Example #26
Source File: WorkerPoolRegistry.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
public void terminate(
        @Observes(notifyObserver = Reception.IF_EXISTS) @Priority(100) @BeforeDestroyed(ApplicationScoped.class) Object event) {
    if (!workerExecutors.isEmpty()) {
        for (WorkerExecutor executor : workerExecutors.values()) {
            executor.close();
        }
    }
}
 
Example #27
Source File: SmallRyeConfigBuilder.java    From smallrye-config with Apache License 2.0 5 votes vote down vote up
private static int getPriority(Converter<?> converter) {
    int priority = 100;
    Priority priorityAnnotation = converter.getClass().getAnnotation(Priority.class);
    if (priorityAnnotation != null) {
        priority = priorityAnnotation.value();
    }
    return priority;
}
 
Example #28
Source File: MonitorAccountAccess.java    From Java-EE-8-and-Angular with MIT License 5 votes vote down vote up
public void lockForFailedAttempts(
        @Observes @Priority(1) LoginEvent event) {
    if(event.getAttemptsMade() >= MAX_ATTEMPTS) {
        event.setLockAccount(true);
        System.out.println("Account is locked");
        //do more work to push status in database
    }
}
 
Example #29
Source File: ViewEngineFinder.java    From krazo with Apache License 2.0 5 votes vote down vote up
/**
 * Finds view engine for a viewable.
 *
 * @param viewable the viewable to be used.
 * @return selected view engine or {@code null} if none found.
 */
public ViewEngine find(Viewable viewable) {
    Optional<ViewEngine> engine;
    final String view = viewable.getView();

    // If engine specified in viewable, use it
    final Class<? extends ViewEngine> engineClass = viewable.getViewEngine();
    if (engineClass != null) {
        engine = Optional.of(cdiUtils.newBean(engineClass));
    } else {
        // Check cache first
        engine = Optional.ofNullable(cache.get(view));

        if (!engine.isPresent()) {
            List<ViewEngine> engines = CdiUtils.getApplicationBeans(ViewEngine.class);

            // Gather set of candidates
            final Set<ViewEngine> candidates = engines.stream()
                    .filter(e -> e.supports(view)).collect(toSet());

            // Find candidate with highest priority
            engine = candidates.stream().max(
                    (e1, e2) -> {
                        final Priority p1 = getAnnotation(e1.getClass(), Priority.class);
                        final int v1 = p1 != null ? p1.value() : ViewEngine.PRIORITY_APPLICATION;
                        final Priority p2 = getAnnotation(e2.getClass(), Priority.class);
                        final int v2 = p2 != null ? p2.value() : ViewEngine.PRIORITY_APPLICATION;
                        return v1 - v2;
                    });
            // Update cache
            if (engine.isPresent()) {
                cache.put(view, engine.get());
            }
        }
    }
    return engine.isPresent() ? engine.get() : null;
}
 
Example #30
Source File: LocaleResolverChain.java    From krazo with Apache License 2.0 5 votes vote down vote up
public Locale resolve(ContainerRequestContext requestContext) {

        // prepare context instance
        LocaleResolverContext context = new LocaleResolverContextImpl(configuration, requestContext);

        List<LocaleResolver> resolvers = CdiUtils.getApplicationBeans(LocaleResolver.class);

        // candidates as sorted list
        List<LocaleResolver> candidates = StreamSupport.stream(resolvers.spliterator(), false)
                .sorted((resolver1, resolver2) -> {
                    final Priority prio1 = getAnnotation(resolver1.getClass(), Priority.class);
                    final Priority prio2 = getAnnotation(resolver2.getClass(), Priority.class);
                    final int value1 = prio1 != null ? prio1.value() : 1000;
                    final int value2 = prio2 != null ? prio2.value() : 1000;
                    return value2 - value1;
                })
                .collect(Collectors.toList());

        // do the resolving
        for (LocaleResolver candidate : candidates) {
            Locale locale = candidate.resolveLocale(context);
            if (locale != null) {
                return locale;
            }
        }

        throw new IllegalStateException("Could not resolve locale with any of the " + candidates.size()
                + " resolver implementations");

    }