Java Code Examples for java.lang.annotation.Annotation

The following are top voted examples for showing how to use java.lang.annotation.Annotation. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: primeval-reflex   File: RepeatedAnnotationObjectInterceptor.java   View source code 6 votes vote down vote up
private static <A extends Annotation, E extends Throwable> char callChar(
        AnnotationInterceptor<A> annotationInterceptor,
        int annotationId, A[] annotations, CallContext context, Arguments currentArguments,
        ToCharFunction<Arguments> terminalInvokeFun) throws E {

    A annotation = annotations[annotationId];
    if (annotationId == annotations.length - 1) { // last annotation
        return annotationInterceptor.onCall(annotation, context,
                new SimpleCharInterceptionHandler(currentArguments, terminalInvokeFun));
    } else {
        return annotationInterceptor.onCall(annotation, context,
                new SimpleCharInterceptionHandler(currentArguments,
                        (args) -> callChar(annotationInterceptor, annotationId + 1, annotations, context, args,
                                terminalInvokeFun)));
    }
}
 
Example 2
Project: nymph   File: ScannerNymphBeans.java   View source code 6 votes vote down vote up
/**
 * 解析jar包中的类
 * @param jarFile			表示jar文件
 * @param packageLocation	扫描的包路径
 * @throws Exception 反射时的异常
 */
private void resolveJar(JarFile jarFile, String packageLocation) throws Exception {
	Enumeration<JarEntry> entries = jarFile.entries();
	while (entries.hasMoreElements()) {
		String classLocation = entries.nextElement().getName();
		// 当jar文件中的路径是以packageLocation指定的路径开头,并且是以.class结尾时
		if (classLocation.startsWith(packageLocation) && classLocation.endsWith(".class")) {
			String location = classLocation.replace(".class", "").replace("/", ".");
			Class<?> forName = Class.forName(location);
			configurationBeansHandler(forName);
			Annotation[] annos = forName.getAnnotations();
			if (AnnoUtil.exist(annos, Bean.class) && !forName.isInterface()) {
				beansInitializedHandler(forName);
			}
		}
	}
}
 
Example 3
Project: OpenJSharp   File: TypeInfo.java   View source code 6 votes vote down vote up
public TypeInfo(QName tagName, Type type, Annotation... annotations) {
        if(tagName==null || type==null || annotations==null) {
            String nullArgs = "";

            if(tagName == null)     nullArgs = "tagName";
            if(type == null)        nullArgs += (nullArgs.length() > 0 ? ", type" : "type");
            if(annotations == null) nullArgs += (nullArgs.length() > 0 ? ", annotations" : "annotations");

//            Messages.ARGUMENT_CANT_BE_NULL.format(nullArgs);

            throw new IllegalArgumentException( "Argument(s) \"" + nullArgs + "\" can''t be null.)");
        }

        this.tagName = new QName(tagName.getNamespaceURI().intern(), tagName.getLocalPart().intern(), tagName.getPrefix());
        this.type = type;
        if (type instanceof Class && ((Class<?>)type).isPrimitive()) nillable = false;
        this.annotations = annotations;
    }
 
Example 4
Project: dropwizard-vavr   File: ValueMessageBodyWriter.java   View source code 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@SuppressWarnings("unchecked")
@Override
public void writeTo(Value<?> entity,
                    Class<?> type,
                    Type genericType,
                    Annotation[] annotations,
                    MediaType mediaType,
                    MultivaluedMap<String, Object> httpHeaders,
                    OutputStream entityStream)
        throws IOException {
    final Object entityValue = entity.getOrElseThrow(() -> EmptyValueException.INSTANCE);
    final Class<?> entityClass = entityValue.getClass();

    final Type actualGenericTypeArgument;
    if (genericType instanceof ParameterizedType) {
        actualGenericTypeArgument = ((ParameterizedType) genericType).getActualTypeArguments()[0];
    } else {
        actualGenericTypeArgument = entityClass;
    }

    final MessageBodyWriter writer = mbw.get().getMessageBodyWriter(entityClass, actualGenericTypeArgument, annotations, mediaType);
    writer.writeTo(entityValue, entityClass, actualGenericTypeArgument, annotations, mediaType, httpHeaders, entityStream);
}
 
Example 5
Project: Elasticsearch   File: Elements.java   View source code 6 votes vote down vote up
private <T> AnnotatedElementBuilder exposeInternal(Key<T> key) {
    if (privateElements == null) {
        addError("Cannot expose %s on a standard binder. "
                + "Exposed bindings are only applicable to private binders.", key);
        return new AnnotatedElementBuilder() {
            @Override
            public void annotatedWith(Class<? extends Annotation> annotationType) {
            }

            @Override
            public void annotatedWith(Annotation annotation) {
            }
        };
    }

    ExposureBuilder<T> builder = new ExposureBuilder<>(this, getSource(), key);
    privateElements.addExposureBuilder(builder);
    return builder;
}
 
Example 6
Project: vertx-zero   File: Anno.java   View source code 6 votes vote down vote up
/**
 * Query clazz's methods to getPlugin all annotated spec annotations.
 *
 * @param clazz
 * @param methodCls
 * @return
 */
public static Annotation[] query(final Class<?> clazz,
                                 final Class<? extends Annotation> methodCls) {
    return Fn.get(() -> {
        final Method[] methods = clazz.getDeclaredMethods();
        final List<Method> methodSet = Arrays.asList(methods);
        final List<Method> result = methodSet.stream()
                .filter(item -> item.isAnnotationPresent(methodCls))
                .collect(Collectors.toList());
        final List<Annotation> resultAnnos = new ArrayList<>();
        for (final Method method : result) {
            final Annotation anno = method.getAnnotation(methodCls);
            if (null != anno) {
                resultAnnos.add(anno);
            }
        }
        return resultAnnos.toArray(new Annotation[]{});
    }, clazz, methodCls);
}
 
Example 7
Project: SwiftModule   File: IntentMethod.java   View source code 6 votes vote down vote up
private Bundle prepareBundle(Object[] args) {
  Bundle bundle = new Bundle();
  int paramCount = parameterTypes.length;
  if (parameterTypes != null && paramCount > 0){
    for (int i = 0; i < paramCount; i++) {
      String key;
      Annotation[] paramAnnotations = parameterAnnotationsArray[i];
      for (Annotation anno: paramAnnotations) {
        if (anno instanceof Key){
          key = ((Key) anno).value();
          handleParams(bundle, key, parameterTypes[i], args[i]);
        }else if(anno instanceof FieldMap){

        }else{
          throw new IllegalStateException("不支持的参数注解: " + anno.toString() );
        }
      }
    }
  }
  return bundle;
}
 
Example 8
Project: beadledom   File: FilteringJacksonJsonProvider.java   View source code 6 votes vote down vote up
@Override
public void writeTo(
    Object o, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
    MultivaluedMap<String, Object> httpHeaders, OutputStream os) throws IOException {
  String fields = uriInfo.getQueryParameters() == null ? null
      : uriInfo.getQueryParameters().getFirst("fields");

  FieldFilter fieldFilter = FieldFilter.create(fields);
  if (!fieldFilter.hasFilters()) {
    super.writeTo(o, type, genericType, annotations, mediaType, httpHeaders, os);
    return;
  }

  JsonGenerator jgen = objectMapper.getFactory().createGenerator(os);
  TokenBuffer tokenBuffer = new TokenBuffer(objectMapper, false);
  objectMapper.writeValue(tokenBuffer, o);
  JsonParser jsonParser = tokenBuffer.asParser();
  fieldFilter.writeJson(jsonParser, jgen);
  jgen.flush();
}
 
Example 9
Project: OpenJSharp   File: ExternalMetadataReader.java   View source code 6 votes vote down vote up
private Annotation[] doMerge(Annotation[] annotations, Annotation[] externalAnnotations) {
    HashMap<String, Annotation> mergeMap = new HashMap<String, Annotation>();
    if (annotations != null) {
        for (Annotation reflectionAnnotation : annotations) {
            mergeMap.put(reflectionAnnotation.annotationType().getName(), reflectionAnnotation);
        }
    }

    // overriding happens here, based on annotationType().getName() ...
    if (externalAnnotations != null) {
        for (Annotation externalAnnotation : externalAnnotations) {
            mergeMap.put(externalAnnotation.annotationType().getName(), externalAnnotation);
        }
    }
    Collection<Annotation> values = mergeMap.values();
    int size = values.size();
    return size == 0 ? null : values.toArray(new Annotation[size]);
}
 
Example 10
Project: syndesis   File: SyndesisExtensionActionProcessor.java   View source code 6 votes vote down vote up
protected void writeIfNotEmpty(Properties prop, String key, Object value) throws InvocationTargetException, IllegalAccessException {
    if(value != null && !"".equals(value.toString().trim())) {
        if(value instanceof String[]){
            String[] arr = (String[])value;
            if(arr.length > 0){
                prop.put(key, String.join(",", arr));
            }
        } else if(Object[].class.isInstance(value)) {
            Object[] array = (Object[]) value;
            for (int i=0; i<array.length; i++) {
                if (propertyEnumAnnotationClass.isInstance(array[i])) {
                    Annotation enumAnn = (Annotation) array[i];
                    Properties props = gatherProperties(enumAnn, propertyEnumAnnotationClass);
                    for (String propName : props.stringPropertyNames()) {
                        prop.put(key + "[" + i + "]." + propName, props.getProperty(propName));
                    }
                }
            }
        } else {
            prop.put(key, value.toString());
        }
    }
}
 
Example 11
Project: teasy   File: MethodsInvoker.java   View source code 6 votes vote down vote up
protected TestClassContext(Class testClass, AbstractTest testInstance, Class<? extends Annotation> annotationClassToInvokeMethods, ITestContext testContext) {
    this.testClass = testClass;
    this.testInstance = testInstance;
    this.annotationClassToInvokeMethods = annotationClassToInvokeMethods;
    if (testContext.getExcludedGroups() == null) {
        this.excludedGroups = new String[0];
    } else {
        this.excludedGroups = Arrays.copyOf(testContext.getExcludedGroups(), testContext.getExcludedGroups().length);
    }
    if (testContext.getIncludedGroups() == null) {
        this.includedGroups = new String[0];
    } else {
        this.includedGroups = Arrays.copyOf(testContext.getIncludedGroups(), testContext.getIncludedGroups().length);
    }
    this.testContext = testContext;
}
 
Example 12
Project: vertx-zero   File: AffluxThread.java   View source code 6 votes vote down vote up
private void scanSpecific(final Field field) {
    // Vert.x Defined
    final Set<Class<? extends Annotation>> defineds
            = Plugins.INFIX_MAP.keySet();
    final Annotation[] annotations = field.getDeclaredAnnotations();
    // Annotation counter
    final Set<String> set = new HashSet<>();
    final Annotation hitted = Observable.fromArray(annotations)
            .filter(annotation -> defineds.contains(annotation.annotationType()))
            .map(annotation -> {
                set.add(annotation.annotationType().getName());
                return annotation;
            }).blockingFirst();
    // Duplicated annotated
    Fn.flingUp(Values.ONE < set.size(), LOGGER,
            MultiAnnotatedException.class, getClass(),
            field.getName(), field.getDeclaringClass().getName(), set);
    // Fill typed directly.
    LOGGER.info(Info.SCANED_FIELD, this.reference,
            field.getName(),
            field.getDeclaringClass().getName(),
            hitted.annotationType().getName());
    this.fieldMap.put(field.getName(), field.getType());
}
 
Example 13
Project: polymorphia   File: TypesModel.java   View source code 6 votes vote down vote up
public TypesModel(final Set<Class<?>> classes, final Set<String> packages, final Set<Class<? extends Annotation>> ignoreAnnotations) {
    this.ignoreAnnotations = ignoreAnnotations != null ? ignoreAnnotations : Collections.emptySet();

    // first index all direct classes
    if (classes != null) {
        for (Class<?> aClass : classes) {
            indexClass(aClass);
        }
    }

    if (packages != null && !packages.isEmpty()) {
        Indexer indexer = getIndexer();
        for (String aPackage : packages) {
            for (Class<?> clazz : indexer.getClassesForPackage(aPackage)) {
                indexClass(clazz);
            }
        }
    }
    this.classHierarchy = buildClassHierarchy(allClasses);
}
 
Example 14
Project: spring-jdbc-orm   File: ReflectionUtils.java   View source code 6 votes vote down vote up
/**
 * 获取constructors数组中匹配的annotationClass注解
 *
 * @param constructors    constructor对象数组
 * @param annotationClass annotationClass注解
 * @return List
 */
public static <T extends Annotation> List<T> getAnnotations(
        Constructor[] constructors, Class annotationClass) {

    if (isEmpty(constructors)) {
        return null;
    }

    List<T> result = new ArrayList<T>();

    for (Constructor constructor : constructors) {
        Annotation annotation = getAnnotation(constructor, annotationClass);
        if (annotation != null) {
            result.add((T) annotation);
        }
    }

    return result;
}
 
Example 15
Project: GitHub   File: RetrofitTest.java   View source code 6 votes vote down vote up
@Test public void responseConverterFactoryQueried() {
  Type type = String.class;
  Annotation[] annotations = new Annotation[0];

  Converter<ResponseBody, ?> expectedAdapter = mock(Converter.class);
  Converter.Factory factory = mock(Converter.Factory.class);

  Retrofit retrofit = new Retrofit.Builder()
      .baseUrl("http://example.com/")
      .addConverterFactory(factory)
      .build();

  doReturn(expectedAdapter).when(factory).responseBodyConverter(type, annotations, retrofit);

  Converter<ResponseBody, ?> actualAdapter = retrofit.responseBodyConverter(type, annotations);
  assertThat(actualAdapter).isSameAs(expectedAdapter);

  verify(factory).responseBodyConverter(type, annotations, retrofit);
  verifyNoMoreInteractions(factory);
}
 
Example 16
Project: hadoop   File: AdminSecurityInfo.java   View source code 6 votes vote down vote up
@Override
public KerberosInfo getKerberosInfo(Class<?> protocol, Configuration conf) {
  if (!protocol.equals(ResourceManagerAdministrationProtocolPB.class)) {
    return null;
  }
  return new KerberosInfo() {

    @Override
    public Class<? extends Annotation> annotationType() {
      return null;
    }

    @Override
    public String serverPrincipal() {
      return YarnConfiguration.RM_PRINCIPAL;
    }

    @Override
    public String clientPrincipal() {
      return null;
    }
  };
}
 
Example 17
Project: lams   File: JPAOverriddenAnnotationReader.java   View source code 5 votes vote down vote up
/**
 * Adds a @MapKeyEnumerated annotation to the specified annotationList if the specified element
 * contains a map-key-enumerated sub-element. This should only be the case for
 * element-collection, many-to-many, or one-to-many associations.
 */
private void getMapKeyEnumerated(List<Annotation> annotationList, Element element) {
	Element subelement = element != null ? element.element( "map-key-enumerated" ) : null;
	if ( subelement != null ) {
		AnnotationDescriptor ad = new AnnotationDescriptor( MapKeyEnumerated.class );
		EnumType value = EnumType.valueOf( subelement.getTextTrim() );
		ad.setValue( "value", value );
		annotationList.add( AnnotationFactory.create( ad ) );
	}
}
 
Example 18
Project: GPigValidator   File: SizeValidator.java   View source code 5 votes vote down vote up
@Override
public boolean isCorrect(Object objectValue, Annotation annotation) {
    if (areWrongPreconditions(objectValue, annotation))
        return false;

    Size sizeAnnotation = (Size) annotation;

    int size = getSize(objectValue);
    return sizeAnnotation.min() <= size && size <= sizeAnnotation.max();
}
 
Example 19
Project: GitHub   File: AnnotatedConverters.java   View source code 5 votes vote down vote up
@Override public Converter<?, RequestBody> requestBodyConverter(Type type,
    Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
  for (Annotation annotation : parameterAnnotations) {
    Converter.Factory factory = factories.get(annotation.annotationType());
    if (factory != null) {
      return factory.requestBodyConverter(type, parameterAnnotations, methodAnnotations,
          retrofit);
    }
  }
  return null;
}
 
Example 20
Project: GitHub   File: Retrofit.java   View source code 5 votes vote down vote up
/**
 * Returns a {@link Converter} for {@link ResponseBody} to {@code type} from the available
 * {@linkplain #converterFactories() factories} except {@code skipPast}.
 *
 * @throws IllegalArgumentException if no converter available for {@code type}.
 */
public <T> Converter<ResponseBody, T> nextResponseBodyConverter(Converter.Factory skipPast,
    Type type, Annotation[] annotations) {
  checkNotNull(type, "type == null");
  checkNotNull(annotations, "annotations == null");

  int start = converterFactories.indexOf(skipPast) + 1;
  for (int i = start, count = converterFactories.size(); i < count; i++) {
    Converter<ResponseBody, ?> converter =
        converterFactories.get(i).responseBodyConverter(type, annotations, this);
    if (converter != null) {
      //noinspection unchecked
      return (Converter<ResponseBody, T>) converter;
    }
  }

  StringBuilder builder = new StringBuilder("Could not locate ResponseBody converter for ")
      .append(type)
      .append(".\n");
  if (skipPast != null) {
    builder.append("  Skipped:");
    for (int i = 0; i < start; i++) {
      builder.append("\n   * ").append(converterFactories.get(i).getClass().getName());
    }
    builder.append('\n');
  }
  builder.append("  Tried:");
  for (int i = start, count = converterFactories.size(); i < count; i++) {
    builder.append("\n   * ").append(converterFactories.get(i).getClass().getName());
  }
  throw new IllegalArgumentException(builder.toString());
}
 
Example 21
Project: GitHub   File: FastJsonProvider.java   View source code 5 votes vote down vote up
/**
 * Method that JAX-RS container calls to try to check whether values of
 * given type (and media type) can be deserialized by this provider.
 */
public boolean isReadable(Class<?> type, //
                          Type genericType, //
                          Annotation[] annotations, //
                          MediaType mediaType) {

    if (!hasMatchingMediaType(mediaType)) {
        return false;
    }

    return isValidType(type, annotations);
}
 
Example 22
Project: lams   File: ClassUtils.java   View source code 5 votes vote down vote up
public static boolean isAnnotationPresent(Class<?> clazz, Class<? extends Annotation> a) {
    for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
        if (c.isAnnotationPresent(a))
            return true;
        if(isAnnotationPresentOnInterfaces(c, a))
            return true;
    }
    return false;
}
 
Example 23
Project: xtf   File: MsaProfileFilter.java   View source code 5 votes vote down vote up
@Override
public boolean exclude(final Class<?> testClass) {
	for (final Annotation annotation : Arrays.asList(testClass.getAnnotations())) {
		if (annotation instanceof VertxProfile && "vertx".equals(this.msaProvider)) {
			return false;
		} else if (annotation instanceof SpringBootProfile && "springboot".equals(this.msaProvider)) {
			return false;
		} else if (annotation instanceof WildFlySwarmProfile && "wildfly-swarm".equals(this.msaProvider)) {
			return false;
		} else if (annotation instanceof JavaS2IProfile && "java-s2i".equals(this.msaProvider)) {
			return false;
		}
	}
	return true;
}
 
Example 24
Project: vertx-zero   File: AffluxThread.java   View source code 5 votes vote down vote up
private void scanQualifier(final Field field,
                           final List<Class<?>> instanceCls) {
    // Field must annotated with @Qualifier
    final Annotation annotation = field.getAnnotation(Qualifier.class);

    Fn.flingUp(null == annotation,
            LOGGER, QualifierMissedException.class,
            getClass(), field.getName(), field.getDeclaringClass().getName());

    // All implementation class must be annotated with @Named
    final boolean match = instanceCls.stream()
            .allMatch(item -> item.isAnnotationPresent(Named.class));

    final Set<String> names = instanceCls.stream()
            .map(Class::getName).collect(Collectors.toSet());

    Fn.flingUp(!match,
            LOGGER, NamedImplementionException.class,
            getClass(), names, field.getType().getName());

    // Named value must be reflect with @Qualifier
    final String value = Instance.invoke(annotation, "value");

    final Optional<Class<?>> verified = instanceCls.stream()
            .filter(item -> {
                final Annotation target = item.getAnnotation(Named.class);
                final String targetValue = Instance.invoke(target, "value");
                return value.equals(targetValue)
                        && !StringUtil.isNil(targetValue);
            }).findAny();

    Fn.flingUp(!verified.isPresent(),
            LOGGER, NamedNotFoundException.class,
            getClass(), names, value);

    // Passed all specification
    this.fieldMap.put(field.getName(), verified.get());
}
 
Example 25
Project: garlicts   File: BeanLoaderTemplate.java   View source code 5 votes vote down vote up
/**
 * 获取包名下带有某注解的所有类 
 */
public List<Class<?>> getBeanClassListByAnnotation(Class<? extends Annotation> annotationClass) {
	
	List<Class<?>> classList = new ArrayList<Class<?>>();
	Map<Class<?>,Object> beanMap = BeanContainerAbility.getBeanMap();
	
       for (Class<?> cls : beanMap.keySet()) {
           if (cls.isAnnotationPresent(annotationClass)) {
           	classList.add(cls);
           }
       }
       return classList;

}
 
Example 26
Project: super-volley   File: DeserializeErrorBody.java   View source code 5 votes vote down vote up
public static void main(String... args) throws IOException {
    // Create our Service instance with a SuperVolley pointing at the local web server and Gson.
    SuperVolley volley = new SuperVolley.Builder()
            .baseUrl(Constants.API_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    // Create a MockSuperVolley object with a NetworkBehavior which manages the fake behavior of calls.
    NetworkBehavior behavior = NetworkBehavior.create();
    MockSuperVolley mockSuperVolley = new MockSuperVolley.Builder(volley)
            .networkBehavior(behavior)
            .build();

    BehaviorDelegate<Service> delegate = mockSuperVolley.create(Service.class);
    MockService service = new MockService(delegate);

    Call<Void> call = service.getUser();

    Response<Void> response = call.execute();

    // Normally you would check response.isSuccess() here before doing the following, but we know
    // this call will always fail. You could also use response.code() to determine whether to
    // convert the error body and/or which type to use for conversion.

    // Look up a converter for the Error type on the SuperVolley instance.
    Converter<ResponseBody, Error> errorConverter =
            volley.responseBodyConverter(Error.class, new Annotation[0]);
    // Convert the error body into our Error type.
    Error error = errorConverter.convert(response.errorBody());
    System.out.println("ERROR: " + error.message);
}
 
Example 27
Project: oscm   File: ReflectiveClone.java   View source code 5 votes vote down vote up
private static boolean needsToCascade(Field field) {
    Class<?> fieldtype = field.getType();
    if (!DomainObject.class.isAssignableFrom(fieldtype))
        return false;
    Annotation ann;
    CascadeType[] cascades = null;
    ann = field.getAnnotation(OneToOne.class);
    if (ann != null) {
        cascades = ((OneToOne) ann).cascade();
    } else {
        ann = field.getAnnotation(OneToMany.class);
        if (ann != null) {
            cascades = ((OneToMany) ann).cascade();
        } else {
            ann = field.getAnnotation(ManyToOne.class);
            if (ann != null) {
                cascades = ((ManyToOne) ann).cascade();
            } else {
                ann = field.getAnnotation(ManyToMany.class);
                if (ann != null) {
                    cascades = ((ManyToMany) ann).cascade();
                }
            }
        }
    }
    if (cascades == null)
        return false;
    for (CascadeType cas : cascades) {
        if ((cas == CascadeType.ALL) || (cas == CascadeType.MERGE)
                || (cas == CascadeType.PERSIST)
                || (cas == CascadeType.REMOVE)) {
            return true;
        }
    }
    return false;
}
 
Example 28
Project: OpenJSharp   File: TypeReference.java   View source code 5 votes vote down vote up
/**
 * Finds the specified annotation from the array and returns it.
 * Null if not found.
 */
public <A extends Annotation> A get( Class<A> annotationType ) {
    for (Annotation a : annotations) {
        if(a.annotationType()==annotationType)
            return annotationType.cast(a);
    }
    return null;
}
 
Example 29
Project: lams   File: JPAOverriddenAnnotationReader.java   View source code 5 votes vote down vote up
private void buildMapKeyJoinColumns(List<Annotation> annotationList, Element element) {
	MapKeyJoinColumn[] joinColumns = getMapKeyJoinColumns( element );
	if ( joinColumns.length > 0 ) {
		AnnotationDescriptor ad = new AnnotationDescriptor( MapKeyJoinColumns.class );
		ad.setValue( "value", joinColumns );
		annotationList.add( AnnotationFactory.create( ad ) );
	}
}
 
Example 30
Project: bootstrap   File: NotFoundResponseFilterTest.java   View source code 5 votes vote down vote up
@Test
public void filterNoAnnotation() {
	final ContainerRequestContext requestContext = Mockito.mock(ContainerRequestContext.class);
	final ContainerResponseContext responseContext = Mockito.mock(ContainerResponseContext.class);
	Mockito.when(responseContext.getStatus()).thenReturn(204);
	final Annotation[] annotations = new Annotation[] {};
	Mockito.when(responseContext.getEntityAnnotations()).thenReturn(annotations);
	filter.filter(requestContext, responseContext);
}
 
Example 31
Project: OpenJSharp   File: Symbol.java   View source code 5 votes vote down vote up
@Override
protected <A extends Annotation> A[] getInheritedAnnotations(Class<A> annoType) {

    ClassSymbol sup = getSuperClassToSearchForAnnotations();

    return sup == null ? super.getInheritedAnnotations(annoType)
                       : sup.getAnnotationsByType(annoType);
}
 
Example 32
Project: GitHub   File: AnnotatedConverters.java   View source code 5 votes vote down vote up
public Builder add(Class<? extends Annotation> cls, Converter.Factory factory) {
  if (cls == null) {
    throw new NullPointerException("cls == null");
  }
  if (factory == null) {
    throw new NullPointerException("factory == null");
  }
  factories.put(cls, factory);
  return this;
}
 
Example 33
Project: lams   File: JPAOverriddenAnnotationReader.java   View source code 5 votes vote down vote up
private Annotation getConvertsForAttribute(List<Element> elementsForProperty, XMLContext.Default defaults) {
	// NOTE : we use a map here to make sure that an xml and annotation referring to the same attribute
	// properly overrides.  Very sparse map, yes, but easy setup.
	// todo : revisit this
	// although bear in mind that this code is no longer used in 5.0...

	final Map<String,Convert> convertAnnotationsMap = new HashMap<String, Convert>();

	for ( Element element : elementsForProperty ) {
		final boolean isBasic = "basic".equals( element.getName() );
		final boolean isEmbedded = "embedded".equals( element.getName() );

		// todo : can be collections too

		final boolean canHaveConverts = isBasic || isEmbedded;

		if ( !canHaveConverts ) {
			continue;
		}

		final String attributeNamePrefix = isBasic ? null : propertyName;
		applyXmlDefinedConverts( element, defaults, attributeNamePrefix, convertAnnotationsMap );
	}

	// NOTE : per section 12.2.3.16 of the spec <convert/> is additive, although only if "metadata-complete" is not
	// specified in the XML

	if ( defaults.canUseJavaAnnotations() ) {
		// todo : note sure how to best handle attributeNamePrefix here
		applyPhysicalConvertAnnotations( propertyName, convertAnnotationsMap );
	}

	if ( !convertAnnotationsMap.isEmpty() ) {
		final AnnotationDescriptor groupingDescriptor = new AnnotationDescriptor( Converts.class );
		groupingDescriptor.setValue( "value", convertAnnotationsMap.values().toArray( new Convert[convertAnnotationsMap.size()]) );
		return AnnotationFactory.create( groupingDescriptor );
	}

	return null;
}
 
Example 34
Project: GitHub   File: BehaviorDelegate.java   View source code 5 votes vote down vote up
@SuppressWarnings("unchecked") // Single-interface proxy creation guarded by parameter safety.
public <R> T returning(Call<R> call) {
  final Call<R> behaviorCall = new BehaviorCall<>(behavior, executor, call);
  return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class[] { service },
      new InvocationHandler() {
        @Override
        public T invoke(Object proxy, Method method, Object[] args) throws Throwable {
          Type returnType = method.getGenericReturnType();
          Annotation[] methodAnnotations = method.getAnnotations();
          CallAdapter<R, T> callAdapter =
              (CallAdapter<R, T>) retrofit.callAdapter(returnType, methodAnnotations);
          return callAdapter.adapt(behaviorCall);
        }
      });
}
 
Example 35
Project: XSnow   File: GsonConverterFactory.java   View source code 5 votes vote down vote up
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
    if (type != null && type.equals(String.class)) {
        return new JsonResponseBodyConverter<>();
    }
    TypeAdapter<?> adapter = null;
    if (type != null) {
        adapter = gson.getAdapter(TypeToken.get(type));
    }
    return new GsonResponseBodyConverter<>(gson, adapter);
}
 
Example 36
Project: Elasticsearch   File: MapBinder.java   View source code 5 votes vote down vote up
/**
 * Returns a new mapbinder that collects entries of {@code keyType}/{@code valueType} in a
 * {@link Map} that is itself bound with {@code annotation}.
 */
public static <K, V> MapBinder<K, V> newMapBinder(Binder binder,
                                                  TypeLiteral<K> keyType, TypeLiteral<V> valueType, Annotation annotation) {
    binder = binder.skipSources(MapBinder.class, RealMapBinder.class);
    return newMapBinder(binder, valueType,
            Key.get(mapOf(keyType, valueType), annotation),
            Key.get(mapOfProviderOf(keyType, valueType), annotation),
            Multibinder.newSetBinder(binder, entryOfProviderOf(keyType, valueType), annotation));
}
 
Example 37
Project: bootstrap   File: UnixTimestampParameterHandler.java   View source code 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> ParamConverter<T> getConverter(final Class<T> rawType, final Type genericType, final Annotation[] annotations) { // NOSONAR
	
	// Basic date handler
	if (rawType.equals(Date.class)) {
		return (ParamConverter<T>) converter;
	}
	
	// LocalDate handler
	if (rawType.equals(LocalDate.class)) {
		return (ParamConverter<T>) localDateconverter;
	}
	return null;
}
 
Example 38
Project: Reer   File: AbstractMultiTestRunner.java   View source code 5 votes vote down vote up
public <A extends Annotation> A getAnnotation(Class<A> type) {
    A annotation = test.getAnnotation(type);
    if (annotation != null) {
        return annotation;
    }
    return parent.getAnnotation(type);
}
 
Example 39
Project: OpenJSharp   File: ClassInfoImpl.java   View source code 5 votes vote down vote up
/**
 * Gets an annotation that are allowed on both class and type.
 */
private <T extends Annotation> T getClassOrPackageAnnotation(Class<T> type) {
    T t = reader().getClassAnnotation(type,clazz,this);
    if(t!=null)
        return t;
    // defaults to the package level
    return reader().getPackageAnnotation(type,clazz,this);
}
 
Example 40
Project: GPigValidator   File: SizeValidator.java   View source code 5 votes vote down vote up
@Override
public Optional<String> getErrorMessage(Object objectValue, Annotation annotation) {
    if (isCorrect(objectValue, annotation))
        return Optional.absent();

    Size sizeAnnotation = (Size) annotation;

    if (objectValue instanceof String) {
        return Optional.of(createErrorMessageForString(sizeAnnotation));
    } else {
        return Optional.of(createErrorMessageForCollection(sizeAnnotation));
    }
}