Java Code Examples for org.reflections.ReflectionUtils#getAllFields()

The following examples show how to use org.reflections.ReflectionUtils#getAllFields() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: StreamsScalaSourceGenerator.java    From streams with Apache License 2.0 6 votes vote down vote up
private String renderCase(Class<?> pojoClass) {
  StringBuffer stringBuffer = new StringBuffer();
  stringBuffer.append("package ");
  stringBuffer.append(pojoClass.getPackage().getName().replace(".pojo.json", ".scala"));
  stringBuffer.append(LS);
  stringBuffer.append("case class " + pojoClass.getSimpleName());
  stringBuffer.append("(");
  Set<Field> fields = ReflectionUtils.getAllFields(pojoClass);
  appendFields(stringBuffer, fields, "var", ",");
  stringBuffer.append(")");
  if ( pojoClass.getSuperclass() != null && !pojoClass.getSuperclass().equals(java.lang.Object.class)) {
    stringBuffer.append(" extends " + pojoClass.getSuperclass().getPackage().getName().replace(".pojo.json", ".scala") + ".traits." + pojoClass.getSuperclass().getSimpleName());
  }
  stringBuffer.append(LS);

  return stringBuffer.toString();
}
 
Example 2
Source File: ColumnsExtractor.java    From xcelite with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void extractAnyColumn() {
  Set<Field> anyColumnFields = ReflectionUtils.getAllFields(type, withAnnotation(AnyColumn.class));    
  if (anyColumnFields.size() > 0) {
    if (anyColumnFields.size() > 1) {
      throw new XceliteException("Multiple AnyColumn fields are not allowed");
    }
    Field anyColumnField = anyColumnFields.iterator().next();
    if (!anyColumnField.getType().isAssignableFrom(Map.class)) {
      throw new XceliteException(
          String.format("AnyColumn field \"%s\" should be of type Map.class or assignable from Map.class",
              anyColumnField.getName()));
    }
    anyColumn = new Col(anyColumnField.getName(), anyColumnField.getName());
    anyColumn.setAnyColumn(true);
    AnyColumn annotation = anyColumnField.getAnnotation(AnyColumn.class);
    anyColumn.setType(annotation.as());
    if (annotation.converter() != NoConverterClass.class) {
      anyColumn.setConverter(annotation.converter());
    }
  }    
}
 
Example 3
Source File: ViewColumnHelper.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 6 votes vote down vote up
private static ClassViewDescriptor createClassViewDescriptor(@NonNull final Class<?> dataType)
{
	@SuppressWarnings("unchecked")
	final Set<Field> fields = ReflectionUtils.getAllFields(dataType, ReflectionUtils.withAnnotations(ViewColumn.class));

	final ImmutableList<ClassViewColumnDescriptor> columns = fields.stream()
			.map(field -> createClassViewColumnDescriptor(field))
			.collect(ImmutableList.toImmutableList());
	if (columns.isEmpty())
	{
		return ClassViewDescriptor.EMPTY;
	}

	return ClassViewDescriptor.builder()
			.columns(columns)
			.build();

}
 
Example 4
Source File: GPGFileEncryptor.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * Convert a string cipher name to the integer tag used by GPG
 * @param cipherName the cipher name
 * @return integer tag for the cipher
 */
private static int symmetricKeyAlgorithmNameToTag(String cipherName) {
  // Use CAST5 if no cipher specified
  if (StringUtils.isEmpty(cipherName)) {
    return PGPEncryptedData.CAST5;
  }

  Set<Field> fields = ReflectionUtils.getAllFields(PGPEncryptedData.class, ReflectionUtils.withName(cipherName));

  if (fields.isEmpty()) {
    throw new RuntimeException("Could not find tag for cipher name " + cipherName);
  }

  try {
    return fields.iterator().next().getInt(null);
  } catch (IllegalAccessException e) {
    throw new RuntimeException("Could not access field " + cipherName, e);
  }
}
 
Example 5
Source File: JsonFieldRender.java    From gecco with MIT License 6 votes vote down vote up
@Override
@SuppressWarnings({ "unchecked" })
public void render(HttpRequest request, HttpResponse response, BeanMap beanMap, SpiderBean bean) {
	Map<String, Object> fieldMap = new HashMap<String, Object>();
	Set<Field> jsonPathFields = ReflectionUtils.getAllFields(bean.getClass(), ReflectionUtils.withAnnotation(JSONPath.class));
	String jsonStr = response.getContent();
	jsonStr = jsonp2Json(jsonStr);
	if (jsonStr == null) {
		return;
	}
	try {
		Object json = JSON.parse(jsonStr);
		for (Field field : jsonPathFields) {
			Object value = injectJsonField(request, field, json);
			if(value != null) {
				fieldMap.put(field.getName(), value);
			}
		}
	} catch(JSONException ex) {
		//throw new RenderException(ex.getMessage(), bean.getClass());
		RenderException.log("json parse error : " + request.getUrl(), bean.getClass(), ex);
	}
	beanMap.putAll(fieldMap);
}
 
Example 6
Source File: EsPropertyNamingStrategy.java    From soundwave with Apache License 2.0 6 votes vote down vote up
public EsPropertyNamingStrategy(Class type, Class<? extends EsStore> store) {
  this.effectiveType = type;

  for (Field field : ReflectionUtils.getAllFields(type)) {
    JsonProperty jsonProperty = field.getAnnotation(JsonProperty.class);
    EsStoreMappingProperty
        storeSpecificProperty =
        field.getAnnotation(EsStoreMappingProperty.class);

    if ((jsonProperty == null && storeSpecificProperty == null)
        || (storeSpecificProperty != null && storeSpecificProperty.ignore())) {
      continue;
    }

    if (storeSpecificProperty == null || storeSpecificProperty.store() != store) {
      fieldToJsonMapping.put(jsonProperty.value(), jsonProperty.value());
    } else if (storeSpecificProperty.value().indexOf('.') < 0) {
      fieldToJsonMapping.put(jsonProperty.value(), storeSpecificProperty.value());
    }
  }
}
 
Example 7
Source File: RequestFieldRender.java    From gecco with MIT License 5 votes vote down vote up
@Override
@SuppressWarnings({"unchecked" })
public void render(HttpRequest request, HttpResponse response, BeanMap beanMap, SpiderBean bean) {
	Set<Field> requestFields = ReflectionUtils.getAllFields(bean.getClass(), ReflectionUtils.withAnnotation(Request.class));
	for(Field field : requestFields) {
		beanMap.put(field.getName(), request);
	}
}
 
Example 8
Source File: StreamsScalaSourceGenerator.java    From streams with Apache License 2.0 5 votes vote down vote up
private String renderClass(Class<?> pojoClass) {
  StringBuffer stringBuffer = new StringBuffer();
  stringBuffer.append("package ");
  stringBuffer.append(pojoClass.getPackage().getName().replace(".pojo.json", ".scala"));
  stringBuffer.append(LS);
  stringBuffer.append("import org.apache.commons.lang.builder.{HashCodeBuilder, EqualsBuilder, ToStringBuilder}");
  stringBuffer.append(LS);
  stringBuffer.append("class ").append(pojoClass.getSimpleName());
  stringBuffer.append(" (");

  Set<Field> fields = ReflectionUtils.getAllFields(pojoClass);
  appendFields(stringBuffer, fields, "var", ",");

  stringBuffer.append(")");
  stringBuffer.append(" extends ").append(pojoClass.getPackage().getName().replace(".pojo.json", ".scala")).append(".traits.").append(pojoClass.getSimpleName());
  stringBuffer.append(" with Serializable ");
  stringBuffer.append("{ ");
  stringBuffer.append(LS);
  stringBuffer.append("override def equals(obj: Any) = obj match { ");
  stringBuffer.append(LS);
  stringBuffer.append("  case other: ");
  stringBuffer.append(pojoClass.getSimpleName());
  stringBuffer.append(" => other.getClass == getClass && EqualsBuilder.reflectionEquals(this,obj)");
  stringBuffer.append(LS);
  stringBuffer.append("  case _ => false");
  stringBuffer.append(LS);
  stringBuffer.append("}");
  stringBuffer.append(LS);
  stringBuffer.append("override def hashCode = new HashCodeBuilder().hashCode");
  stringBuffer.append(LS);
  stringBuffer.append("}");

  return stringBuffer.toString();
}
 
Example 9
Source File: AnnotatedClass.java    From valdr-bean-validation with MIT License 5 votes vote down vote up
/**
 * Parses all fields and builds validation rules for those with relevant annotations.
 *
 * @return validation rules for all fields that have at least one rule
 * @see AnnotatedClass(Class, Iterable)
 */
ClassConstraints extractValidationRules() {
  final ClassConstraints classConstraints = new ClassConstraints();
  Set<Field> allFields = ReflectionUtils.getAllFields(clazz, buildAnnotationsPredicate());
  for (Field field : allFields) {
    if (isNotExcluded(field)) {
      FieldConstraints fieldValidationRules = new AnnotatedField(field,
        relevantAnnotationClasses).extractValidationRules();
      if (fieldValidationRules.size() > 0) {
        classConstraints.put(field.getName(), fieldValidationRules);
      }
    }
  }
  return classConstraints;
}
 
Example 10
Source File: AjaxFieldRender.java    From gecco with MIT License 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void render(HttpRequest request, HttpResponse response, BeanMap beanMap, SpiderBean bean) {
	Map<String, Object> fieldMap = new HashMap<String, Object>();
	Set<Field> ajaxFields = ReflectionUtils.getAllFields(bean.getClass(), ReflectionUtils.withAnnotation(Ajax.class));
	for (Field ajaxField : ajaxFields) {
		Object value = injectAjaxField(request, beanMap, ajaxField);
		if(value != null) {
			fieldMap.put(ajaxField.getName(), value);
		}
	}
	beanMap.putAll(fieldMap);
}
 
Example 11
Source File: JSVarFieldRender.java    From gecco with MIT License 5 votes vote down vote up
@Override
@SuppressWarnings({ "unchecked" })
public void render(HttpRequest request, HttpResponse response, BeanMap beanMap, SpiderBean bean) {
	Context cx = Context.enter();
	ScriptableObject scope = cx.initSafeStandardObjects();
	String windowScript = "var window = {};var document = {};";
	cx.evaluateString(scope, windowScript, "window", 1, null);
	HtmlParser parser = new HtmlParser(request.getUrl(), response.getContent());
	for (Element ele : parser.$("script")) {
		String sc = ele.html();
		if (StringUtils.isNotEmpty(sc)) {
			try {
				cx.evaluateString(scope, sc, "", 1, null);
			} catch (Exception ex) {
				// ex.printStackTrace();
			}
		}
	}
	Map<String, Object> fieldMap = new HashMap<String, Object>();
	Set<Field> jsVarFields = ReflectionUtils.getAllFields(bean.getClass(), ReflectionUtils.withAnnotation(JSVar.class));
	for (Field jsVarField : jsVarFields) {
		Object value = injectJsVarField(request, beanMap, jsVarField, cx, scope);
		if(value != null) {
			fieldMap.put(jsVarField.getName(), value);
		}
	}
	beanMap.putAll(fieldMap);
	Context.exit();
}
 
Example 12
Source File: ImageFieldRender.java    From gecco with MIT License 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void render(HttpRequest request, HttpResponse response, BeanMap beanMap, SpiderBean bean) {
	Map<String, Object> fieldMap = new HashMap<String, Object>();
	Set<Field> imageFields = ReflectionUtils.getAllFields(bean.getClass(), ReflectionUtils.withAnnotation(Image.class));
	for (Field imageField : imageFields) {
		Object value = injectImageField(request, beanMap, bean, imageField);
		if(value != null) {
			fieldMap.put(imageField.getName(), value);
		}
	}
	beanMap.putAll(fieldMap);
}
 
Example 13
Source File: HtmlFieldRender.java    From gecco with MIT License 5 votes vote down vote up
@Override
public void render(HttpRequest request, HttpResponse response, BeanMap beanMap, SpiderBean bean) {
	Map<String, Object> fieldMap = new HashMap<String, Object>();
	Set<Field> htmlFields = ReflectionUtils.getAllFields(bean.getClass(), ReflectionUtils.withAnnotation(HtmlField.class));
	for (Field htmlField : htmlFields) {
		Object value = injectHtmlField(request, response, htmlField, bean.getClass());
		if(value != null) {
			fieldMap.put(htmlField.getName(), value);
		}
	}
	beanMap.putAll(fieldMap);
}
 
Example 14
Source File: ModelInfoLookup.java    From archie with Apache License 2.0 5 votes vote down vote up
private void addAttributeInfo(Class clazz, RMTypeInfo typeInfo) {
    //TODO: it's possible to constrain some method as well. should we do that here too?
    TypeToken typeToken = TypeToken.of(clazz);

    for(Field field: ReflectionUtils.getAllFields(clazz)) {
        addRMAttributeInfo(clazz, typeInfo, typeToken, field);
    }
}
 
Example 15
Source File: BeanParamExtractor.java    From rest-schemagen with Apache License 2.0 5 votes vote down vote up
private <A extends Annotation> Multimap<String, Object> getQueryParameters(Object bean,
        Class<A> annotationClass, Function<A, String> parameterNameExtractor,
        boolean useTemplate) {
    Multimap<String, Object> result = ArrayListMultimap.create();
    if (bean != null) {
        @SuppressWarnings("unchecked")
        Set<Field> fields = ReflectionUtils.getAllFields(bean.getClass(), f -> f
                .isAnnotationPresent(annotationClass));
        for (Field field : fields) {
            A annotation = field.getAnnotation(annotationClass);
            if (!field.isAccessible()) {
                field.setAccessible(true);
                logger.trace("bean parameter field {} is not public", field.getName());
            }
            try {
                String parameterName = parameterNameExtractor.apply(annotation);

                Object parameterValue = field.get(bean);
                if (parameterValue != null) {
                    if (parameterValue instanceof Iterable) {
                        result.putAll(parameterName, (Iterable<?>) parameterValue);
                    } else {
                        result.put(parameterName, parameterValue);
                    }
                } else if (useTemplate) {
                    result.put(parameterName, "{" + parameterName + "}");
                }
            } catch (IllegalAccessException e) {
                throw new IllegalStateException(e);
            }
        }
    }
    return result;
}
 
Example 16
Source File: ColumnsExtractor.java    From xcelite with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public void extract() {    
  Set<Field> columnFields = ReflectionUtils.getAllFields(type, withAnnotation(Column.class));
  for (Field columnField : columnFields) {
    Column annotation = columnField.getAnnotation(Column.class);
    Col col = null;
    if (annotation.name().isEmpty()) {
      col = new Col(columnField.getName(), columnField.getName());        
    } else {
      col = new Col(annotation.name(), columnField.getName());        
    }      
    
    if (annotation.ignoreType()) {
      col.setType(String.class);
    } else {
      col.setType(columnField.getType());
    }
    if (!annotation.dataFormat().isEmpty()) {
      col.setDataFormat(annotation.dataFormat());
    }
    if (annotation.converter() != NoConverterClass.class) {
      col.setConverter(annotation.converter());
    }
    columns.add(col);
  }   
  
  if (colsOrdering != null) {
    orderColumns();
  }
  
  extractAnyColumn();
}
 
Example 17
Source File: ObjectAdapter.java    From soundwave with Apache License 2.0 5 votes vote down vote up
public static Map<String, Field> getAllFields(Class classType) {
  if (!classAllFieldsCache.containsKey(classType)) {
    Set<Field> objectFieldsSet = ReflectionUtils.getAllFields(classType);
    Map<String, Field> objectFieldsMap = new HashMap<>();
    for (Field f : objectFieldsSet) {
      objectFieldsMap.put(f.getName(), f);
    }
    classAllFieldsCache.put(classType, objectFieldsMap);
  }
  return classAllFieldsCache.get(classType);
}
 
Example 18
Source File: ResourceFactory.java    From gravitee-gateway with Apache License 2.0 4 votes vote down vote up
private Set<Field> lookingForInjectableFields(Class<?> resourceClass) {
    return ReflectionUtils.getAllFields(resourceClass, withAnnotation(Inject.class));
}
 
Example 19
Source File: UiFormSchemaGenerator.java    From sf-java-ui with MIT License 4 votes vote down vote up
public UiForm generate(Class<? extends Serializable> formDto) throws JsonMappingException {
	Set<Field> declaredFields = ReflectionUtils.getAllFields(formDto,
			field -> !Modifier.isStatic(field.getModifiers()));
	ObjectMapper mapper = new ObjectMapper();

	JsonSchemaGenerator schemaGen = initSchemaGen(mapper);
	JsonSchema schema = generateSchema(formDto, schemaGen);

	Map<Field, JsonNode> nodes = initFieldsFormDefinition(mapper, declaredFields);

	Map<Field, JsonNode> sortedNodes = reorderFieldsBasedOnIndex(nodes);

	handlerGroupedFields(mapper, declaredFields, sortedNodes);

	Optional<ObjectNode> tabbedFields = Optional
			.ofNullable(handleTabbedFields(mapper, declaredFields, sortedNodes));

	ArrayNode formDefinition = mapper.createArrayNode();
	tabbedFields.ifPresent(formDefinition::add);
	sortedNodes.entrySet().stream().forEach(nodesElement -> formDefinition.add(nodesElement.getValue()));

	handleActionsAnnotation(mapper, formDto, formDefinition);

	return new UiForm(schema, formDefinition);
}
 
Example 20
Source File: EsMapper.java    From soundwave with Apache License 2.0 4 votes vote down vote up
/**
 * Get the fields for a particular ES index. It uses JsonProperty field value if no specific
 * EsStoreMappingProperty is set
 * @param type
 * @param store
 * @return
 */
public static String[] getIncludeFields(Class type, Class<? extends EsStore> store) {
  String key = String.format("%s_%s", type.getTypeName(), store.getTypeName());
  String[] ret = fieldsCache.get(key);
  if (ret == null) {
    List<String> fields = new ArrayList<>();
    for (Field field : ReflectionUtils.getAllFields(type)) {
      JsonProperty jsonProperty = field.getAnnotation(JsonProperty.class);
      EsStoreMappingProperty
          storeSpecificProperty =
          field.getAnnotation(EsStoreMappingProperty.class);

      if ((jsonProperty == null && storeSpecificProperty == null)
          || (storeSpecificProperty != null && storeSpecificProperty.ignore())) {
        //Either has no Json Property or it is set to ignore
        continue;
      }

      if (storeSpecificProperty == null
          || (storeSpecificProperty.store() != store && !storeSpecificProperty.store()
              .isAssignableFrom(store))) {
        //No store set. Just use json property
        //Or the store class in store property is not the same as the current store or a
        // superclass for the store.
        fields.add(jsonProperty.value());
      } else {
        int idx = storeSpecificProperty.value().indexOf('.');
        if (idx > 0) {
          fields.add(storeSpecificProperty.value().substring(0, idx));
        } else {
          fields.add(storeSpecificProperty.value());
        }
      }
    }
    fields = ImmutableSet.copyOf(fields).asList();
    ret = new String[fields.size()];
    ret = fields.toArray(ret);
    fieldsCache.put(key, ret);
  }
  return ret;
}