java.lang.annotation.Annotation Java Examples
The following examples show how to use
java.lang.annotation.Annotation.
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: BasicBinder.java From jadira with Apache License 2.0 | 6 votes |
private <S, T> Converter<S, T> determineConverter(Class<S> candidateClass, Class<T> output, Class<? extends Annotation> qualifier) { if (!candidateClass.equals(Object.class)) { Converter<S, T> match = findConverter(candidateClass, output, qualifier); if (match != null) { return match; } @SuppressWarnings("unchecked") Class<S>[] interfaces = (Class<S>[])candidateClass.getInterfaces(); for (Class<S> candidateInterface : interfaces) { match = determineConverter(candidateInterface, output, qualifier); if (match != null) { return match; } } Class<? super S> superClass = (Class<? super S>)candidateClass.getSuperclass(); @SuppressWarnings("unchecked") Converter<S,T> superMatch = (Converter<S, T>) determineConverter(superClass, output, qualifier); return superMatch; } else { return null; } }
Example #2
Source File: AnnotatedElementUtils.java From java-technology-stack with MIT License | 6 votes |
/** * Build an adapted {@link AnnotatedElement} for the given annotations, * typically for use with other methods on {@link AnnotatedElementUtils}. * @param annotations the annotations to expose through the {@code AnnotatedElement} * @since 4.3 */ public static AnnotatedElement forAnnotations(final Annotation... annotations) { return new AnnotatedElement() { @Override @SuppressWarnings("unchecked") @Nullable public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { for (Annotation ann : annotations) { if (ann.annotationType() == annotationClass) { return (T) ann; } } return null; } @Override public Annotation[] getAnnotations() { return annotations; } @Override public Annotation[] getDeclaredAnnotations() { return annotations; } }; }
Example #3
Source File: DefaultParameterContextTest.java From mango with Apache License 2.0 | 6 votes |
@Test public void testTryExpandBindingParameter() throws Exception { List<Annotation> empty = Collections.emptyList(); ParameterDescriptor p0 = ParameterDescriptor.create(0, String.class, empty, "1"); ParameterDescriptor p1 = ParameterDescriptor.create(1, User.class, empty, "2"); List<ParameterDescriptor> pds = Arrays.asList(p0, p1); ParameterContext ctx = DefaultParameterContext.create(pds); BindingParameter bp = BindingParameter.create("userBag", "item.itemId", null); BindingParameter nbp = ctx.tryExpandBindingParameter(bp); bp = BindingParameter.create("userId", "", null); nbp = ctx.tryExpandBindingParameter(bp); assertThat(nbp, equalTo(BindingParameter.create("2", "userId", null))); bp = BindingParameter.create("userIds", "", null); nbp = ctx.tryExpandBindingParameter(bp); assertThat(nbp, nullValue()); }
Example #4
Source File: TargetMethodAnalyzer.java From guice-persist-orient with MIT License | 6 votes |
@SuppressWarnings({"unchecked", "PMD.AvoidInstantiatingObjectsInLoops"}) private static MatchedMethod analyzeMethod(final Method method, final List<Class<?>> params, final GenericsContext targetGenerics) { final List<ParamInfo> ordinalParamsInfo = Lists.newArrayList(); final List<Class<?>> types = targetGenerics.method(method).resolveParameters(); final Annotation[][] annotations = method.getParameterAnnotations(); boolean extended = false; for (int i = 0; i < types.size(); i++) { // ignore extensions (they always add value) try { if (ExtUtils.findParameterExtension(annotations[i]) == null) { ordinalParamsInfo.add(new ParamInfo(i, types.get(i))); } else { extended = true; } } catch (Exception ex) { throw new IllegalStateException(String.format("Error analysing method %s parameter %s", RepositoryUtils.methodToString(method), i), ex); } } MatchedMethod res = null; if (isParametersCompatible(params, ordinalParamsInfo)) { res = new MatchedMethod(method, ordinalParamsInfo, extended); } return res; }
Example #5
Source File: DataIndexBuilder.java From simple-spring-memcached with MIT License | 6 votes |
private Integer getIndexOfAnnotatedParam(final Method method, final Class<? extends Annotation> annotationClass) { final Annotation[][] paramAnnotationArrays = method.getParameterAnnotations(); Integer foundIndex = null; if (paramAnnotationArrays != null && paramAnnotationArrays.length > 0) { for (int ix = 0; ix < paramAnnotationArrays.length; ix++) { if (getAnnotation(annotationClass, paramAnnotationArrays[ix]) != null) { if (foundIndex != null) { throwException("Multiple annotations of type [%s] found on method [%s]", annotationClass, method); } foundIndex = ix; } } } return foundIndex; }
Example #6
Source File: ExternalMetadataReader.java From openjdk-8 with GNU General Public License v2.0 | 6 votes |
public Annotation[][] getParameterAnnotations(final Method m) { Merger<Annotation[][]> merger = new Merger<Annotation[][]>(reader(m.getDeclaringClass())) { Annotation[][] reflection() { return ExternalMetadataReader.super.getParameterAnnotations(m); } Annotation[][] external() { JavaMethod jm = getJavaMethod(m, reader); Annotation[][] a = m.getParameterAnnotations(); for (int i = 0; i < m.getParameterTypes().length; i++) { if (jm == null) continue; JavaParam jp = jm.getJavaParams().getJavaParam().get(i); a[i] = getAnnotations(jp.getParamAnnotation()); } return a; } }; return merger.merge(); }
Example #7
Source File: FileBinder.java From restcommander with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") public File bind(String name, Annotation[] annotations, String value, Class actualClass, Type genericType) { if (value == null || value.trim().length() == 0) { return null; } List<Upload> uploads = (List<Upload>) Request.current().args.get("__UPLOADS"); for (Upload upload : uploads) { if (upload.getFieldName().equals(value)) { File file = upload.asFile(); if (file.length() > 0) { return file; } return null; } } return null; }
Example #8
Source File: MultipartProvider.java From cxf with Apache License 2.0 | 6 votes |
private <T> Object fromAttachment(Attachment multipart, Class<T> c, Type t, Annotation[] anns) throws IOException { if (DataHandler.class.isAssignableFrom(c)) { return multipart.getDataHandler(); } else if (DataSource.class.isAssignableFrom(c)) { return multipart.getDataHandler().getDataSource(); } else if (Attachment.class.isAssignableFrom(c)) { return multipart; } else { if (mediaTypeSupported(multipart.getContentType())) { mc.put("org.apache.cxf.multipart.embedded", true); mc.put("org.apache.cxf.multipart.embedded.ctype", multipart.getContentType()); mc.put("org.apache.cxf.multipart.embedded.input", multipart.getDataHandler().getInputStream()); anns = new Annotation[]{}; } MessageBodyReader<T> r = mc.getProviders().getMessageBodyReader(c, t, anns, multipart.getContentType()); if (r != null) { InputStream is = multipart.getDataHandler().getInputStream(); return r.readFrom(c, t, anns, multipart.getContentType(), multipart.getHeaders(), is); } } return null; }
Example #9
Source File: GrpcServerHost.java From grpc-java-contrib with BSD 3-Clause "New" or "Revised" License | 6 votes |
private Collection<BindableService> getServicesFromApplicationContext() { Map<String, Object> possibleServices = new HashMap<>(); for (Class<? extends Annotation> annotation : serverFactory.forAnnotations()) { possibleServices.putAll(applicationContext.getBeansWithAnnotation(annotation)); } Collection<String> invalidServiceNames = possibleServices.entrySet().stream() .filter(e -> !(e.getValue() instanceof BindableService)) .map(Map.Entry::getKey) .collect(Collectors.toList()); if (!invalidServiceNames.isEmpty()) { throw new IllegalStateException((format( "The following beans are annotated with @GrpcService, but are not BindableServices: %s", String.join(", ", invalidServiceNames)))); } return possibleServices.values().stream().map(s -> (BindableService) s).collect(Collectors.toList()); }
Example #10
Source File: RouteExecutionStrategyUtils.java From servicetalk with Apache License 2.0 | 6 votes |
/** * Returns {@link ExecutionStrategy} for the specified {@link Method} and validates that configuration of * {@link RouteExecutionStrategy} annotation is correct if present. * * @param method {@link Method} to validate * @param clazz {@link Class} to validate * @param strategyFactory a {@link RouteExecutionStrategyFactory} that creates a specific{@link ExecutionStrategy} * @param errors collection to track all errors related to misconfiguration * @param noOffloadsExecutionStrategy an {@link ExecutionStrategy} for {@link NoOffloadsRouteExecutionStrategy} * @param <T> specific implementation type of {@link ExecutionStrategy} * @return a defined {@link ExecutionStrategy} or {@code null} if not defined */ @Nullable public static <T extends ExecutionStrategy> T getAndValidateRouteExecutionStrategyAnnotationIfPresent( final Method method, final Class<?> clazz, final RouteExecutionStrategyFactory<T> strategyFactory, final Set<String> errors, final T noOffloadsExecutionStrategy) { final Annotation annotation = validateAnnotation(method, clazz, errors); if (annotation == null) { return null; } if (annotation instanceof NoOffloadsRouteExecutionStrategy) { return noOffloadsExecutionStrategy; } return validateId(annotation, method, strategyFactory, errors); }
Example #11
Source File: RouteExecutionStrategyUtils.java From servicetalk with Apache License 2.0 | 6 votes |
/** * Returns {@link RouteExecutionStrategy} annotation if exists on {@link Method} or {@link Class}. * * @param method an endpoint method * @param clazz an endpoint class * @return {@link RouteExecutionStrategy} annotation if exists on {@link Method} or {@link Class} */ @Nullable public static Annotation getRouteExecutionStrategyAnnotation(final Method method, final Class<?> clazz) { Annotation annotation = method.getAnnotation(NoOffloadsRouteExecutionStrategy.class); if (annotation != null) { return annotation; } annotation = method.getAnnotation(RouteExecutionStrategy.class); if (annotation != null) { return annotation; } annotation = clazz.getAnnotation(NoOffloadsRouteExecutionStrategy.class); if (annotation != null) { return annotation; } return clazz.getAnnotation(RouteExecutionStrategy.class); }
Example #12
Source File: NativeHeaderTest.java From jdk8u60 with GNU General Public License v2.0 | 6 votes |
/** Combo test to run all test cases in all modes. */ void run() throws Exception { javac = JavacTool.create(); fm = javac.getStandardFileManager(null, null, null); for (RunKind rk: RunKind.values()) { for (GenKind gk: GenKind.values()) { for (Method m: getClass().getDeclaredMethods()) { Annotation a = m.getAnnotation(Test.class); if (a != null) { init(rk, gk, m.getName()); try { m.invoke(this, new Object[] { rk, gk }); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); throw (cause instanceof Exception) ? ((Exception) cause) : e; } System.err.println(); } } } } System.err.println(testCount + " tests" + ((errorCount == 0) ? "" : ", " + errorCount + " errors")); if (errorCount > 0) throw new Exception(errorCount + " errors found"); }
Example #13
Source File: PropertiesReader.java From boost with Eclipse Public License 1.0 | 6 votes |
@Override public Properties readFrom(Class<Properties> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { JsonReader jr = Json.createReader(entityStream); JsonObject json = jr.readObject(); Properties retVal = new Properties(); json.keySet().forEach(key -> { JsonValue value = json.get(key); if (!JsonValue.NULL.equals(value)) { if (value.getValueType() != JsonValue.ValueType.STRING) { throw new IllegalArgumentException( "Non-String JSON prop value found in payload. Sample data is more than this sample can deal with. It's not intended to handle any payload."); } JsonString jstr = (JsonString) value; retVal.setProperty(key, jstr.getString()); } }); return retVal; }
Example #14
Source File: PageableMethodArgumentResolver.java From es with Apache License 2.0 | 6 votes |
/** * Asserts that every {@link Pageable} parameter of the given parameters carries an {@link org.springframework.beans.factory.annotation.Qualifier} annotation to * distinguish them from each other. * * @param parameterTypes * @param annotations */ private void assertQualifiersFor(Class<?>[] parameterTypes, Annotation[][] annotations) { Set<String> values = new HashSet<String>(); for (int i = 0; i < annotations.length; i++) { if (Pageable.class.equals(parameterTypes[i])) { Qualifier qualifier = findAnnotation(annotations[i]); if (null == qualifier) { throw new IllegalStateException( "Ambiguous Pageable arguments in handler method. If you use multiple parameters of type Pageable you need to qualify them with @Qualifier"); } if (values.contains(qualifier.value())) { throw new IllegalStateException("Values of the user Qualifiers must be unique!"); } values.add(qualifier.value()); } } }
Example #15
Source File: NativeHeaderTest.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
/** Combo test to run all test cases in all modes. */ void run() throws Exception { javac = JavacTool.create(); fm = javac.getStandardFileManager(null, null, null); for (RunKind rk: RunKind.values()) { for (GenKind gk: GenKind.values()) { for (Method m: getClass().getDeclaredMethods()) { Annotation a = m.getAnnotation(Test.class); if (a != null) { init(rk, gk, m.getName()); try { m.invoke(this, new Object[] { rk, gk }); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); throw (cause instanceof Exception) ? ((Exception) cause) : e; } System.err.println(); } } } } System.err.println(testCount + " tests" + ((errorCount == 0) ? "" : ", " + errorCount + " errors")); if (errorCount > 0) throw new Exception(errorCount + " errors found"); }
Example #16
Source File: TarsInvokeContext.java From TarsJava with BSD 3-Clause "New" or "Revised" License | 5 votes |
@SuppressWarnings("unchecked") public TarsInvokeContext(Method method, Object[] arguments, Map<String, String> attachments) { super(method, arguments, attachments); Annotation[][] as = method.getParameterAnnotations(); for (int i = 0, length = as.length; i < length; i++) { if (TarsHelper.isContext(as[i])) { getAttachments().putAll((Map<String, String>) arguments[i]); } } }
Example #17
Source File: GeciAnnotationTools.java From javageci with Apache License 2.0 | 5 votes |
private static String geParam(Annotation annotation, Method method) { try { method.setAccessible(true); return (String) method.invoke(annotation); } catch (IllegalAccessException | InvocationTargetException e) { return ""; } }
Example #18
Source File: KriptonProcessor.java From kripton with Apache License 2.0 | 5 votes |
protected Set<Class<? extends Annotation>> getSupportedAnnotationClasses() { Set<Class<? extends Annotation>> annotations = new LinkedHashSet<Class<? extends Annotation>>(); annotations.addAll(typeProcessor.getSupportedAnnotationClasses()); annotations.addAll(sharedPreferencesProcessor.getSupportedAnnotationClasses()); annotations.addAll(dataSourceProcessor.getSupportedAnnotationClasses()); annotations.addAll(many2ManyProcessor.getSupportedAnnotationClasses()); return annotations; }
Example #19
Source File: Observers.java From tomee with Apache License 2.0 | 5 votes |
private boolean isObserver(final Method method) { for (final Annotation[] annotations : method.getParameterAnnotations()) { for (final Annotation annotation : annotations) { if (annotation.annotationType().equals(Observes.class)) { return true; } } } return false; }
Example #20
Source File: ModelParser.java From typescript-generator with MIT License | 5 votes |
protected boolean isAnnotatedPropertyIncluded(Function<Class<? extends Annotation>, Annotation> getAnnotationFunction, String propertyDescription) { boolean isIncluded = settings.includePropertyAnnotations.isEmpty() || Utils.hasAnyAnnotation(getAnnotationFunction, settings.includePropertyAnnotations); if (!isIncluded) { TypeScriptGenerator.getLogger().verbose("Skipping '" + propertyDescription + "' because it doesn't have any annotation from 'includePropertyAnnotations'"); return false; } boolean isExcluded = Utils.hasAnyAnnotation(getAnnotationFunction, settings.excludePropertyAnnotations); if (isExcluded) { TypeScriptGenerator.getLogger().verbose("Skipping '" + propertyDescription + "' because it has some annotation from 'excludePropertyAnnotations'"); return false; } return true; }
Example #21
Source File: ParamObtainUtil.java From Aria with Apache License 2.0 | 5 votes |
/** * 判断是否是任务失败的回调注解 * * @return {@code true}是任务失败的回调注解 */ private boolean isFailAnnotation(Class<? extends Annotation> annotationClazz) { return annotationClazz == Download.onTaskFail.class || annotationClazz == DownloadGroup.onTaskFail.class || annotationClazz == DownloadGroup.onSubTaskFail.class || annotationClazz == Upload.onTaskFail.class; }
Example #22
Source File: AnnotationsInheritanceOrderRedefinitionTest.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
private static String toSimpleString(Annotation ann) { Class<? extends Annotation> annotationType = ann.annotationType(); Object value; try { value = annotationType.getDeclaredMethod("value").invoke(ann); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new RuntimeException(e); } return "@" + annotationType.getSimpleName() + "(" + value + ")"; }
Example #23
Source File: CustomAutowireConfigurer.java From blog_demos with Apache License 2.0 | 5 votes |
@Override @SuppressWarnings("unchecked") public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { if (this.customQualifierTypes != null) { if (!(beanFactory instanceof DefaultListableBeanFactory)) { throw new IllegalStateException( "CustomAutowireConfigurer needs to operate on a DefaultListableBeanFactory"); } DefaultListableBeanFactory dlbf = (DefaultListableBeanFactory) beanFactory; if (!(dlbf.getAutowireCandidateResolver() instanceof QualifierAnnotationAutowireCandidateResolver)) { dlbf.setAutowireCandidateResolver(new QualifierAnnotationAutowireCandidateResolver()); } QualifierAnnotationAutowireCandidateResolver resolver = (QualifierAnnotationAutowireCandidateResolver) dlbf.getAutowireCandidateResolver(); for (Object value : this.customQualifierTypes) { Class<? extends Annotation> customType = null; if (value instanceof Class) { customType = (Class<? extends Annotation>) value; } else if (value instanceof String) { String className = (String) value; customType = (Class<? extends Annotation>) ClassUtils.resolveClassName(className, this.beanClassLoader); } else { throw new IllegalArgumentException( "Invalid value [" + value + "] for custom qualifier type: needs to be Class or String."); } if (!Annotation.class.isAssignableFrom(customType)) { throw new IllegalArgumentException( "Qualifier type [" + customType.getName() + "] needs to be annotation type"); } resolver.addQualifierType(customType); } } }
Example #24
Source File: DefaultBeanFactory.java From ymate-platform-v2 with Apache License 2.0 | 5 votes |
@Override public void registerHandler(Class<? extends Annotation> annoClass, IBeanHandler handler) { if (!__beanHandlerMap.containsKey(annoClass)) { __beanHandlerMap.put(annoClass, handler); // if (__owner.getConfig().isDevelopMode() && _LOG.isInfoEnabled()) { _LOG.info("Handler class [" + annoClass.getSimpleName() + ":" + handler.getClass().getName() + "] registered."); } } else if (__owner.getConfig().isDevelopMode() && _LOG.isWarnEnabled()) { _LOG.warn("Handler class [" + annoClass.getSimpleName() + ":" + handler.getClass().getName() + "] duplicate registration is not allowed"); } }
Example #25
Source File: DefaultObsRegistry.java From jblink with BSD 3-Clause "New" or "Revised" License | 5 votes |
public void addObserver (Object obs, Class<? extends Annotation> annot) throws BlinkException { if (om != null) { for (Method m : obs.getClass ().getMethods ()) if (m.isAnnotationPresent (annot)) pendObservers.add (new PendObs (m, obs)); } else throw new RuntimeException ("DefaultObsRegistry: Cannot add " + "dynamic observer if no data model is " + "specified: " + obs.getClass ()); }
Example #26
Source File: AbstractRouteRegistryInitializer.java From flow with Apache License 2.0 | 5 votes |
private void validateRouteAnnotation(Class<?> route, Class<? extends Annotation> annotation) { Route routeAnnotation = route.getAnnotation(Route.class); if (routeAnnotation != null && !UI.class.equals(routeAnnotation.layout())) { if (route.isAnnotationPresent(annotation)) { throw new InvalidRouteLayoutConfigurationException(String .format("%s annotation needs to be on the top parent layout '%s' not on '%s'", annotation.getSimpleName(), RouteUtil .getTopParentLayout(route, RouteUtil.resolve(route, routeAnnotation)) .getName(), route.getName())); } List<Class<? extends RouterLayout>> parentLayouts = RouteUtil .getParentLayouts(route, RouteUtil.resolve(route, routeAnnotation)); Class<? extends RouterLayout> topParentLayout = RouteUtil .getTopParentLayout(route, RouteUtil.resolve(route, routeAnnotation)); validateParentAnnotation(parentLayouts, topParentLayout, annotation); } }
Example #27
Source File: HttpCacheImpl.java From jqm with Apache License 2.0 | 5 votes |
@Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { for (Annotation a : responseContext.getEntityAnnotations()) { if (a.annotationType() == HttpCache.class) { String value = ((HttpCache) a).value(); responseContext.getHeaders().putSingle(HttpHeaders.CACHE_CONTROL, value); break; } } }
Example #28
Source File: MCRContentAbstractWriter.java From mycore with GNU General Public License v3.0 | 5 votes |
private static Optional<String> getTransformerId(Annotation[] annotations, String format, String detail) { return Stream.of(annotations) .filter(a -> MCRParams.class.isAssignableFrom(a.annotationType())) .map(MCRParams.class::cast) .flatMap(p -> Stream.of(p.values())) .filter(p -> p.name().equals(PARAM_OBJECTTYPE)) .findAny() .map(MCRParam::value) .map(objectType -> objectType + "-" + format + "-" + detail); }
Example #29
Source File: AegisElementProviderTest.java From cxf with Apache License 2.0 | 5 votes |
@Test public void testWriteTo() throws Exception { MessageBodyWriter<Object> p = new AegisElementProvider<>(); ByteArrayOutputStream os = new ByteArrayOutputStream(); AegisTestBean bean = new AegisTestBean(); bean.setBoolValue(Boolean.TRUE); bean.setStrValue("hovercraft"); p.writeTo(bean, null, null, new Annotation[]{}, MediaType.APPLICATION_OCTET_STREAM_TYPE, new MetadataMap<String, Object>(), os); byte[] bytes = os.toByteArray(); String xml = new String(bytes, "utf-8"); assertEquals(simpleBeanXml, xml); }
Example #30
Source File: JAXBElementProviderTest.java From cxf with Apache License 2.0 | 5 votes |
@Test public void testWriteWithCustomPrefixes() throws Exception { JAXBElementProvider<TagVO2> provider = new JAXBElementProvider<>(); provider.setNamespacePrefixes( Collections.singletonMap("http://tags", "prefix")); TagVO2 tag = new TagVO2("a", "b"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); provider.writeTo(tag, TagVO2.class, TagVO2.class, new Annotation[0], MediaType.TEXT_XML_TYPE, new MetadataMap<String, Object>(), bos); assertTrue(bos.toString().contains("prefix:thetag")); }