org.reflections.ReflectionUtils Java Examples

The following examples show how to use org.reflections.ReflectionUtils. 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: 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 #3
Source File: AbstractHandlerProvider.java    From enode with 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 #4
Source File: ConfigDriveBuilderTest.java    From cloudstack with 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 #5
Source File: ConfigDriveBuilderTest.java    From cloudstack with 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 #6
Source File: ConstraintParser.java    From valdr-bean-validation with 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 #7
Source File: AppMetadata.java    From chassis with 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 #8
Source File: StreamsScalaSourceGenerator.java    From streams with 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 #9
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 #10
Source File: ModelInfoLookup.java    From archie with 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 #11
Source File: ConfigDriveBuilderTest.java    From cloudstack with 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 #12
Source File: ResourceFactory.java    From gravitee-gateway with 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 #13
Source File: WebuiProcessClassInfo.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 6 votes vote down vote up
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 #14
Source File: ConfigDriveBuilderTest.java    From cloudstack with 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 #15
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 #16
Source File: ConfigDriveBuilderTest.java    From cloudstack with 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 #17
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 #18
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 #19
Source File: ViewActionDescriptorsFactory.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 6 votes vote down vote up
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 #20
Source File: RepositoryRestrictionTest.java    From cloudbreak with 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 #21
Source File: FlagFieldScanner.java    From java-flagz with 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 #22
Source File: RepositoryRestrictionTest.java    From cloudbreak with 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 #23
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 #24
Source File: ConfigDriveBuilderTest.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test(expected = CloudRuntimeException.class)
public void writeFileTestwriteFileTestIOExceptionWhileWritingFile() throws Exception {
    PowerMockito.mockStatic(FileUtils.class);

    //Does not look good, I know... but this is the price of static methods.
    Method method = ReflectionUtils.getMethods(FileUtils.class, ReflectionUtils.withParameters(File.class, CharSequence.class, Charset.class, Boolean.TYPE)).iterator().next();
    PowerMockito.when(FileUtils.class, method).withArguments(Mockito.any(File.class), Mockito.anyString(), Mockito.any(Charset.class), Mockito.anyBoolean()).thenThrow(IOException.class);

    ConfigDriveBuilder.writeFile(new File("folder"), "subfolder", "content");
}
 
Example #25
Source File: AnnotatedClass.java    From valdr-bean-validation with MIT License 5 votes vote down vote up
private Predicate<? super Field> buildAnnotationsPredicate() {
  Collection<Predicate<? super Field>> predicates = Lists.newArrayList();
  for (Class<? extends Annotation> annotationClass : relevantAnnotationClasses) {
    predicates.add(ReflectionUtils.withAnnotation(annotationClass));
  }
  return Predicates.or(predicates);
}
 
Example #26
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 #27
Source File: ConfigDriveBuilderTest.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
@PrepareForTest({ConfigDriveBuilder.class})
public void buildConfigDriveTest() throws Exception {
    PowerMockito.mockStatic(ConfigDriveBuilder.class);

    Method writeVendorAndNetworkEmptyJsonFileMethod = ReflectionUtils.getMethods(ConfigDriveBuilder.class, ReflectionUtils.withName("writeVendorAndNetworkEmptyJsonFile")).iterator().next();
    PowerMockito.doNothing().when(ConfigDriveBuilder.class, writeVendorAndNetworkEmptyJsonFileMethod).withArguments(Mockito.any(File.class));

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

    Method linkUserDataMethod = ReflectionUtils.getMethods(ConfigDriveBuilder.class, ReflectionUtils.withName("linkUserData")).iterator().next();
    PowerMockito.doNothing().when(ConfigDriveBuilder.class, linkUserDataMethod).withArguments(Mockito.anyString());

    Method generateAndRetrieveIsoAsBase64IsoMethod = ReflectionUtils.getMethods(ConfigDriveBuilder.class, ReflectionUtils.withName("generateAndRetrieveIsoAsBase64Iso")).iterator().next();
    PowerMockito.doReturn("mockIsoDataBase64").when(ConfigDriveBuilder.class, generateAndRetrieveIsoAsBase64IsoMethod).withArguments(Mockito.anyString(), Mockito.anyString(), Mockito.anyString());

    //force execution of real method
    PowerMockito.when(ConfigDriveBuilder.class, new ArrayList<>(), "teste", "C:").thenCallRealMethod();

    String returnedIsoData = ConfigDriveBuilder.buildConfigDrive(new ArrayList<>(), "teste", "C:");

    Assert.assertEquals("mockIsoDataBase64", returnedIsoData);

    PowerMockito.verifyStatic(ConfigDriveBuilder.class);
    ConfigDriveBuilder.writeVendorAndNetworkEmptyJsonFile(Mockito.any(File.class));
    ConfigDriveBuilder.writeVmMetadata(Mockito.anyListOf(String[].class), Mockito.anyString(), Mockito.any(File.class));
    ConfigDriveBuilder.linkUserData(Mockito.anyString());
    ConfigDriveBuilder.generateAndRetrieveIsoAsBase64Iso(Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
}
 
Example #28
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 #29
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 #30
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);
}