Exemplo n.º 1
0
  /**
   * Converts the given value parameter (parameter) to a type that is accepted by the set method of
   * this property. This method attempts to convert the value regardless of the value being null.
   * However, this method short circuits and returns the value unchanged if value is runtime
   * assignable to the type of this BaseBeanProperty.
   *
   * @param values The String values to convert.
   * @param context The current context.
   * @param field The field that the conversion is occurring for. This is used to look for
   *     conversion annotations.
   * @return The value parameter converted to the correct type.
   * @throws ConversionException If there was a problem converting the parameter.
   */
  protected Object convert(final String[] values, Context context, Field field)
      throws ConversionException {
    Object newValue = values;

    // First look for annotations
    if (field != null) {
      Annotation[] annotations = field.getAnnotations();
      for (Annotation annotation : annotations) {
        ConverterAnnotation converterAnnotation =
            annotation.annotationType().getAnnotation(ConverterAnnotation.class);
        if (converterAnnotation != null) {
          AnnotationConverter converter = converterProvider.lookup(annotation);
          return converter.convertFromStrings(
              annotation, values, type, context.getAttributes(), context.getExpression());
        }
      }
    }

    // The converter does this, but pre-emptively checking these conditions will speed up conversion
    // times
    Class<?> typeClass = TypeTools.rawType(type);
    if (!typeClass.isInstance(values)) {
      GlobalConverter converter = converterProvider.lookup(typeClass);
      if (converter == null) {
        throw new ConverterStateException(
            "No type converter found for the type [" + typeClass.getName() + "]");
      }

      newValue =
          converter.convertFromStrings(
              values, type, context.getAttributes(), context.getExpression());
    }

    return newValue;
  }
 @Test
 public void acceptedCommandsCanBeSerializedTest() throws Exception {
   Field commandsField = JaxbCommandsRequest.class.getDeclaredField("commands");
   XmlElements xmlElemsAnno = (XmlElements) commandsField.getAnnotations()[0];
   XmlElement[] xmlElems = xmlElemsAnno.value();
   Set<Class> cmdSet = new HashSet<Class>(AcceptedCommands.getSet());
   assertEquals(cmdSet.size(), xmlElems.length);
   Set<String> xmlElemNameSet = new HashSet<String>();
   for (XmlElement xmlElemAnno : xmlElems) {
     Class cmdClass = xmlElemAnno.type();
     String name = xmlElemAnno.name();
     assertTrue(name + " is used twice as a name.", xmlElemNameSet.add(name));
     assertTrue(
         cmdClass.getSimpleName()
             + " is present in "
             + JaxbCommandsRequest.class.getSimpleName()
             + " but not in "
             + AcceptedCommands.class.getSimpleName(),
         cmdSet.remove(cmdClass));
   }
   for (Class cmdClass : cmdSet) {
     System.out.println("Missing: " + cmdClass.getSimpleName());
   }
   assertTrue(
       "See output for classes in "
           + AcceptedCommands.class.getSimpleName()
           + " that are not in "
           + JaxbCommandsRequest.class.getSimpleName(),
       cmdSet.size() == 0);
 }
Exemplo n.º 3
0
  /** Creates a {@link PluginPropertyField} based on the given field. */
  private PluginPropertyField createPluginProperty(Field field, TypeToken<?> resolvingType)
      throws UnsupportedTypeException {
    TypeToken<?> fieldType = resolvingType.resolveType(field.getGenericType());
    Class<?> rawType = fieldType.getRawType();

    Name nameAnnotation = field.getAnnotation(Name.class);
    Description descAnnotation = field.getAnnotation(Description.class);
    String name = nameAnnotation == null ? field.getName() : nameAnnotation.value();
    String description = descAnnotation == null ? "" : descAnnotation.value();

    if (rawType.isPrimitive()) {
      return new PluginPropertyField(name, description, rawType.getName(), true);
    }

    rawType = Primitives.unwrap(rawType);
    if (!rawType.isPrimitive() && !String.class.equals(rawType)) {
      throw new UnsupportedTypeException("Only primitive and String types are supported");
    }

    boolean required = true;
    for (Annotation annotation : field.getAnnotations()) {
      if (annotation.annotationType().getName().endsWith(".Nullable")) {
        required = false;
        break;
      }
    }

    return new PluginPropertyField(
        name, description, rawType.getSimpleName().toLowerCase(), required);
  }
Exemplo n.º 4
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());
     }
   }
 }
Exemplo n.º 5
0
  public static List<? extends Map<String, ?>> getMapped(List<?> objects, String[] desired_fields) {
    ArrayList<Map<String, ?>> list = new ArrayList<Map<String, ?>>();
    for (Object object : objects) {
      HashMap<String, Object> map = new HashMap<String, Object>();
      Class<? extends Object> c = object.getClass();
      for (Field field : c.getFields()) {
        Annotation[] ann = (Annotation[]) field.getAnnotations();
        for (Annotation annotation : ann) {
          if (annotation instanceof Element || annotation instanceof Attribute) {
            try {
              boolean is_in = false;
              for (String desired_field : desired_fields) {
                if (desired_field.equals(field.getName())) {
                  is_in = true;
                  break;
                }
              }
              if (is_in) {
                map.put(field.getName(), field.get(object));
              }

            } catch (IllegalArgumentException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            } catch (IllegalAccessException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }
          }
        }
      }
      list.add(map);
    }
    return list;
  }
 public Annotation[] getAllFieldAnnotations(Field field, Locatable srcPos) {
   Annotation[] r = field.getAnnotations();
   for (int i = 0; i < r.length; i++) {
     r[i] = LocatableAnnotation.create(r[i], srcPos);
   }
   return r;
 }
 @Override
 public void enrich(final SearchContext searchContext, Object target) {
   Collection<Field> fields =
       ReflectionHelper.getFieldsWithAnnotation(target.getClass(), JavaScript.class);
   for (Field field : fields) {
     GrapheneContext grapheneContext =
         searchContext == null
             ? null
             : ((GrapheneProxyInstance) searchContext).getGrapheneContext();
     if (grapheneContext == null) {
       grapheneContext =
           GrapheneContext.getContextFor(ReflectionHelper.getQualifier(field.getAnnotations()));
     }
     if (!field.isAccessible()) {
       field.setAccessible(true);
     }
     try {
       field.set(target, JSInterfaceFactory.create(grapheneContext, field.getType()));
     } catch (Exception e) {
       throw new IllegalStateException(
           "Can't inject value to the field '"
               + field.getName()
               + "' declared in class '"
               + field.getDeclaringClass().getName()
               + "'",
           e);
     }
   }
 }
Exemplo n.º 8
0
 public TypeWrapper(Class c) throws IntrospectionException {
   Map<String, Field> fields = new HashMap();
   loadFields(c, fields);
   BeanInfo bi = Introspector.getBeanInfo(c, Object.class);
   PropertyDescriptor[] props = bi.getPropertyDescriptors();
   for (int i = 0; i < props.length; i++) {
     PropertyDescriptor pd = props[i];
     Annotation[] ann = null;
     Field f = fields.get(pd.getName());
     if (f != null) {
       f.getAnnotations();
     }
     Class type = pd.getPropertyType();
     boolean arrayFlag = type.isArray();
     PropertyInfo pi =
         new PropertyInfo(
             pd.getName(),
             ann,
             (arrayFlag ? type.getComponentType() : type),
             arrayFlag,
             pd.getReadMethod(),
             pd.getWriteMethod());
     this.properties.put(pi.getName(), pi);
   }
 }
Exemplo n.º 9
0
 /**
  * Get the form parameters to be submitted
  *
  * @return The Map objection that has the forms variable names and values
  */
 public Body getParameters() {
   Body body = new Body();
   // get all declared files
   Field[] fields = this.getClass().getDeclaredFields();
   for (Field field : fields) {
     // get all the annotations
     try {
       Annotation[] annotations = field.getAnnotations();
       for (Annotation annotation : annotations) {
         if (annotation instanceof FormField) {
           FormField formField = (FormField) annotation;
           if (!field.isAccessible()) {
             field.setAccessible(true);
           }
           // add the form fields
           body.addField(formField.name(), field.get(this));
         }
       }
     } catch (IllegalArgumentException e) {
       e.printStackTrace();
     } catch (IllegalAccessException e) {
       e.printStackTrace();
     }
   }
   return body;
 }
Exemplo n.º 10
0
  /**
   * use annotation based class parsing to detect the configurable properties of a <code>
   * Configurable</code>-class
   *
   * @param configurable of type Class
   */
  private static Map<Field, Annotation> parseClass(Class<? extends Configurable> configurable) {
    Field[] classFields = configurable.getFields();

    Map<Field, Annotation> s4props = new HashMap<Field, Annotation>();
    for (Field field : classFields) {
      Annotation[] annotations = field.getAnnotations();

      for (Annotation annotation : annotations) {
        Annotation[] superAnnotations = annotation.annotationType().getAnnotations();

        for (Annotation superAnnotation : superAnnotations) {
          if (superAnnotation instanceof S4Property) {
            int fieldModifiers = field.getModifiers();
            assert Modifier.isStatic(fieldModifiers) : "property fields are assumed to be static";
            assert Modifier.isPublic(fieldModifiers) : "property fields are assumed to be public";
            assert Modifier.isFinal(fieldModifiers) : "property fields are assumed to be final";
            assert field.getType().equals(String.class)
                : "properties fields are assumed to be instances of java.lang.String";

            s4props.put(field, annotation);
          }
        }
      }
    }

    return s4props;
  }
Exemplo n.º 11
0
  private boolean scanForAnnotations(Class<?> clazz) {
    if (clazz != null) {
      while (clazz != Object.class) {
        Field[] fields = clazz.getDeclaredFields();
        if (fields != null) {
          for (Field field : fields) {
            if (field.getAnnotations().length > 0) {
              return true;
            }
          }
        }

        Method[] methods = clazz.getDeclaredMethods();
        if (methods != null) {
          for (Method method : methods) {
            if (method.getDeclaredAnnotations().length > 0) {
              return true;
            }
          }
        }

        clazz = clazz.getSuperclass();
      }
    }

    return false;
  }
Exemplo n.º 12
0
  /**
   * @param clazz the class to be handled (read from and wrote to)
   * @param file the file to be processed
   */
  public void handleConfig(Class<?> clazz, File file) {
    if (!hasRun) {
      hasRun = true;
      for (Field field : clazz.getDeclaredFields()) {
        for (Annotation annotation : field.getAnnotations()) {
          if (annotation.annotationType() == Config.String.class)
            handleString(clazz, field, (Config.String) annotation);
          else if (annotation.annotationType() == Config.Integer.class)
            handleInteger(clazz, field, (Config.Integer) annotation);
          else if (annotation.annotationType() == Config.Boolean.class)
            handleBoolean(clazz, field, (Config.Boolean) annotation);
          else if (annotation.annotationType() == Config.List.class)
            handleList(clazz, field, (Config.List) annotation);
          else if (annotation.annotationType() == Config.Map.class)
            handleMap(clazz, field, (Config.Map) annotation);
          else if (annotation.annotationType() == Config.Long.class)
            handleLong(clazz, field, (Config.Long) annotation);
          else if (annotation.annotationType() == Config.Float.class)
            handleFloat(clazz, field, (Config.Float) annotation);
          else if (annotation.annotationType() == Config.Double.class)
            handleDouble(clazz, field, (Config.Double) annotation);
          else if (annotation.annotationType() == Config.Character.class)
            handleCharacter(clazz, field, (Config.Character) annotation);
        }
      }
    }

    try (BufferedReader reader =
        new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"))) {
      String line;
      while ((line = reader.readLine()) != null) {
        if (line.contains("{")) {
          char[] chars = line.toCharArray();
          boolean hasNotEncounteredText = true;
          StringBuilder stringBuilder = new StringBuilder();
          for (Character character : chars) {
            if ((!character.equals(' ') && !character.equals('\t')) || hasNotEncounteredText) {
              hasNotEncounteredText = false;
              stringBuilder.append(character);
            } else if (character.equals(' ')) break;
          }
          categories
              .getOrDefault(stringBuilder.toString(), categories.get("General"))
              .read(clazz, reader);
        }
      }
    } catch (IOException ignored) {
    }

    StringBuilder stringBuilder = new StringBuilder();
    categories.values().forEach(category -> category.write(stringBuilder));
    String fileString = stringBuilder.toString();

    try (BufferedWriter writer =
        new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"))) {
      writer.append(fileString);
    } catch (IOException ignored) {
    }
  }
 protected boolean isFieldAllowed(Field field) {
   Annotation[] annotations = field.getAnnotations();
   for (Annotation annotation : annotations) {
     if (hasCompatibleAnnotation(annotation)) {
       return true;
     }
   }
   return false;
 }
Exemplo n.º 14
0
  @SuppressWarnings("rawtypes")
  @Test
  public void metodo1() throws IllegalArgumentException, Exception {
    this.scanningProvider = new ClassPathScanningCandidateComponentProvider(false);
    this.scanningProvider.addIncludeFilter(
        new AnnotationTypeFilter(javax.persistence.Entity.class));

    List<Class<? extends Object>> classes = new ArrayList<Class<? extends Object>>();
    for (BeanDefinition beanDef : this.scanningProvider.findCandidateComponents("br.com")) {
      classes.add(Class.forName(beanDef.getBeanClassName()));
    }

    CLAZZ:
    for (Class clazz : classes) {

      Field listaCampo[] = clazz.getDeclaredFields();
      for (Field campo : listaCampo) {
        if (campo.getName().trim().equalsIgnoreCase("id")) {

          for (Annotation anotacao : campo.getAnnotations()) {
            if (anotacao.toString().contains("sequenceName")) {
              String array[] = anotacao.toString().split(",");
              String sequence = "";
              for (String item : array) {
                if (item.contains("sequenceName")) {
                  sequence = item.replace("sequenceName=", "");
                  break;
                }
              }
              if (sequence != null && !sequence.equals("")) {
                // Descobre o maior id do banco
                Integer ultimoId = dao.max(clazz);
                if (ultimoId == null) {
                  ultimoId = 1;
                }
                Session session = dao.getCurrentSession();

                String sql = "SELECT setval('SISFIE." + sequence.trim() + "', " + ultimoId + ");";

                if (duplicadas.contains(sequence.trim())) {
                  throw new IllegalArgumentException();
                }
                duplicadas.add(sequence.trim());
                session.createSQLQuery(sql).uniqueResult();
                sequences.add(new SelectItem(ultimoId, sequence.trim()));
                continue CLAZZ;
              }
            }
          }
        }
      }
    }
    System.out.println("Total :" + sequences.size());
    for (SelectItem item : sequences) {
      System.out.println(item.getLabel() + ": " + item.getValue());
    }
  }
Exemplo n.º 15
0
 private Annotation getFactory(Field field) {
   Annotation[] annotations = field.getAnnotations();
   for (Annotation annotation : annotations) {
     if (factories.containsKey(annotation.annotationType())) {
       return annotation;
     }
   }
   return null;
 }
  private OOFactSet create_factset(Class<?> classObj, boolean all_discrete) {
    // System.out.println("WorkingMemory.create_factset element "+ element );

    OOFactSet newfs = new OOFactSet(classObj);

    Field[] element_fields = classObj.getDeclaredFields();
    for (Field f : element_fields) {
      String f_name = f.getName();
      Class<?>[] f_class = {f.getType()};
      System.out.println(
          "WHat is this f: "
              + f.getType()
              + " the name "
              + f_name
              + " class "
              + f.getClass()
              + " and the name"
              + f.getClass().getName());
      if (Util.isSimpleType(f_class)) {

        Domain<?> fieldDomain;
        if (!domainset.containsKey(f_name)) {
          fieldDomain = DomainFactory.createDomainFromClass(f.getType(), f_name);
          domainset.put(f_name, fieldDomain);
        } else fieldDomain = domainset.get(f_name);

        Annotation[] annotations = f.getAnnotations();
        // iterate over the annotations to locate the MaxLength constraint if it exists
        DomainSpec spec = null;
        for (Annotation a : annotations) {
          if (a instanceof DomainSpec) {
            spec = (DomainSpec) a; // here it is !!!
            break;
          }
        }

        if (spec != null) {
          fieldDomain.setReadingSeq(spec.readingSeq());
          if (!all_discrete) fieldDomain.setDiscrete(spec.discrete());
        }
        /*
         * ID3 would
         * if it is integer and the annotation saying that the field is continuous
         * 		ignore the domain
         * if it is double / float and the annotation saying that the field is continuous
         * 		ignore the domain if it has more than 10 values ?
         * if it is string and the annotation saying that the field is continuous
         * 		what to do??
         */

        newfs.addDomain(f_name, fieldDomain);
      }
    }
    factsets.put(classObj.getName(), newfs);
    return newfs;
  }
  /**
   * Answers whether the Field should be copied. By default it ignores (answers 'false' to) static,
   * final, volatile and transient fields.
   *
   * @param f a Field of a Class.
   * @return true if the field should be copied into the resource. Otherwise, false.
   */
  private boolean isIncluded(Field f) {
    if ((inclusionAnnotations == null && exclusionAnnotations == null)
        || f.getAnnotations().length == 0) {
      return ((f.getModifiers() & IGNORED_FIELD_MODIFIERS) == 0);
    }

    for (Annotation annotation : f.getAnnotations()) {
      Class<? extends Annotation> type = annotation.annotationType();

      if (inclusionAnnotations != null && inclusionAnnotations.contains(type)) {
        return true;
      }

      if (exclusionAnnotations != null && exclusionAnnotations.contains(type)) {
        return false;
      }
    }

    return ((f.getModifiers() & IGNORED_FIELD_MODIFIERS) == 0);
  }
Exemplo n.º 18
0
 /**
  * Return the annotations that are present on this field.
  *
  * @return an array of all the annotations set on the field
  * @since 1.4
  */
 public Collection<Annotation> getAnnotations() {
   if (annotations == null) {
     Pair<Class<?>, String> key = new Pair<Class<?>, String>(parentClazz, name);
     annotations = ANNOTATION_CACHE.getElement(key);
     if (annotations == null) {
       annotations = Collections.unmodifiableCollection(Arrays.asList(field.getAnnotations()));
       ANNOTATION_CACHE.addElement(key, annotations);
     }
   }
   return annotations;
 }
Exemplo n.º 19
0
  public void print() {

    System.out.println(" ->" + this.identifier + " " + this.texto1 + " " + this.texto2);

    Class c = this.getClass();

    for (Field f : c.getFields()) {

      for (Annotation a : f.getAnnotations()) {
        System.out.println(a);
      }
    }
  }
Exemplo n.º 20
0
  public static void main(String[] args)
      throws ClassNotFoundException, InstantiationException, IllegalAccessException {
    Field[] fields = Student.class.getDeclaredFields();
    for (Field f : fields) {
      Annotation[] an = f.getAnnotations();
      for (Annotation a : an) {
        System.out.println(a.toString());
      }
    }

    //		String str="你好";
    //		String type="java.lang.String";
    //		Class c=Class.forName(type);
    //		Object object=c.newInstance();
    //		if(object instanceof String){
    //			System.out.println((String)str);
    //		}

    //		System.out.println(new Date(1384496589000l).toLocaleString());
    //		System.out.println(new Date().getTime());
    //		System.out.println(object instanceof String);
    //		System.out.println(String.class==c);
    //		Timestamp ts=new Timestamp(1384420259541l);
    //		System.out.println(ts.getTime());

    //		Date date=new Date(1384420259541l);
    //		System.out.println(date.toLocaleString());
    //		Date date=new Date(1384420259541l);
    //		System.out.println((java.sql.Date)date);

    //		Class<ORMDBTable> c=ORMDBTable.class;
    //		System.out.println(c.getName());
    //
    //	System.out.println(c.getName().substring(c.getName().lastIndexOf(".")+1,c.getName().length()-1)+"-------------------"+c.getAnnotation(DBTable.class).name());
    //		System.out.println(c.getAnnotation(DBTable.class)==null);

    //		Class<TestBean> c=TestBean.class;
    //		Field[] fields=c.getDeclaredFields();
    //		System.out.println(fields.length);
    //		for(Field f:fields){
    //			Annotation[] annotations=f.getAnnotations();
    //			System.out.println(f.getName()+"----------"+annotations.length);
    //			for (Annotation a:annotations) {
    //
    //			}
    //			System.out.println(f.getAnnotations());
    //			if(f.getAnnotation(DBColumn.class).date()){
    //				System.out.println(f.getType());
    //			}
    //		}
  }
 /** Checks if the field is accepted as a JAXB property. */
 static boolean isFieldAccepted(Field field, XmlAccessType accessType) {
   // We only accept non static fields which are not marked @XmlTransient
   if (Modifier.isStatic(field.getModifiers()) || field.isAnnotationPresent(XmlTransient.class)) {
     return false;
   }
   if (accessType == XmlAccessType.PUBLIC_MEMBER && !Modifier.isPublic(field.getModifiers())) {
     return false;
   }
   if (accessType == XmlAccessType.NONE || accessType == XmlAccessType.PROPERTY) {
     return checkJaxbAnnotation(field.getAnnotations());
   } else {
     return true;
   }
 }
Exemplo n.º 22
0
  /**
   * Finds the class's Id property.
   *
   * @param entityClass the entityClass to find the id of
   * @return the id's property name or null if none is defined
   */
  public static String getIdName(Class<?> clazz) {
    while (clazz != null) {
      for (Field field : clazz.getDeclaredFields()) {
        for (Annotation annotation : field.getAnnotations()) {
          if (Id.class.isAssignableFrom(annotation.annotationType())) {
            return field.getName();
          }
        }
      }
      clazz = clazz.getSuperclass();
    }

    return null;
  }
Exemplo n.º 23
0
 private void findContextFields(Class<?> cls, Object provider) {
   if (cls == Object.class || cls == null) {
     return;
   }
   for (Field f : cls.getDeclaredFields()) {
     for (Annotation a : f.getAnnotations()) {
       if (a.annotationType() == Context.class) {
         contextFields = addContextField(contextFields, f);
         if (f.getType().isInterface()) {
           checkContextClass(f.getType());
           addToMap(getFieldProxyMap(true), f, getFieldThreadLocalProxy(f, provider));
         }
       }
     }
   }
   findContextFields(cls.getSuperclass(), provider);
 }
Exemplo n.º 24
0
  /**
   * Get list of public fields which is annotated as input of modules.
   *
   * @param c
   * @return
   */
  public static List<Field> getInputFields(Class<?> c) {
    List<Field> result = new ArrayList<Field>();

    Field[] fields = c.getFields();

    for (Field f : fields) {
      Annotation[] fieldAnnotations = f.getAnnotations();
      for (Annotation a : fieldAnnotations) {
        if (a instanceof In) {
          result.add(f);
          break;
        }
      }
    }

    return result;
  }
Exemplo n.º 25
0
 private Map<String, BeanPair> getValuesFromBeanParam(
     Object bean, Class<? extends Annotation> annClass, Map<String, BeanPair> values) {
   for (Method m : bean.getClass().getMethods()) {
     if (m.getName().startsWith("set")) {
       try {
         String propertyName = m.getName().substring(3);
         Annotation annotation = m.getAnnotation(annClass);
         boolean beanParam = m.getAnnotation(BeanParam.class) != null;
         if (annotation != null || beanParam) {
           Method getter = bean.getClass().getMethod("get" + propertyName, new Class[] {});
           Object value = getter.invoke(bean, new Object[] {});
           if (value != null) {
             if (annotation != null) {
               String annotationValue = AnnotationUtils.getAnnotationValue(annotation);
               values.put(annotationValue, new BeanPair(value, m.getParameterAnnotations()[0]));
             } else {
               getValuesFromBeanParam(value, annClass, values);
             }
           }
         } else {
           String fieldName = StringUtils.uncapitalize(propertyName);
           Field f = InjectionUtils.getDeclaredField(bean.getClass(), fieldName);
           if (f == null) {
             continue;
           }
           annotation = f.getAnnotation(annClass);
           if (annotation != null) {
             Object value = ReflectionUtil.accessDeclaredField(f, bean, Object.class);
             if (value != null) {
               String annotationValue = AnnotationUtils.getAnnotationValue(annotation);
               values.put(annotationValue, new BeanPair(value, f.getAnnotations()));
             }
           } else if (f.getAnnotation(BeanParam.class) != null) {
             Object value = ReflectionUtil.accessDeclaredField(f, bean, Object.class);
             if (value != null) {
               getValuesFromBeanParam(value, annClass, values);
             }
           }
         }
       } catch (Throwable t) {
         // ignore
       }
     }
   }
   return values;
 }
Exemplo n.º 26
0
 /** 获得实体类中每个非Transient注解字段的连接串用于select * from语句中代替“*” */
 public static <T> String getClassAttrs(Class<T> c) {
   Field[] field = c.getDeclaredFields();
   StringBuilder sb = new StringBuilder();
   int i = 0;
   for (Field f : field) {
     String name = f.getName();
     Annotation[] annotations = f.getAnnotations();
     if (!findAnnotation(annotations)) {
       i++;
       if (i == 1) {
         sb.append(name);
       } else {
         sb.append("," + name);
       }
     }
   }
   return sb.toString() == "" ? "*" : sb.toString();
 }
Exemplo n.º 27
0
  /** Scans the class and generates metadata. */
  public void generate(Class<?> clazz) throws IllegalAccessException {
    if (clazz == null) {
      return;
    }

    for (Field field : clazz.getDeclaredFields()) {
      if (field.getType().getName().startsWith(PACKAGE_TO_SCAN) && !field.isEnumConstant()) {
        generate(field.getType());
      } else {
        for (Annotation annotation : field.getAnnotations()) {
          if (annotation.annotationType().equals(ProviderMappings.class)) {
            ProviderMappings providerAnnotations = (ProviderMappings) annotation;
            for (Provider provider : providerAnnotations.value()) {
              Map<String, ProviderMappingInfo> mappings = providerMappings.get(provider.name());

              if (mappings == null) {
                mappings = new HashMap<String, ProviderMappingInfo>();
                providerMappings.put(provider.name(), mappings);
              }

              Converter<?> converter = (Converter<?>) getConverter(field, provider.converter());
              String target = clazz.getSimpleName().toLowerCase() + "." + field.getName();
              ProviderMappingInfo pm =
                  new ProviderMappingInfo(provider.property(), target, converter);
              mappings.put(pm.getSource(), pm);
              logger.trace("Added provider mapping {}: {}", provider.name(), pm);
            }
          } else if (annotation.annotationType().equals(ForecastMappings.class)) {
            ForecastMappings forecastsAnnotations = (ForecastMappings) annotation;
            for (Forecast forecast : forecastsAnnotations.value()) {
              List<String> forecastProperties = forecastMappings.get(forecast.provider());
              if (forecastProperties == null) {
                forecastProperties = new ArrayList<String>();
                forecastMappings.put(forecast.provider(), forecastProperties);
              }
              forecastProperties.add(forecast.property());
              logger.trace(
                  "Added forecast mapping {}: {}", forecast.provider(), forecast.property());
            }
          }
        }
      }
    }
  }
Exemplo n.º 28
0
  /**
   * Obtiene las propiedades de la entidad a la cual pertenece el DAO.
   *
   * @param object entidad a la que pertenece el DAO.
   * @param clave la entidad embebida que contiene la clave primaria
   * @return Mapa con las propiedades y los valores, el cual será utilizado para la construcción de
   *     los criterios en la ejecución de la búsqueda.
   */
  @SuppressWarnings("unchecked")
  private Map<String, Object> obtenerPropiedades(Object object, String... clave) {
    Class<T> classe = (Class<T>) object.getClass();
    Field[] fields = classe.getDeclaredFields();
    Map<String, Object> mapa = new HashMap<String, Object>(fields.length);
    for (Field field : fields) {
      Boolean isClob = Boolean.FALSE;
      Annotation[] anotaciones = field.getAnnotations();
      for (Annotation annotation : anotaciones) {
        if ("@javax.persistence.Lob()".equals(annotation.toString())
            || "@javax.persistence.Transient()".equals(annotation.toString())) {
          isClob = Boolean.TRUE;
          break;
        }
      }
      if (!isClob) {
        String fieldName = field.getName();
        String methodName =
            "get" + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
        try {
          Method method = classe.getMethod(methodName, new Class[] {});
          Object result = method.invoke(object, new Object[] {});

          if (result != null) {
            if (clave != null && clave.length == 1) {
              mapa.put(clave[0] + "." + field.getName(), result);
            } else {
              mapa.put(field.getName(), result);
            }
          }
        } catch (RuntimeException e) {
          continue;
        } catch (NoSuchMethodException e) {
          continue;
        } catch (IllegalAccessException e) {
          continue;
        } catch (InvocationTargetException e) {
          continue;
        }
      }
    }
    return mapa;
  }
  private List<Field> GetFields(java.lang.reflect.Field[] fields) {
    List<Field> list = new ArrayList<>();
    for (java.lang.reflect.Field field : fields) {
      String visibility = this.GetVisibility(field.getModifiers());
      boolean isStatic = this.GetIsStatic(field.getModifiers());
      boolean isFinal = this.GetIsFinal(field.getModifiers());
      String type = field.getGenericType().toString();
      String name = field.getName();
      if (name.contains("_")) continue;
      List<String> annotationList = this.GetAnnotations(field.getAnnotations());
      String defaultValue = "";

      Field item =
          ModelFactory.GetFieldWithValue(
              type, name, visibility, defaultValue, annotationList, isStatic, isFinal);
      list.add(item);
    }
    return list;
  }
Exemplo n.º 30
0
 static OptionInfo createFromField(Field field) {
   Preconditions.checkNotNull(field);
   CmdLine cmdLine = field.getAnnotation(CmdLine.class);
   if (cmdLine == null) {
     throw new Configuration.ConfigurationException(
         "No @CmdLine Arg annotation for field " + field);
   }
   @SuppressWarnings("unchecked")
   OptionInfo optionInfo =
       new OptionInfo(
           checkValidName(cmdLine.name()),
           cmdLine.help(),
           ArgumentInfo.getArgForField(field),
           TypeUtil.getTypeParamTypeToken(field),
           field.getDeclaringClass().getCanonicalName(),
           Arrays.asList(field.getAnnotations()),
           cmdLine.parser());
   return optionInfo;
 }