Ejemplo n.º 1
0
  @Nullable
  private static String getNamedAnnotationValue(
      final Class<?> injectClass, final Class<?> intoClass) {

    for (final Constructor<?> constructor : intoClass.getConstructors()) {

      if (!constructor.isAnnotationPresent(Inject.class)) {
        continue;
      }

      final Annotation[][] paramAnnotations = constructor.getParameterAnnotations();

      final Class<?>[] paramTypes = constructor.getParameterTypes();

      for (int i = 0; i < paramTypes.length; ++i) {

        if (!injectClass.equals(paramTypes[i])) {
          continue;
        }

        for (int j = 0; j < paramAnnotations[i].length; ++j) {

          final Annotation paramAnnotation = paramAnnotations[i][j];

          if (Named.class.equals(paramAnnotation.annotationType())) {

            return ((Named) paramAnnotation).value();
          }
        }
      }
    }

    return null;
  }
Ejemplo n.º 2
0
 private static Constructor fullConstructor(Class klass) {
   Constructor[] array = klass.getConstructors();
   for (Constructor constructor : array) {
     if (constructor.isAnnotationPresent(FullConstructor.class)) {
       return constructor;
     }
   }
   return null;
 }
Ejemplo n.º 3
0
  public static boolean isValidConstructor(Class<?> type) {
    for (Constructor<?> ctor : type.getDeclaredConstructors()) {
      if (ctor.getParameterTypes().length == 0) return true;

      if (ctor.isAnnotationPresent(Inject.class)) return true;
    }

    return false;
  }
Ejemplo n.º 4
0
  /**
   * 取得构造方法中的annotation列表
   *
   * @param constructors 构造方法数组
   * @param annotationClass 指定的annotation类型
   * @return
   */
  @SuppressWarnings("unchecked")
  public static <T extends Annotation> List<T> getConstructorAnnotations(
      Constructor<?>[] constructors, Class<? extends Annotation> annotationClass) {
    Assert.notNull(constructors, "constructors不能为空");
    List<T> list = new ArrayList<T>();
    for (Constructor<?> constructor : constructors) {
      constructor.setAccessible(true);
      Annotation[] annotations = constructor.getAnnotations();
      for (Annotation annotation : annotations) {
        if (annotationClass != null) {
          if (annotation.equals(annotationClass)
              && constructor.isAnnotationPresent(annotationClass)) {
            list.add((T) annotation);
          }
        } else {
          list.add((T) annotation);
        }
      }
    }

    return list;
  }
Ejemplo n.º 5
0
  @BeforeClass
  public static void beforeClass() throws Exception {
    List<Class<?>> analysisClasses = getClassesForPackage("org.apache.lucene.analysis");
    tokenizers = new ArrayList<Constructor<? extends Tokenizer>>();
    tokenfilters = new ArrayList<Constructor<? extends TokenFilter>>();
    charfilters = new ArrayList<Constructor<? extends CharFilter>>();
    for (final Class<?> c : analysisClasses) {
      final int modifiers = c.getModifiers();
      if (
      // don't waste time with abstract classes or deprecated known-buggy ones
      Modifier.isAbstract(modifiers)
          || !Modifier.isPublic(modifiers)
          || c.isSynthetic()
          || c.isAnonymousClass()
          || c.isMemberClass()
          || c.isInterface()
          || c.isAnnotationPresent(Deprecated.class)
          || !(Tokenizer.class.isAssignableFrom(c)
              || TokenFilter.class.isAssignableFrom(c)
              || CharFilter.class.isAssignableFrom(c))) {
        continue;
      }

      for (final Constructor<?> ctor : c.getConstructors()) {
        // don't test synthetic or deprecated ctors, they likely have known bugs:
        if (ctor.isSynthetic()
            || ctor.isAnnotationPresent(Deprecated.class)
            || brokenConstructors.get(ctor) == ALWAYS) {
          continue;
        }
        if (Tokenizer.class.isAssignableFrom(c)) {
          assertTrue(
              ctor.toGenericString() + " has unsupported parameter types",
              allowedTokenizerArgs.containsAll(Arrays.asList(ctor.getParameterTypes())));
          tokenizers.add(castConstructor(Tokenizer.class, ctor));
        } else if (TokenFilter.class.isAssignableFrom(c)) {
          assertTrue(
              ctor.toGenericString() + " has unsupported parameter types",
              allowedTokenFilterArgs.containsAll(Arrays.asList(ctor.getParameterTypes())));
          tokenfilters.add(castConstructor(TokenFilter.class, ctor));
        } else if (CharFilter.class.isAssignableFrom(c)) {
          assertTrue(
              ctor.toGenericString() + " has unsupported parameter types",
              allowedCharFilterArgs.containsAll(Arrays.asList(ctor.getParameterTypes())));
          charfilters.add(castConstructor(CharFilter.class, ctor));
        } else {
          fail("Cannot get here");
        }
      }
    }

    final Comparator<Constructor<?>> ctorComp =
        new Comparator<Constructor<?>>() {
          @Override
          public int compare(Constructor<?> arg0, Constructor<?> arg1) {
            return arg0.toGenericString().compareTo(arg1.toGenericString());
          }
        };
    Collections.sort(tokenizers, ctorComp);
    Collections.sort(tokenfilters, ctorComp);
    Collections.sort(charfilters, ctorComp);
    if (VERBOSE) {
      System.out.println("tokenizers = " + tokenizers);
      System.out.println("tokenfilters = " + tokenfilters);
      System.out.println("charfilters = " + charfilters);
    }
  }
 /**
  * Returns whether the constructor was explicitly selected (by {@link PersistenceConstructor}).
  *
  * @return
  */
 public boolean isExplicitlyAnnotated() {
   return constructor.isAnnotationPresent(PersistenceConstructor.class);
 }
Ejemplo n.º 7
0
  /**
   * Register managed beans as Errai services
   *
   * @param event -
   * @param <T> -
   */
  @SuppressWarnings("UnusedDeclaration")
  public <T> void observeResources(@Observes final ProcessAnnotatedType<T> event) {
    final AnnotatedType<T> type = event.getAnnotatedType();

    for (final Annotation a : type.getJavaClass().getAnnotations()) {
      if (a.annotationType().isAnnotationPresent(Qualifier.class)) {
        beanQualifiers.put(a.annotationType().getName(), a);
      }
    }

    // services
    if (type.isAnnotationPresent(Service.class)) {
      log.debug("discovered Errai annotation on type: " + type);
      boolean isRpc = false;

      final Class<T> javaClass = type.getJavaClass();
      for (final Class<?> intf : javaClass.getInterfaces()) {
        isRpc = intf.isAnnotationPresent(Remote.class);

        if (isRpc) {
          if (!managedTypes.getRemoteInterfaces().contains(intf)) {
            managedTypes.addRemoteInterface(intf);
          }
        }
      }

      if (!isRpc) {
        managedTypes.addServiceEndpoint(type);
      }
    } else {
      for (final AnnotatedMethod method : type.getMethods()) {
        if (method.isAnnotationPresent(Service.class)) {
          managedTypes.addServiceMethod(type, method);
        }
      }
    }

    // veto on client side implementations that contain CDI annotations
    // (i.e. @Observes) Otherwise Weld might try to invoke on them
    if (vetoClasses.contains(type.getJavaClass().getName())
        || (type.getJavaClass().getPackage().getName().contains("client")
            && !type.getJavaClass().isInterface())) {
      event.veto();
    }
    /** We must scan for Event consumer injection points to build the tables */
    final Class clazz = type.getJavaClass();

    for (final Field f : clazz.getDeclaredFields()) {
      if (f.isAnnotationPresent(Inject.class) && f.isAnnotationPresent(ObserverModel.class)) {
        processEventInjector(f.getType(), f.getGenericType(), f.getAnnotations());
      }
    }
    for (final Method m : clazz.getDeclaredMethods()) {
      if (m.isAnnotationPresent(Inject.class) && m.isAnnotationPresent(ObserverModel.class)) {
        final Class<?>[] parameterTypes = m.getParameterTypes();
        for (int i = 0, parameterTypesLength = parameterTypes.length;
            i < parameterTypesLength;
            i++) {
          final Class<?> parmType = parameterTypes[i];
          processEventInjector(
              parmType, m.getGenericParameterTypes()[i], m.getParameterAnnotations()[i]);
        }
      }
    }
    for (final Constructor c : clazz.getDeclaredConstructors()) {
      if (c.isAnnotationPresent(Inject.class) && c.isAnnotationPresent(ObserverModel.class)) {
        final Class<?>[] parameterTypes = c.getParameterTypes();
        for (int i = 0, parameterTypesLength = parameterTypes.length;
            i < parameterTypesLength;
            i++) {
          final Class<?> parmType = parameterTypes[i];
          processEventInjector(
              parmType, c.getGenericParameterTypes()[i], c.getParameterAnnotations()[i]);
        }
      }
    }
  }
Ejemplo n.º 8
0
  @SuppressWarnings("unchecked")
  public static <T> JsapResultsWithObject<T> constructObject(
      Class<T> clazz, String[] rawArguments, String mainHelp, Parameter[] otherParameters)
      throws JSAPException, IOException, IllegalArgumentException, ReflectiveOperationException {
    Constructor<T> constructor = null;
    for (Constructor<?> constr : clazz.getConstructors()) {
      boolean annotationPresent = constr.isAnnotationPresent(CommandLine.class);
      if (annotationPresent) {
        constructor = (Constructor<T>) constr;
        break;
      }
    }
    if (constructor == null)
      throw new IllegalAccessError(
          "Class " + clazz + " must have a constructor annotated with @CommandLine");

    String[] argNames = constructor.getAnnotation(CommandLine.class).argNames();
    if (argNames.length != constructor.getParameterCount())
      throw new IllegalAnnotationException(
          "Annotation @CommandLine argNames are out of sync with the constructor arguments.");

    boolean[] isSerializedFile = new boolean[argNames.length];

    SimpleJSAP jsap = new SimpleJSAP(clazz.getName(), mainHelp, otherParameters);
    int i = 0;
    for (java.lang.reflect.Parameter x : constructor.getParameters()) {
      Parameter option;
      if (x.getType().equals(boolean.class)) {
        isSerializedFile[i] = false;
        option =
            new Switch(
                argNames[i],
                JSAP.NO_SHORTFLAG,
                argNames[i],
                "Set the value of " + argNames[i] + " for " + clazz.getSimpleName() + " as true.");
      } else {
        StringParser parser;
        String help;
        try {
          parser = getParserFor(x.getType());
          isSerializedFile[i] = false;
          help = "The " + x.getType().getSimpleName() + " value of " + argNames[i];
        } catch (NoJSAPParserForThisTypeException e) {
          parser = JSAP.STRING_PARSER;
          isSerializedFile[i] = true;
          help =
              "A serialized " + x.getType().getSimpleName() + " file to initialize " + argNames[i];
        }
        option = new UnflaggedOption(argNames[i], parser, JSAP.REQUIRED, help);
      }

      jsap.registerParameter(option);

      i++;
    }

    JSAPResult args = jsap.parse(rawArguments);
    if (jsap.messagePrinted()) System.exit(1);

    LOGGER.info("Initializing...");
    Object[] arguments = new Object[argNames.length];
    i = 0;
    for (String argName : argNames) {
      if (isSerializedFile[i]) arguments[i] = SerializationUtils.read(args.getString(argName));
      else arguments[i] = args.getObject(argName);
      i++;
    }
    T object = constructor.newInstance(arguments);
    LOGGER.info("Ready.");

    return new JsapResultsWithObject<T>(args, object);
  }