下面列出了怎么用javax.annotation.Priority的API类实例代码及写法,或者点击链接到github查看源代码。
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);
}
});
}
/**
* 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());
}
}
@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());
}
}
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());
}
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());
}
@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();
}
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);
}
}
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));
});
}
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();
}
}
}
private static int getPriority(Converter<?> converter) {
int priority = 100;
Priority priorityAnnotation = converter.getClass().getAnnotation(Priority.class);
if (priorityAnnotation != null) {
priority = priorityAnnotation.value();
}
return priority;
}
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
}
}
/**
* 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;
}
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");
}
private int getPriority(Object o) {
Priority priority = o.getClass().getAnnotation(Priority.class);
if (priority != null) {
return priority.value();
} else {
return 0;
}
}
/**
* 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);
}
}
@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();
}
}
}
});
}
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);
}
}
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);
}
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();
}
}
}
void onApplicationStart(@Observes @Priority(javax.interceptor.Interceptor.Priority.LIBRARY_BEFORE) StartupEvent event) {
try {
mediatorManager.initializeAndRun();
} catch (Exception e) {
throw new DeploymentException(e);
}
}
@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);
}
/**
* 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;
}
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");
}
/**
* 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);
}
}
@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());
}
/**
* 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;
}
/**
* 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;
}
/**
* 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;
}
/**
* 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;
}
/**
* 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;
}