@Test
  public void testMethodId() throws SecurityException, NoSuchMethodException {
    TestAnnotatedTypeBuilder<Chair> builder = new TestAnnotatedTypeBuilder<Chair>(Chair.class);
    builder.addToMethod(Chair.class.getMethod("sit"), new ProducesLiteral());
    AnnotatedType<Chair> chair3 = builder.create();
    Iterator<AnnotatedMethod<? super Chair>> it = chair3.getMethods().iterator();
    AnnotatedMethod<? super Chair> method = it.next();
    while (!method.getJavaMember().getName().equals("sit")) method = it.next();
    String id = AnnotatedTypes.createCallableId(method);
    Assert.assertEquals(
        "org.jboss.weld.tests.unit.util.Chair.sit[@javax.enterprise.inject.Produces()]()",
        id,
        "wrong id for method :" + id);

    builder = new TestAnnotatedTypeBuilder<Chair>(Chair.class);
    chair3 = builder.create();
    it = chair3.getMethods().iterator();
    method = it.next();
    while (!method.getJavaMember().getName().equals("sit")) method = it.next();
    id = AnnotatedTypes.createCallableId(method);
    Assert.assertEquals(
        "org.jboss.weld.tests.unit.util.Chair.sit()", id, "wrong id for method :" + id);

    builder = new TestAnnotatedTypeBuilder<Chair>(Chair.class);
    builder.addToMethod(Chair.class.getMethod("sit"), new ComfyChairLiteral());
    chair3 = builder.create();
    it = chair3.getMethods().iterator();
    method = it.next();
    while (!method.getJavaMember().getName().equals("sit")) method = it.next();
    id = AnnotatedTypes.createCallableId(method);
    Assert.assertEquals(
        "org.jboss.weld.tests.unit.util.Chair.sit[@org.jboss.weld.tests.unit.util.ComfyChair(softness=1)]()",
        id,
        "wrong id for method :" + id);
  }
Exemple #2
0
  /** Compares two annotated types and returns true if they are the same */
  public static boolean compareAnnotatedTypes(AnnotatedType<?> t1, AnnotatedType<?> t2) {
    if (!t1.getJavaClass().equals(t2.getJavaClass())) {
      return false;
    }
    if (!compareAnnotated(t1, t2)) {
      return false;
    }

    if (t1.getFields().size() != t2.getFields().size()) {
      return false;
    }
    Map<Field, AnnotatedField<?>> fields = new HashMap<Field, AnnotatedField<?>>();
    for (AnnotatedField<?> f : t2.getFields()) {
      fields.put(f.getJavaMember(), f);
    }
    for (AnnotatedField<?> f : t1.getFields()) {
      if (fields.containsKey(f.getJavaMember())) {
        if (!compareAnnotatedField(f, fields.get(f.getJavaMember()))) {
          return false;
        }
      } else {
        return false;
      }
    }

    if (t1.getMethods().size() != t2.getMethods().size()) {
      return false;
    }
    Map<Method, AnnotatedMethod<?>> methods = new HashMap<Method, AnnotatedMethod<?>>();
    for (AnnotatedMethod<?> f : t2.getMethods()) {
      methods.put(f.getJavaMember(), f);
    }
    for (AnnotatedMethod<?> f : t1.getMethods()) {
      if (methods.containsKey(f.getJavaMember())) {
        if (!compareAnnotatedCallable(f, methods.get(f.getJavaMember()))) {
          return false;
        }
      } else {
        return false;
      }
    }
    if (t1.getConstructors().size() != t2.getConstructors().size()) {
      return false;
    }
    Map<Constructor<?>, AnnotatedConstructor<?>> constructors =
        new HashMap<Constructor<?>, AnnotatedConstructor<?>>();
    for (AnnotatedConstructor<?> f : t2.getConstructors()) {
      constructors.put(f.getJavaMember(), f);
    }
    for (AnnotatedConstructor<?> f : t1.getConstructors()) {
      if (constructors.containsKey(f.getJavaMember())) {
        if (!compareAnnotatedCallable(f, constructors.get(f.getJavaMember()))) {
          return false;
        }
      } else {
        return false;
      }
    }
    return true;
  }
  private void introspectInjectMethod(
      AnnotatedType<X> type, ArrayList<ConfigProgram> injectProgramList) {

    for (AnnotatedMethod method : type.getMethods()) {
      if (method.getAnnotations().size() == 0) continue;

      if (method.isAnnotationPresent(Inject.class)) {
        // boolean isOptional = isQualifierOptional(field);

        List<AnnotatedParameter<?>> params = method.getParameters();

        InjectionPoint[] args = new InjectionPoint[params.size()];

        for (int i = 0; i < args.length; i++) {
          InjectionPoint ij = new InjectionPointImpl(getBeanManager(), this, params.get(i));

          _injectionPointSet.add(ij);

          args[i] = ij;
        }

        injectProgramList.add(new MethodInjectProgram(method.getJavaMember(), args));
      } else {
        InjectionPointHandler handler = getBeanManager().getInjectionPointHandler(method);

        if (handler != null) {
          ConfigProgram program = new MethodHandlerProgram(method, handler);

          injectProgramList.add(program);
        }
      }
    }
  }
  private void introspectDestroy(ArrayList<ConfigProgram> destroyList, AnnotatedType<?> type)
      throws ConfigException {
    if (type == null || type.equals(Object.class)) return;

    if (type.isAnnotationPresent(Interceptor.class)) {
      return;
    }

    for (AnnotatedMethod<?> method : type.getMethods()) {
      if (method.isAnnotationPresent(PreDestroy.class)) {
        Method javaMethod = method.getJavaMember();

        Class<?>[] types = javaMethod.getParameterTypes();

        if (types.length == 0) {
        } else if (types.length == 1 && types[0].equals(InvocationContext.class)) {
          // XXX:
          continue;
        } else
          throw new ConfigException(
              location(javaMethod) + L.l("@PreDestroy is requires zero arguments"));

        PreDestroyInject destroyProgram = new PreDestroyInject(javaMethod);

        if (!destroyList.contains(destroyProgram)) destroyList.add(destroyProgram);
      }
    }
  }
Exemple #5
0
 /**
  * Generates a unique signature for an annotated type. Members without annotations are omitted to
  * reduce the length of the signature
  *
  * @param <X>
  * @param annotatedType
  * @return
  */
 public static <X> String createTypeId(AnnotatedType<X> annotatedType) {
   return createTypeId(
       annotatedType.getJavaClass(),
       annotatedType.getAnnotations(),
       annotatedType.getMethods(),
       annotatedType.getFields(),
       annotatedType.getConstructors());
 }
 private void validateWsEndpointAnnotatedType(AnnotatedType<TranslatorEndpoint> annotatedType) {
   assertEquals(annotatedType.getBaseType(), TranslatorEndpoint.class);
   // translate()
   assertEquals(annotatedType.getMethods().size(), 1);
   Set<Type> typeClosure = annotatedType.getTypeClosure();
   // Translator, TranslatorEndpoint, Object
   assertTrue(
       typeSetMatches(typeClosure, Translator.class, TranslatorEndpoint.class, Object.class));
 }
Exemple #7
0
 private RequestMappingInfo findMethodRequestMapping(FacesContext context, Bean<?> bean) {
   RequestMappingInfo result = null;
   Class clazz = bean.getBeanClass();
   AnnotatedType annotatedType = beanManager.createAnnotatedType(clazz);
   Set<AnnotatedMethod> annotatedMethodSet = annotatedType.getMethods();
   for (AnnotatedMethod method : annotatedMethodSet) {
     if (method.isAnnotationPresent(RequestMapping.class)) {
       RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
       String[] mappings = requestMapping.value();
       String mapping = null;
       for (String current : mappings) {
         String pathInfo = context.getExternalContext().getRequestPathInfo();
         if (pathInfo.equals(current)) {
           result = new RequestMappingInfo();
           result.setBean(bean);
           result.setMethod(method.getJavaMember());
           result.setRequestMapping(mapping);
           result.setMappingType(RequestMappingInfo.MappingType.EXACT);
           break;
         } else if (current.endsWith("*")) {
           current = current.substring(0, current.length() - 1);
           if (pathInfo.startsWith(current)) {
             if (result == null) {
               result = new RequestMappingInfo();
               result.setBean(bean);
               result.setMethod(method.getJavaMember());
               result.setRequestMapping(current);
               result.setMappingType(RequestMappingInfo.MappingType.PREFIX);
             } else if (current.length() > result.getLength()) {
               result.setBean(bean);
               result.setMethod(method.getJavaMember());
               result.setRequestMapping(current);
               result.setMappingType(RequestMappingInfo.MappingType.PREFIX);
             }
           }
         } else if (current.startsWith("*")) {
           current = current.substring(1);
           if (pathInfo.endsWith(current)) {
             result = new RequestMappingInfo();
             result.setBean(bean);
             result.setMethod(method.getJavaMember());
             result.setRequestMapping(current);
             result.setMappingType(RequestMappingInfo.MappingType.EXTENSION);
             break;
           }
         }
       }
     }
     if (result != null
         && (result.getMappingType().equals(RequestMappingInfo.MappingType.EXACT)
             || (result.getMappingType().equals(RequestMappingInfo.MappingType.EXTENSION)))) {
       break;
     }
   }
   return result;
 }
 @Test
 public void testWatchAlternatives_stereotypedMethod_enable() throws Exception {
   // prepare, global alternative
   when(at.isAnnotationPresent(Priority.class)).thenReturn(true);
   when(at.isAnnotationPresent(TestStereotype.class)).thenReturn(false);
   final Set<Annotated> annotated = asAnnotatedSet(StereotypedMethod.class.getDeclaredMethods());
   when(at.getMethods()).thenReturn(annotated);
   when(at.getJavaClass()).thenReturn(StereotypedMethod.class);
   // act
   subject.watchAlternatives(pat);
   // assert, not vetoed
   verify(pat, times(0)).veto();
 }
 @Test
 @SpecAssertion(section = PAT, id = "ba")
 public void testGetAnnotatedType() {
   AnnotatedType<Dog> annotatedType = ProcessAnnotatedTypeObserver.getDogAnnotatedType();
   assertEquals(annotatedType.getBaseType(), Dog.class);
   Set<AnnotatedMethod<? super Dog>> annotatedMethods = annotatedType.getMethods();
   assertEquals(annotatedMethods.size(), 3);
   for (AnnotatedMethod<? super Dog> annotatedMethod : annotatedMethods) {
     Set<String> validMethodNames =
         new HashSet<String>(Arrays.asList("bite", "live", "drinkMilk"));
     if (!validMethodNames.contains(annotatedMethod.getJavaMember().getName())) {
       fail("Invalid method name found" + annotatedMethod.getJavaMember().getName());
     }
   }
 }
 @SuppressWarnings("unchecked")
 private <X, A extends AnnotatedMember<? super X>> A getAnnotatedMember(
     Class<X> javaClass, String memberName) {
   AnnotatedType<X> type = getCurrentManager().createAnnotatedType(javaClass);
   for (AnnotatedField<? super X> field : type.getFields()) {
     if (field.getJavaMember().getName().equals(memberName)) {
       return (A) field;
     }
   }
   for (AnnotatedMethod<? super X> method : type.getMethods()) {
     if (method.getJavaMember().getName().equals(memberName)) {
       return (A) method;
     }
   }
   throw new IllegalArgumentException("Member " + memberName + " not found on " + javaClass);
 }
    @Override
    public void run() {
      if (System.currentTimeMillis() > expiryTime) {
        scheduledExecutorService.shutdown();
        throw new RuntimeException(
            "failed to discover beans: " + managedTypes.getServiceEndpoints());
      }

      if (registered.isEmpty()) {
        scheduledExecutorService.shutdown();
        log.info("all services registered successfully");
        return;
      }

      for (final AnnotatedType<?> type : managedTypes.getServiceEndpoints()) {
        if (!registered.contains(type) || beanManager.getBeans(type.getJavaClass()).size() == 0) {
          continue;
        }

        final MessageCallback callback =
            (MessageCallback) CDIServerUtil.lookupBean(beanManager, type.getJavaClass());

        registered.remove(type);

        // Discriminate on @Command
        final Map<String, Method> commandPoints = new HashMap<String, Method>();
        for (final AnnotatedMethod method : type.getMethods()) {
          if (method.isAnnotationPresent(Command.class)) {
            final Command command = method.getAnnotation(Command.class);
            for (String cmdName : command.value()) {
              if (cmdName.equals("")) cmdName = method.getJavaMember().getName();
              commandPoints.put(cmdName, method.getJavaMember());
            }
          }
        }

        final String subjectName = CDIServerUtil.resolveServiceName(type.getJavaClass());

        if (commandPoints.isEmpty()) {
          bus.subscribe(subjectName, callback);
        } else {
          bus.subscribeLocal(
              subjectName, new CommandBindingsCallback(commandPoints, callback, bus));
        }
      }
    }
  private <T> void determineConstrainedMethods(
      AnnotatedType<T> type,
      BeanDescriptor beanDescriptor,
      Set<AnnotatedCallable<? super T>> callables) {
    List<Method> overriddenAndImplementedMethods =
        InheritedMethodsHelper.getAllMethods(type.getJavaClass());

    for (AnnotatedMethod<? super T> annotatedMethod : type.getMethods()) {
      Method method = annotatedMethod.getJavaMember();

      boolean isGetter = ReflectionHelper.isGetterMethod(method);

      // obtain @ValidateOnExecution from the top-most method in the hierarchy
      Method methodForExecutableTypeRetrieval =
          replaceWithOverriddenOrInterfaceMethod(method, overriddenAndImplementedMethods);

      EnumSet<ExecutableType> classLevelExecutableTypes =
          executableTypesDefinedOnType(methodForExecutableTypeRetrieval.getDeclaringClass());
      EnumSet<ExecutableType> memberLevelExecutableType =
          executableTypesDefinedOnMethod(methodForExecutableTypeRetrieval, isGetter);

      ExecutableType currentExecutableType =
          isGetter ? ExecutableType.GETTER_METHODS : ExecutableType.NON_GETTER_METHODS;

      // validation is enabled per default, so explicit configuration can just veto whether
      // validation occurs
      if (veto(classLevelExecutableTypes, memberLevelExecutableType, currentExecutableType)) {
        continue;
      }

      boolean needsValidation;
      if (isGetter) {
        needsValidation = isGetterConstrained(method, beanDescriptor);
      } else {
        needsValidation = isNonGetterConstrained(method, beanDescriptor);
      }

      if (needsValidation) {
        callables.add(annotatedMethod);
      }
    }
  }
 private UnbackedAnnotatedType(
     AnnotatedType<X> source, AnnotatedTypeIdentifier identifier, SharedObjectCache cache) {
   super(source.getBaseType(), source.getTypeClosure(), source.getAnnotations());
   this.javaClass = source.getJavaClass();
   ImmutableSet.Builder<AnnotatedConstructor<X>> constructors = ImmutableSet.builder();
   for (AnnotatedConstructor<X> constructor : source.getConstructors()) {
     constructors.add(UnbackedAnnotatedConstructor.of(constructor, this, cache));
   }
   this.constructors = constructors.build();
   ImmutableSet.Builder<AnnotatedMethod<? super X>> methods = ImmutableSet.builder();
   for (AnnotatedMethod<? super X> originalMethod : source.getMethods()) {
     methods.add(UnbackedAnnotatedMethod.of(originalMethod, this, cache));
   }
   this.methods = methods.build();
   ImmutableSet.Builder<AnnotatedField<? super X>> fields = ImmutableSet.builder();
   for (AnnotatedField<? super X> originalField : source.getFields()) {
     fields.add(UnbackedAnnotatedField.of(originalField, this, cache));
   }
   this.fields = fields.build();
   this.identifier = identifier;
 }
  public static void introspectInit(ArrayList<ConfigProgram> initList, AnnotatedType<?> type)
      throws ConfigException {
    for (AnnotatedMethod<?> annMethod : type.getMethods()) {
      Method method = annMethod.getJavaMember();

      if (!annMethod.isAnnotationPresent(PostConstruct.class)) {
        // && ! isAnnotationPresent(annList, Inject.class)) {
        continue;
      }

      if (method.getParameterTypes().length == 1
          && InvocationContext.class.equals(method.getParameterTypes()[0])) continue;

      if (method.isAnnotationPresent(PostConstruct.class)
          && method.getParameterTypes().length != 0) {
        throw new ConfigException(
            location(method) + L.l("{0}: @PostConstruct is requires zero arguments"));
      }

      PostConstructProgram initProgram = new PostConstructProgram(method);

      if (!initList.contains(initProgram)) initList.add(initProgram);
    }
  }
  /**
   * 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]);
        }
      }
    }
  }
 void addSecuredType(AnnotatedType<?> annotatedType) {
   for (AnnotatedMethod<?> securedMethod : annotatedType.getMethods()) {
     addSecuredMethod(securedMethod);
   }
 }