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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
Source File: ElementRepAnnoTester.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
private boolean compareArrVals(Annotation[] actualAnnos, String[] expectedAnnos) { // Look if test case was run. if (actualAnnos == specialAnnoArray) { return false; // no testcase matches } if (actualAnnos.length != expectedAnnos.length) { System.out.println("Length not same. " + " actualAnnos length = " + actualAnnos.length + " expectedAnnos length = " + expectedAnnos.length); printArrContents(actualAnnos); printArrContents(expectedAnnos); return false; } else { int i = 0; String[] actualArr = new String[actualAnnos.length]; for (Annotation a : actualAnnos) { actualArr[i++] = a.toString(); } List<String> actualList = Arrays.asList(actualArr); List<String> expectedList = Arrays.asList(expectedAnnos); if (!actualList.containsAll(expectedList)) { System.out.println("Array values are not same"); printArrContents(actualAnnos); printArrContents(expectedAnnos); return false; } } return true; }
Example #17
Source File: KMSJSONReader.java From ranger with Apache License 2.0 | 5 votes |
@Override public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { return JsonUtilsV2.getMapper().readValue(entityStream, type); }
Example #18
Source File: PandroidCallAdapterFactory.java From pandroid with Apache License 2.0 | 5 votes |
@Override public CallAdapter<?, PandroidCall> get(Type returnType, Annotation[] annotations, Retrofit retrofit) { if (returnType instanceof ParameterizedType && (((ParameterizedType) returnType).getRawType() == PandroidCall.class || ((ParameterizedType) returnType).getRawType() == RxPandroidCall.class || ((ParameterizedType) returnType).getRawType() == Call.class)) { Type[] actualTypeArguments = ((ParameterizedType) returnType).getActualTypeArguments(); return new ResponseCallAdapter(actualTypeArguments[0], annotations); } return null; }
Example #19
Source File: Class.java From openjdk-8 with GNU General Public License v2.0 | 5 votes |
/** * @throws NullPointerException {@inheritDoc} * @since 1.8 */ @Override @SuppressWarnings("unchecked") public <A extends Annotation> A getDeclaredAnnotation(Class<A> annotationClass) { Objects.requireNonNull(annotationClass); return (A) annotationData().declaredAnnotations.get(annotationClass); }
Example #20
Source File: OpenApiTransformer.java From spring-openapi with MIT License | 5 votes |
protected void applyArrayAnnotationDetails(ArrayProperty schema, Annotation annotation) { if (annotation instanceof Size) { schema.setMinItems(((Size) annotation).min()); schema.setMaxItems(((Size) annotation).max()); } else if (annotation instanceof Deprecated) { schema.setVendorExtension("x-deprecated", true); } }
Example #21
Source File: ParameterDeserializer.java From flow with Apache License 2.0 | 5 votes |
/** * Check if the parameter value is annotated as OptionalParameter. * * @param navigationTarget * navigation target to check for optional * @param parameterAnnotation * annotation to check parameter for * @return parameter is optional */ public static boolean isAnnotatedParameter(Class<?> navigationTarget, Class<? extends Annotation> parameterAnnotation) { if (!HasUrlParameter.class.isAssignableFrom(navigationTarget)) { return false; } String methodName = "setParameter"; assert methodName.equals(ReflectTools .getFunctionalMethod(HasUrlParameter.class).getName()); // Raw method has no parameter annotations if compiled by Eclipse Type parameterType = GenericTypeReflector.getTypeParameter( navigationTarget, HasUrlParameter.class.getTypeParameters()[0]); if (parameterType == null) { parameterType = GenericTypeReflector.getTypeParameter( navigationTarget.getGenericSuperclass(), HasUrlParameter.class.getTypeParameters()[0]); } if (parameterType == null) { for (Type iface : navigationTarget.getGenericInterfaces()) { parameterType = GenericTypeReflector.getTypeParameter(iface, HasUrlParameter.class.getTypeParameters()[0]); if (parameterType != null) { break; } } } Class<?> parameterClass = GenericTypeReflector.erase(parameterType); return Stream.of(navigationTarget.getMethods()) .filter(method -> methodName.equals(method.getName())) .filter(method -> hasValidParameterTypes(method, parameterClass)) .anyMatch(method -> method.getParameters()[1] .isAnnotationPresent(parameterAnnotation)); }
Example #22
Source File: CmisPropertySetter.java From spring-content with Apache License 2.0 | 5 votes |
void setCmisProperty(Class<? extends Annotation> cmisAnnotationClass, BeanWrapper wrapper, List<?> values) { Field[] fields = findCmisProperty(cmisAnnotationClass, wrapper); if (fields != null) { for (Field field : fields) { if (!isIndexedProperty(field) && !isMapProperty(field)) { wrapper.setPropertyValue(field.getName(), (values.size() >= 1) ? values.get(0) : null); } else { wrapper.setPropertyValue(field.getName(), values); } } } }
Example #23
Source File: Annotations.java From businessworks with Apache License 2.0 | 5 votes |
/** * If the annotation is the class {@code javax.inject.Named}, canonicalizes to * com.google.guice.name.Named. Returns the given annotation class otherwise. */ public static Class<? extends Annotation> canonicalizeIfNamed( Class<? extends Annotation> annotationType) { if (annotationType == javax.inject.Named.class) { return Named.class; } else { return annotationType; } }
Example #24
Source File: FormEncodingProviderTest.java From cxf with Apache License 2.0 | 5 votes |
@Test public void testReadFrom() throws Exception { @SuppressWarnings("rawtypes") FormEncodingProvider<MultivaluedMap> ferp = new FormEncodingProvider<>(); InputStream is = getClass().getResourceAsStream("singleValPostBody.txt"); @SuppressWarnings("unchecked") MultivaluedMap<String, String> mvMap = ferp.readFrom(MultivaluedMap.class, null, new Annotation[]{}, MediaType.APPLICATION_FORM_URLENCODED_TYPE, null, is); assertEquals("Wrong entry for foo", "bar", mvMap.getFirst("foo")); assertEquals("Wrong entry for boo", "far", mvMap.getFirst("boo")); }
Example #25
Source File: DTOContractTest.java From phoenicis with GNU Lesser General Public License v3.0 | 5 votes |
private static Optional<Constructor<?>> getConstructorAnnotatedWithJsonCreator(Class<?> clazz) { for (Constructor<?> constructor : clazz.getConstructors()) { for (Annotation annotation : constructor.getAnnotations()) { if (annotation.annotationType() == JsonCreator.class) { return Optional.of(constructor); } } } return Optional.empty(); }
Example #26
Source File: InVertexMethodHandler.java From Ferma with Apache License 2.0 | 5 votes |
@Override public <E> DynamicType.Builder<E> processMethod(final DynamicType.Builder<E> builder, final Method method, final Annotation annotation) { final java.lang.reflect.Parameter[] arguments = method.getParameters(); if (ReflectionUtility.isGetMethod(method)) if (arguments == null || arguments.length == 0) return this.getNode(builder, method, annotation); else throw new IllegalStateException(method.getName() + " was annotated with @InVertex but had arguments."); else throw new IllegalStateException(method.getName() + " was annotated with @InVertex but did not begin with: get"); }
Example #27
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 #28
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")); }
Example #29
Source File: ManagedObjectRegistrar.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
/** * Construct mbean for given {@link BeanEntry} discovering its attributes and operations. */ private MBean mbean(final ManagedObject descriptor, final BeanEntry<Annotation, Object> entry) throws Exception { Class<?> type = entry.getImplementationClass(); ReflectionMBeanBuilder builder = new ReflectionMBeanBuilder(type); // attach manged target builder.target(new Supplier<Object>() { @Override public Object get() { return entry.getProvider().get(); } }); // allow custom description, or expose what sisu tells us String description = Strings.emptyToNull(descriptor.description()); if (description == null) { description = entry.getDescription(); } builder.description(description); // discover managed members builder.discover(); return builder.build(); }
Example #30
Source File: SecurityUtils.java From deltaspike with Apache License 2.0 | 5 votes |
public static Annotation resolveSecurityBindingType(Annotation annotation) { List<Annotation> result = getAllAnnotations(annotation.annotationType().getAnnotations(), new HashSet<Integer>()); for (Annotation foundAnnotation : result) { if (foundAnnotation.annotationType().isAnnotationPresent(SecurityBindingType.class)) { return foundAnnotation; } } throw new IllegalStateException(annotation.annotationType().getName() + " is a " + Stereotype.class.getName() + " but it isn't annotated with " + SecurityBindingType.class.getName()); }