コード例 #1
1
ファイル: ResourcesModule.java プロジェクト: mikexliu/stack
  protected void configure() {
    final Set<Class<?>> resources = new HashSet<>();
    final Map<Class<?>, Class<?>> resourcesWithContainers = new HashMap<>();
    injector
        .getAllBindings()
        .entrySet()
        .forEach(
            entry -> {
              final Key<?> key = entry.getKey();
              final Class<?> classObject = key.getTypeLiteral().getRawType();
              final Class<?> superClassObject = classObject.getSuperclass();
              if (classObject.isAnnotationPresent(Path.class)) {
                log.info("Loaded Resource " + classObject);
                resources.add(classObject);
              } else if (!Object.class.equals(classObject)
                  && !classObject.isInterface()
                  && superClassObject.isAnnotationPresent(Path.class)) {
                log.info("Loaded Resource " + superClassObject + " with Container " + classObject);
                resourcesWithContainers.put(superClassObject, classObject);
              }
            });

    for (final Class<?> resource : resources) {
      final Object container = injector.getInstance(resource);
      bind((Class) resource).toInstance(container);
      log.info("Binding Resource " + resource + " to Container " + container);
    }

    for (final Map.Entry<Class<?>, Class<?>> entry : resourcesWithContainers.entrySet()) {
      bindResourceToLocalContainer(entry.getKey(), entry.getValue());
      log.info("Binding Resource " + entry.getKey() + " to Container " + entry.getValue());
    }
  }
コード例 #2
1
  /**
   * Computes the set of classes that are annotated with {@link Replace} and removes transitive
   * dependencies, so that the most specific classes are returned.
   *
   * <p><b>Example:</b> Given the following two classes
   *
   * <pre>
   * public class A {
   * }
   *
   * &#064;Replace
   * public class B extends A {
   * }
   * </pre>
   *
   * The invocation of <code>getReplacingLeafClasses(new Class[] {A.class, B.class, String.class})
   * </code> returns a set that contains <code>B.class</code> only. <code>String.class</code> is not
   * annotated with {@link Replace} and <code>A.class</code> is not a leaf replacement, but further
   * replaced by <code>B.class</code>.
   *
   * @param classes
   * @return Returns the set of replacing leaf classes or an empty set.
   * @since 3.8.2
   */
  public static <T> Set<Class<? extends T>> getReplacingLeafClasses(Class<? extends T>[] classes) {
    // gather all replacing and replaced classes (i.e. those annotated with @Replace and their super
    // classes)
    Set<Class<? extends T>> replacingClasses = new HashSet<Class<? extends T>>();
    Set<Class<?>> replacedClasses = new HashSet<Class<?>>();
    for (Class<? extends T> c : classes) {
      if (c.isAnnotationPresent(Replace.class)) {
        replacingClasses.add(c);
        Class<?> tmpClass = c;
        do {
          tmpClass = tmpClass.getSuperclass();
          replacedClasses.add(tmpClass);
        } while (tmpClass.isAnnotationPresent(Replace.class));
      }
    }

    if (replacingClasses.isEmpty()) {
      return Collections.emptySet();
    }

    // remove transitive replacements (e.g. if A replaces B and B replaces C, A and B are replacing
    // classes but we are interested in A only)
    replacingClasses.removeAll(replacedClasses);
    return replacingClasses;
  }
コード例 #3
1
ファイル: GenericDaoImpl.java プロジェクト: zishinan/xuhuamao
    @Override
    public List<T> handle(ResultSet rs) throws SQLException {
      List<T> list = new LinkedList<>();
      while (rs.next()) {
        try {
          T t = this.clz.newInstance();
          BeanInfo beanInfo = Introspector.getBeanInfo(this.clz, Object.class);
          PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();

          Map<String, Object> map = new HashMap<String, Object>();
          for (PropertyDescriptor pd : descriptors) {
            String propertyName = pd.getName();
            Class<?> propertyType = pd.getPropertyType();
            if (propertyType.isAnnotationPresent(Entry.class)) {
              propertyName = propertyName + "_id";
            }
            Object value = rs.getObject(propertyName);
            if (propertyType.isAnnotationPresent(Entry.class)) {
              value = getObject(value, propertyType);
            }
            map.put(pd.getName(), value);
          }
          BeanUtils.copyProperties(t, map);
          list.add(t);

        } catch (InstantiationException
            | IllegalAccessException
            | IntrospectionException
            | InvocationTargetException e) {
          e.printStackTrace();
        }
      }
      return list;
    }
コード例 #4
1
 @SuppressWarnings("unchecked")
 @Override
 public T readFrom(
     Class<T> type,
     Type genericType,
     Annotation[] annotations,
     MediaType mediaType,
     MultivaluedMap<String, String> httpHeaders,
     InputStream entityStream)
     throws IOException, WebApplicationException {
   if (type.isAnnotationPresent(DTO.class)) {
     return DtoFactory.getInstance().createDtoFromJson(entityStream, type);
   } else if (type.isAssignableFrom(List.class) && genericType instanceof ParameterizedType) {
     ParameterizedType parameterizedType = (ParameterizedType) genericType;
     Type elementType = parameterizedType.getActualTypeArguments()[0];
     if (elementType instanceof Class) {
       Class elementClass = (Class) elementType;
       if (elementClass.isAnnotationPresent(DTO.class)) {
         return (T) DtoFactory.getInstance().createListDtoFromJson(entityStream, elementClass);
       }
     }
   }
   return (T)
       delegate.readFrom(type, genericType, annotations, mediaType, httpHeaders, entityStream);
 }
コード例 #5
1
 private void addControllerServlet(Class<?> klass)
     throws InstantiationException, IllegalAccessException {
   assert klass != null;
   ControllerServlet servlet = null;
   Controller controller;
   if (Controller.class.isAssignableFrom(klass)) {
     controller = controllerFactory.createController(klass.asSubclass(Controller.class));
   } else {
     SimpleControllerWrapper.checkValidSimpleControllerClass(klass);
     SimpleControllerWrapper simpleController =
         SimpleControllerWrapper.createInstance(controllerFactory.createController(klass));
     configure(simpleController);
     controller = simpleController;
   }
   URL url = klass.getAnnotation(URL.class);
   servlet = new ControllerServlet(controller);
   AllowedHttpMethods httpMethods = klass.getAnnotation(AllowedHttpMethods.class);
   if (httpMethods != null) {
     servlet.setValidHttpMethods(httpMethods.value());
   }
   ControllerServlet.AfterControllerAction action = null;
   if (klass.isAnnotationPresent(ForwardTo.class)) {
     action = new ControllerServlet.ForwardAction(klass.getAnnotation(ForwardTo.class).value());
   } else if (klass.isAnnotationPresent(RedirectTo.class)) {
     action = new ControllerServlet.ForwardAction(klass.getAnnotation(RedirectTo.class).value());
   }
   servlet.setAfterControllerAction(action);
   ServletRegistration.Dynamic dynamic = context.addServlet(klass.getSimpleName(), servlet);
   dynamic.addMapping(url.value());
 }
コード例 #6
1
ファイル: JPAPlugin.java プロジェクト: visan/play1
  @Override
  public Object bind(
      RootParamNode rootParamNode,
      String name,
      Class clazz,
      java.lang.reflect.Type type,
      Annotation[] annotations) {
    // TODO need to be more generic in order to work with JPASupport
    if (clazz.isAnnotationPresent(Entity.class)) {

      ParamNode paramNode = rootParamNode.getChild(name, true);

      String[] keyNames = new JPAModelLoader(clazz).keyNames();
      ParamNode[] ids = new ParamNode[keyNames.length];
      // Collect the matching ids
      int i = 0;
      for (String keyName : keyNames) {
        ids[i++] = paramNode.getChild(keyName, true);
      }
      if (ids != null && ids.length > 0) {
        try {
          EntityManager em = JPABase.getJPAConfig(clazz).getJPAContext().em();
          StringBuilder q =
              new StringBuilder().append("from ").append(clazz.getName()).append(" o where");
          int keyIdx = 1;
          for (String keyName : keyNames) {
            q.append(" o.").append(keyName).append(" = ?").append(keyIdx++).append(" and ");
          }
          if (q.length() > 4) {
            q = q.delete(q.length() - 4, q.length());
          }
          Query query = em.createQuery(q.toString());
          // The primary key can be a composite.
          Class[] pk = new JPAModelLoader(clazz).keyTypes();
          int j = 0;
          for (ParamNode id : ids) {
            if (id.getValues() == null
                || id.getValues().length == 0
                || id.getFirstValue(null) == null
                || id.getFirstValue(null).trim().length() <= 0) {
              // We have no ids, it is a new entity
              return GenericModel.create(rootParamNode, name, clazz, annotations);
            }
            query.setParameter(
                j + 1,
                Binder.directBind(
                    id.getOriginalKey(), annotations, id.getValues()[0], pk[j++], null));
          }
          Object o = query.getSingleResult();
          return GenericModel.edit(rootParamNode, name, o, annotations);
        } catch (NoResultException e) {
          // ok
        } catch (Exception e) {
          throw new UnexpectedException(e);
        }
      }
      return GenericModel.create(rootParamNode, name, clazz, annotations);
    }
    return null;
  }
コード例 #7
0
  protected static boolean matchesSegment(Field field, String segmentTag) {
    Class<?> clz = field.getType();

    if (Collection.class.isAssignableFrom(clz)) {
      clz = getCollectionType(field);
    }

    if (clz.isAnnotationPresent(EDISegment.class)) {
      EDISegment es = clz.getAnnotation(EDISegment.class);
      if (StringUtils.equals(segmentTag, es.tag())) {
        return true;
      }
    } else if (clz.isAnnotationPresent(EDISegmentGroup.class)) {
      EDISegmentGroup esg = clz.getAnnotation(EDISegmentGroup.class);

      String ediSegmentGroupTag = esg.header();

      if (StringUtils.isNotBlank(ediSegmentGroupTag)) {
        if (StringUtils.equals(segmentTag, ediSegmentGroupTag)) {
          return true;
        }
      } else {
        // get the segement group's first field, and recurse.
        if (clz.getDeclaredFields().length > 0) {
          return matchesSegment(clz.getDeclaredFields()[0], segmentTag);
        }
      }
    }

    return false;
  }
コード例 #8
0
 @Override
 @SuppressWarnings("unchecked")
 protected void configure() {
   // Bind mock controllet to this instance, to automatically replay/verify all mocks created by
   // runner.
   bind(MockController.class).toInstance(this);
   // map field values by type
   for (Field field : fields.keySet()) {
     TypeLiteral literal = TypeLiteral.get(field.getGenericType());
     AnnotatedBindingBuilder builder = bind(literal);
     // Check field annotations.
     Annotation[] fieldAnnotations = field.getAnnotations();
     for (Annotation annotation : fieldAnnotations) {
       Class<? extends Annotation> annotationType = annotation.annotationType();
       if (
       /* annotationType.isAnnotationPresent(Qualifier.class)|| */ annotationType
           .isAnnotationPresent(BindingAnnotation.class)) {
         builder.annotatedWith(annotation);
       }
       if (annotationType.isAnnotationPresent(ScopeAnnotation.class)) {
         builder.in(annotationType);
       }
     }
     Binding binding = fields.get(field);
     if (null != binding.getValue()) {
       builder.toInstance(binding.getValue());
     } else if (null != binding.getImplementation()) {
       builder.to(binding.getImplementation());
     } else if (null != binding.getProvider()) {
       builder.toProvider(binding.getProvider());
     }
   }
 }
コード例 #9
0
  // override it e.g. for test-cases
  protected ResourceBundle getResourceBundle() {
    if (this.resourceBundle == null) {
      Class bundleClass = getClass().getSuperclass();

      if (!bundleClass.isAnnotationPresent(Bundle.class)) {
        bundleClass = null;
        for (Class interfaceClass : getClass().getInterfaces()) {
          if (interfaceClass.isAnnotationPresent(Bundle.class)) {
            bundleClass = interfaceClass;
            break;
          }
        }
      }

      if (bundleClass == null) {
        throw new IllegalStateException(
            getClass()
                + " has to extend a class or implement an interface "
                + "which is annotated with @"
                + Bundle.class.getName());
      }

      if (qualifierClass != null) {
        this.resourceBundle =
            BeanManagerProvider.getInstance()
                .getContextualReference(ResourceBundle.class, DefaultAnnotation.of(qualifierClass));
      } else {
        this.resourceBundle =
            BeanManagerProvider.getInstance().getContextualReference(ResourceBundle.class);
      }
      this.resourceBundle.useBundle(bundleClass);
    }
    return resourceBundle;
  }
コード例 #10
0
ファイル: GwtcContext.java プロジェクト: CecillieNelson/xapi
 private Object findAncestor(Class<?> clazz) {
   // First check enclosing classes
   Class<?> c = clazz.getDeclaringClass();
   while (c != null) {
     if (c.isAnnotationPresent(Gwtc.class)) {
       return c;
     }
     c = c.getDeclaringClass();
   }
   Package p = clazz.getPackage();
   if (p.getAnnotation(Gwtc.class) != null) {
     return p;
   }
   Object o = findAncestor(p);
   if (o == null) {
     c = clazz.getSuperclass();
     while (c != null) {
       if (c.isAnnotationPresent(Gwtc.class)) {
         return c;
       }
       c = c.getSuperclass();
     }
   }
   return o;
 }
コード例 #11
0
  /**
   * 从类定义中解析表定义<br>
   * 仅解析传入类型:不对传入类型的接口,以及父类进行注解获取<br>
   * <功能详细描述>
   *
   * @param type
   * @return [参数说明]
   * @return JPAEntityTableDef [返回类型说明]
   * @exception throws [异常类型] [异常说明]
   * @see [类、类#方法、类#成员]
   */
  private static JPAEntityTableDef doAnalyzeTableDef(Class<?> type) {
    // 没有注解的时候默认使用类名当作表名
    String tableName = type.getSimpleName();
    String comment = "";
    // 如果存在javax注解中的Entity读取其Name
    // org.hibernate.annotations.Entity该类中不含有表名,不进行解析
    if (type.isAnnotationPresent(Entity.class)) {
      String entityName = type.getAnnotation(Entity.class).name();
      if (!StringUtils.isEmpty(entityName)) {
        tableName = entityName.toUpperCase();
      }
    }
    if (type.isAnnotationPresent(Table.class)) {
      // 如果含有注解:javax.persistence.Table
      String annoTableName = type.getAnnotation(Table.class).name();
      if (!StringUtils.isEmpty(annoTableName)) {
        tableName = annoTableName.toUpperCase();
      }
    }
    if (type.isAnnotationPresent(org.hibernate.annotations.Table.class)) {
      // 如果含有注解:javax.persistence.Table
      String annoTableComment = type.getAnnotation(org.hibernate.annotations.Table.class).comment();
      if (!StringUtils.isEmpty(annoTableComment)) {
        comment = annoTableComment;
      }
    }

    JPAEntityTableDef tableDef = new JPAEntityTableDef();
    tableDef.setTableName(tableName);
    tableDef.setComment(comment);
    return tableDef;
  }
コード例 #12
0
  protected static <T> void parseEDISegmentOrSegmentGroup(
      EDIMessage ediMessage,
      T object,
      Iterator<Field> fieldIterator,
      Queue<String> lookAhead,
      SegmentIterator segmentIterator)
      throws EDIMessageException, IllegalAccessException, InvocationTargetException,
          InstantiationException, ClassNotFoundException, ConversionException {
    if (!fieldIterator.hasNext()) {
      throw new EDIMessageException("No more fields to read.");
    }

    if (!segmentIterator.hasNext() && lookAhead.size() == 0) {
      return;
    }

    // get the queued object first...
    String line = lookAhead.size() > 0 ? lookAhead.remove() : segmentIterator.next();

    // match up the field with the line...
    FieldMatch fm = advanceToMatch(ediMessage, fieldIterator, line);

    //

    if (fm != null) {
      Class<?> fieldType = getEDISegmentOrGroupType(fm.getField());
      if (fieldType.isAnnotationPresent(EDISegment.class)) {
        processSegment(ediMessage, object, lookAhead, segmentIterator, fm);
      } else if (fieldType.isAnnotationPresent(EDISegmentGroup.class)) {
        processSegmentGroup(ediMessage, object, lookAhead, segmentIterator, fm);
      }
    } else {
      lookAhead.add(line);
    }
  }
コード例 #13
0
  protected static String getSegmentTag(Field field, boolean inner) {
    Class<?> clz = field.getType();

    if (Collection.class.isAssignableFrom(clz)) {
      clz = getCollectionType(field);
    }

    if (clz.isAnnotationPresent(EDISegment.class)) {
      EDISegment es = clz.getAnnotation(EDISegment.class);
      return es.tag();
    } else if (clz.isAnnotationPresent(EDISegmentGroup.class)) {
      EDISegmentGroup esg = clz.getAnnotation(EDISegmentGroup.class);

      String ediSegmentGroupTag = esg.header();

      if (!inner && StringUtils.isNotBlank(ediSegmentGroupTag)) {
        return ediSegmentGroupTag;
      } else {
        // get the segement group's first field, and recurse.
        if (clz.getDeclaredFields().length > 0) {
          return getSegmentTag(clz.getDeclaredFields()[0], false);
        }
      }
    }

    return null;
  }
コード例 #14
0
 public void register(@NotNull Class<? extends Command> commandClass) {
   if (commandClass.isAnnotationPresent(CommandName.class)
       && commandClass.isAnnotationPresent(ManPage.class)) {
     register(
         commandClass.getAnnotation(CommandName.class).value(),
         commandClass.getAnnotation(ManPage.class).value());
   }
 }
コード例 #15
0
ファイル: WebBeanReader.java プロジェクト: newisso/firefly
 private String getId(Class<?> c) {
   if (c.isAnnotationPresent(Controller.class)) return c.getAnnotation(Controller.class).value();
   else if (c.isAnnotationPresent(Interceptor.class))
     return c.getAnnotation(Interceptor.class).value();
   else if (c.isAnnotationPresent(Component.class))
     return c.getAnnotation(Component.class).value();
   else return "";
 }
コード例 #16
0
 /**
  * Checks for both kinds of @Named; uses fully-qualified classname if name is missing or blank.
  */
 private static String getRepositoryHint(final Class<?> implementation) {
   String name = null;
   if (implementation.isAnnotationPresent(javax.inject.Named.class)) {
     name = implementation.getAnnotation(javax.inject.Named.class).value();
   } else if (implementation.isAnnotationPresent(com.google.inject.name.Named.class)) {
     name = implementation.getAnnotation(com.google.inject.name.Named.class).value();
   }
   return StringUtils.isNotBlank(name) ? name : implementation.getName();
 }
コード例 #17
0
  /**
   * input/output simple records.
   *
   * @throws Exception if test was failed
   */
  @SuppressWarnings("unchecked")
  @Test
  public void simple_record() throws Exception {
    ModelLoader loader = generate();

    Class<?> type = loader.modelType("Simple");
    assertThat(type.isAnnotationPresent(ModelInputLocation.class), is(true));
    assertThat(type.isAnnotationPresent(ModelOutputLocation.class), is(true));

    ModelWrapper object = loader.newModel("Simple");
    DataOutputBuffer output = new DataOutputBuffer();
    ModelOutput<Object> modelOut =
        (ModelOutput<Object>)
            type.getAnnotation(ModelOutputLocation.class)
                .value()
                .getDeclaredConstructor(RecordEmitter.class)
                .newInstance(new TsvEmitter(new OutputStreamWriter(output, "UTF-8")));

    object.set("sid", 1L);
    object.set("value", new Text("hello"));
    modelOut.write(object.unwrap());

    object.set("sid", 2L);
    object.set("value", new Text("world"));
    modelOut.write(object.unwrap());

    object.set("sid", 3L);
    object.set("value", null);
    modelOut.write(object.unwrap());
    modelOut.close();

    DataInputBuffer input = new DataInputBuffer();
    input.reset(output.getData(), output.getLength());
    ModelInput<Object> modelIn =
        (ModelInput<Object>)
            type.getAnnotation(ModelInputLocation.class)
                .value()
                .getDeclaredConstructor(RecordParser.class)
                .newInstance(new TsvParser(new InputStreamReader(input, "UTF-8")));
    ModelWrapper copy = loader.newModel("Simple");

    modelIn.readTo(copy.unwrap());
    assertThat(copy.get("sid"), is((Object) 1L));
    assertThat(copy.get("value"), is((Object) new Text("hello")));

    modelIn.readTo(copy.unwrap());
    assertThat(copy.get("sid"), is((Object) 2L));
    assertThat(copy.get("value"), is((Object) new Text("world")));

    modelIn.readTo(copy.unwrap());
    assertThat(copy.get("sid"), is((Object) 3L));
    assertThat(copy.getOption("value").isNull(), is(true));

    assertThat(input.read(), is(-1));
    modelIn.close();
  }
コード例 #18
0
ファイル: WebBeanReader.java プロジェクト: newisso/firefly
 @Override
 protected BeanDefinition getBeanDefinition(Class<?> c) {
   if (c.isAnnotationPresent(Controller.class) || c.isAnnotationPresent(Component.class)) {
     log.info("classes [{}]", c.getName());
     return componentParser(c);
   } else if (c.isAnnotationPresent(Interceptor.class)) {
     log.info("classes [{}]", c.getName());
     return interceptorParser(c);
   } else return null;
 }
コード例 #19
0
    public static void writeJavaAnnotationDescriptions(
        ToolPageContext page, AnnotatedElement annotated) throws IOException {

      List<Annotation> presentAnnotations = Arrays.asList(annotated.getAnnotations());
      List<Class<? extends Annotation>> possibleAnnotationClasses =
          new ArrayList<Class<? extends Annotation>>();

      for (Class<? extends Annotation> ac : ClassFinder.Static.findClasses(Annotation.class)) {
        if (!ac.isAnnotationPresent(Deprecated.class)
            && ac.isAnnotationPresent(
                annotated instanceof Field
                    ? ObjectField.AnnotationProcessorClass.class
                    : ObjectType.AnnotationProcessorClass.class)) {
          possibleAnnotationClasses.add(ac);
          continue;
        }
      }

      Collections.sort(
          possibleAnnotationClasses,
          new Comparator<Class<? extends Annotation>>() {

            @Override
            public int compare(Class<? extends Annotation> x, Class<? extends Annotation> y) {
              return x.getName().compareTo(y.getName());
            }
          });

      if (!presentAnnotations.isEmpty()) {
        page.writeStart("h2");
        page.writeHtml("Present Annotations");
        page.writeEnd();

        page.writeStart("ul");
        for (Annotation a : presentAnnotations) {
          page.writeStart("li");
          writeJavaAnnotationDescription(page, a);
          page.writeEnd();
        }
        page.writeEnd();
      }

      page.writeStart("h2");
      page.writeHtml("Possible Annotations");
      page.writeEnd();

      page.writeStart("ul");
      for (Class<? extends Annotation> ac : possibleAnnotationClasses) {
        page.writeStart("li");
        page.writeJavaClassLink(ac);
        page.writeEnd();
      }
      page.writeEnd();
    }
コード例 #20
0
  @SuppressWarnings("unchecked")
  public void register(Class<?> requiredType, Class<?> type) {
    logger.debug("Registering " + requiredType.getName() + " with " + type.getName());

    boolean overriding = alreadyRegistered(requiredType);
    if (overriding) {
      logger.debug("Overriding interface " + requiredType.getName() + " with " + type.getName());
    }
    if (type.isAnnotationPresent(ApplicationScoped.class)) {
      logger.debug("Registering " + type.getName() + " as an application component");
      this.applicationScoped.put(requiredType, type);
      if (initialized) {
        logger.warn(
            "VRaptor was already initialized, the contexts were created but you are registering a component."
                + "This is nasty. The original component might already be in use."
                + "Avoid doing it: "
                + requiredType.getName());
        this.appContainer.addComponent(requiredType, type);
      }
    } else if (type.isAnnotationPresent(SessionScoped.class)) {
      logger.debug("Registering " + type.getName() + " as a session component");
      this.sessionScoped.put(requiredType, type);
    } else if (type.isAnnotationPresent(PrototypeScoped.class)) {
      logger.debug("Registering " + type.getName() + " as a prototype component");
      this.prototypeScoped.put(requiredType, type);
    } else {
      // default behaviour: even without @RequestScoped
      if (!type.isAnnotationPresent(RequestScoped.class)) {
        logger.info(
            "Class being registered as @RequestScoped, since there is no Scope annotation " + type);
      }
      logger.debug("Registering " + type.getName() + " as a request component");
      this.requestScoped.put(requiredType, type);
    }

    if (ComponentFactory.class.isAssignableFrom(type)
        && !requiredType.equals(ComponentFactory.class)) {
      componentFactoryRegistry.register((Class<? extends ComponentFactory<?>>) type);

      if (type.isAnnotationPresent(ApplicationScoped.class) && initialized) {
        if (initialized) {
          logger.warn(
              "VRaptor was already initialized, the contexts were created but you are registering a component."
                  + "This is nasty. The original component might already be in use."
                  + "Avoid doing it: "
                  + requiredType.getName());
          Class<?> targetType =
              new ComponentFactoryIntrospector().targetTypeForComponentFactory(type);
          this.appContainer.addAdapter(
              new PicoComponentAdapter(targetType, (Class<? extends ComponentFactory<?>>) type));
        }
      }
    }
  }
コード例 #21
0
  private EntityType introspectParent(Class parentClass) throws SQLException {
    if (parentClass == null) return null;

    getInternalEntityConfig(parentClass, _annotationCfg);

    if (!_annotationCfg.isNull()) return (EntityType) _configManager.introspect(parentClass);
    else if (parentClass.isAnnotationPresent(javax.persistence.Entity.class))
      return (EntityType) _configManager.introspect(parentClass);
    else if (parentClass.isAnnotationPresent(javax.persistence.MappedSuperclass.class))
      return (EntityType) _configManager.introspect(parentClass);
    else return null;
  }
コード例 #22
0
ファイル: JPAPlugin.java プロジェクト: visan/play1
 public static Set<Field> getModelFields(Class<?> clazz) {
   Set<Field> fields = new LinkedHashSet<Field>();
   Class<?> tclazz = clazz;
   while (!tclazz.equals(Object.class)) {
     // Only add fields for mapped types
     if (tclazz.isAnnotationPresent(Entity.class)
         || tclazz.isAnnotationPresent(MappedSuperclass.class))
       Collections.addAll(fields, tclazz.getDeclaredFields());
     tclazz = tclazz.getSuperclass();
   }
   return fields;
 }
コード例 #23
0
ファイル: FunLib.java プロジェクト: jgralab/jgralab
 FunctionInfo(String name, Function func) {
   this.name = name;
   functionClass = func.getClass();
   ArrayList<Signature> functionSignatures = new ArrayList<>();
   function = func;
   needsGraphArgument = functionClass.isAnnotationPresent(NeedsGraphArgument.class);
   acceptsUndefinedValues = functionClass.isAnnotationPresent(AcceptsUndefinedArguments.class);
   needsEvaluatorArgument = functionClass.isAnnotationPresent(NeedsEvaluatorArgument.class);
   registerSignatures(functionSignatures, functionClass);
   signatures = new Signature[functionSignatures.size()];
   functionSignatures.toArray(signatures);
   Arrays.sort(signatures, new SignatureComparator());
 }
コード例 #24
0
ファイル: NovaLauncher.java プロジェクト: sguthals/NOVA-Core
  private void generateAndAddDependencies(Class<?> mod) {
    List<MavenDependency> deps;
    if (mod.isAnnotationPresent(Dependency.class)) {
      Dependency dependency = mod.getAnnotation(Dependency.class);
      deps = Collections.singletonList(new MavenDependency(dependency));
    } else if (mod.isAnnotationPresent(Dependencies.class)) {
      Dependency[] dependencies = mod.getAnnotation(Dependencies.class).value();
      deps = Arrays.stream(dependencies).map(MavenDependency::new).collect(Collectors.toList());
    } else {
      return;
    }

    neededDeps.put(mod.getAnnotation(Mod.class), deps);
  }
コード例 #25
0
ファイル: JPAPlugin.java プロジェクト: visan/play1
 private Class<?> getCompositeKeyClass() {
   Class<?> tclazz = clazz;
   while (!tclazz.equals(Object.class)) {
     // Only consider mapped types
     if (tclazz.isAnnotationPresent(Entity.class)
         || tclazz.isAnnotationPresent(MappedSuperclass.class)) {
       IdClass idClass = tclazz.getAnnotation(IdClass.class);
       if (idClass != null) return idClass.value();
     }
     tclazz = tclazz.getSuperclass();
   }
   throw new UnexpectedException(
       "Invalid mapping for class " + clazz + ": multiple IDs with no @IdClass annotation");
 }
コード例 #26
0
  /**
   * all primitive types.
   *
   * @throws Exception if test was failed
   */
  @SuppressWarnings("unchecked")
  @Test
  public void primitives() throws Exception {
    ModelLoader loader = generate();

    Class<?> type = loader.modelType("Primitives");
    assertThat(type.isAnnotationPresent(ModelInputLocation.class), is(true));
    assertThat(type.isAnnotationPresent(ModelOutputLocation.class), is(true));

    ModelWrapper object = loader.newModel("Primitives");

    object.set("type_boolean", true);
    object.set("type_byte", (byte) 64);
    object.set("type_short", (short) 256);
    object.set("type_int", 100);
    object.set("type_long", 200L);
    object.set("type_float", 300.f);
    object.set("type_double", 400.d);
    object.set("type_decimal", new BigDecimal("1234.567"));
    object.set("type_text", new Text("Hello, world!"));
    object.set("type_date", new Date(2011, 3, 31));
    object.set("type_datetime", new DateTime(2011, 3, 31, 23, 30, 1));

    DataOutputBuffer output = new DataOutputBuffer();
    ModelOutput<Object> modelOut =
        (ModelOutput<Object>)
            type.getAnnotation(ModelOutputLocation.class)
                .value()
                .getDeclaredConstructor(RecordEmitter.class)
                .newInstance(new TsvEmitter(new OutputStreamWriter(output, "UTF-8")));
    modelOut.write(object.unwrap());
    modelOut.write(object.unwrap());
    modelOut.write(object.unwrap());
    modelOut.close();

    DataInputBuffer input = new DataInputBuffer();
    input.reset(output.getData(), output.getLength());
    ModelInput<Object> modelIn =
        (ModelInput<Object>)
            type.getAnnotation(ModelInputLocation.class)
                .value()
                .getDeclaredConstructor(RecordParser.class)
                .newInstance(new TsvParser(new InputStreamReader(input, "UTF-8")));
    ModelWrapper copy = loader.newModel("Primitives");
    modelIn.readTo(copy.unwrap());
    assertThat(object.unwrap(), equalTo(copy.unwrap()));
    assertThat(input.read(), is(-1));
    modelIn.close();
  }
コード例 #27
0
  protected void addViewMetaData(Annotation currentAnnotation, List<Annotation> metaDataList) {
    Class<? extends Annotation> annotationClass = currentAnnotation.annotationType();

    if (annotationClass.isAnnotationPresent(ViewMetaData.class)) {
      metaDataList.add(currentAnnotation);
    }

    if (annotationClass.isAnnotationPresent(Stereotype.class)) {
      for (Annotation inheritedViaStereotype : annotationClass.getAnnotations()) {
        if (inheritedViaStereotype.annotationType().isAnnotationPresent(ViewMetaData.class)) {
          metaDataList.add(inheritedViaStereotype);
        }
      }
    }
  }
コード例 #28
0
 protected boolean isWrapped(
     Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
   if ((Collection.class.isAssignableFrom(type) || type.isArray()) && genericType != null) {
     Class baseType = Types.getCollectionBaseType(type, genericType);
     if (baseType == null) return false;
     return (baseType.isAnnotationPresent(XmlRootElement.class)
             || baseType.isAnnotationPresent(XmlType.class)
             || baseType.isAnnotationPresent(XmlSeeAlso.class)
             || JAXBElement.class.equals(baseType))
         && (FindAnnotation.findAnnotation(baseType, annotations, DoNotUseJAXBProvider.class)
             == null)
         && !IgnoredMediaTypes.ignored(baseType, annotations, mediaType);
   }
   return false;
 }
コード例 #29
0
 private void processClass(MutablePicoContainer picoContainer, Class[] classes) {
   for (Class aClass : classes) {
     ClassProcessor classProcessor = null;
     if (aClass.isAnnotationPresent(
         net.codjo.dataprocess.common.table.annotations.Handler.class)) {
       classProcessor = new HandlerCommandClassProcessor(picoContainer, aClass, handlerFactoryMap);
     }
     if (aClass.isAnnotationPresent(Table.class)) {
       classProcessor = new TableClassProcessor(picoContainer, aClass, handlerFactoryMap);
     }
     if (classProcessor != null) {
       classProcessor.process();
     }
   }
 }
コード例 #30
0
ファイル: RouterEntity.java プロジェクト: hahazql/gameTool
  /**
   * 遍历项目导入所有的Router
   *
   * @throws UnsupportedEncodingException
   * @throws RouterException
   */
  public static void loadRouter() throws RouterException {
    try {
      List<String> classNames = PackageUtil.getClassName("model.controller");
      for (String className : classNames) {
        System.out.println(classNames);
        Class clazz = Class.forName(className);
        if (!clazz.isAnnotationPresent(Controller.class)) // 只有有Controller注解的类才处理
        continue;
        /** 遍历类下的方法 */
        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
          if (!method.isAnnotationPresent(RequestMapping.class)) // 只有有RequestMapping的方法才生成router
          continue;

          Annotation annotation = method.getAnnotation(RequestMapping.class);
          Action action = new Action();
          action.setActionPath(((RequestMapping) annotation).value());
          action.setController(clazz.newInstance());
          action.setMethod(method);
          addRouter(action);
        }
      }
    } catch (ClassNotFoundException e) {
      throw (new RouterException(e));
    } catch (InstantiationException e) {
      throw (new RouterException(e));
    } catch (IllegalAccessException e) {
      throw (new RouterException(e));
    } catch (UnsupportedEncodingException e) {
      // TODO Auto-generated catch block
      throw (new RouterException(e));
    }
  }