Java Code Examples for org.reflections.ReflectionUtils

The following examples show how to use org.reflections.ReflectionUtils. These examples are extracted from open source projects. 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 Project: enode   Source File: AbstractHandlerProvider.java    License: MIT License 6 votes vote down vote up
private void registerHandler(Class<?> handlerType) {
    Set<Method> handleMethods = ReflectionUtils.getMethods(handlerType, this::isHandleMethodMatch);
    handleMethods.forEach(method -> {
        try {
            //反射Method转换为MethodHandle,提高效率
            MethodHandle handleMethod = lookup.findVirtual(handlerType, method.getName(), MethodType.methodType(method.getReturnType(), method.getParameterTypes()));
            TKey key = getKey(method);
            List<THandlerProxyInterface> handlers = handlerDict.computeIfAbsent(key, k -> new ArrayList<>());
            IObjectContainer objectContainer = getObjectContainer();
            if (objectContainer == null) {
                throw new IllegalArgumentException("IObjectContainer is null");
            }
            // prototype
            THandlerProxyInterface handlerProxy = objectContainer.resolve(getHandlerProxyImplementationType());
            if (handlerProxy == null) {
                throw new EnodeRuntimeException("THandlerProxyInterface is null, " + getHandlerProxyImplementationType().getName());
            }
            handlerProxy.setHandlerType(handlerType);
            handlerProxy.setMethod(method);
            handlerProxy.setMethodHandle(handleMethod);
            handlers.add(handlerProxy);
        } catch (Exception e) {
            throw new RegisterComponentException(e);
        }
    });
}
 
Example 2
Source Project: soundwave   Source File: EsPropertyNamingStrategy.java    License: 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 3
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
private static WebuiProcessClassInfo createWebuiProcessClassInfo(final Class<?> processClass) throws Exception
{
	final ProcessClassInfo processClassInfo = ProcessClassInfo.of(processClass);

	final WebuiProcess webuiProcessAnn = processClass.getAnnotation(WebuiProcess.class);

	@SuppressWarnings("unchecked")
	final Set<Method> lookupValuesProviderMethods = ReflectionUtils.getAllMethods(processClass, ReflectionUtils.withAnnotation(ProcessParamLookupValuesProvider.class));
	final ImmutableMap<String, LookupDescriptorProvider> paramLookupValuesProviders = lookupValuesProviderMethods.stream()
			.map(method -> createParamLookupValuesProvider(method))
			.collect(GuavaCollectors.toImmutableMap());

	//
	// Check is there were no settings at all so we could return our NULL instance
	if (ProcessClassInfo.isNull(processClassInfo)
			&& paramLookupValuesProviders.isEmpty())
	{
		return NULL;
	}

	return new WebuiProcessClassInfo(processClassInfo, webuiProcessAnn, paramLookupValuesProviders);
}
 
Example 5
private static final ViewActionDescriptorsList createFromClass(@NonNull final Class<?> clazz)
{
	final ActionIdGenerator actionIdGenerator = new ActionIdGenerator();

	@SuppressWarnings("unchecked")
	final Set<Method> viewActionMethods = ReflectionUtils.getAllMethods(clazz, ReflectionUtils.withAnnotation(ViewAction.class));
	final List<ViewActionDescriptor> viewActions = viewActionMethods.stream()
			.map(viewActionMethod -> {
				try
				{
					return createViewActionDescriptor(actionIdGenerator.getActionId(viewActionMethod), viewActionMethod);
				}
				catch (final Throwable ex)
				{
					logger.warn("Failed creating view action descriptor for {}. Ignored", viewActionMethod, ex);
					return null;
				}
			})
			.filter(actionDescriptor -> actionDescriptor != null)
			.collect(Collectors.toList());

	return ViewActionDescriptorsList.of(viewActions);
}
 
Example 6
Source Project: java-flagz   Source File: FlagFieldScanner.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Set<FlagField<?>> scanAndBind() {
  Set<FlagField<?>> fields = new HashSet<>();
  for (Object obj : objectsToScan) {
    ReflectionUtils.getAllFields(
        obj.getClass(),
        ReflectionUtils.withTypeAssignableTo(Flag.class),
        ReflectionUtils.withAnnotation(FlagInfo.class),
        ReflectionUtils.withModifier(Modifier.FINAL),
        not(ReflectionUtils.withModifier(Modifier.STATIC)))
        .stream()
        .map(f -> boundFlagField(f, obj))
        .forEach(fields::add);
  }
  return fields;
}
 
Example 7
Source Project: gravitee-gateway   Source File: ResourceFactory.java    License: Apache License 2.0 6 votes vote down vote up
private Constructor<? extends Resource> lookingForConstructor(Class<? extends Resource> resourceClass) {
    LOGGER.debug("Looking for a constructor to inject resource configuration");
    Constructor <? extends Resource> constructor = null;

    Set<Constructor> resourceConstructors =
            ReflectionUtils.getConstructors(resourceClass,
                    withModifier(Modifier.PUBLIC),
                    withParametersAssignableFrom(ResourceConfiguration.class),
                    withParametersCount(1));

    if (resourceConstructors.isEmpty()) {
        LOGGER.debug("No configuration can be injected for {} because there is no valid constructor. " +
                "Using default empty constructor.", resourceClass.getName());
        try {
            constructor = resourceClass.getConstructor();
        } catch (NoSuchMethodException nsme) {
            LOGGER.error("Unable to find default empty constructor for {}", resourceClass.getName(), nsme);
        }
    } else if (resourceConstructors.size() == 1) {
        constructor = resourceConstructors.iterator().next();
    } else {
        LOGGER.info("Too much constructors to instantiate resource {}", resourceClass.getName());
    }

    return constructor;
}
 
Example 8
Source Project: archie   Source File: ModelInfoLookup.java    License: Apache License 2.0 6 votes vote down vote up
private Method getAddMethod(Class clazz, TypeToken typeToken, Field field, String javaFieldNameUpperCased, Method getMethod) {
    Method addMethod = null;
    if (Collection.class.isAssignableFrom(getMethod.getReturnType())) {
        Type[] typeArguments = ((ParameterizedType) getMethod.getGenericReturnType()).getActualTypeArguments();
        if (typeArguments.length == 1) {
            TypeToken singularParameter = typeToken.resolveType(typeArguments[0]);
            //TODO: does this work or should we use the typeArguments[0].getSomething?
            String addMethodName = "add" + toSingular(javaFieldNameUpperCased);
            addMethod = getMethod(clazz, addMethodName, singularParameter.getRawType());
            if (addMethod == null) {
                //Due to generics, this does not always work
                Set<Method> allAddMethods = ReflectionUtils.getAllMethods(clazz, ReflectionUtils.withName(addMethodName));
                if (allAddMethods.size() == 1) {
                    addMethod = allAddMethods.iterator().next();
                } else {
                    logger.warn("strange number of add methods for field {} on class {}", field.getName(), clazz.getSimpleName());
                }
            }
        }
    }
    return addMethod;
}
 
Example 9
Source Project: gecco   Source File: JsonFieldRender.java    License: 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 10
Source Project: incubator-gobblin   Source File: GPGFileEncryptor.java    License: 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 11
Source Project: valdr-bean-validation   Source File: ConstraintParser.java    License: MIT License 6 votes vote down vote up
private Iterable<? extends Class<? extends Annotation>> getConfiguredCustomAnnotations() {
  return Iterables.transform(options.getCustomAnnotationClasses(), new Function<String,
    Class<? extends Annotation>>() {
    @Override
    @SuppressWarnings("unchecked")
    public Class<? extends Annotation> apply(String className) {
      Class<?> validatorClass = ReflectionUtils.forName(className);
      if (validatorClass.isAnnotation()) {
        return (Class<? extends Annotation>) validatorClass;
      } else {
        logger.warn("The configured custom annotation class '{}' is not an annotation. It will be ignored.",
          validatorClass);
        return null;
      }
    }
  });
}
 
Example 12
Source Project: chassis   Source File: AppMetadata.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
private Method findLifecycleMethod(final Class lifecycleAnnotationClass) {
       Set<Method> methods = ReflectionUtils.getMethods(declaringClass, new Predicate<Method>() {
           @Override
           public boolean apply(Method input) {
               return input != null && input.getAnnotation(lifecycleAnnotationClass) != null;
           }
       });
       if (methods.isEmpty()) {
           return null;
       }
       if (methods.size() > 1) {
           throw new BootstrapException("Found multiple " + lifecycleAnnotationClass.getSimpleName() + " methods in class " + declaringClass.getSimpleName() + ". Only 1 is allowed.");
       }
       return methods.iterator().next();
   }
 
Example 13
Source Project: streams   Source File: StreamsScalaSourceGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private String renderTrait(Class<?> pojoClass) {
  StringBuffer stringBuffer = new StringBuffer();
  stringBuffer.append("package ");
  stringBuffer.append(pojoClass.getPackage().getName().replace(".pojo.json", ".scala"));
  stringBuffer.append(".traits");
  stringBuffer.append(LS);
  stringBuffer.append("trait ").append(pojoClass.getSimpleName());
  stringBuffer.append(" extends Serializable");
  stringBuffer.append(" {");

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

  stringBuffer.append("}");

  return stringBuffer.toString();
}
 
Example 14
Source Project: streams   Source File: StreamsScalaSourceGenerator.java    License: 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 15
Source Project: xcelite   Source File: ColumnsExtractor.java    License: 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 16
Source Project: cloudbreak   Source File: RepositoryRestrictionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
@DisplayName("Testing if environment module's components are using the repositories trough delegated method(s) from the related service")
void testForSingleRepositoryUsage() {
    Set<Class<? extends Repository>> repos = getRepos();
    Set<Class<?>> compos = getServicesAndComponents();
    repos.forEach(repo -> {
        AtomicLong count = new AtomicLong(0);
        Set<String> compoNames = new LinkedHashSet<>();
        compos.forEach(service -> {
            Set<? extends Class<?>> injectedFields = ReflectionUtils.getFields(service)
                    .stream()
                    .map(Field::getType)
                    .collect(toSet());
            if (injectedFields.stream().anyMatch(fieldClass -> fieldClass.equals(repo))) {
                count.addAndGet(1L);
                compoNames.add(service.getSimpleName());
            }
        });
        Assertions.assertTrue(count.get() <= 1, getExceptionMessage(repo.getSimpleName(), compoNames));
    });
}
 
Example 17
Source Project: cloudbreak   Source File: RepositoryRestrictionTest.java    License: Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@SuppressWarnings("unchecked")
@MethodSource("testDataProvider")
@DisplayName("Testing if core module's components are using the repositories trough delegated method(s) from the related service")
void testForSingleRepositoryUsage(String basePath) {
    Set<Class<? extends Repository>> repos = getRepos(basePath);
    Set<Class<?>> compos = getServicesAndComponents(basePath);
    repos.forEach(repo -> {
        AtomicLong count = new AtomicLong(0);
        Set<String> compoNames = new LinkedHashSet<>();
        compos.forEach(service -> {
            Set<? extends Class<?>> injectedFields = ReflectionUtils.getFields(service)
                    .stream()
                    .filter(this::isFieldInjected)
                    .map(Field::getType)
                    .collect(toSet());
            if (injectedFields.stream().anyMatch(fieldClass -> fieldClass.equals(repo))) {
                count.addAndGet(1L);
                compoNames.add(service.getSimpleName());
            }
        });
        Assertions.assertTrue(count.get() <= 1, getExceptionMessage(repo.getSimpleName(), compoNames));
    });
}
 
Example 18
Source Project: cloudstack   Source File: ConfigDriveBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@PrepareForTest({ConfigDriveBuilder.class})
@Test(expected = CloudRuntimeException.class)
public void buildConfigDriveTestIoException() throws Exception {
    PowerMockito.mockStatic(ConfigDriveBuilder.class);

    Method method1 = ReflectionUtils.getMethods(ConfigDriveBuilder.class, ReflectionUtils.withName("writeFile")).iterator().next();
    Method method = ReflectionUtils.getMethods(ConfigDriveBuilder.class, ReflectionUtils.withName("writeVendorAndNetworkEmptyJsonFile")).iterator().next();

    PowerMockito.when(ConfigDriveBuilder.class, method).withArguments(nullable(File.class)).thenThrow(CloudRuntimeException.class);

    //This is odd, but it was necessary to allow us to check if we catch the IOexception and re-throw as a CloudRuntimeException
    //We are mocking the class being tested; therefore, we needed to force the execution of the real method we want to test.
    PowerMockito.when(ConfigDriveBuilder.class, new ArrayList<>(), "teste", "C:").thenCallRealMethod();

    ConfigDriveBuilder.buildConfigDrive(new ArrayList<>(), "teste", "C:");
}
 
Example 19
Source Project: cloudstack   Source File: ConfigDriveBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
@PrepareForTest({ConfigDriveBuilder.class})
public void writeVmMetadataTest() throws Exception {
    PowerMockito.mockStatic(ConfigDriveBuilder.class);

    Method method = getWriteVmMetadataMethod();
    PowerMockito.when(ConfigDriveBuilder.class, method).withArguments(Mockito.anyListOf(String[].class), anyString(), any(File.class)).thenCallRealMethod();

    Method createJsonObjectWithVmDataMethod = ReflectionUtils.getMethods(ConfigDriveBuilder.class, ReflectionUtils.withName("createJsonObjectWithVmData")).iterator().next();

    PowerMockito.when(ConfigDriveBuilder.class, createJsonObjectWithVmDataMethod).withArguments(Mockito.anyListOf(String[].class), Mockito.anyString()).thenReturn(new JsonObject());

    List<String[]> vmData = new ArrayList<>();
    vmData.add(new String[] {"dataType", "fileName", "content"});
    vmData.add(new String[] {"dataType2", "fileName2", "content2"});

    ConfigDriveBuilder.writeVmMetadata(vmData, "metadataFile", new File("folder"));

    PowerMockito.verifyStatic(ConfigDriveBuilder.class);
    ConfigDriveBuilder.createJsonObjectWithVmData(vmData, "metadataFile");
    ConfigDriveBuilder.writeFile(Mockito.any(File.class), Mockito.eq("meta_data.json"), Mockito.eq("{}"));
}
 
Example 20
Source Project: cloudstack   Source File: ConfigDriveBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test(expected = CloudRuntimeException.class)
@PrepareForTest({Script.class, ConfigDriveBuilder.class})
public void generateAndRetrieveIsoAsBase64IsoTestGenIsoFailure() throws Exception {
    PowerMockito.mockStatic(Script.class, ConfigDriveBuilder.class);

    Script scriptMock = Mockito.mock(Script.class);
    PowerMockito.whenNew(Script.class).withAnyArguments().thenReturn(scriptMock);

    Mockito.doReturn("scriptMessage").when(scriptMock).execute();

    Method method = ReflectionUtils.getMethods(ConfigDriveBuilder.class, ReflectionUtils.withName("generateAndRetrieveIsoAsBase64Iso")).iterator().next();
    PowerMockito.when(ConfigDriveBuilder.class, method).withArguments(nullable(String.class), nullable(String.class), nullable(String.class)).thenCallRealMethod();

    Method getProgramToGenerateIsoMethod = ReflectionUtils.getMethods(ConfigDriveBuilder.class, ReflectionUtils.withName("getProgramToGenerateIso")).iterator().next();
    PowerMockito.when(ConfigDriveBuilder.class, getProgramToGenerateIsoMethod).withNoArguments().thenReturn("/usr/bin/genisoimage");

    ConfigDriveBuilder.generateAndRetrieveIsoAsBase64Iso("isoFileName", "driveLabel", "tempDirName");
}
 
Example 21
Source Project: cloudstack   Source File: ConfigDriveBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test(expected = CloudRuntimeException.class)
@PrepareForTest({File.class, Script.class, ConfigDriveBuilder.class})
public void generateAndRetrieveIsoAsBase64IsoTestIsoTooBig() throws Exception {
    PowerMockito.mockStatic(File.class, Script.class, ConfigDriveBuilder.class);

    File fileMock = Mockito.mock(File.class);
    PowerMockito.whenNew(File.class).withAnyArguments().thenReturn(fileMock);

    Script scriptMock = Mockito.mock(Script.class);
    PowerMockito.whenNew(Script.class).withAnyArguments().thenReturn(scriptMock);

    Mockito.doReturn(StringUtils.EMPTY).when(scriptMock).execute();
    Mockito.doReturn(64L * 1024L * 1024L + 1l).when(fileMock).length();

    Method method = ReflectionUtils.getMethods(ConfigDriveBuilder.class, ReflectionUtils.withName("generateAndRetrieveIsoAsBase64Iso")).iterator().next();
    PowerMockito.when(ConfigDriveBuilder.class, method).withArguments(nullable(String.class), nullable(String.class), nullable(String.class)).thenCallRealMethod();

    Method getProgramToGenerateIsoMethod = ReflectionUtils.getMethods(ConfigDriveBuilder.class, ReflectionUtils.withName("getProgramToGenerateIso")).iterator().next();
    PowerMockito.when(ConfigDriveBuilder.class, getProgramToGenerateIsoMethod).withNoArguments().thenReturn("/usr/bin/genisoimage");

    ConfigDriveBuilder.generateAndRetrieveIsoAsBase64Iso("isoFileName", "driveLabel", "tempDirName");
}
 
Example 22
Source Project: cloudstack   Source File: ConfigDriveBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
@PrepareForTest({ConfigDriveBuilder.class})
public void createJsonObjectWithVmDataTesT() throws Exception {
    PowerMockito.mockStatic(ConfigDriveBuilder.class);

    Method method = ReflectionUtils.getMethods(ConfigDriveBuilder.class, ReflectionUtils.withName("createJsonObjectWithVmData")).iterator().next();
    PowerMockito.when(ConfigDriveBuilder.class, method).withArguments(Mockito.anyListOf(String[].class), Mockito.anyString()).thenCallRealMethod();

    List<String[]> vmData = new ArrayList<>();
    vmData.add(new String[] {"dataType", "fileName", "content"});
    vmData.add(new String[] {"dataType2", "fileName2", "content2"});

    ConfigDriveBuilder.createJsonObjectWithVmData(vmData, "tempDirName");

    PowerMockito.verifyStatic(ConfigDriveBuilder.class, Mockito.times(1));
    ConfigDriveBuilder.createFileInTempDirAnAppendOpenStackMetadataToJsonObject(Mockito.eq("tempDirName"), Mockito.any(JsonObject.class), Mockito.eq("dataType"), Mockito.eq("fileName"),
            Mockito.eq("content"));
    ConfigDriveBuilder.createFileInTempDirAnAppendOpenStackMetadataToJsonObject(Mockito.eq("tempDirName"), Mockito.any(JsonObject.class), Mockito.eq("dataType2"), Mockito.eq("fileName2"),
            Mockito.eq("content2"));
}
 
Example 23
Source Project: soundwave   Source File: ObjectAdapter.java    License: 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 24
private Constructor<?> lookingForConstructor(Class<?> policyClass) {
    Constructor constructor = constructors.get(policyClass);
    if (constructor == null) {
        logger.debug("Looking for a constructor to inject policy configuration");

        Set<Constructor> policyConstructors =
                ReflectionUtils.getConstructors(policyClass,
                        withModifier(Modifier.PUBLIC),
                        withParametersAssignableFrom(PolicyConfiguration.class),
                        withParametersCount(1));

        if (policyConstructors.isEmpty()) {
            logger.debug("No configuration can be injected for {} because there is no valid constructor. " +
                    "Using default empty constructor.", policyClass.getName());
            try {
                constructor = policyClass.getConstructor();
            } catch (NoSuchMethodException nsme) {
                logger.error("Unable to find default empty constructor for {}", policyClass.getName(), nsme);
            }
        } else if (policyConstructors.size() == 1) {
            constructor = policyConstructors.iterator().next();
        } else {
            logger.info("Too much constructors to instantiate policy {}", policyClass.getName());
        }

        constructors.put(policyClass, constructor);
    }

    return constructor;
}
 
Example 25
Source Project: genericdao   Source File: JPAUtil.java    License: Artistic License 2.0 5 votes vote down vote up
/**
 * 获取实体中所有简单的数据库映射字段
 */
public static List<String> getSimpleORMFieldInEntity(Class entityClass){
	if(entityClass==null){
		return null ;
	}
	//获取所有声明的字段
	Set<Field> fields = ReflectionUtils.getAllFields(entityClass) ;
	List<String> simpleFields = new ArrayList<String>() ;
	for (Field field : fields) {
		if(isSimpleORMField(field)){
			simpleFields.add(field.getName()) ;
		}
	}
	return simpleFields ;
}
 
Example 26
Source Project: rest-schemagen   Source File: BeanParamExtractor.java    License: 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 27
Source Project: gravitee-gateway   Source File: PolicyFactoryImpl.java    License: Apache License 2.0 5 votes vote down vote up
private Constructor<?> lookingForConstructor(Class<?> policyClass) {
    Constructor constructor = constructors.get(policyClass);
    if (constructor == null) {
        LOGGER.debug("Looking for a constructor to inject policy configuration");

        Set<Constructor> policyConstructors =
                ReflectionUtils.getConstructors(policyClass,
                        withModifier(Modifier.PUBLIC),
                        withParametersAssignableFrom(PolicyConfiguration.class),
                        withParametersCount(1));

        if (policyConstructors.isEmpty()) {
            LOGGER.debug("No configuration can be injected for {} because there is no valid constructor. " +
                    "Using default empty constructor.", policyClass.getName());
            try {
                constructor = policyClass.getConstructor();
            } catch (NoSuchMethodException nsme) {
                LOGGER.error("Unable to find default empty constructor for {}", policyClass.getName(), nsme);
            }
        } else if (policyConstructors.size() == 1) {
            constructor = policyConstructors.iterator().next();
        } else {
            LOGGER.info("Too much constructors to instantiate policy {}", policyClass.getName());
        }

        constructors.put(policyClass, constructor);
    }

    return constructor;
}
 
Example 28
Source Project: gravitee-gateway   Source File: PolicyTest.java    License: Apache License 2.0 5 votes vote down vote up
private Method resolvePolicyMethod(Class<?> clazz, Class<? extends Annotation> annotationClass) {
    Set<Method> methods = ReflectionUtils.getMethods(
            clazz,
            withModifier(Modifier.PUBLIC),
            withAnnotation(annotationClass));

    if (methods.isEmpty()) {
        return null;
    }

    return methods.iterator().next();
}
 
Example 29
Source Project: archie   Source File: ModelInfoLookup.java    License: 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 30
Source Project: gecco   Source File: RequestFieldRender.java    License: 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);
	}
}