Пример #1
0
 @Nonnull
 public static String nameFor(@Nonnull Object instance, @Nonnull String suffix) {
   Named annotation = instance.getClass().getAnnotation(Named.class);
   if (annotation != null && !isBlank(annotation.value())) {
     return annotation.value();
   } else {
     return getLogicalPropertyName(instance.getClass().getName(), suffix);
   }
 }
Пример #2
0
  /**
   * Get the name of the bean for the given object.
   *
   * @param instance the object.
   * @return the name.
   */
  private String getName(Object instance) {
    String name =
        instance.getClass().getSimpleName().substring(0, 1).toLowerCase()
            + instance.getClass().getSimpleName().substring(1);

    Named named = instance.getClass().getAnnotation(Named.class);
    if (named != null && named.value() != null && !named.value().trim().equals("")) {
      name = named.value();
    }
    return name;
  }
  /**
   * Create component descriptors for the passed component implementation class and component role
   * class. There can be more than one descriptor if the component class has specified several
   * hints.
   *
   * @param componentClass the component implementation class
   * @param componentRoleClass the component role class
   * @return the component descriptors with resolved component dependencies
   */
  public List<ComponentDescriptor> createComponentDescriptors(
      Class<?> componentClass, Class<?> componentRoleClass) {
    List<ComponentDescriptor> descriptors = new ArrayList<ComponentDescriptor>();

    // If there's a @Named annotation, use it and ignore hints specified in the @Component
    // annotation.
    String[] hints;
    Named named = componentClass.getAnnotation(Named.class);
    if (named != null) {
      hints = new String[] {named.value()};
    } else {
      // If the Component annotation has several hints specified ignore the default hint value and
      // for each
      // specified hint create a Component Descriptor
      Component component = componentClass.getAnnotation(Component.class);
      if (component != null && component.hints().length > 0) {
        hints = component.hints();
      } else {
        if (component != null && component.value().trim().length() > 0) {
          hints = new String[] {component.value().trim()};
        } else {
          hints = new String[] {"default"};
        }
      }
    }

    // Create the descriptors
    for (String hint : hints) {
      descriptors.add(createComponentDescriptor(componentClass, hint, componentRoleClass));
    }

    return descriptors;
  }
  /**
   * @param field
   * @return bean name
   */
  private String getBeanName(final Field field) {
    SpringBean annot = field.getAnnotation(SpringBean.class);

    String name;
    boolean required;
    if (annot != null) {
      name = annot.name();
      required = annot.required();
    } else {
      Named named = field.getAnnotation(Named.class);
      name = named != null ? named.value() : "";
      required = false;
    }

    if (Strings.isEmpty(name)) {
      name = beanNameCache.get(field.getType());
      if (name == null) {
        name = getBeanNameOfClass(contextLocator.getSpringContext(), field.getType(), required);

        if (name != null) {
          beanNameCache.put(field.getType(), name);
        }
      }
    }
    return name;
  }
 /**
  * If there are more more than 1 implementation Guice will complain, this is intentional because
  * we want an interface to have only 1 implementation
  *
  * @param holder
  */
 private void bindInterfaceToImplementation(InterfaceAndImplementations holder) {
   // todo refactor this, maybe have two different streams in configure, one for named and one for
   // unnamed..
   holder
       .getTheImplementations()
       .forEach(
           impl -> {
             final Annotation annotation = impl.getAnnotation(Named.class);
             if (annotation == null) {
               logger.debug(
                   "binding {} to {}",
                   holder.getTheInterface().getSimpleName(),
                   impl.getSimpleName());
               bind(holder.getTheInterface()).to(impl);
               return;
             }
             final Named namedAnnotation = (Named) annotation;
             final String name = namedAnnotation.value();
             logger.debug(
                 "binding {} named {} to {}",
                 holder.getTheInterface().getSimpleName(),
                 name,
                 impl.getSimpleName());
             bind(holder.getTheInterface()).annotatedWith(Names.named(name)).to(impl);
           });
 }
Пример #6
0
    private CallbackEntry(Class<?> beanClass, Class<? extends Annotation> callbackMarker) {
      this.targetBeanClass = beanClass;

      Named named = this.targetBeanClass.getAnnotation(Named.class);

      if (named != null && !"".equals(named.value())) {
        this.beanName = named.value();
      } else {
        // fallback to the default (which might exist) -> TODO check meta-data of Bean<T>
        this.beanName = Introspector.decapitalize(targetBeanClass.getSimpleName());
      }

      List<String> processedMethodNames = new ArrayList<String>();

      findMethodWithCallbackMarker(callbackMarker, beanClass, processedMethodNames);
    }
 private String getKey(IObjectDescriptor descriptor) {
   if (descriptor.hasQualifier(Named.class)) {
     Named namedAnnotation = descriptor.getQualifier(Named.class);
     return namedAnnotation.value();
   }
   Type elementType = descriptor.getDesiredType();
   return typeToString(elementType);
 }
Пример #8
0
    public boolean equals(Object o) {
      if (!(o instanceof Named)) {
        return false;
      }

      Named other = (Named) o;
      return value.equals(other.value());
    }
  public <I> void hear(TypeLiteral<I> injectableType, TypeEncounter<I> encounter) {

    Class<? super I> type = injectableType.getRawType();
    Set<Field> loggerFields = getLoggerFieldsAnnotatedWithResource(type);
    if (loggerFields.size() == 0) return;

    Logger logger = loggerFactory.getLogger(type.getName());

    for (Field field : loggerFields) {
      if (field.isAnnotationPresent(Named.class)) {
        Named name = field.getAnnotation(Named.class);
        encounter.register(
            new AssignLoggerToField<I>(loggerFactory.getLogger(name.value()), field));
      } else {
        encounter.register(new AssignLoggerToField<I>(logger, field));
      }
    }
  }
Пример #10
0
  private void bindQueryNamedParameters(
      Query jpaQuery, JpaFinderProxy.FinderDescriptor descriptor, Object[] arguments) {
    for (int i = 0; i < arguments.length; i++) {
      Object argument = arguments[i];
      Object annotation = descriptor.parameterAnnotations[i];

      if (null == annotation)
      //noinspection UnnecessaryContinue
      {
        continue; // skip param as it's not bindable
      } else if (annotation instanceof Named) {
        Named named = (Named) annotation;
        jpaQuery.setParameter(named.value(), argument);
      } else if (annotation instanceof javax.inject.Named) {
        javax.inject.Named named = (javax.inject.Named) annotation;
        jpaQuery.setParameter(named.value(), argument);
      } else if (annotation instanceof FirstResult) {
        jpaQuery.setFirstResult((Integer) argument);
      } else if (annotation instanceof MaxResults) {
        jpaQuery.setMaxResults((Integer) argument);
      }
    }
  }
  @Nonnull
  protected List<Annotation> harvestQualifiers(@Nonnull Field field) {
    List<Annotation> list = new ArrayList<>();
    Annotation[] annotations = field.getAnnotations();
    for (Annotation annotation : annotations) {
      if (AnnotationUtils.isAnnotatedWith(annotation, Qualifier.class)) {
        if (BindTo.class.isAssignableFrom(annotation.getClass())) {
          continue;
        }

        // special case for @Named
        if (Named.class.isAssignableFrom(annotation.getClass())) {
          Named named = (Named) annotation;
          if (isBlank(named.value())) {
            list.add(named(getPropertyName(field.getName())));
            continue;
          }
        }
        list.add(annotation);
      }
    }
    return list;
  }
Пример #12
0
 @Nonnull
 public static List<Annotation> harvestQualifiers(@Nonnull Class<?> klass) {
   requireNonNull(klass, "Argument 'class' must not be null");
   List<Annotation> list = new ArrayList<>();
   Annotation[] annotations = klass.getAnnotations();
   for (Annotation annotation : annotations) {
     if (AnnotationUtils.isAnnotatedWith(annotation, Qualifier.class)) {
       // special case @BindTo is only used during tests
       if (BindTo.class.isAssignableFrom(annotation.getClass())) {
         continue;
       }
       // special case for @Named
       if (Named.class.isAssignableFrom(annotation.getClass())) {
         Named named = (Named) annotation;
         if (isBlank(named.value())) {
           list.add(named(getPropertyName(klass)));
           continue;
         }
       }
       list.add(annotation);
     }
   }
   return list;
 }
Пример #13
0
  private void grabAnnotations(
      TreeLogger logger,
      ModelMagic models,
      HasModelFields fields,
      JMethod method,
      Annotation[] annos,
      JClassType type) {

    GetterFor getter = method.getAnnotation(GetterFor.class);
    ClientToServer c2s = method.getAnnotation(ClientToServer.class);
    ServerToClient s2c = method.getAnnotation(ServerToClient.class);
    Persistent persist = method.getAnnotation(Persistent.class);
    Serializable serial = method.getAnnotation(Serializable.class);
    Named name = method.getAnnotation(Named.class);

    for (Annotation annotation : annos) {
      if (getter == null && annotation.annotationType() == GetterFor.class)
        getter = (GetterFor) annotation;
      else if (serial == null && annotation.annotationType() == Serializable.class)
        serial = (Serializable) annotation;
      else if (persist == null && annotation.annotationType() == Persistent.class)
        persist = (Persistent) annotation;
      else if (c2s == null && annotation.annotationType() == ClientToServer.class)
        c2s = (ClientToServer) annotation;
      else if (s2c == null && annotation.annotationType() == ServerToClient.class)
        s2c = (ServerToClient) annotation;
      else if (name == null && annotation.annotationType() == Named.class)
        name = (Named) annotation;
    }

    String fieldName;
    if (name == null) {
      fieldName = ModelGeneratorGwt.fieldName(method, models);
    } else {
      fieldName = name.value();
      if (X_Runtime.isDebug()) {
        logger.log(
            Type.TRACE,
            "Named method "
                + method.getJsniSignature()
                + " "
                + fieldName
                + ", from @Named attribute.  Heuristic name: "
                + ModelGeneratorGwt.fieldName(method, models));
      }
    }
    if ("".equals(fieldName)) fieldName = method.getName();
    ModelField field = fields.getOrMakeField(fieldName);

    if (field.getPersistent() == null) {
      field.setPersistent(persist);
    } else {
      assert persist == null || (persist.patchable() == field.getPersistent().patchable())
          : "Model annotation mismatch! Field "
              + field.getName()
              + " of type "
              + type.getQualifiedSourceName()
              + " contained multiple @Persistent annotations which did not match.  "
              + "You may have to override an annotated supertype method with the correct "
              + "@Persistent annotation.";
    }

    if (field.getSerializable() == null) {
      field.setSerializable(serial);
    } else {
      //      assert serial == null ||
      //        ( // this block is all assert, so it will compile out of production.
      //          serial.clientToServer() == field.getSerializable().clientToServer() &&
      //          serial.serverToClient() == field.getSerializable().serverToClient() &&
      //          serial.obfuscated() == field.getSerializable().obfuscated()
      //          ) : "Model annotation mismatch! Field "+field.getName()+" contained " +
      //          		"multiple @Serializable annotations which did not match.  You may " +
      //          		"have to override an annotated supertype method with the correct " +
      //          		"@Serializable annotation.";
    }
    if (field.getServerToClient() == null) {
      field.setServerToClient(s2c);
    } else {
      assert s2c == null || s2c.enabled() == field.getServerToClient().enabled()
          : "Model annotation mismatch! Field "
              + field.getName()
              + " was marked as "
              + "both "
              + "serverToClient"
              + " enabled and disabled.  Please correct this ambiguity;"
              + " your model is now undeterministic and may break unexpectedly.";
    }
    if (field.getClientToServer() == null) {
      field.setClientToServer(c2s);
    } else {
      assert c2s == null || c2s.enabled() == field.getClientToServer().enabled()
          : "Model annotation mismatch! Field "
              + field.getName()
              + " was marked as "
              + "both "
              + "clientToServer"
              + " enabled and disabled.  Please correct this ambiguity;"
              + " your model is now undeterministic and may break unexpectedly.";
    }
  }
  @Override
  public final InjectorImpl getInjector(Stage stage) {
    Binder binder = new AnnotationBinder();

    Collection<Class<?>> components = new ArrayList<Class<?>>();

    components.addAll(DSAnnotatedLoader.loadManagedBeans(packagePrefix));
    components.addAll(DSAnnotatedLoader.loadSingletons(packagePrefix));
    components.addAll(DSAnnotatedLoader.loadNamed(packagePrefix));

    for (Class<?> clazz : components) {
      String name = null;
      Named named = clazz.getAnnotation(Named.class);
      if (named != null) {
        name = named.value();
      }
      ProvidedBy providedBy = clazz.getAnnotation(ProvidedBy.class);
      Provider provider = null;
      try {
        if (providedBy != null) {
          provider = (Provider) providedBy.value().newInstance();
        }
      } catch (Exception ex) {
        logger.log(Level.SEVERE, null, ex);
      }
      OnStage onStage = clazz.getAnnotation(OnStage.class);
      Stage stag = null;
      if (onStage != null) {
        stag = onStage.value();
      }
      Annotation[] annotations = clazz.getAnnotations();
      Class<? extends Annotation> qualifier = null;
      boolean qualifierPresent = false;
      for (Annotation anno : annotations) {
        if ((anno.annotationType().isAnnotationPresent(Qualifier.class))
            && !(anno instanceof Named)) {
          if (qualifierPresent) {
            logger.log(
                Level.WARNING,
                new StringBuilder()
                    .append("Class ")
                    .append(clazz.getSimpleName())
                    .append(" has more than one qualifier.\n")
                    .append("Qualifier @")
                    .append(anno.annotationType().getSimpleName())
                    .append(" will override @")
                    .append(qualifier.getSimpleName())
                    .append(".")
                    .toString());
          } else {
            qualifierPresent = true;
          }
          qualifier = anno.annotationType();
        }
      }
      Class<?>[] superInterfaces = clazz.getSuperclass().getInterfaces();
      Class<?> superType = clazz.getSuperclass();
      Class<?>[] typeInterfaces = clazz.getInterfaces();
      if (typeInterfaces.length > 0) {
        for (Class interf : typeInterfaces) {
          Binding binding = new Binding(qualifier, name, interf, clazz, provider, stag);
          binder.getBindings().put(binding, binding);
        }
      } else if (superInterfaces.length > 0) {
        Class superClass = superType;
        while (superInterfaces.length > 0) {
          for (Class interf : superInterfaces) {
            Binding binding = new Binding(qualifier, name, interf, clazz, provider, stag);
            binder.getBindings().put(binding, binding);
          }
          superClass = superClass.getSuperclass();
          superInterfaces = superClass.getInterfaces();
        }
      } else {
        while (superType != null) {
          if (!superType.equals(Object.class)) {
            Binding binding = new Binding(qualifier, name, superType, clazz, provider, stag);
            binder.getBindings().put(binding, binding);
            superType = superType.getSuperclass();
          } else {
            superType = null;
          }
        }
        Binding binding = new Binding(qualifier, name, clazz, clazz, provider, stag);
        binder.getBindings().put(binding, binding);
      }
    }
    if (showBindings) {
      for (Binding b : binder.getBindings().values()) {
        System.out.println(b);
      }
    }
    return InjectorBuilder.makeInjector(binder, new PluginsLoader(), stage);
  }