Example #1
0
 public List<Model.Property> listProperties() {
   List<Model.Property> properties = new ArrayList<Model.Property>();
   Set<Field> fields = new LinkedHashSet<Field>();
   Class<?> tclazz = clazz;
   while (!tclazz.equals(Object.class)) {
     Collections.addAll(fields, tclazz.getDeclaredFields());
     tclazz = tclazz.getSuperclass();
   }
   for (Field f : fields) {
     int mod = f.getModifiers();
     if (Modifier.isTransient(mod) || Modifier.isStatic(mod)) {
       continue;
     }
     if (f.isAnnotationPresent(Transient.class)) {
       continue;
     }
     if (f.isAnnotationPresent(NoBinding.class)) {
       NoBinding a = f.getAnnotation(NoBinding.class);
       List<String> values = Arrays.asList(a.value());
       if (values.contains("*")) {
         continue;
       }
     }
     Model.Property mp = buildProperty(f);
     if (mp != null) {
       properties.add(mp);
     }
   }
   return properties;
 }
  // TODO: https://issues.jboss.org/browse/JBPM-4296
  private static Long findProcessInstanceId(Object command) {
    if (command instanceof AuditCommand) {
      return null;
    }
    try {
      Field[] fields = command.getClass().getDeclaredFields();

      for (Field field : fields) {
        field.setAccessible(true);
        if (field.isAnnotationPresent(XmlAttribute.class)) {
          String attributeName = field.getAnnotation(XmlAttribute.class).name();
          if ("process-instance-id".equalsIgnoreCase(attributeName)) {
            return (Long) field.get(command);
          }
        } else if (field.isAnnotationPresent(XmlElement.class)) {
          String elementName = field.getAnnotation(XmlElement.class).name();
          if ("process-instance-id".equalsIgnoreCase(elementName)) {
            return (Long) field.get(command);
          }
        } else if (field.getName().equals("processInstanceId")) {
          return (Long) field.get(command);
        }
      }
    } catch (Exception e) {
      logger.debug(
          "Unable to find process instance id on command {} due to {}", command, e.getMessage());
    }

    return null;
  }
 public static Serializable getIdentifier(final Object obj) {
   if (obj instanceof BaseDO<?>) {
     return getIdentifier((BaseDO<?>) obj);
   }
   for (final Field field : obj.getClass().getDeclaredFields()) {
     if (field.isAnnotationPresent(Id.class) == true
         && field.isAnnotationPresent(GeneratedValue.class) == true) {
       final boolean isAccessible = field.isAccessible();
       try {
         field.setAccessible(true);
         final Object idObject = field.get(obj);
         field.setAccessible(isAccessible);
         if (idObject != null
             && Serializable.class.isAssignableFrom(idObject.getClass()) == true) {
           return (Serializable) idObject;
         }
       } catch (final IllegalArgumentException e) {
         e.printStackTrace();
       } catch (final IllegalAccessException e) {
         e.printStackTrace();
       }
     }
   }
   return null;
 }
Example #4
0
 Field[] keyFields() {
   Class c = clazz;
   try {
     List<Field> fields = new ArrayList<Field>();
     while (!c.equals(Object.class)) {
       for (Field field : c.getDeclaredFields()) {
         // TODO: add cashe field->isAnnotationPresent
         if (InternalCache.isEnableAnnotationPresent()) {
           if (InternalCache.isAnnotationPresent(Id.class, field)
               || InternalCache.isAnnotationPresent(EmbeddedId.class, field)) {
             field.setAccessible(true);
             fields.add(field);
           }
         } else {
           if (field.isAnnotationPresent(Id.class)
               || field.isAnnotationPresent(EmbeddedId.class)) {
             field.setAccessible(true);
             fields.add(field);
           }
         }
       }
       c = c.getSuperclass();
     }
     final Field[] f = fields.toArray(new Field[fields.size()]);
     if (f.length == 0) {
       throw new UnexpectedException("Cannot get the object @Id for an object of type " + clazz);
     }
     return f;
   } catch (Exception e) {
     throw new UnexpectedException(
         "Error while determining the object @Id for an object of type " + clazz);
   }
 }
Example #5
0
  public void injectResources(Object serviceInstance) {

    if (resources == null && entityManagers == null && typedResources == null) {
      return;
    }

    List<Member> members = ReflectionUtils.findMembers(serviceInstance.getClass());
    for (Member member : members) {
      if (member instanceof Field) {
        Field field = (Field) member;
        if (field.isAnnotationPresent(Resource.class)) {
          Resource resource = field.getAnnotation(Resource.class);
          if (!injectNamedResource(serviceInstance, field, resource)) {
            injectTypedResource(serviceInstance, field);
          }
        }
        if (hasPersistenceContextInClassPath) {
          try {
            if (field.isAnnotationPresent(PersistenceContext.class)) {
              PersistenceContext resource = field.getAnnotation(PersistenceContext.class);
              injectEntityManager(serviceInstance, field, resource);
            }
          } catch (NoClassDefFoundError e) {
            hasPersistenceContextInClassPath = false;
          }
        }
      }
    }
  }
Example #6
0
  /**
   * TODO: not yet commented.
   *
   * @return
   */
  public Set<Attribute> getAttributes() {
    Set<Attribute> result = new HashSet<Attribute>();

    /*
     * Search on this entity, climbing up the class hierarchy.
     */
    Class<?> self = this.getClass();
    while (!Object.class.equals(self)) {
      for (Field f : self.getClass().getDeclaredFields()) {
        if (f.isAnnotationPresent(Attribute.class)) {
          result.add(f.getAnnotation(Attribute.class));
        } // if
      } // for
      self = self.getSuperclass();
    } // while

    /*
     * Search on all mixins.
     */
    for (Object o : this.getMixins()) {
      for (Field f : o.getClass().getDeclaredFields()) {
        if (f.isAnnotationPresent(Attribute.class)) {
          result.add(f.getAnnotation(Attribute.class));
        } // if
      } // for
    } // for

    return result;
  }
Example #7
0
  /**
   * 解析字段定义<br>
   * <功能详细描述>
   *
   * @param type
   * @param pd
   * @return [参数说明]
   * @return JPAEntityColumnDef [返回类型说明]
   * @exception throws [异常类型] [异常说明]
   * @see [类、类#方法、类#成员]
   */
  private static JPAEntityColumnDef doAnalyzeCoumnDef(
      String tableName, Class<?> type, PropertyDescriptor pd) {
    JPAEntityColumnDef colDef = null;

    String columnComment = "";
    String propertyName = pd.getName();
    String columnName = propertyName;
    Class<?> javaType = pd.getPropertyType();
    int size = 0;
    int scale = 0;
    boolean required = false;

    // 获取字段
    Field field = FieldUtils.getField(type, propertyName, true);
    if (field != null) {
      if (field.isAnnotationPresent(Transient.class)) {
        // 如果含有忽略的字段则跳过该字段
        return null;
      }
      if (field.isAnnotationPresent(OneToMany.class)) {
        // 如果含有忽略的字段则跳过该字段
        return null;
      }
      if (field.isAnnotationPresent(Column.class)) {
        Column columnAnno = field.getAnnotation(Column.class);
        columnName = columnAnno.name();
        required = !columnAnno.nullable();
        size = Math.max(columnAnno.length(), columnAnno.precision());
        scale = columnAnno.scale();
      }
    }

    // 获取读方法
    Method readMethod = pd.getReadMethod();
    if (readMethod != null) {
      if (readMethod.isAnnotationPresent(Transient.class)) {
        // 如果含有忽略的字段则跳过该字段
        return null;
      }
      if (readMethod.isAnnotationPresent(OneToMany.class)) {
        // 如果含有忽略的字段则跳过该字段
        return null;
      }
      if (readMethod.isAnnotationPresent(Column.class)) {
        Column columnAnno = readMethod.getAnnotation(Column.class);
        columnName = columnAnno.name();
        required = !columnAnno.nullable();
        size = Math.max(columnAnno.length(), columnAnno.precision());
        scale = columnAnno.scale();
      }
    }

    JdbcTypeEnum jdbcType = JPAEntityTypeRegistry.getJdbcType(javaType); // 获取对应的jdbcType
    colDef = new JPAEntityColumnDef(columnName, javaType, jdbcType, size, scale, required);
    colDef.setComment(columnComment);
    return colDef;
  }
  @SuppressWarnings("unchecked")
  public final void process(Class<?> clazz, EntityMetadata metadata) {
    metadata.setIndexName(clazz.getSimpleName());
    Index idx = (Index) clazz.getAnnotation(Index.class);
    List columnsToBeIndexed = new ArrayList();

    if (null != idx) {
      boolean isIndexable = idx.index();
      metadata.setIndexable(isIndexable);

      String indexName = idx.name();
      if ((indexName != null) && (!(indexName.isEmpty()))) {
        metadata.setIndexName(indexName);
      } else {
        metadata.setIndexName(clazz.getSimpleName());
      }

      if ((idx.columns() != null) && (idx.columns().length != 0)) {
        columnsToBeIndexed = Arrays.asList(idx.columns());
      }

      if (!(isIndexable)) {
        log.debug(
            new StringBuilder()
                .append("@Entity ")
                .append(clazz.getName())
                .append(" will not be indexed for ")
                .append((columnsToBeIndexed.isEmpty()) ? "all columns" : columnsToBeIndexed)
                .toString());

        return;
      }
    }

    log.debug(
        new StringBuilder()
            .append("Processing @Entity ")
            .append(clazz.getName())
            .append(" for Indexes.")
            .toString());

    for (Field f : clazz.getDeclaredFields()) {
      if (f.isAnnotationPresent(Id.class)) {
        String alias = f.getName();
        alias = getIndexName(f, alias);
        // metadata.addIndexProperty(new PropertyIndex(f, alias));
      } else {
        if (!(f.isAnnotationPresent(Column.class))) continue;
        String alias = f.getName();
        alias = getIndexName(f, alias);

        if ((!(columnsToBeIndexed.isEmpty())) && (!(columnsToBeIndexed.contains(alias)))) continue;
        // metadata.addIndexProperty(new PropertyIndex(f, alias));
      }
    }
  }
 private void parseProperty(AnnotationInfo ai, Class c, Field field) {
   // TODO add support for OneToOne
   if (!field.isAnnotationPresent(Transient.class)
       && (field.isAnnotationPresent(ManyToMany.class)
           || field.isAnnotationPresent(OneToMany.class)
           || field.isAnnotationPresent(ManyToOne.class)
           || field.isAnnotationPresent(Id.class))) {
     ai.addField(field);
   }
 }
Example #10
0
  @GwtIncompatible("reflection")
  public void testGetField() {
    Field foo = Enums.getField(AnEnum.FOO);
    assertEquals("FOO", foo.getName());
    assertTrue(foo.isAnnotationPresent(ExampleAnnotation.class));

    Field bar = Enums.getField(AnEnum.BAR);
    assertEquals("BAR", bar.getName());
    assertFalse(bar.isAnnotationPresent(ExampleAnnotation.class));
  }
Example #11
0
 static boolean detectJOhmCollection(final Field field) {
   boolean isJOhmCollection = false;
   if (field.isAnnotationPresent(CollectionList.class)
       || field.isAnnotationPresent(CollectionSet.class)
       || field.isAnnotationPresent(CollectionSortedSet.class)
       || field.isAnnotationPresent(CollectionMap.class)) {
     isJOhmCollection = true;
   }
   return isJOhmCollection;
 }
Example #12
0
 @SuppressWarnings("unchecked")
 static void initCollections(final Object model, final Nest<?> nest) {
   if (model == null || nest == null) {
     return;
   }
   for (Field field : model.getClass().getDeclaredFields()) {
     field.setAccessible(true);
     try {
       if (field.isAnnotationPresent(CollectionList.class)) {
         Validator.checkValidCollection(field);
         List<Object> list = (List<Object>) field.get(model);
         if (list == null) {
           CollectionList annotation = field.getAnnotation(CollectionList.class);
           RedisList<Object> redisList =
               new RedisList<Object>(annotation.of(), nest, field, model);
           field.set(model, redisList);
         }
       }
       if (field.isAnnotationPresent(CollectionSet.class)) {
         Validator.checkValidCollection(field);
         Set<Object> set = (Set<Object>) field.get(model);
         if (set == null) {
           CollectionSet annotation = field.getAnnotation(CollectionSet.class);
           RedisSet<Object> redisSet = new RedisSet<Object>(annotation.of(), nest, field, model);
           field.set(model, redisSet);
         }
       }
       if (field.isAnnotationPresent(CollectionSortedSet.class)) {
         Validator.checkValidCollection(field);
         Set<Object> sortedSet = (Set<Object>) field.get(model);
         if (sortedSet == null) {
           CollectionSortedSet annotation = field.getAnnotation(CollectionSortedSet.class);
           RedisSortedSet<Object> redisSortedSet =
               new RedisSortedSet<Object>(annotation.of(), annotation.by(), nest, field, model);
           field.set(model, redisSortedSet);
         }
       }
       if (field.isAnnotationPresent(CollectionMap.class)) {
         Validator.checkValidCollection(field);
         Map<Object, Object> map = (Map<Object, Object>) field.get(model);
         if (map == null) {
           CollectionMap annotation = field.getAnnotation(CollectionMap.class);
           RedisMap<Object, Object> redisMap =
               new RedisMap<Object, Object>(
                   annotation.key(), annotation.value(), nest, field, model);
           field.set(model, redisMap);
         }
       }
     } catch (IllegalArgumentException e) {
       throw new InvalidFieldException();
     } catch (IllegalAccessException e) {
       throw new InvalidFieldException();
     }
   }
 }
  /*
   * (non-Javadoc)
   *
   * @see java.util.concurrent.Callable#call()
   */
  public AnnotationInfo call() throws Exception {
    Field riakKeyField = null;
    Field riakVClockField = null;
    Field usermetaMapField = null;
    Field linksField = null;
    List<UsermetaField> usermetaItemFields = new ArrayList<UsermetaField>();
    List<RiakIndexField> indexFields = new ArrayList<RiakIndexField>();

    final Field[] fields = classToScan.getDeclaredFields();

    for (Field field : fields) {

      if (field.isAnnotationPresent(RiakKey.class)) {

        riakKeyField = ClassUtil.checkAndFixAccess(field);
      }

      if (field.isAnnotationPresent(RiakVClock.class)) {

        // restrict the field type to byte[] or VClock
        if (!(field.getType().isArray() && field.getType().getComponentType().equals(byte.class))
            && !field.getType().isAssignableFrom(VClock.class)) {
          throw new IllegalArgumentException(field.getType().toString());
        }

        riakVClockField = ClassUtil.checkAndFixAccess(field);
      }

      if (field.isAnnotationPresent(RiakUsermeta.class)) {
        RiakUsermeta a = field.getAnnotation(RiakUsermeta.class);
        String key = a.key();

        if (!"".equals(key)) {
          usermetaItemFields.add(new UsermetaField(ClassUtil.checkAndFixAccess(field)));
        } else {
          usermetaMapField = ClassUtil.checkAndFixAccess(field);
        }
      }

      if (field.isAnnotationPresent(RiakIndex.class)) {
        indexFields.add(new RiakIndexField(ClassUtil.checkAndFixAccess(field)));
      }

      if (field.isAnnotationPresent(RiakLinks.class)) {
        linksField = ClassUtil.checkAndFixAccess(field);
      }
    }
    return new AnnotationInfo(
        riakKeyField,
        usermetaItemFields,
        usermetaMapField,
        indexFields,
        linksField,
        riakVClockField);
  }
Example #14
0
  public Map<String, Object> dumpStats() {
    HashMap<String, Object> map = new HashMap<String, Object>();
    for (Class<?> clazz = this.getClass(); clazz != null; clazz = clazz.getSuperclass()) {
      Field[] fields = clazz.getDeclaredFields();
      for (Field field : fields) {
        if (field.isAnnotationPresent(ManagedAttribute.class)
            || (field.isAnnotationPresent(Property.class)
                && field.getAnnotation(Property.class).exposeAsManagedAttribute())) {
          String attributeName = field.getName();
          try {
            field.setAccessible(true);
            Object value = field.get(this);
            map.put(attributeName, value != null ? value.toString() : null);
          } catch (Exception e) {
            log.warn("Could not retrieve value of attribute (field) " + attributeName, e);
          }
        }
      }

      Method[] methods = this.getClass().getMethods();
      for (Method method : methods) {
        if (method.isAnnotationPresent(ManagedAttribute.class)
            || (method.isAnnotationPresent(Property.class)
                && method.getAnnotation(Property.class).exposeAsManagedAttribute())) {

          String method_name = method.getName();
          if (method_name.startsWith("is") || method_name.startsWith("get")) {
            try {
              Object value = method.invoke(this);
              String attributeName = Util.methodNameToAttributeName(method_name);
              map.put(attributeName, value != null ? value.toString() : null);
            } catch (Exception e) {
              log.warn("Could not retrieve value of attribute (method) " + method_name, e);
            }
          } else if (method_name.startsWith("set")) {
            String stem = method_name.substring(3);
            Method getter = ResourceDMBean.findGetter(getClass(), stem);
            if (getter != null) {
              try {
                Object value = getter.invoke(this);
                String attributeName = Util.methodNameToAttributeName(method_name);
                map.put(attributeName, value != null ? value.toString() : null);
              } catch (Exception e) {
                log.warn("Could not retrieve value of attribute (method) " + method_name, e);
              }
            }
          }
        }
      }
    }
    return map;
  }
Example #15
0
  public List<Method> getMethods(Object objeto) {

    List<Method> methodGet = mappedMethods.get(objeto.getClass());

    if (methodGet != null) {
      return methodGet;
    }

    methodGet = new ArrayList<Method>();
    Method methods[] = objeto.getClass().getMethods();

    List exclude = Arrays.asList(EXCLUDED_FIELDS);

    try {
      Field field;
      String fieldName;
      for (int j = 0; j < methods.length; j++) {
        field = null;
        fieldName = "";
        try {
          if (methods[j] != null
              && !methods[j].isAnnotationPresent(Transient.class)
              && !methods[j].isAnnotationPresent(NotAudited.class)
              && !methods[j].isAnnotationPresent(Id.class)
              && !exclude.contains(methods[j].getName())) {
            fieldName = getMethodName(methods[j]);
          }
          if (fieldName != null && !fieldName.equals("")) {
            try {
              field = getDeclaredField(methods[j].getDeclaringClass(), fieldName);
            } catch (NoSuchFieldException ex) {
              continue;
            }
            if (field != null
                && !field.isAnnotationPresent(Transient.class)
                && !field.isAnnotationPresent(NotAudited.class)
                && !field.isAnnotationPresent(Id.class)) {
              methodGet.add(methods[j]);
            }
          }
        } catch (Exception ex) {
          logger.log(Level.SEVERE, ex.getMessage(), ex);
        }
      }
    } catch (Exception ex) {
      logger.log(Level.SEVERE, ex.getMessage(), ex);
    }
    mappedMethods.put(objeto.getClass(), methodGet);
    return methodGet;
  }
Example #16
0
 public void inJectAll(Activity activity) {
   Field[] fields = activity.getClass().getDeclaredFields();
   if (fields != null && fields.length > 0) {
     for (Field field : fields) {
       if (field.isAnnotationPresent(InjectView.class)) {
         injectView(activity, field);
       } else if (field.isAnnotationPresent(InjectResource.class)) {
         injectResource(activity, field);
       } else if (field.isAnnotationPresent(Inject.class)) {
         inject(activity, field);
       }
     }
   }
 }
 /** {@inheritDoc} */
 @Override
 public Object postProcessAfterInitialization(Object bean, String beanName) {
   if (bean == null) return null;
   Class<?> beanClass = bean.getClass();
   Field[] fields = beanClass.getDeclaredFields();
   for (Field field : fields) {
     // Expect to get annnotation Autowired
     if (field.isAnnotationPresent(AutowiredFF4JProperty.class)) {
       autoWiredProperty(bean, field);
     } else if (field.isAnnotationPresent(AutowiredFF4JFeature.class)) {
       autoWiredFeature(bean, field);
     }
   }
   return bean;
 }
 public List<Model.Property> listProperties() {
   List<Model.Property> properties = new ArrayList<Model.Property>();
   Set<Field> fields = new HashSet<Field>();
   Class<?> tclazz = clazz;
   while (!tclazz.equals(Object.class)) {
     Collections.addAll(fields, tclazz.getDeclaredFields());
     tclazz = tclazz.getSuperclass();
   }
   for (Field f : fields) {
     if (Modifier.isTransient(f.getModifiers())) {
       continue;
     }
     if (Modifier.isStatic(f.getModifiers())) {
       continue;
     }
     if (f.isAnnotationPresent(Transient.class) && !f.getType().equals(Blob.class)) {
       continue;
     }
     Model.Property mp = buildProperty(f);
     if (mp != null) {
       properties.add(mp);
     }
   }
   return properties;
 }
  public int parse(Class<?> clazz) throws Exception {

    if (!doesClassHaveExcelReaderAnnotation(clazz)) {
      return 0;
    }

    String fileName = getFileName(clazz);

    Sheet sheet = getSheet(fileName);

    Field[] fields = clazz.getDeclaredFields();
    int count = 0;

    for (Field field : fields) {
      if (field.isAnnotationPresent(TestCase.class)) {
        try {
          // method.invoke(null);
          System.out.println("Field name: " + field.getName());
          count++;
        } catch (Exception e) {
        }
      }
    }

    return count;
  }
Example #20
0
 /**
  * Takes care of the id properties, either identifying the Ids or getting them from idProperties
  * of @Path
  *
  * @throws Exception
  */
 private void parseNodeProperty() throws Exception {
   if (Is.empty(treeAnnotation.idProperties())) {
     idProperties = "";
     for (Field field : nodeClass.getDeclaredFields()) {
       if (field.isAnnotationPresent(Id.class)) {
         if (!Is.empty(idProperties)) {
           idProperties = idProperties + ",";
         }
         idProperties = idProperties + field.getName();
       }
     }
   } else {
     idProperties = treeAnnotation.idProperties();
   }
   if (Is.empty(idProperties)) {
     throw new Exception(XavaResources.getString("error.nodePropertiesUndefined"));
   }
   String[] properties = idProperties.split(",");
   idPropertiesList = new ArrayList<String>();
   for (String property : properties) {
     if (!Is.empty(property.trim())) {
       idPropertiesList.add(property.trim());
     }
   }
 }
  /**
   * 构建ResultMap对象
   *
   * @param id
   * @param clazz
   * @param configuration
   * @return
   */
  private ResultMap buildResultMap(String id, Class<?> clazz, Configuration configuration) {
    // 判断是否已经存在缓存里
    if (configuration.hasResultMap(id)) {
      return configuration.getResultMap(id);
    }
    List<ResultMapping> resultMappings = Lists.newArrayList();
    Map<String, Field> columns = EntityUtil.getFields(clazz);
    for (Map.Entry<String, Field> column : columns.entrySet()) {
      Field field = column.getValue();
      String fieldName = field.getName();
      Class<?> columnTypeClass = resolveResultJavaType(clazz, fieldName, null);
      List<ResultFlag> flags = Lists.newArrayList();
      if (field.isAnnotationPresent(Id.class)) {
        flags.add(ResultFlag.ID);
      }
      String columnName = column.getKey();
      resultMappings.add(
          buildResultMapping(configuration, fieldName, columnName, columnTypeClass, flags));
    }

    // 构建ResultMap
    ResultMap.Builder resultMapBuilder =
        new ResultMap.Builder(configuration, id, clazz, resultMappings);
    ResultMap rm = resultMapBuilder.build();
    // 放到缓存中
    configuration.addResultMap(rm);
    return rm;
  }
Example #22
0
  /** Initialize all options */
  static {
    logger.info("Initialize all options.");

    Field[] fields = Config.class.getDeclaredFields();
    for (Field field : fields) {
      if (field.isAnnotationPresent(Ora2PgOption.class)) {
        Ora2PgOption option = field.getAnnotation(Ora2PgOption.class);

        Builder builder = null;
        if (StringUtils.isEmpty(option.opt())) {
          builder = Option.builder();
        } else {
          builder = Option.builder(option.opt());
        }
        builder.longOpt(option.longOpt());

        if (option.hasArg()) {
          builder
              .hasArg(true)
              .argName(option.argName())
              .optionalArg(option.optionalArg())
              .type(option.type());
        } else {
          builder.hasArg(false);
        }

        OPTIONS.addOption(builder.desc(option.desc()).build());
      }
    }
  }
Example #23
0
 /**
  * 获取一组声明了特殊注解的字段
  *
  * @param ann 注解类型
  * @return 字段数组
  */
 public <AT extends Annotation> Field[] getFields(Class<AT> ann) {
   List<Field> fields = new LinkedList<Field>();
   for (Field f : this.getFields()) {
     if (f.isAnnotationPresent(ann)) fields.add(f);
   }
   return fields.toArray(new Field[fields.size()]);
 }
Example #24
0
  /**
   * get ViewHolder class and make reference for evert @link(DynamicViewId) to the actual view if
   * target contains HashMap<String, Integer> will replaced with the idsMap
   */
  public static void parseDynamicView(
      Object target, View container, HashMap<String, Integer> idsMap) {

    for (Field field : target.getClass().getDeclaredFields()) {
      if (field.isAnnotationPresent(DynamicViewId.class)) {
        /* if variable is annotated with @DynamicViewId */
        final DynamicViewId dynamicViewIdAnnotation = field.getAnnotation(DynamicViewId.class);
        /* get the Id of the view. if it is not set in annotation user the variable name */
        String id = dynamicViewIdAnnotation.id();
        if (id.equalsIgnoreCase("")) id = field.getName();
        if (idsMap.containsKey(id)) {
          try {
            /* get the view Id from the Hashmap and make the connection to the real View */
            field.set(target, container.findViewById(idsMap.get(id)));
          } catch (IllegalArgumentException e) {
          } catch (IllegalAccessException e) {
            e.printStackTrace();
          }
        }
      } else if ((field.getName().equalsIgnoreCase("ids"))
          && (field.getType() == idsMap.getClass())) {
        try {
          field.set(target, idsMap);
        } catch (IllegalArgumentException e) {
        } catch (IllegalAccessException e) {
          e.printStackTrace();
        }
      }
    }
  }
  /** Removed fields cache from original code. */
  protected static Collection<Field> getFields(Class<?> clazz) {
    Collection<Field> fields = ReflectUtil.getFields(clazz);
    Iterator<Field> iterator = fields.iterator();

    while (iterator.hasNext()) {
      Field field = iterator.next();
      if (!field.isAnnotationPresent(SpringBean.class)) {
        iterator.remove();
      } else if (!field.isAccessible()) {
        // If the field isn't public, try to make it accessible
        try {
          field.setAccessible(true);
        } catch (SecurityException se) {
          throw new StripesRuntimeException(
              "Field "
                  + clazz.getName()
                  + "."
                  + field.getName()
                  + "is marked "
                  + "with @SpringBean and is not public. An attempt to call "
                  + "setAccessible(true) resulted in a SecurityException. Please "
                  + "either make the field public, annotate a public setter instead "
                  + "or modify your JVM security policy to allow Stripes to "
                  + "setAccessible(true).",
              se);
        }
      }
    }

    return fields;
  }
 public CacheKeyFilter(Class<?> cachedClass) {
   for (Field field : cachedClass.getDeclaredFields()) {
     if (field.isAnnotationPresent(CacheKey.class)) {
       cachedKeys.add(field.getName());
     }
   }
 }
Example #27
0
  /**
   * Method to validate that the properties object has been correctly loaded
   *
   * @param props: The Properties object to validate
   * @return true if valid, false otherwise
   */
  private static boolean validateProps(Properties props) {
    /* Validate size */
    if (props != null && props.entrySet().size() == IndexerConstants.NUM_PROPERTIES) {
      /* Get all required properties and ensure they have been set */
      Field[] flds = IndexerConstants.class.getDeclaredFields();
      boolean valid = true;
      Object key;

      for (Field f : flds) {
        if (f.isAnnotationPresent(RequiredConstant.class)) {
          try {
            key = f.get(null);
            if (!props.containsKey(key) || props.get(key) == null) {
              System.err.println("The required property " + f.getName() + " is not set");
              valid = false;
            }
          } catch (IllegalArgumentException e) {

          } catch (IllegalAccessException e) {

          }
        }
      }

      return valid;
    }

    return false;
  }
 public static String collectSecureSettings(Context paramContext) {
   StringBuilder localStringBuilder = new StringBuilder();
   Field[] arrayOfField = Settings.Secure.class.getFields();
   int i = arrayOfField.length;
   int j = 0;
   while (true)
     if (j < i) {
       Field localField = arrayOfField[j];
       if ((!localField.isAnnotationPresent(Deprecated.class))
           && (localField.getType() == String.class)
           && (isAuthorized(localField))) ;
       try {
         String str =
             Settings.Secure.getString(
                 paramContext.getContentResolver(), (String) localField.get(null));
         if (str != null)
           localStringBuilder.append(localField.getName()).append("=").append(str).append("\n");
         j++;
       } catch (IllegalArgumentException localIllegalArgumentException) {
         while (true) Log.w(ACRA.LOG_TAG, "Error : ", localIllegalArgumentException);
       } catch (IllegalAccessException localIllegalAccessException) {
         while (true) Log.w(ACRA.LOG_TAG, "Error : ", localIllegalAccessException);
       }
     }
   return localStringBuilder.toString();
 }
  protected void retrieveClassModelStructure() {

    this.classHandleName = objectClassModel.getAnnotation(ObjectClass.class).name();

    fields = objectClassModel.getDeclaredFields();
    Map<Class, Coder> tmpMapCoder = new HashMap<Class, Coder>();
    Coder coderTmp = null;

    try {
      for (Field f : fields) {
        if (f.isAnnotationPresent(Attribute.class)) {
          coderTmp = tmpMapCoder.get(f.getAnnotation(Attribute.class).coder());
          if (coderTmp == null) {
            coderTmp = f.getAnnotation(Attribute.class).coder().newInstance();
            tmpMapCoder.put(f.getAnnotation(Attribute.class).coder(), coderTmp);
          }
          matchingObjectCoderIsValid(f, coderTmp);
          mapFieldCoder.put(f.getAnnotation(Attribute.class).name(), coderTmp);
        }
      }
    } catch (InstantiationException | IllegalAccessException e) {
      logger.error("Error in retreving the annotations of the fields");
      e.printStackTrace();
    } finally {
      tmpMapCoder = null;
      coderTmp = null;
    }
  }
    private Field getUniqueUiField(String alias) {
      Set<Field> resourceFields = GwtReflectionUtils.getFields(owner.getClass());
      if (resourceFields.size() == 0) {
        return null;
      }

      Field result = null;

      for (Field f : resourceFields) {
        if (alias.equals(f.getName()) && f.isAnnotationPresent(UiField.class)) {
          if (result != null) {
            throw new GwtTestUiBinderException(
                "There are more than one '"
                    + f.getName()
                    + "' @UiField in class '"
                    + owner.getClass().getName()
                    + "' or its superclass");
          }

          result = f;
        }
      }

      return result;
    }