예제 #1
0
  /**
   * Vérifie qu'une interface est bien présente dans les interfaces d'un composant.
   *
   * @param name nom de l'interface dans le xml et l'annotation
   * @param intNames noms des classes annotées
   * @param comp composant censé contenir l'interface
   * @return
   * @throws ClassNotFoundException
   * @throws InstantiationException
   * @throws IllegalAccessException
   */
  private boolean isOneOf(String name, Set<String> intNames, Composant comp)
      throws ClassNotFoundException, InstantiationException, IllegalAccessException {
    for (String intName : intNames) {
      Class intC = loader.loadClass(intName);
      if (AccessibleObject.class.isAssignableFrom(intC) && Member.class.isAssignableFrom(intC)) {
        AccessibleObject member = (AccessibleObject) intC.newInstance();

        // Faut check qu'il est bien de la bonne classe
        if (((Member) member).getDeclaringClass().equals(comp.getClass())) {
          // Faut check que l'annotation a bien pName comme value.
          RequiredInterface annotation = member.getAnnotation(RequiredInterface.class);
          if (annotation == null) {
            ProvidedInterface annotation1 = member.getAnnotation(ProvidedInterface.class);
            if (annotation1.value().equals(name)) {
              return true;
            }
          } else {
            if (annotation.value().equals(name)) {
              return true;
            }
          }
        }
      }
    }
    return false;
  }
예제 #2
0
  @Around("execution(* javax.validation.ConstraintValidator.isValid(..)) && args(value, context)")
  public Object aroundValid(
      ProceedingJoinPoint jointPoint, Object value, ConstraintValidatorContext context)
      throws Throwable {
    if (value == null) {
      // @NotNullのケースが有るため、処理させる。他Validationは通常Null時はパスなので
      return jointPoint.proceed();
    }
    ValidateContext validateContext = ValidateContext.instance();
    Object declaring = null;
    Condition condition = null;
    if (validateContext.isAnnotatedClass()) {
      condition = value.getClass().getAnnotation(Condition.class);
      declaring = value;
    } else if (validateContext.isAnnotatedField() || validateContext.isAnnotatedMethod()) {
      AccessibleObject accessible = (AccessibleObject) validateContext.getAnnotated();
      condition = accessible.getAnnotation(Condition.class);
      declaring = validateContext.getDeclared();
    }

    if (condition != null && declaring != null && !judgeCondition(condition, declaring)) {
      // @Condition判定処理結果がfalseなので、Validate処理外
      return true;
    }
    return jointPoint.proceed();
  }
예제 #3
0
  @SafeVarargs
  public static List<Accessor> getAnnotatedAccessors(
      Class<?> cls,
      Comparator<Accessor> comparator,
      Class<? extends Annotation>... annotationClasses) {
    List<Accessor> accessors = new ArrayList<>();
    List<AccessibleObject> accessibleObjects = new ArrayList<>();

    accessibleObjects.addAll(Arrays.asList(cls.getDeclaredFields()));
    accessibleObjects.addAll(Arrays.asList(cls.getDeclaredMethods()));

    for (AccessibleObject accessibleObject : accessibleObjects) {
      for (Class<? extends Annotation> annotationClass : annotationClasses) {
        if (accessibleObject.getAnnotation(annotationClass) != null) {
          accessors.add(createAccessor(accessibleObject));
          break;
        }
      }
    }

    if (comparator != null) {
      Collections.sort(accessors, comparator);
    }

    return accessors;
  }
예제 #4
0
  private void initialize() {
    this.type = GenericAssociationInfo.associationTypeOf(accessor);
    this.qualifiedName = QualifiedName.fromAccessor(accessor);
    this.immutable = metaInfo.get(Immutable.class) != null;
    this.aggregated = metaInfo.get(Aggregated.class) != null;

    final Queryable queryable = accessor.getAnnotation(Queryable.class);
    this.queryable = queryable == null || queryable.value();
  }
 private Annotation findAutowiredAnnotation(AccessibleObject ao) {
   for (Class<? extends Annotation> type : this.autowiredAnnotationTypes) {
     Annotation annotation = ao.getAnnotation(type);
     if (annotation != null) {
       return annotation;
     }
   }
   return null;
 }
예제 #6
0
  private void introspect() {
    introspectTypes();

    ElementCollection elementCollectionAnn = _field.getAnnotation(ElementCollection.class);

    if (elementCollectionAnn != null) introspectElementCollection(elementCollectionAnn);

    CollectionTable collectionTableAnn = _field.getAnnotation(CollectionTable.class);

    if (collectionTableAnn != null)
      _collectionTable = new CollectionTableConfig(collectionTableAnn);
    else {
      _collectionTable = new CollectionTableConfig(getRelatedType().getName(), _fieldName);
    }

    /*
    OrderBy orderByAnn = _field.getAnnotation(OrderBy.class);

    if (orderByAnn != null)
      _orderBy = orderByAnn.value();
    */
  }
  /**
   * Returns the {@link Annotation} object if an annotation for the specified type is present on the
   * injection target, otherwise null.
   *
   * <p>If the {@link AccessibleObject} of the injection target is of type {@link Method} or {@link
   * Constructor}, then the {@link Annotation} may be specified on the {@link AccessibleObject} or
   * on the corresponding parameter.
   *
   * @param annotationClass - the Class object corresponding to the annotation type
   * @return annotation for the specified annotation type if present on this element, otherwise null
   * @throws NullPointerException - if the given annotation class is null
   */
  @SuppressWarnings("unchecked")
  public <T> T getAnnotation(final Class<? extends Annotation> annotationClass) {
    final Annotation annotation = accessibleObject.getAnnotation(annotationClass);
    if (annotation != null) {
      return (T) annotation;
    }

    for (final Annotation parameterAnnotation : parameterAnnotations) {
      if (parameterAnnotation.annotationType() == annotationClass) {
        return (T) parameterAnnotation;
      }
    }

    return null;
  }
예제 #8
0
  void getMemberInfo(AccessibleObject[] accessers, MemberType type) {
    for (AccessibleObject a : accessers) {
      if (!a.isAnnotationPresent(JsApi.class) && !a.isAnnotationPresent(JsConstructor.class))
        continue;

      MemberInfo mInfo = new MemberInfo();
      String name = ((Member) a).getName();
      mInfo.javaName = name;
      mInfo.accesser = a;
      mInfo.isStatic = Modifier.isStatic(((Member) a).getModifiers());
      if (a.isAnnotationPresent(JsApi.class)) {
        JsApi mAnno = a.getAnnotation(JsApi.class);

        // Get eventList from properties.
        if (type == MemberType.JS_PROPERTY && mAnno.isEventList()) {
          if (!((Field) a).getType().equals(String[].class)) {
            Log.w(TAG, "Invalid type for Supported JS event list" + name);
            continue;
          }
          try {
            // Event List should be a class property with "static".
            eventList = (String[]) (((Field) a).get(null));
          } catch (IllegalArgumentException | IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
          continue;
        }

        mInfo.type = type;
        mInfo.isWritable = mAnno.isWritable();
        mInfo.isEntryPoint = mAnno.isEntryPoint();
        mInfo.withPromise = mAnno.withPromise();
        mInfo.jsName = name;
        mInfo.wrapArgs = mAnno.wrapArgs();
        mInfo.wrapReturns = mAnno.wrapReturns();
      } else if (a.isAnnotationPresent(JsConstructor.class)) {
        if (type != MemberType.JS_METHOD) {
          Log.w(TAG, "Invalid @JsConstructor on non-function member:" + name);
          continue;
        }
        JsConstructor cAnno = a.getAnnotation(JsConstructor.class);
        mInfo.type = MemberType.JS_CONSTRUCTOR;
        mInfo.isEntryPoint = cAnno.isEntryPoint();
        mInfo.mainClass = cAnno.mainClass();
        // Currently Constructor with promise is not supported.
        mInfo.withPromise = false;
        // TODO: more detail checking for main class.
        // Is there a way to throw compile error if main class missing?
        if (mInfo.mainClass == null) continue;

        mInfo.jsName = mInfo.mainClass.getSimpleName();
        // Create relections for constructor main classes.
        bindingClasses.put(mInfo.mainClass.getName(), mInfo.jsName);
        constructorReflections.put(mInfo.jsName, new ReflectionHelper(mInfo.mainClass));
      }

      if (mInfo.isEntryPoint) {
        // Always get the first entry point setting.
        if (entryPoint != null) {
          Log.w(TAG, "Entry point already exist, try to set another:" + mInfo.jsName);
          continue;
        }
        // Flag isEntryPoint only meaningful for methods, constructors and BindingObjects.
        if (type == MemberType.JS_PROPERTY
            && !(isBindingClass(((Field) (mInfo.accesser)).getType()))) {
          Log.w(TAG, "Invalid entry point setting on property:" + name);
          continue;
        }
        // The first entry point will be used.
        entryPoint = mInfo;
      }
      if (members.containsKey(mInfo.jsName)) {
        Log.w(TAG, "Conflict namespace - " + mInfo.jsName);
        continue;
      }
      members.put(mInfo.jsName, mInfo);
    }
  }
예제 #9
0
  protected void scanOptions(final Object object) {
    final Class<?> class1 = object.getClass();

    final List<Field> fields = new LinkedList<Field>();
    final List<Method> privateMethods = new LinkedList<Method>();

    final List<Method> otherPackageNonPrivateMethods = new LinkedList<Method>();

    final List<Method> currentPackageNonPrivateMethods = new LinkedList<Method>();

    Class<?> parentClass = class1;
    while (parentClass != null && !parentClass.equals(Object.class)) {
      // We cannot override fields in child classes, so we simple collect
      // all fields we found
      fields.addAll(Arrays.asList(parentClass.getDeclaredFields()));

      // for methods, we need to respect overridden methods when
      // inspecting the parent classes
      for (final Method method : parentClass.getDeclaredMethods()) {
        if (isPrivate(method)) {
          privateMethods.add(method);
        } else if (isPublicOrProtected(method)) {
          if (!containsMethod(otherPackageNonPrivateMethods, method)
              && !containsMethod(currentPackageNonPrivateMethods, method)) {
            currentPackageNonPrivateMethods.add(method);
          }
        } else if (isPackagePrivate(method)) {
          // if (!containsMethod(publicOrProtectedMethods, method)) {
          // method not overloaded
          if (isPackagePrivate(method)) {
            if (!containsMethod(currentPackageNonPrivateMethods, method)) {
              currentPackageNonPrivateMethods.add(method);
            }
          }
        }
      }

      final Package pack = parentClass.getPackage();
      parentClass = parentClass.getSuperclass();
      if ((pack == null && parentClass.getPackage() != null)
          || (pack != null && !pack.equals(parentClass.getPackage()))) {
        otherPackageNonPrivateMethods.addAll(currentPackageNonPrivateMethods);
        currentPackageNonPrivateMethods.clear();
      }
    }

    // inspect elements
    final Set<AccessibleObject> elements = new LinkedHashSet<AccessibleObject>();
    elements.addAll(fields);
    elements.addAll(privateMethods);
    elements.addAll(otherPackageNonPrivateMethods);
    elements.addAll(currentPackageNonPrivateMethods);

    for (final AccessibleObject element : elements) {

      if (element instanceof Field && element.getAnnotation(CmdOptionDelegate.class) != null) {
        debug("Found delegate object at: {0}", element);
        try {
          final boolean origAccessibleFlag = element.isAccessible();
          if (!origAccessibleFlag) {
            element.setAccessible(true);
          }
          final Object delegate = ((Field) element).get(object);
          if (!origAccessibleFlag) {
            // do not leave doors open
            element.setAccessible(origAccessibleFlag);
          }
          if (delegate != null) {
            scanOptions(delegate);
          }
        } catch (final IllegalArgumentException e) {
          debug("Could not scan delegate object at: {0}", element);
        } catch (final IllegalAccessException e) {
          debug("Could not scan delegate object at: {0}", element);
        }
        continue;
      }

      final CmdOption anno = element.getAnnotation(CmdOption.class);
      if (anno == null) {
        continue;
      }

      if (element instanceof Field && Modifier.isFinal(((Field) element).getModifiers())) {
        debug("Detected option on final field: {0}", element);
        // continue;
      }

      final String[] names = anno.names();

      final CmdOptionHandler handler = findHandler(element, anno.args().length, anno.handler());
      if (handler == null) {
        final PreparedI18n msg =
            i18n.preparetr(
                "No suitable handler found for option(s): {0} ({1} argument(s))",
                FList.mkString(anno.names(), ","), anno.args().length);
        throw new CmdlineParserException(msg.notr(), msg.tr());
      }

      if (names == null || names.length == 0) {
        // No names means this is the ONLY parameter
        if (parameter != null) {
          final PreparedI18n msg =
              i18n.preparetr(
                  "More than one parameter definition found. First definition: {0} Second definition: {1}",
                  parameter.getElement(), element);
          throw new CmdlineParserException(msg.notr(), msg.tr());
        }
        // TODO: should we ignore the help parameter?
        final OptionHandle paramHandle =
            new OptionHandle(
                new String[] {},
                anno.description(),
                handler,
                object,
                element,
                anno.args(),
                anno.minCount(),
                anno.maxCount(),
                false /*
                       * cannot
                       * be
                       * a
                       * help
                       * option
                       */,
                anno.hidden(),
                anno.requires(),
                anno.conflictsWith());

        if (paramHandle.getArgsCount() <= 0) {
          final PreparedI18n msg =
              i18n.preparetr("Parameter definition must support at least on argument.");
          throw new CmdlineParserException(msg.notr(), msg.tr());
        }
        parameter = paramHandle;

      } else {
        final OptionHandle option =
            new OptionHandle(
                names,
                anno.description(),
                handler,
                object,
                element,
                anno.args(),
                anno.minCount(),
                anno.maxCount(),
                anno.isHelp(),
                anno.hidden(),
                anno.requires(),
                anno.conflictsWith());

        for (final String name : names) {
          if (quickCommandMap.containsKey(name) || quickOptionMap.containsKey(name)) {
            final PreparedI18n msg =
                i18n.preparetr(
                    "Duplicate command/option name \"{0}\" found in: {1}", name, element);
            throw new CmdlineParserException(msg.notr(), msg.tr());
          }
          quickOptionMap.put(name, option);
        }
        options.add(option);
      }
    }
  }