private static boolean arrayMemberEquals(
     Class<?> paramClass, Object paramObject1, Object paramObject2) {
   if (paramClass.isAnnotation()) {
     return annotationArrayMemberEquals((Annotation[]) paramObject1, (Annotation[]) paramObject2);
   }
   if (paramClass.equals(Byte.TYPE)) {
     return Arrays.equals((byte[]) paramObject1, (byte[]) paramObject2);
   }
   if (paramClass.equals(Short.TYPE)) {
     return Arrays.equals((short[]) paramObject1, (short[]) paramObject2);
   }
   if (paramClass.equals(Integer.TYPE)) {
     return Arrays.equals((int[]) paramObject1, (int[]) paramObject2);
   }
   if (paramClass.equals(Character.TYPE)) {
     return Arrays.equals((char[]) paramObject1, (char[]) paramObject2);
   }
   if (paramClass.equals(Long.TYPE)) {
     return Arrays.equals((long[]) paramObject1, (long[]) paramObject2);
   }
   if (paramClass.equals(Float.TYPE)) {
     return Arrays.equals((float[]) paramObject1, (float[]) paramObject2);
   }
   if (paramClass.equals(Double.TYPE)) {
     return Arrays.equals((double[]) paramObject1, (double[]) paramObject2);
   }
   if (paramClass.equals(Boolean.TYPE)) {
     return Arrays.equals((boolean[]) paramObject1, (boolean[]) paramObject2);
   }
   return Arrays.equals((Object[]) paramObject1, (Object[]) paramObject2);
 }
Example #2
0
  /**
   * Create a new AnnotationImpl.
   *
   * @param className className
   * @param cl classloader
   * @param parameterTypes parameterTypes
   * @param memberName memberName
   * @param onMethod onMethod
   * @param onField onField
   * @param annotationClass annotationClass
   */
  @SuppressWarnings("unchecked")
  public AnnotationImpl(
      String className,
      ClassLoader cl,
      List<String> parameterTypes,
      String memberName,
      boolean onMethod,
      boolean onField,
      Class<?> annotationClass) {
    super();
    this.className = className;
    this.cl = cl;
    if (parameterTypes != null) {
      this.parameterTypes = new ArrayList<String>(parameterTypes.size());
      this.parameterTypes.addAll(parameterTypes);
    } else {
      this.parameterTypes = new ArrayList<String>(0);
    }

    this.memberName = memberName;
    this.onMethod = onMethod;
    this.onField = onField;
    if (annotationClass.isAnnotation()) {
      this.annotationClass = (Class<? extends java.lang.annotation.Annotation>) annotationClass;
    } else {
      throw MESSAGES.notAnAnnotation(annotationClass);
    }
  }
  @SuppressWarnings("unchecked")
  private void parseConstraintDefinitions(
      List<ConstraintDefinitionType> constraintDefinitionList, String defaultPackage) {
    for (ConstraintDefinitionType constraintDefinition : constraintDefinitionList) {
      String annotationClassName = constraintDefinition.getAnnotation();

      Class<?> clazz = getClass(annotationClassName, defaultPackage);
      if (!clazz.isAnnotation()) {
        throw log.getIsNotAnAnnotationException(annotationClassName);
      }
      Class<? extends Annotation> annotationClass = (Class<? extends Annotation>) clazz;

      ValidatedByType validatedByType = constraintDefinition.getValidatedBy();
      List<Class<? extends ConstraintValidator<? extends Annotation, ?>>>
          constraintValidatorClasses = newArrayList();
      if (validatedByType.getIncludeExistingValidators() != null
          && validatedByType.getIncludeExistingValidators()) {
        constraintValidatorClasses.addAll(findConstraintValidatorClasses(annotationClass));
      }
      for (String validatorClassName : validatedByType.getValue()) {
        Class<? extends ConstraintValidator<?, ?>> validatorClass;
        validatorClass =
            (Class<? extends ConstraintValidator<?, ?>>)
                ReflectionHelper.loadClass(validatorClassName, this.getClass());

        if (!ConstraintValidator.class.isAssignableFrom(validatorClass)) {
          throw log.getIsNotAConstraintValidatorClassException(validatorClass);
        }

        constraintValidatorClasses.add(validatorClass);
      }
      constraintHelper.addConstraintValidatorDefinition(
          annotationClass, constraintValidatorClasses);
    }
  }
  @Override
  protected void doParse(
      final Element element,
      final ParserContext parserContext,
      final BeanDefinitionBuilder builder) {
    String serviceRef = element.getAttribute("service-ref");
    builder.addConstructorArgValue(":" + serviceRef);
    builder.addConstructorArgReference(serviceRef);
    String marker = element.getAttribute("marker");
    if (StringUtils.hasLength(marker)) {
      Class<?> theClass =
          ClassUtils.resolveClassName(marker, Thread.currentThread().getContextClassLoader());
      if (!theClass.isAnnotation()) {
        throw new ConfigurationException(
            String.format("The class '%s' is not an annotation", marker));
      }
      builder.addPropertyValue("markerAnnotation", theClass);
    }

    // Register the post processor if there is not already one in this context
    String beanName = NamespaceBeanFactoryPostProcessor.class.getName();
    if (!parserContext.getRegistry().containsBeanDefinition(beanName)) {
      BeanDefinitionBuilder namespacePostProcessor =
          BeanDefinitionBuilder.genericBeanDefinition(NamespaceBeanFactoryPostProcessor.class);
      parserContext.registerBeanComponent(
          new BeanComponentDefinition(namespacePostProcessor.getBeanDefinition(), beanName));
    }
  }
  // this GwtCreateHandler has been introduced to make possible the
  // instanciation of abstract classes
  // that gwt-test-utils doesn't patch right now
  public Object create(Class<?> classLiteral) throws Exception {
    if (classLiteral.isAnnotation()
        || classLiteral.isArray()
        || classLiteral.isEnum()
        || classLiteral.isInterface()
        || !Modifier.isAbstract(classLiteral.getModifiers())) {
      return null;
    }

    Class<?> newClass = cache.get(classLiteral);

    if (newClass != null) {
      return newClass.newInstance();
    }

    CtClass ctClass = GwtClassPool.getCtClass(classLiteral);
    CtClass subClass = GwtClassPool.get().makeClass(classLiteral.getCanonicalName() + "SubClass");

    subClass.setSuperclass(ctClass);

    for (CtMethod m : ctClass.getDeclaredMethods()) {
      if (javassist.Modifier.isAbstract(m.getModifiers())) {
        CtMethod copy = new CtMethod(m, subClass, null);
        subClass.addMethod(copy);
      }
    }

    GwtPatcherUtils.patch(subClass, null);

    newClass = subClass.toClass(GwtClassLoader.get(), null);
    cache.put(classLiteral, newClass);

    return newClass.newInstance();
  }
Example #6
0
  // This method is part of the javax.lang.model API, do not use this in javac code.
  public <A extends Annotation> A getAnnotation(Class<A> annoType) {

    if (!annoType.isAnnotation())
      throw new IllegalArgumentException("Not an annotation type: " + annoType);

    Attribute.Compound c = getAttribute(annoType);
    return c == null ? null : AnnotationProxyMaker.generateAnnotation(c, annoType);
  }
  /**
   * @param context
   * @param scis
   * @throws Exception
   */
  public void createServletContainerInitializerAnnotationHandlers(
      WebAppContext context, List<ServletContainerInitializer> scis) throws Exception {
    if (scis == null || scis.isEmpty()) return; // nothing to do

    List<ContainerInitializer> initializers = new ArrayList<ContainerInitializer>();
    context.setAttribute(CONTAINER_INITIALIZERS, initializers);

    for (ServletContainerInitializer service : scis) {
      HandlesTypes annotation = service.getClass().getAnnotation(HandlesTypes.class);
      ContainerInitializer initializer = null;
      if (annotation != null) {
        // There is a HandlesTypes annotation on the on the ServletContainerInitializer
        Class<?>[] classes = annotation.value();
        if (classes != null) {
          initializer = new ContainerInitializer(service, classes);

          // If we haven't already done so, we need to register a handler that will
          // process the whole class hierarchy to satisfy the ServletContainerInitializer
          if (context.getAttribute(CLASS_INHERITANCE_MAP) == null) {
            // MultiMap<String> map = new MultiMap<>();
            ConcurrentHashMap<String, ConcurrentHashSet<String>> map = new ClassInheritanceMap();
            context.setAttribute(CLASS_INHERITANCE_MAP, map);
            _classInheritanceHandler = new ClassInheritanceHandler(map);
          }

          for (Class<?> c : classes) {
            // The value of one of the HandlesTypes classes is actually an Annotation itself so
            // register a handler for it
            if (c.isAnnotation()) {
              if (LOG.isDebugEnabled())
                LOG.debug("Registering annotation handler for " + c.getName());
              _containerInitializerAnnotationHandlers.add(
                  new ContainerInitializerAnnotationHandler(initializer, c));
            }
          }
        } else {
          initializer = new ContainerInitializer(service, null);
          if (LOG.isDebugEnabled())
            LOG.debug("No classes in HandlesTypes on initializer " + service.getClass());
        }
      } else {
        initializer = new ContainerInitializer(service, null);
        if (LOG.isDebugEnabled()) LOG.debug("No annotation on initializer " + service.getClass());
      }

      initializers.add(initializer);
    }

    // add a bean to the context which will call the servletcontainerinitializers when appropriate
    ServletContainerInitializersStarter starter =
        (ServletContainerInitializersStarter) context.getAttribute(CONTAINER_INITIALIZER_STARTER);
    if (starter != null)
      throw new IllegalStateException("ServletContainerInitializersStarter already exists");
    starter = new ServletContainerInitializersStarter(context);
    context.setAttribute(CONTAINER_INITIALIZER_STARTER, starter);
    context.addBean(starter, true);
  }
  /**
   * Helper method called to construct and initialize instance of {@link TypeResolverBuilder} if
   * given annotated element indicates one is needed.
   */
  @SuppressWarnings("deprecation")
  protected TypeResolverBuilder<?> _findTypeResolver(
      MapperConfig<?> config, Annotated ann, JavaType baseType) {
    // First: maybe we have explicit type resolver?
    TypeResolverBuilder<?> b;
    JsonTypeInfo info = _findAnnotation(ann, JsonTypeInfo.class);
    JsonTypeResolver resAnn = _findAnnotation(ann, JsonTypeResolver.class);

    if (resAnn != null) {
      if (info == null) {
        return null;
      }
      /* let's not try to force access override (would need to pass
       * settings through if we did, since that's not doable on some
       * platforms)
       */
      b = config.typeResolverBuilderInstance(ann, resAnn.value());
    } else { // if not, use standard one, if indicated by annotations
      if (info == null) {
        return null;
      }
      // bit special; must return 'marker' to block use of default typing:
      if (info.use() == JsonTypeInfo.Id.NONE) {
        return _constructNoTypeResolverBuilder();
      }
      b = _constructStdTypeResolverBuilder();
    }
    // Does it define a custom type id resolver?
    JsonTypeIdResolver idResInfo = _findAnnotation(ann, JsonTypeIdResolver.class);
    TypeIdResolver idRes =
        (idResInfo == null) ? null : config.typeIdResolverInstance(ann, idResInfo.value());
    if (idRes != null) { // [JACKSON-359]
      idRes.init(baseType);
    }
    b = b.init(info.use(), idRes);
    /* 13-Aug-2011, tatu: One complication wrt [JACKSON-453]; external id
     *   only works for properties; so if declared for a Class, we will need
     *   to map it to "PROPERTY" instead of "EXTERNAL_PROPERTY"
     */
    JsonTypeInfo.As inclusion = info.include();
    if (inclusion == JsonTypeInfo.As.EXTERNAL_PROPERTY && (ann instanceof AnnotatedClass)) {
      inclusion = JsonTypeInfo.As.PROPERTY;
    }
    b = b.inclusion(inclusion);
    b = b.typeProperty(info.property());
    Class<?> defaultImpl = info.defaultImpl();

    // 08-Dec-2014, tatu: To deprecated `JsonTypeInfo.None` we need to use other placeholder(s);
    //   and since `java.util.Void` has other purpose (to indicate "deser as null"), we'll instead
    //   use `JsonTypeInfo.class` itself. But any annotation type will actually do, as they have no
    //   valid use (can not instantiate as default)
    if (defaultImpl != JsonTypeInfo.None.class && !defaultImpl.isAnnotation()) {
      b = b.defaultImpl(defaultImpl);
    }
    b = b.typeIdVisibility(info.visible());
    return b;
  }
Example #9
0
  /**
   * Runs the test using the specified harness.
   *
   * @param harness the test harness (<code>null</code> not permitted).
   */
  public void test(TestHarness harness) {
    // create instance of a class Object
    final Object o = new Object();

    // get a runtime class of an object "o"
    final Class c = o.getClass();

    harness.check(!c.isAnnotation());
  }
Example #10
0
  public static boolean isAnnotationReturnType(Class cls) {
    // TODO review this calculation
    Class targetType = cls;
    if (cls.isArray() && (targetType = cls.getComponentType()).isArray()) {
      return false;
    }

    return (targetType.isAnnotation() || targetType.isEnum() || targetType.isPrimitive())
        || (!targetType.isAnonymousClass() && !targetType.isLocalClass());
  }
  /**
   * 注册类到Guice
   *
   * @param binder
   * @param classToBind
   */
  private void bindClass(final Binder binder, final Class classToBind) {

    // don't bind anonymous classes  匿名内部类
    if (classToBind.isAnonymousClass()) return;

    // don't bind annotations 注解定义类
    if (classToBind.isAnnotation()) return;

    binder.bind(classToBind);
  }
Example #12
0
  /**
   * Checks that the class found through reflection matches the specification from the API xml file.
   */
  @SuppressWarnings("unchecked")
  private void checkClassCompliance() {
    try {
      mAbsoluteClassName = mPackageName + "." + mShortClassName;
      mClass = findMatchingClass();

      if (mClass == null) {
        // No class found, notify the observer according to the class type
        if (JDiffType.INTERFACE.equals(mClassType)) {
          mResultObserver.notifyFailure(
              SignatureTestActivity.FAILURE_TYPE.MISSING_INTERFACE,
              mAbsoluteClassName,
              "Classloader is unable to find " + mAbsoluteClassName);
        } else {
          mResultObserver.notifyFailure(
              SignatureTestActivity.FAILURE_TYPE.MISSING_CLASS,
              mAbsoluteClassName,
              "Classloader is unable to find " + mAbsoluteClassName);
        }

        return;
      }
      if (!checkClassModifiersCompliance()) {
        logMismatchInterfaceSignature(
            mAbsoluteClassName,
            "Non-compatible class found when looking for " + toSignatureString());
        return;
      }

      if (!checkClassAnnotationCompliace()) {
        logMismatchInterfaceSignature(mAbsoluteClassName, "Annotation mismatch");
        return;
      }

      if (!mClass.isAnnotation()) {
        // check father class
        if (!checkClassExtendsCompliance()) {
          logMismatchInterfaceSignature(mAbsoluteClassName, "Extends mismatch");
          return;
        }

        // check implements interface
        if (!checkClassImplementsCompliance()) {
          logMismatchInterfaceSignature(mAbsoluteClassName, "Implements mismatch");
          return;
        }
      }
    } catch (Exception e) {
      SignatureTestLog.e("Got exception when checking field compliance", e);
      mResultObserver.notifyFailure(
          SignatureTestActivity.FAILURE_TYPE.CAUGHT_EXCEPTION, mAbsoluteClassName, "Exception!");
    }
  }
Example #13
0
 /**
  * Checks if the class under test is compliant with regards to annnotations when compared to the
  * API.
  *
  * @return true if the class is compliant
  */
 private boolean checkClassAnnotationCompliace() {
   if (mClass.isAnnotation()) {
     // check annotation
     for (String inter : implInterfaces) {
       if ("java.lang.annotation.Annotation".equals(inter)) {
         return true;
       }
     }
     return false;
   }
   return true;
 }
 protected <A extends Annotation> A getAnnotation(Class<A> annoType, Symbol annotated) {
   if (!annoType.isAnnotation()) {
     throw new IllegalArgumentException("Not an annotation type: " + annoType);
   }
   String name = annoType.getName();
   for (Attribute.Compound attr : annotated.getAnnotationMirrors()) {
     if (name.equals(attr.type.tsym.flatName().toString())) {
       return AnnotationProxyMaker.generateAnnotation(env, attr, annoType);
     }
   }
   return null;
 }
Example #15
0
  /**
   * Find all occurrences of targetClass in targetObject. Be careful. This stuff may be recursive !
   * Should be improved to prevent endless recursive loops.
   *
   * @param
   * @return
   * @param targetObject
   * @param targetClass
   * @param nestedPath
   * @return
   * @throws Exception
   */
  public static Map<String, ?> findNestedPaths(
      Object targetObject,
      Class<?> targetClass,
      String nestedPath,
      List<String> ignoreList,
      Set<Object> visited,
      int maxDepth)
      throws Exception {

    Assert.notNull(targetObject);
    Assert.notNull(targetClass);
    Assert.notNull(ignoreList);
    HashMap<String, Object> nestedPaths = new HashMap<String, Object>();
    if (maxDepth <= 0) {
      return nestedPaths;
    }

    nestedPath = (nestedPath == null ? "" : nestedPath);
    BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(targetObject);
    PropertyDescriptor[] props = bw.getPropertyDescriptors();

    for (PropertyDescriptor pd : props) {
      Class<?> clazz = pd.getPropertyType();
      if (clazz != null
          && !clazz.equals(Class.class)
          && !clazz.isAnnotation()
          && !clazz.isPrimitive()) {
        Object value = null;
        String pathName = pd.getName();
        if (!ignoreList.contains(pathName)) {
          try {
            value = bw.getPropertyValue(pathName);
          } catch (Exception e) {
          } // ignore any exceptions here
          if (StringUtils.hasText(nestedPath)) {
            pathName = nestedPath + PropertyAccessor.NESTED_PROPERTY_SEPARATOR + pathName;
          }
          // TODO break up this stuff into checking and excecution a la ReflectionUtils
          if (targetClass.isAssignableFrom(clazz)) {
            nestedPaths.put(pathName, value);
          }
          // exclude objects already visited from further inspection to prevent circular references
          // unfortunately this stuff isn't fool proof as there are ConcurrentModificationExceptions
          // when adding objects to the visited list
          if (value != null && !isInstanceVisited(visited, value)) {
            nestedPaths.putAll(
                findNestedPaths(value, targetClass, pathName, ignoreList, visited, maxDepth - 1));
          }
        }
      }
    }
    return nestedPaths;
  }
Example #16
0
 public static AnnotationValuePairDefinition.ValuePairType buildValuePairType(Class cls) {
   if (cls.isEnum()) {
     return AnnotationValuePairDefinition.ValuePairType.ENUM;
   } else if (cls.isAnnotation()) {
     return AnnotationValuePairDefinition.ValuePairType.ANNOTATION;
   } else if (cls.getName().equals(String.class.getName())) {
     return AnnotationValuePairDefinition.ValuePairType.STRING;
   } else if (NamingUtils.isPrimitiveTypeId(cls.getName())) {
     return AnnotationValuePairDefinition.ValuePairType.PRIMITIVE;
   } else {
     return AnnotationValuePairDefinition.ValuePairType.CLASS;
   }
 }
Example #17
0
  public static AnnotationDefinition buildAnnotationDefinition(Class cls) {

    if (!cls.isAnnotation()) return null;

    AnnotationDefinitionImpl annotationDefinition =
        new AnnotationDefinitionImpl(NamingUtils.normalizeClassName(cls.getName()));

    // set retention and target.
    DriverUtils.copyAnnotationRetention(cls, annotationDefinition);
    DriverUtils.copyAnnotationTarget(cls, annotationDefinition);

    Method[] methods = cls.getMethods();
    Method method;
    AnnotationValuePairDefinitionImpl valuePairDefinition;
    Class returnType;
    boolean isArray = false;

    for (int i = 0; methods != null && i < methods.length; i++) {
      method = methods[i];
      if (DriverUtils.isAnnotationMember(cls, method)) {
        returnType = method.getReturnType();
        if ((isArray = returnType.isArray())) returnType = returnType.getComponentType();
        valuePairDefinition =
            new AnnotationValuePairDefinitionImpl(
                method.getName(),
                NamingUtils.normalizeClassName(returnType.getName()),
                DriverUtils.buildValuePairType(returnType),
                isArray,
                // TODO, review this default value assignment, when we have annotations the default
                // value should be an AnnotationInstance
                method.getDefaultValue() != null ? method.getDefaultValue().toString() : null);
        if (valuePairDefinition.isAnnotation()) {
          valuePairDefinition.setAnnotationDefinition(buildAnnotationDefinition(returnType));
        }
        if (valuePairDefinition.isEnum()) {
          Object[] enumConstants = returnType.getEnumConstants();
          if (enumConstants != null) {
            String[] strEnumConstants = new String[enumConstants.length];
            for (int j = 0; j < enumConstants.length; j++) {
              strEnumConstants[j] = enumConstants[j].toString();
            }
            valuePairDefinition.setEnumValues(strEnumConstants);
          }
        }
        annotationDefinition.addValuePair(valuePairDefinition);
      }
    }

    return annotationDefinition;
  }
 private static boolean memberEquals(
     Class<?> paramClass, Object paramObject1, Object paramObject2) {
   if (paramObject1 == paramObject2) {
     return true;
   }
   if ((paramObject1 == null) || (paramObject2 == null)) {
     return false;
   }
   if (paramClass.isArray()) {
     return arrayMemberEquals(paramClass.getComponentType(), paramObject1, paramObject2);
   }
   if (paramClass.isAnnotation()) {
     return equals((Annotation) paramObject1, (Annotation) paramObject2);
   }
   return paramObject1.equals(paramObject2);
 }
Example #19
0
  /**
   * @return Null if class might be a bean; type String (that identifies why it's not a bean) if not
   */
  public static String canBeABeanType(Class<?> type) {
    // First: language constructs that ain't beans:
    if (type.isAnnotation()) {
      return "annotation";
    }
    if (type.isArray()) {
      return "array";
    }
    if (type.isEnum()) {
      return "enum";
    }
    if (type.isPrimitive()) {
      return "primitive";
    }

    // Anything else? Seems valid, then
    return null;
  }
  private ServletContainerInitializerInfo buildInitializerInfo(
      InstanceFactoryFactory factory, Class<? extends ServletContainerInitializer> clazz) {

    Set<Class<?>> types = new HashSet<>();

    HandlesTypes handlesTypes = clazz.getAnnotation(HandlesTypes.class);
    if (handlesTypes != null) {
      for (Class<?> type : handlesTypes.value()) {
        if (type.isAnnotation()) {
          types.addAll(annotationDatabase.getTypes((Class<? extends Annotation>) type));
        }
      }
    }

    InstanceFactory<? extends ServletContainerInitializer> instanceFactory =
        factory.getInstanceFactory(clazz);

    return new ServletContainerInitializerInfo(clazz, instanceFactory, types);
  }
Example #21
0
 @Test
 public void testAnnotation_1() {
   try {
     final XExpression expression = this.expression("42", false);
     final Procedure1<JvmAnnotationType> _function =
         new Procedure1<JvmAnnotationType>() {
           public void apply(final JvmAnnotationType it) {
             EList<JvmMember> _members = it.getMembers();
             JvmTypeReference _typeForName =
                 JvmModelGeneratorTest.this.references.getTypeForName(int.class, expression);
             final Procedure1<JvmOperation> _function =
                 new Procedure1<JvmOperation>() {
                   public void apply(final JvmOperation it) {
                     JvmModelGeneratorTest.this.builder.setBody(it, expression);
                   }
                 };
             JvmOperation _method =
                 JvmModelGeneratorTest.this.builder.toMethod(
                     expression, "theTruth", _typeForName, _function);
             JvmModelGeneratorTest.this.builder.<JvmOperation>operator_add(_members, _method);
           }
         };
     final JvmAnnotationType clazz =
         this.builder.toAnnotationType(expression, "my.test.Foo", _function);
     Resource _eResource = expression.eResource();
     final Class<? extends Object> compiledClass = this.compile(_eResource, clazz);
     boolean _isAnnotation = compiledClass.isAnnotation();
     Assert.assertTrue(_isAnnotation);
     Method[] _methods = compiledClass.getMethods();
     final Method method =
         IterableExtensions.<Method>head(((Iterable<Method>) Conversions.doWrapArray(_methods)));
     String _name = method.getName();
     Assert.assertEquals("theTruth", _name);
     Object _defaultValue = method.getDefaultValue();
     Assert.assertEquals(Integer.valueOf(42), _defaultValue);
   } catch (Exception _e) {
     throw Exceptions.sneakyThrow(_e);
   }
 }
 private Set<ClassInfo> processHandlesType(DotName typeName, Class<?> type, CompositeIndex index)
     throws DeploymentUnitProcessingException {
   Set<ClassInfo> classes = new HashSet<ClassInfo>();
   if (type.isAnnotation()) {
     List<AnnotationInstance> instances = index.getAnnotations(typeName);
     for (AnnotationInstance instance : instances) {
       AnnotationTarget annotationTarget = instance.target();
       if (annotationTarget instanceof ClassInfo) {
         classes.add((ClassInfo) annotationTarget);
       } else if (annotationTarget instanceof FieldInfo) {
         classes.add(((FieldInfo) annotationTarget).declaringClass());
       } else if (annotationTarget instanceof MethodInfo) {
         classes.add(((MethodInfo) annotationTarget).declaringClass());
       } else if (annotationTarget instanceof MethodParameterInfo) {
         classes.add(((MethodParameterInfo) annotationTarget).method().declaringClass());
       }
     }
   } else {
     classes.addAll(index.getAllKnownSubclasses(typeName));
     classes.addAll(index.getAllKnownImplementors(typeName));
   }
   return classes;
 }
Example #23
0
 /**
  * Works out the correct scanner based on the class passed in
  *
  * <p>Note that these could be better architected by breaking out filters into strategy objects,
  * but for now this suits my needs
  *
  * @param clazz the type to scan for
  * @return a scanner suitable for handling the type passed in
  * @see AnnotationsScanner
  * @see InterfaceClassScanner
  * @see ImplementationClassScanner
  */
 protected ClassScanner getScanner(Class clazz) {
   if (clazz.isInterface()) {
     if (clazz.isAnnotation()) {
       AnnotationFilter filter = null;
       Annotation[] annos = clazz.getDeclaredAnnotations();
       for (int i = 0; i < annos.length; i++) {
         Annotation anno = annos[i];
         if (anno instanceof Target) {
           if (((Target) anno).value()[0] == ElementType.ANNOTATION_TYPE) {
             filter = new MetaAnnotationTypeFilter(clazz, classLoader);
           }
         }
       }
       if (filter == null) {
         filter = new AnnotationTypeFilter(clazz);
       }
       return new AnnotationsScanner(filter);
     } else {
       return new InterfaceClassScanner(clazz);
     }
   } else {
     return new ImplementationClassScanner(clazz);
   }
 }
  /**
   * This method is used to filter classes that are added to the {@link DeployedUnit}. When this
   * method is used, only classes that are meant to be used with serialization are added to the
   * deployment. This feature can be used to, for example, make sure that
   * non-serialization-compatible classes (such as interfaces), do not complicate the use of a
   * deployment with the remote services (REST/JMS/WS). Note to other developers, it's possible that
   * classpath problems may arise, because of either classloader or lazy class resolution problems:
   * I simply don't know enough about the inner workings of the JAXB implementations (plural!) to
   * figure this out.
   *
   * @param deployedUnit The {@link DeployedUnit} to which the classes are added. The {@link
   *     DeployedUnit} to which the classes are added. The {@link DeployedUnit} to which the classes
   *     are added.
   * @param classToAdd The class to add to the {@link DeployedUnit}.
   */
  private static void filterClassesAddedToDeployedUnit(
      DeployedUnit deployedUnit, Class classToAdd) {

    if (classToAdd.isInterface()
        || classToAdd.isAnnotation()
        || classToAdd.isLocalClass()
        || classToAdd.isMemberClass()) {
      return;
    }

    boolean jaxbClass = false;
    boolean remoteableClass = false;
    // @XmlRootElement and @XmlType may be used with inheritance
    for (Annotation anno : classToAdd.getAnnotations()) {
      if (XmlRootElement.class.equals(anno.annotationType())) {
        jaxbClass = true;
        break;
      }
      if (XmlType.class.equals(anno.annotationType())) {
        jaxbClass = true;
        break;
      }
    }
    // @Remotable is not inheritable, and may not be used as such
    for (Annotation anno : classToAdd.getDeclaredAnnotations()) {
      if (Remotable.class.equals(anno.annotationType())) {
        remoteableClass = true;
        break;
      }
    }

    if (jaxbClass || remoteableClass) {
      DeployedUnitImpl deployedUnitImpl = (DeployedUnitImpl) deployedUnit;
      deployedUnitImpl.addClass(classToAdd);
    }
  }
Example #25
0
  private boolean isInstrumentClass(Class c) {

    if (!instrumentation.isModifiableClass(c)) {
      LOG.trace("NO INSTRUMENT: Class " + c.getName() + " is not modifiable");
      return false;
    }
    if (!configuration.isAudit(c.getName())) {
      LOG.trace("NO INSTRUMENT: Class " + c.getName() + " is blacklisted");
      return false;
    }
    if (c.isArray()
        || c.isAnnotation()
        || c.isInterface()
        || c.isPrimitive()
        || c.isSynthetic()
        || c.isEnum()) {
      LOG.trace(
          "NO INSTRUMENT: Class "
              + c.getName()
              + " is an array, primitive, annotation or enum etc");
      return false;
    }
    return true;
  }
Example #26
0
 @Test
 public void testAnnotation_2() {
   try {
     final XExpression expression = this.expression("typeof(String)", false);
     final Procedure1<JvmAnnotationType> _function =
         new Procedure1<JvmAnnotationType>() {
           public void apply(final JvmAnnotationType it) {
             EList<JvmMember> _members = it.getMembers();
             JvmWildcardTypeReference _wildCard = JvmModelGeneratorTest.this.references.wildCard();
             JvmTypeReference _typeForName =
                 JvmModelGeneratorTest.this.references.getTypeForName(
                     Class.class, expression, _wildCard);
             final Procedure1<JvmOperation> _function =
                 new Procedure1<JvmOperation>() {
                   public void apply(final JvmOperation it) {
                     JvmModelGeneratorTest.this.builder.setBody(it, expression);
                   }
                 };
             JvmOperation _method =
                 JvmModelGeneratorTest.this.builder.toMethod(
                     expression, "value", _typeForName, _function);
             JvmModelGeneratorTest.this.builder.<JvmOperation>operator_add(_members, _method);
             EList<JvmMember> _members_1 = it.getMembers();
             JvmTypeReference _typeForName_1 =
                 JvmModelGeneratorTest.this.references.getTypeForName(int.class, expression);
             final Procedure1<JvmOperation> _function_1 =
                 new Procedure1<JvmOperation>() {
                   public void apply(final JvmOperation it) {}
                 };
             JvmOperation _method_1 =
                 JvmModelGeneratorTest.this.builder.toMethod(
                     expression, "otherValue", _typeForName_1, _function_1);
             JvmModelGeneratorTest.this.builder.<JvmOperation>operator_add(_members_1, _method_1);
           }
         };
     final JvmAnnotationType clazz =
         this.builder.toAnnotationType(expression, "my.test.Foo", _function);
     Resource _eResource = expression.eResource();
     final Class<? extends Object> compiledClass = this.compile(_eResource, clazz);
     boolean _isAnnotation = compiledClass.isAnnotation();
     Assert.assertTrue(_isAnnotation);
     Method[] _methods = compiledClass.getMethods();
     final Function1<Method, Boolean> _function_1 =
         new Function1<Method, Boolean>() {
           public Boolean apply(final Method it) {
             String _name = it.getName();
             boolean _equals = Objects.equal(_name, "value");
             return Boolean.valueOf(_equals);
           }
         };
     Method _findFirst =
         IterableExtensions.<Method>findFirst(
             ((Iterable<Method>) Conversions.doWrapArray(_methods)), _function_1);
     Object _defaultValue = _findFirst.getDefaultValue();
     Assert.assertEquals(String.class, _defaultValue);
     Method[] _methods_1 = compiledClass.getMethods();
     final Function1<Method, Boolean> _function_2 =
         new Function1<Method, Boolean>() {
           public Boolean apply(final Method it) {
             String _name = it.getName();
             boolean _equals = Objects.equal(_name, "otherValue");
             return Boolean.valueOf(_equals);
           }
         };
     Method _findFirst_1 =
         IterableExtensions.<Method>findFirst(
             ((Iterable<Method>) Conversions.doWrapArray(_methods_1)), _function_2);
     Object _defaultValue_1 = _findFirst_1.getDefaultValue();
     Assert.assertNull(_defaultValue_1);
   } catch (Exception _e) {
     throw Exceptions.sneakyThrow(_e);
   }
 }
Example #27
0
  private void addClass(Class<?> classZ) {
    if (classZ.isInterface()
        || classZ.isMemberClass()
        || classZ.isEnum()
        || classZ.isAnnotation()
        || classZ.isAnonymousClass()) return;
    int modify = classZ.getModifiers();
    if (Modifier.isAbstract(modify) || (!Modifier.isPublic(modify))) return;
    IocBean iocBean = classZ.getAnnotation(IocBean.class);
    if (iocBean != null) {
      if (log.isDebugEnabled()) log.debugf("Found a Class with Ioc-Annotation : %s", classZ);

      // 采用 @IocBean->name
      String beanName = iocBean.name();
      if (Strings.isBlank(beanName)) {
        // 否则采用 @InjectName
        InjectName innm = classZ.getAnnotation(InjectName.class);
        if (null != innm && !Strings.isBlank(innm.value())) {
          beanName = innm.value();
        }
        // 大哥(姐),您都不设啊!? 那就用 simpleName 吧
        else {
          beanName = Strings.lowerFirst(classZ.getSimpleName());
        }
      }

      if (map.containsKey(beanName))
        throw Lang.makeThrow(
            IocException.class,
            "Duplicate beanName=%s, by %s !!  Have been define by %s !!",
            beanName,
            classZ,
            map.get(beanName).getClass());

      IocObject iocObject = new IocObject();
      iocObject.setType(classZ);
      map.put(beanName, iocObject);

      iocObject.setSingleton(iocBean.singleton());
      if (!Strings.isBlank(iocBean.scope())) iocObject.setScope(iocBean.scope());

      // 看看构造函数都需要什么函数
      String[] args = iocBean.args();
      // if (null == args || args.length == 0)
      // args = iocBean.param();
      if (null != args && args.length > 0)
        for (String value : args) iocObject.addArg(convert(value));

      // 设置Events
      IocEventSet eventSet = new IocEventSet();
      iocObject.setEvents(eventSet);
      if (!Strings.isBlank(iocBean.create())) eventSet.setCreate(iocBean.create().trim().intern());
      if (!Strings.isBlank(iocBean.depose())) eventSet.setDepose(iocBean.depose().trim().intern());
      if (!Strings.isBlank(iocBean.fetch())) eventSet.setFetch(iocBean.fetch().trim().intern());

      // 处理字段(以@Inject方式,位于字段)
      List<String> fieldList = new ArrayList<String>();
      Mirror<?> mirror = Mirror.me(classZ);
      Field[] fields = mirror.getFields(Inject.class);
      for (Field field : fields) {
        Inject inject = field.getAnnotation(Inject.class);
        // 无需检查,因为字段名是唯一的
        // if(fieldList.contains(field.getName()))
        // throw duplicateField(classZ,field.getName());
        IocField iocField = new IocField();
        iocField.setName(field.getName());
        IocValue iocValue;
        if (Strings.isBlank(inject.value())) {
          iocValue = new IocValue();
          iocValue.setType(IocValue.TYPE_REFER);
          iocValue.setValue(field.getName());
        } else iocValue = convert(inject.value());
        iocField.setValue(iocValue);
        iocObject.addField(iocField);
        fieldList.add(iocField.getName());
      }
      // 处理字段(以@Inject方式,位于set方法)
      Method[] methods;
      try {
        methods = classZ.getMethods();
      } catch (Exception e) {
        // 如果获取失败,就忽略之
        log.info("Fail to call getMethods(), miss class or Security Limit, ignore it", e);
        methods = new Method[0];
      }
      for (Method method : methods) {
        Inject inject = method.getAnnotation(Inject.class);
        if (inject == null) continue;
        // 过滤特殊方法
        int m = method.getModifiers();
        if (Modifier.isAbstract(m) || (!Modifier.isPublic(m)) || Modifier.isStatic(m)) continue;
        String methodName = method.getName();
        if (methodName.startsWith("set")
            && methodName.length() > 3
            && method.getParameterTypes().length == 1) {
          IocField iocField = new IocField();
          iocField.setName(Strings.lowerFirst(methodName.substring(3)));
          if (fieldList.contains(iocField.getName()))
            throw duplicateField(classZ, iocField.getName());
          IocValue iocValue;
          if (Strings.isBlank(inject.value())) {
            iocValue = new IocValue();
            iocValue.setType(IocValue.TYPE_REFER);
            iocValue.setValue(Strings.lowerFirst(methodName.substring(3)));
          } else iocValue = convert(inject.value());
          iocField.setValue(iocValue);
          iocObject.addField(iocField);
          fieldList.add(iocField.getName());
        }
      }
      // 处理字段(以@IocBean.field方式)
      String[] flds = iocBean.fields();
      if (flds != null && flds.length > 0) {
        for (String fieldInfo : flds) {
          if (fieldList.contains(fieldInfo)) throw duplicateField(classZ, fieldInfo);
          IocField iocField = new IocField();
          if (fieldInfo.contains(":")) { // dao:jndi:dataSource/jdbc形式
            String[] datas = fieldInfo.split(":", 2);
            // 完整形式, 与@Inject完全一致了
            iocField.setName(datas[0]);
            iocField.setValue(convert(datas[1]));
            iocObject.addField(iocField);
          } else {
            // 基本形式, 引用与自身同名的bean
            iocField.setName(fieldInfo);
            IocValue iocValue = new IocValue();
            iocValue.setType(IocValue.TYPE_REFER);
            iocValue.setValue(fieldInfo);
            iocField.setValue(iocValue);
            iocObject.addField(iocField);
          }
          fieldList.add(iocField.getName());
        }
      }
    } else {
      if (log.isWarnEnabled()) {
        Field[] fields = classZ.getDeclaredFields();
        for (Field field : fields)
          if (field.getAnnotation(Inject.class) != null) {
            log.warnf(
                "class(%s) don't has @IocBean, but field(%s) has @Inject! Miss @IocBean ??",
                classZ.getName(), field.getName());
            break;
          }
      }
    }
  }
Example #28
0
  // This method is part of the javax.lang.model API, do not use this in javac code.
  public <A extends Annotation> A[] getAnnotationsByType(Class<A> annoType) {

    if (!annoType.isAnnotation())
      throw new IllegalArgumentException("Not an annotation type: " + annoType);
    // If annoType does not declare a container this is equivalent to wrapping
    // getAnnotation(...) in an array.
    Class<? extends Annotation> containerType = getContainer(annoType);
    if (containerType == null) {
      A res = getAnnotation(annoType);
      int size = res == null ? 0 : 1;

      @SuppressWarnings("unchecked") // annoType is the Class for A
      A[] arr = (A[]) java.lang.reflect.Array.newInstance(annoType, size);
      if (res != null) arr[0] = res;
      return arr;
    }

    // So we have a containing type
    String annoTypeName = annoType.getName();
    String containerTypeName = containerType.getName();
    int directIndex = -1, containerIndex = -1;
    Attribute.Compound direct = null, container = null;
    // Find directly (explicit or implicit) present annotations
    int index = -1;
    for (Attribute.Compound attribute : getAnnotationMirrors()) {
      index++;
      if (attribute.type.tsym.flatName().contentEquals(annoTypeName)) {
        directIndex = index;
        direct = attribute;
      } else if (containerTypeName != null
          && attribute.type.tsym.flatName().contentEquals(containerTypeName)) {
        containerIndex = index;
        container = attribute;
      }
    }

    // Deal with inherited annotations
    if (direct == null && container == null && annoType.isAnnotationPresent(Inherited.class))
      return getInheritedAnnotations(annoType);

    Attribute.Compound[] contained = unpackContained(container);

    // In case of an empty legacy container we might need to look for
    // inherited annos as well
    if (direct == null && contained.length == 0 && annoType.isAnnotationPresent(Inherited.class))
      return getInheritedAnnotations(annoType);

    int size = (direct == null ? 0 : 1) + contained.length;
    @SuppressWarnings("unchecked") // annoType is the Class for A
    A[] arr = (A[]) java.lang.reflect.Array.newInstance(annoType, size);

    // if direct && container, which is first?
    int insert = -1;
    int length = arr.length;
    if (directIndex >= 0 && containerIndex >= 0) {
      if (directIndex < containerIndex) {
        arr[0] = AnnotationProxyMaker.generateAnnotation(direct, annoType);
        insert = 1;
      } else {
        arr[arr.length - 1] = AnnotationProxyMaker.generateAnnotation(direct, annoType);
        insert = 0;
        length--;
      }
    } else if (directIndex >= 0) {
      arr[0] = AnnotationProxyMaker.generateAnnotation(direct, annoType);
      return arr;
    } else {
      // Only container
      insert = 0;
    }

    for (int i = 0; i + insert < length; i++)
      arr[insert + i] = AnnotationProxyMaker.generateAnnotation(contained[i], annoType);

    return arr;
  }
Example #29
0
 public static boolean isValidAnnotationBaseReturnType(Class cls) {
   // TODO review this calculation
   return (cls.isAnnotation() || cls.isEnum() || NamingUtils.isPrimitiveTypeId(cls.getName()))
       || (!cls.isAnonymousClass() && !cls.isLocalClass());
 }
  /**
   * Convert a JDT annotation value as obtained from ElementValuePair.getValue() (e.g., IntConstant,
   * FieldBinding, etc.) to the type expected by a reflective method invocation (e.g., int, an enum
   * constant, etc.).
   *
   * @return a value of type {@code expectedType}, or a dummy value of that type if the actual value
   *     cannot be converted.
   */
  private Object convertJDTValueToReflectionType(
      Object jdtValue, TypeBinding actualType, Class<?> expectedType) {
    if (expectedType.isPrimitive() || String.class.equals(expectedType)) {
      if (jdtValue instanceof Constant) {
        if (boolean.class.equals(expectedType)) {
          return ((Constant) jdtValue).booleanValue();
        } else if (byte.class.equals(expectedType)) {
          return ((Constant) jdtValue).byteValue();
        } else if (char.class.equals(expectedType)) {
          return ((Constant) jdtValue).charValue();
        } else if (double.class.equals(expectedType)) {
          return ((Constant) jdtValue).doubleValue();
        } else if (float.class.equals(expectedType)) {
          return ((Constant) jdtValue).floatValue();
        } else if (int.class.equals(expectedType)) {
          return ((Constant) jdtValue).intValue();
        } else if (long.class.equals(expectedType)) {
          return ((Constant) jdtValue).longValue();
        } else if (short.class.equals(expectedType)) {
          return ((Constant) jdtValue).shortValue();
        } else if (String.class.equals(expectedType)) {
          return ((Constant) jdtValue).stringValue();
        }
      }
      // Primitive or string is expected, but our actual value cannot be coerced into one.
      // TODO: if the actual value is an array of primitives, should we unpack the first one?
      return Factory.getMatchingDummyValue(expectedType);
    } else if (expectedType.isEnum()) {
      Object returnVal = null;
      if (actualType != null && actualType.isEnum() && jdtValue instanceof FieldBinding) {

        FieldBinding binding = (FieldBinding) jdtValue;
        try {
          Field returnedField = null;
          returnedField = expectedType.getField(new String(binding.name));
          if (null != returnedField) {
            returnVal = returnedField.get(null);
          }
        } catch (NoSuchFieldException nsfe) {
          // return null
        } catch (IllegalAccessException iae) {
          // return null
        }
      }
      return null == returnVal ? Factory.getMatchingDummyValue(expectedType) : returnVal;
    } else if (expectedType.isAnnotation()) {
      // member value is expected to be an annotation type.  Wrap it in an Annotation proxy.
      if (actualType.isAnnotationType() && jdtValue instanceof AnnotationBinding) {
        AnnotationMirrorImpl annoMirror =
            (AnnotationMirrorImpl)
                _env.getFactory().newAnnotationMirror((AnnotationBinding) jdtValue);
        return Proxy.newProxyInstance(
            expectedType.getClassLoader(), new Class[] {expectedType}, annoMirror);
      } else {
        // No way to cast a non-annotation value to an annotation type; return null to caller
        return null;
      }
    } else {
      return Factory.getMatchingDummyValue(expectedType);
    }
  }