/** Creates an aspect for interception if the method should be intercepted. */
  @Override
  public AspectGenerator<X> create(AnnotatedMethod<? super X> method, boolean isEnhanced) {
    RunAs runAs = method.getAnnotation(RunAs.class);

    if (runAs == null) runAs = _classRunAs;

    String runAsName = null;

    if (runAs != null) runAsName = runAs.value();

    RolesAllowed rolesAllowed = method.getAnnotation(RolesAllowed.class);

    if (rolesAllowed == null) rolesAllowed = _classRolesAllowed;

    String[] roleNames = null;

    if (rolesAllowed != null) roleNames = rolesAllowed.value();

    PermitAll permitAll = method.getAnnotation(PermitAll.class);

    if (permitAll != null || _classPermitAll != null) roleNames = null;

    DenyAll denyAll = method.getAnnotation(DenyAll.class);

    if (denyAll != null || _classDenyAll != null) roleNames = new String[0];

    if (roleNames != null || runAs != null) {
      AspectGenerator<X> next = super.create(method, true);

      return new SecurityGenerator<X>(this, method, next, roleNames, runAsName);
    } else return super.create(method, isEnhanced);
  }
  @Override
  public ConfigProgram introspectMethod(AnnotatedMethod<?> method) {
    PersistenceContext pContext = method.getAnnotation(PersistenceContext.class);

    Method javaMethod = method.getJavaMember();
    String location = getLocation(javaMethod);

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

    if (!param.isAssignableFrom(EntityManager.class)) {
      throw new ConfigException(
          L.l(
              "{0}: @PersistenceContext method must be assignable from EntityManager.",
              getLocation(javaMethod)));
    }

    BeanValueGenerator gen;

    /*
    if (PersistenceContextType.EXTENDED.equals(type))
      return generateExtendedContext(field, pContext);
    else
    */

    gen = generateTransactionContext(location, pContext);

    return new MethodGeneratorProgram(javaMethod, gen);
  }
Exemplo n.º 3
0
  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);
      }
    }
  }
Exemplo n.º 4
0
  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);
        }
      }
    }
  }
Exemplo n.º 5
0
  protected <Z extends Annotation> Z getAnnotation(
      Class<Z> annotationType,
      AnnotatedMethod<?> apiMethod,
      AnnotatedType<?> apiClass,
      AnnotatedMethod<?> implementationMethod,
      AnnotatedType<?> implementationClass) {
    Z annotation = null;

    if (apiMethod != null) {
      annotation = apiMethod.getAnnotation(annotationType);
    }

    if (annotation == null && apiClass != null) {
      annotation = apiClass.getAnnotation(annotationType);
    }

    if ((annotation == null) && (implementationMethod != null)) {
      annotation = implementationMethod.getAnnotation(annotationType);
    }

    if ((annotation == null) && (implementationClass != null)) {
      annotation = implementationClass.getAnnotation(annotationType);
    }

    return annotation;
  }
Exemplo n.º 6
0
  @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);
  }
Exemplo n.º 7
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;
  }
Exemplo n.º 8
0
  protected <Z extends Annotation> Z getAnnotation(
      Class<Z> annotationType, AnnotatedMethod<?> apiMethod, AnnotatedMethod<?> implMethod) {
    Z annotation;

    annotation = apiMethod.getAnnotation(annotationType);

    if ((annotation == null) && (implMethod != null)) {
      annotation = implMethod.getAnnotation(annotationType);
    }

    return annotation;
  }
Exemplo n.º 9
0
 <X> void registerGenericBean(@Observes ProcessManagedBean<X> event) {
   AnnotatedType<X> type = event.getAnnotatedBeanClass();
   if (type.isAnnotationPresent(GenericConfiguration.class)) {
     Class<? extends Annotation> genericType =
         type.getAnnotation(GenericConfiguration.class).value();
     genericBeans.put(
         genericType, new BeanHolder<X>(event.getAnnotatedBeanClass(), event.getBean()));
     for (AnnotatedMethod<? super X> m : event.getAnnotatedBeanClass().getMethods()) {
       if (m.isAnnotationPresent(Unwraps.class)) {
         unwrapsMethods.put(genericType, m);
       }
     }
   }
 }
Exemplo n.º 10
0
  /**
   * Generates a unique signature for a concrete class
   *
   * @param <X>
   * @param annotatedType
   * @return
   */
  public static <X> String createTypeId(
      Class<X> clazz,
      Collection<Annotation> annotations,
      Collection<AnnotatedMethod<? super X>> methods,
      Collection<AnnotatedField<? super X>> fields,
      Collection<AnnotatedConstructor<X>> constructors) {
    StringBuilder builder = new StringBuilder();

    builder.append(clazz.getName());
    builder.append(createAnnotationCollectionId(annotations));
    builder.append("{");

    // now deal with the fields
    List<AnnotatedField<? super X>> sortedFields = new ArrayList<AnnotatedField<? super X>>();
    sortedFields.addAll(fields);
    Collections.sort(sortedFields, AnnotatedFieldComparator.<X>instance());
    for (AnnotatedField<? super X> field : sortedFields) {
      if (!field.getAnnotations().isEmpty()) {
        builder.append(createFieldId(field));
        builder.append(SEPERATOR);
      }
    }

    // methods
    List<AnnotatedMethod<? super X>> sortedMethods = new ArrayList<AnnotatedMethod<? super X>>();
    sortedMethods.addAll(methods);
    Collections.sort(sortedMethods, AnnotatedMethodComparator.<X>instance());
    for (AnnotatedMethod<? super X> method : sortedMethods) {
      if (!method.getAnnotations().isEmpty() || hasMethodParameters(method)) {
        builder.append(createCallableId(method));
        builder.append(SEPERATOR);
      }
    }

    // constructors
    List<AnnotatedConstructor<? super X>> sortedConstructors =
        new ArrayList<AnnotatedConstructor<? super X>>();
    sortedConstructors.addAll(constructors);
    Collections.sort(sortedConstructors, AnnotatedConstructorComparator.<X>instance());
    for (AnnotatedConstructor<? super X> constructor : sortedConstructors) {
      if (!constructor.getAnnotations().isEmpty() || hasMethodParameters(constructor)) {
        builder.append(createCallableId(constructor));
        builder.append(SEPERATOR);
      }
    }
    builder.append("}");

    return builder.toString();
  }
Exemplo n.º 11
0
 public int compare(AnnotatedMethod<? super T> arg0, AnnotatedMethod<? super T> arg1) {
   int result = callableComparator.compare(arg0, arg1);
   if (result != 0) {
     return result;
   }
   for (int i = 0; i < arg0.getJavaMember().getParameterTypes().length; ++i) {
     Class<?> p0 = arg0.getJavaMember().getParameterTypes()[i];
     Class<?> p1 = arg1.getJavaMember().getParameterTypes()[i];
     result = p0.getName().compareTo(p1.getName());
     if (result != 0) {
       return result;
     }
   }
   return 0;
 }
Exemplo n.º 12
0
 @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());
     }
   }
 }
  public boolean isInjectionPoint() {
    for (Class<?> paramType : _producesMethod.getJavaMember().getParameterTypes()) {
      if (InjectionPoint.class.equals(paramType)) return true;
    }

    return false;
  }
Exemplo n.º 14
0
 @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);
 }
  private void introspect() {
    List<AnnotatedParameter<X>> parameters = _method.getParameters();

    /*
    if (parameters.size() == 1) {
      if (parameters.get(0).isAnnotationPresent(IfExists.class)) {
        _isIfExists = true;
      }

      return;
    }
    */

    _args = new BeanArg[parameters.size()];

    for (int i = 0; i < _args.length; i++) {
      AnnotatedParameter<?> param = parameters.get(i);

      Observes observes = param.getAnnotation(Observes.class);

      if (observes != null) {
        _isIfExists = observes.notifyObserver() == Reception.IF_EXISTS;
      } else {
        _args[i] =
            new BeanArg(param.getBaseType(), _beanManager.getQualifiers(param.getAnnotations()));
      }
    }
  }
  /** Send the event notification. */
  public void notify(T event) {
    Object instance = getInstance();

    if (instance == null) return;

    Method method = _method.getJavaMember();

    try {
      method.invoke(instance, getEventArguments(event));
    } catch (IllegalArgumentException e) {
      String loc = (method.getDeclaringClass().getSimpleName() + "." + method.getName() + ": ");

      throw new InjectionException(loc + e.getMessage(), e.getCause());
    } catch (RuntimeException e) {
      throw e;
    } catch (InvocationTargetException e) {
      String loc = (method.getDeclaringClass().getSimpleName() + "." + method.getName() + ": ");

      throw new InjectionException(loc + e.getMessage(), e.getCause());
    } catch (Exception e) {
      String loc = (method.getDeclaringClass().getSimpleName() + "." + method.getName() + ": ");

      throw new InjectionException(loc + e.getMessage(), e.getCause());
    }
  }
  private void introspectInjectionPoints() {
    for (AnnotatedParameter<?> param : _producesMethod.getParameters()) {
      InjectionPointImpl ip = new InjectionPointImpl(getBeanManager(), this, param);

      _injectionPointSet.add(ip);
    }
  }
  @Override
  protected String getDefaultName() {
    String methodName = _producesMethod.getJavaMember().getName();

    if (methodName.startsWith("get") && methodName.length() > 3) {
      return (Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4));
    } else return methodName;
  }
Exemplo n.º 19
0
    @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));
        }
      }
    }
  @Override
  public ConfigProgram introspectMethod(AnnotatedMethod<?> method) {
    Resource resource = method.getAnnotation(Resource.class);

    Method javaMethod = method.getJavaMember();

    String loc = getLocation(method.getJavaMember());

    String jndiName = (javaMethod.getDeclaringClass().getName() + "/" + javaMethod.getName());

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

    ValueGenerator gen = generateContext(loc, bindType, jndiName, resource);

    bindJndi(javaMethod, gen);

    return new MethodGeneratorProgram(method.getJavaMember(), gen);
  }
Exemplo n.º 21
0
  private void subscribeServices(final BeanManager beanManager, final MessageBus bus) {
    for (final Map.Entry<AnnotatedType, List<AnnotatedMethod>> entry :
        managedTypes.getServiceMethods().entrySet()) {
      final Class<?> type = entry.getKey().getJavaClass();

      for (final AnnotatedMethod method : entry.getValue()) {
        final Service svc = method.getAnnotation(Service.class);
        final String svcName =
            svc.value().equals("") ? method.getJavaMember().getName() : svc.value();

        final Method callMethod = method.getJavaMember();

        bus.subscribe(
            svcName,
            new MessageCallback() {

              @Override
              public void callback(final Message message) {
                final Object targetBean = CDIServerUtil.lookupBean(beanManager, type);

                try {
                  callMethod.invoke(targetBean, message);
                } catch (Exception e) {
                  ErrorHelper.sendClientError(bus, message, "Error dispatching service", e);
                }
              }
            });
      }
    }

    /**
     * Due to the lack of contract in CDI guaranteeing when beans will be available, we use an
     * executor to search for the beans every 100ms until it finds them. Or, after a 25 seconds,
     * blow up if they don't become available.
     */
    final ScheduledExecutorService startupScheduler = Executors.newScheduledThreadPool(1);
    startupScheduler.scheduleAtFixedRate(
        new StartupCallback(beanManager, bus, startupScheduler, 25), 0, 100, TimeUnit.MILLISECONDS);

    for (final Class<?> remoteInterfaceType : managedTypes.getRemoteInterfaces()) {
      createRPCScaffolding(remoteInterfaceType, bus, beanManager);
    }
  }
  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);
      }
    }
  }
Exemplo n.º 23
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;
 }
  ObserverMethodImpl(
      InjectManager beanManager,
      Bean<X> bean,
      AnnotatedMethod<X> method,
      Type type,
      Set<Annotation> qualifiers) {
    _beanManager = beanManager;
    _bean = bean;
    _method = method;
    _method.getJavaMember().setAccessible(true);
    _type = type;
    _qualifiers = qualifiers;

    introspect();
  }
Exemplo n.º 25
0
  /**
   * Generates the body of the method. <code><pre>
   * MyType myMethod(...)
   * {
   *   [pre-try]
   *   try {
   *     [pre-call]
   *     [call]   // retValue = super.myMethod(...)
   *     [post-call]
   *     return retValue;
   *   } catch (RuntimeException e) {
   *     [system-exception]
   *     throw e;
   *   } catch (Exception e) {
   *     [application-exception]
   *     throw e;
   *   } finally {
   *     [finally]
   *   }
   * </pre></code>
   */
  protected void generateContent(JavaWriter out, HashMap<String, Object> map) throws IOException {
    generatePreTry(out);

    out.println();
    out.println("try {");
    out.pushDepth();

    AnnotatedMethod<?> method = getMethod();

    if (!void.class.equals(method.getBaseType())) {
      out.printType(method.getBaseType());
      out.println(" result;");
    }

    generatePreCall(out);

    generateCall(out);

    generatePostCall(out);

    if (!void.class.equals(method.getBaseType())) out.println("return result;");

    out.popDepth();

    generateExceptions(out);

    out.println("} finally {");
    out.pushDepth();

    generateFinally(out);

    out.popDepth();
    out.println("}");

    generatePostFinally(out);
  }
Exemplo n.º 26
0
  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);
    }
  }
  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();

    sb.append(getClass().getSimpleName());
    sb.append("[");

    Method method = _producesMethod.getJavaMember();

    sb.append(getTargetSimpleName());
    sb.append(", ");
    sb.append(method.getDeclaringClass().getSimpleName());
    sb.append(".");
    sb.append(method.getName());
    sb.append("()");

    sb.append(", {");

    boolean isFirst = true;
    for (Annotation ann : getQualifiers()) {
      if (!isFirst) sb.append(", ");

      sb.append(ann);

      isFirst = false;
    }

    sb.append("}");

    if (getName() != null) {
      sb.append(", name=");
      sb.append(getName());
    }

    sb.append("]");

    return sb.toString();
  }
 void registerSecuredMethods() {
   for (AnnotatedMethod<?> method : securedMethods) {
     registerSecuredMethod(method.getDeclaringType().getJavaClass(), method.getJavaMember());
   }
 }
Exemplo n.º 29
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]);
        }
      }
    }
  }
Exemplo n.º 30
0
  void createGenericBeans(@Observes AfterBeanDiscovery event, BeanManager beanManager) {
    beanDiscoveryOver = true;
    // For each generic configuration type, we iterate the generic configurations
    for (Entry<GenericIdentifier, GenericConfigurationHolder> genericConfigurationEntry :
        genericConfigurationPoints.entrySet()) {
      Class<? extends Annotation> producerScope = Dependent.class;
      for (Annotation annotation :
          genericConfigurationEntry.getValue().getAnnotated().getAnnotations()) {
        if (beanManager.isScope(annotation.annotationType())) {
          producerScope = annotation.annotationType();
        }
      }
      GenericConfigurationHolder genericConfigurationHolder = genericConfigurationEntry.getValue();
      GenericIdentifier identifier = genericConfigurationEntry.getKey();

      Class<? extends Annotation> genericConfigurationType = identifier.getAnnotationType();
      if (!genericBeans.containsKey(genericConfigurationType)) {
        throw new IllegalStateException(
            "No generic bean definition exists for "
                + genericConfigurationType
                + ", but a generic producer does: "
                + genericConfigurationHolder.getAnnotated());
      }
      // Add a generic configuration bean for each generic configuration producer (allows us to
      // inject the generic configuration annotation back into the generic bean)
      event.addBean(createGenericConfigurationBean(beanManager, identifier));

      // Register the GenericProduct bean

      event.addBean(createGenericProductAnnotatedMemberBean(beanManager, identifier));

      boolean alternative =
          genericConfigurationHolder.getAnnotated().isAnnotationPresent(Alternative.class);
      Class<?> javaClass = genericConfigurationHolder.getJavaClass();

      if (genericBeanProducerMethods.containsKey(genericConfigurationType)) {
        for (ProducerMethodHolder<?, ?> holder :
            genericBeanProducerMethods.get(genericConfigurationType)) {
          Class<? extends Annotation> scopeOverride = null;
          if (holder.getProducerMethod().isAnnotationPresent(ApplyScope.class)) {
            scopeOverride = producerScope;
          }
          event.addBean(
              createGenericProducerMethod(
                  holder, identifier, beanManager, scopeOverride, alternative, javaClass));
        }
      }
      if (genericBeanProducerFields.containsKey(genericConfigurationType)) {
        for (FieldHolder<?, ?> holder : genericBeanProducerFields.get(genericConfigurationType)) {
          Class<? extends Annotation> scopeOverride = null;
          if (holder.getField().isAnnotationPresent(ApplyScope.class)) {
            scopeOverride = producerScope;
          }
          event.addBean(
              createGenericProducerField(
                  holder.getBean(),
                  identifier,
                  holder.getField(),
                  beanManager,
                  scopeOverride,
                  alternative,
                  javaClass));
        }
      }
      if (genericBeanObserverMethods.containsKey(genericConfigurationType)) {
        for (ObserverMethodHolder<?, ?> holder :
            genericBeanObserverMethods.get(genericConfigurationType)) {
          event.addObserverMethod(
              createGenericObserverMethod(
                  holder.getObserverMethod(), identifier, holder.getMethod(), null, beanManager));
        }
      }
      if (unwrapsMethods.containsKey(genericConfigurationType)) {
        for (AnnotatedMethod<?> i : unwrapsMethods.get(genericConfigurationType)) {
          Annotated annotated = genericConfigurationHolder.getAnnotated();
          Set<Annotation> unwrapsQualifiers =
              Beans.getQualifiers(beanManager, i.getAnnotations(), annotated.getAnnotations());
          if (unwrapsQualifiers.isEmpty()) {
            unwrapsQualifiers.add(DefaultLiteral.INSTANCE);
          }
          Set<Annotation> beanQualifiers =
              Beans.getQualifiers(
                  beanManager, i.getDeclaringType().getAnnotations(), annotated.getAnnotations());
          beanQualifiers.remove(AnyLiteral.INSTANCE);
          if (beanQualifiers.isEmpty()) {
            beanQualifiers.add(DefaultLiteral.INSTANCE);
          }
          beanQualifiers.remove(genericBeanQualifier);
          event.addBean(new UnwrapsProducerBean(i, unwrapsQualifiers, beanQualifiers, beanManager));
        }
      }
      // For each generic bean that uses this genericConfigurationType, register a generic bean for
      // this generic configuration
      for (BeanHolder<?> genericBeanHolder : genericBeans.get(genericConfigurationType)) {
        // Register the generic bean, this is the underlying definition, with the synthetic
        // qualifier
        Class<? extends Annotation> scopeOverride = null;
        if (genericBeanHolder.getType().isAnnotationPresent(ApplyScope.class)) {
          scopeOverride = producerScope;
        }
        Bean<?> genericBean =
            createGenericBean(
                genericBeanHolder, identifier, beanManager, scopeOverride, alternative, javaClass);
        event.addBean(genericBean);
      }
    }
  }