Java Code Examples for com.openpojo.reflection.impl.PojoClassFactory

The following examples show how to use com.openpojo.reflection.impl.PojoClassFactory. 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: tessera   Source File: OpenPojoEntityTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void executeOpenPojoValidationsWithSetter() {

    final Validator pojoValidator =
            ValidatorBuilder.create()
                    .with(new GetterMustExistRule())
                    .with(new SetterMustExistRule())
                    .with(new SetterTester())
                    .with(new GetterTester())
                    .with(new EqualsAndHashCodeMatchRule())
                    .with(new NoPrimitivesRule())
                    .with(new NoPublicFieldsExceptStaticFinalRule())
                    .build();

    pojoValidator.validate(PojoClassFactory.getPojoClass(MessageHash.class));
}
 
Example 2
Source Project: cerberus   Source File: AwsStsPojoTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void test_pojo_structure_and_behavior() {

  List<Class> classes =
      Lists.newArrayList(
          GetCallerIdentityFullResponse.class,
          GetCallerIdentityResponse.class,
          AwsStsHttpHeader.class);

  List<PojoClass> pojoClasses =
      classes.stream().map(PojoClassFactory::getPojoClass).collect(Collectors.toList());

  Validator validator =
      ValidatorBuilder.create()
          .with(new GetterMustExistRule())
          .with(new SetterMustExistRule())
          .with(new SetterTester())
          .with(new GetterTester())
          .build();

  validator.validate(pojoClasses);
}
 
Example 3
Source Project: openpojo   Source File: DefaultRandomGenerator.java    License: Apache License 2.0 6 votes vote down vote up
public Object doGenerate(final Class<?> type) {
  final PojoClass typePojoClass = PojoClassFactory.getPojoClass(type);
  if (typePojoClass.isInterface()) {
    return interfaceRandomGenerator.doGenerate(type);
  }

  if (typePojoClass.isEnum()) {
    return enumRandomGenerator.doGenerate(type);
  }

  if (typePojoClass.isArray()) {
    return arrayRandomGenerator.doGenerate(type);
  }

  LoggerFactory.getLogger(DefaultRandomGenerator.class).debug("Creating basic instance for type=[{0}] using " +
      "InstanceFactory", type);
  return InstanceFactory.getLeastCompleteInstance(PojoClassFactory.getPojoClass(type));

}
 
Example 4
Source Project: openpojo   Source File: ASMServiceEnd2EndTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void tryOutAbstractMethods() {
  AbstractClassWithVariousAbstractMethods instance = getRandomValue(AbstractClassWithVariousAbstractMethods.class);
  PojoClass pojoClass = PojoClassFactory.getPojoClass(AbstractClassWithVariousAbstractMethods.class);
  for (PojoMethod method : pojoClass.getPojoMethods())
    if (!method.isConstructor()) {

      assertThat("Method" + method, method.isAbstract(), is(true));

      final List<PojoParameter> pojoParameters = method.getPojoParameters();
      Object[] params = new Object[pojoParameters.size()];
      for (int idx = 0; idx < params.length; idx++) {
        params[idx] = RandomFactory.getRandomValue(pojoParameters.get(idx));
      }

      final Class<?> returnType = method.getReturnType();
      if (!returnType.equals(Void.class) && !returnType.equals(void.class))
        assertThat("Method " + method, method.invoke(instance, params), notNullValue());
      else
        assertThat("Method " + method, method.invoke(instance, params), nullValue());
    }
}
 
Example 5
Source Project: cia   Source File: AbstractUnitTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Check all classes in package.
 *
 * @param string the string
 * @return true, if successful
 */
protected final boolean checkAllClassesInPackage(final String string) {
	final List<PojoClass> pojoClassesRecursively = PojoClassFactory.getPojoClassesRecursively(string,
			new FilterTestClasses());

	final Validator validator = ValidatorBuilder.create().with(new SetterMustExistRule(), new GetterMustExistRule())
			.with(new SetterTester(), new GetterTester()).with(new InvokeToStringTester())
			.with(new InvokeHashcodeTester()).with(new DummyEqualsTester()).with(new WithTester())
			.with(new ObjectFactoryTester()).with(new EqualsAndHashCodeMatchRule()).build();
	validator.validate(pojoClassesRecursively);

	final List<PojoClass> enumClassesRecursively = PojoClassFactory.getPojoClassesRecursively(string,
			new FilterNonEnumClasses());

	final Validator enumValidator = ValidatorBuilder.create().with(new EnumTester()).build();
	enumValidator.validate(enumClassesRecursively);

	return true;
}
 
Example 6
Source Project: openpojo   Source File: BusinessIdentityUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(expected = UnsupportedOperationException.class)
public void shouldNotBeAbleToConstruct() {
  try {
    PojoClass pojoClass = PojoClassFactory.getPojoClass(BusinessIdentityUtils.class);
    org.testng.Assert.assertEquals(1, pojoClass.getPojoConstructors().size());
    InstanceFactory.getLeastCompleteInstance(pojoClass);
  } catch (ReflectionException re) {
    Throwable cause = re.getCause();
    while (cause != null) {
      if (cause instanceof UnsupportedOperationException)
        throw (UnsupportedOperationException) cause;
      cause = cause.getCause();
    }
  }
  Assert.fail("Should have not been able to construct");
}
 
Example 7
Source Project: openpojo   Source File: ASMServiceEnd2EndTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void implementAbstractToString() {
  final Class<AbstractClassWithAbstractToString> type = AbstractClassWithAbstractToString.class;
  PojoClass pojoClass = PojoClassFactory.getPojoClass(type);
  for (PojoMethod method : pojoClass.getPojoMethods())
    if (method.getName().equals("toString"))
      assertThat(method.isAbstract(), is(true));

  AbstractClassWithAbstractToString abstractToString = getRandomValue(type);
  assertThat(abstractToString, notNullValue());

  final String actual = abstractToString.toString();
  final String expected = type.getName() + SubClassDefinition.GENERATED_CLASS_POSTFIX + " [@";

  assertThat(actual, notNullValue());
  assertThat(actual, startsWith(expected));
}
 
Example 8
Source Project: openpojo   Source File: ClassReaderFactoryTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(expected = UnsupportedOperationException.class)
public void shouldNotBeAbleToConstruct() {
  try {
    PojoClass pojoClass = PojoClassFactory.getPojoClass(ClassReaderFactory.class);
    org.testng.Assert.assertEquals(1, pojoClass.getPojoConstructors().size());
    InstanceFactory.getLeastCompleteInstance(pojoClass);
  } catch (ReflectionException re) {
    Throwable cause = re.getCause();
    while (cause != null) {
      if (cause instanceof UnsupportedOperationException)
        throw (UnsupportedOperationException) cause;
      cause = cause.getCause();
    }
  }
  Assert.fail("Should have not been able to construct");
}
 
Example 9
Source Project: cloudbreak   Source File: DomainTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testPojoStructureAndBehavior() {

    List<PojoClass> pojoClasses = new ArrayList<>();
    pojoClasses.add(PojoClassFactory.getPojoClass(Region.class));
    pojoClasses.add(PojoClassFactory.getPojoClass(CompactView.class));
    pojoClasses.add(PojoClassFactory.getPojoClass(EnvironmentAuthentication.class));

    Validator validator = ValidatorBuilder.create()
            .with(new SetterMustExistRule(),
                    new GetterMustExistRule())
            .with(new GetterTester())
            .with(new NoPublicFieldsExceptStaticFinalRule())
            .with(new NoStaticExceptFinalRule())
            .with(new NoNestedClassRule())
            .with(new NoFieldShadowingRule())
            .build();
    validator.validate(pojoClasses);

    validator = ValidatorBuilder.create()
            .with(new SetterTester())
            .build();
    validator.validate(pojoClasses);
    // openpojo will do for now (seems buggy) but later would worth experimenting with pojo-tester (https://www.pojo.pl/)
}
 
Example 10
Source Project: tessera   Source File: NonceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void pojo() {
    EqualsVerifier.configure().suppress(STRICT_INHERITANCE).forClass(Nonce.class).verify();

    ValidatorBuilder.create()
        .with(new GetterTester())
        .build()
        .validate(PojoClassFactory.getPojoClass(Nonce.class));

}
 
Example 11
Source Project: tessera   Source File: ConfigurationMixinTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void pojoTest() {
    ValidatorBuilder.create()
            .with(new GetterTester())
            .with(new SetterTester())
            .build()
            .validate(PojoClassFactory.getPojoClass(ConfigurationMixin.class));
}
 
Example 12
Source Project: openpojo   Source File: IssueTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHideJacocoFieldAndMethod() throws NoSuchFieldException, NoSuchMethodException {
  Field field = this.getClass().getDeclaredField(JACOCO_FIELD_NAME);
  Assert.assertNotNull("Should not be null", field);

  Method method = this.getClass().getDeclaredMethod(JACOCO_METHOD_NAME);
  Assert.assertNotNull("Should not be null", method);

  PojoClassAdapter jacocoPojoClassAdapter = JacocoPojoClassAdapter.getInstance();
  PojoClass cleansedPojoClass = jacocoPojoClassAdapter.adapt(PojoClassFactory.getPojoClass(this.getClass()));

  for (PojoField pojoField : cleansedPojoClass.getPojoFields()) {
    if (pojoField.getName().equals(JACOCO_FIELD_NAME)) {
      Affirm.fail(JACOCO_FIELD_NAME + " field is still visible!!");
    }
  }

  for (PojoMethod pojoMethod : cleansedPojoClass.getPojoMethods()) {
    if (pojoMethod.getName().equals(JACOCO_METHOD_NAME)) {
      Affirm.fail(JACOCO_METHOD_NAME + " method is still visible!!");
    }
  }

  Assert.assertNotNull(this.getClass().getDeclaredField("JACOCO_FIELD_NAME"));
  Assert.assertNotNull(this.getClass().getDeclaredField("JACOCO_METHOD_NAME"));
  Assert.assertNotNull(this.getClass().getDeclaredMethod("shouldHideJacocoFieldAndMethod"));

}
 
Example 13
@BeforeClass
public static void setup() {
  for (final String pkg : packages) {
    collectionRandomGenerators.addAll(PojoClassFactory.getPojoClassesRecursively(pkg,
        new FilterChain(
            new RandomGeneratorFilter(),
            new FilterNestedClasses(),
            new FilterNonConcrete())));
  }
  Affirm.affirmEquals(MessageFormatter.format("Invalid number of Collection/Map RandomGenerators added/removed? " +
          "expected: " + "[{0}], found: [{1}] which were [{2}] ", EXPECTED_COUNT, collectionRandomGenerators.size(),
      collectionRandomGenerators), EXPECTED_COUNT, collectionRandomGenerators.size());
}
 
Example 14
Source Project: openpojo   Source File: CloverPojoClassAdapterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
  PojoCoverageFilterService allButClover3PojoCoverageFilterService = new DefaultPojoCoverageFilterService();

  allButClover3PojoCoverageFilterService.registerCoverageDetector(Cobertura.getInstance());
  allButClover3PojoCoverageFilterService.registerCoverageDetector(Jacoco.getInstance());

  ServiceRegistrar.getInstance().setPojoCoverageFilterService(allButClover3PojoCoverageFilterService);
  cloverInstrumentedPojoClass = PojoClassFactory.getPojoClass(CloverInstrumentedClass.class);
  ServiceRegistrar.getInstance().setPojoCoverageFilterService(cloverPojoCoverageFilterService);
  cloverCleanedPojoClass = CloverPojoClassAdapter.getInstance().adapt(cloverInstrumentedPojoClass);
}
 
Example 15
Source Project: openpojo   Source File: IssueTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldFixProtocolForJarIfJarDoesNotHaveColonDoubleSlashes() {
  PojoClass pojoClass = PojoClassFactory.getPojoClass(ClassUtil.loadClass(TestingClassData.className));
  String sourcePath = pojoClass.getSourcePath();

  assertThat(sourcePath, startsWith(TestingClassData.expectedPathStartsWith));
  assertThat(sourcePath, containsString(TestingClassData.expectedPathContains1));
  assertThat(sourcePath, containsString(TestingClassData.expectedPathContains2));
  assertThat(sourcePath, endsWith(TestingClassData.expectedPathEndsWith));
}
 
Example 16
Source Project: openpojo   Source File: IssueTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void whenBooleanStartsWith_isAndThirdCharacterIsUpperCase_Getter_IsX_Setter_setX() {
  PojoClass pojoClass = PojoClassFactory.getPojoClass(ClassWithBoolean_isX.class);

  Validator pojoValidator = ValidatorBuilder.create()
      .with(new GetterMustExistRule())
      .with(new SetterMustExistRule())
      .build();

  pojoValidator.validate(pojoClass);
}
 
Example 17
@Test
public void shouldCreateGenericCollection() throws ExecutionException, InterruptedException {
  List<PojoClass> pojoClasses = new ArrayList<PojoClass>(2);
  pojoClasses.add(PojoClassFactory.getPojoClass(AClassWithGenericCollection.class));
  pojoClasses.add(PojoClassFactory.getPojoClass(AClassWithExhaustiveCollection.class));

  Assert.assertEquals(2, pojoClasses.size());

  RejectedExecutionHandlerImpl rejectionHandler = new RejectedExecutionHandlerImpl();

  ThreadPoolExecutor executorPool = new ThreadPoolExecutor(ttl_jobs / per_thread, ttl_jobs / per_thread, 10,
      TimeUnit.SECONDS,
      new ArrayBlockingQueue<Runnable>(ttl_jobs),
      Executors.defaultThreadFactory(), rejectionHandler);

  List<Future> tasksStatus = new ArrayList<Future>(ttl_jobs);
  for (int i = 0; i < ttl_jobs; i++) {
    tasksStatus.add(executorPool.submit(new Verify(pojoClasses)));
  }


  executorPool.shutdown();
  while (!executorPool.isTerminated())
    try {
      Thread.sleep(200);
    } catch (InterruptedException ignored) {
    }

  Assert.assertEquals(ttl_jobs, executorPool.getCompletedTaskCount());
  Assert.assertEquals(0, rejectionHandler.getCount());
  for (Future f : tasksStatus) {
    Assert.assertNull(f.get());
  }
}
 
Example 18
Source Project: openpojo   Source File: ASMDetector.java    License: Apache License 2.0 5 votes vote down vote up
public Version getBundleVersion(Class<?> clazz) {
  Version bundleVersion;

  try {
    PojoClass pojoClass = PojoClassFactory.getPojoClass(clazz);
    String sourcePath = pojoClass.getSourcePath();
    String jarFilePath = JarFileReader.getJarFileNameFromURLPath(sourcePath);
    String bundleVersionManifestEntry = JarFileReader.getInstance(jarFilePath).getManifestEntry(VERSION_MANIFEST_KEY_FALLBACK);
    bundleVersion = VersionFactory.getVersion(bundleVersionManifestEntry);
  } catch (Exception ignored) {
    bundleVersion = VersionFactory.getVersion(null);
  }

  return bundleVersion;
}
 
Example 19
Source Project: openpojo   Source File: IssueTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
  classWithUUID = PojoClassFactory.getPojoClass(AClassWithUUID.class);
  validator = ValidatorBuilder.create()
                .with(new GetterTester())
                .with(new SetterTester())
                .build();
}
 
Example 20
Source Project: openpojo   Source File: MapWithGenericsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testEndToEndMap() {
  Validator pojoValidator = ValidatorBuilder.create()
      .with(new SetterMustExistRule())
      .with(new SetterTester())
      .build();

  pojoValidator.validate(PojoClassFactory.getPojoClass(ClassWithVariousGenericMap.class));
}
 
Example 21
Source Project: openpojo   Source File: IssueTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testEndToEndCollections() {
  pojoValidator = ValidatorBuilder.create().with(new SetterMustExistRule())
      .with(new SetterTester())
      .build();

  pojoValidator.validate(PojoClassFactory.getPojoClass(ClassWithVariousGenericSetList.class));
}
 
Example 22
/**
 * This method returns a random instance for a given interface.
 * The instance will return random values upon method invocations.
 *
 * @param <T>
 *     The type to generate an instance of.
 * @param clazz
 *     The interface to generate the implementations on.
 * @return An instance of the interface.
 */
@SuppressWarnings("unchecked")
public <T> T doGenerate(final Class<T> clazz) {
  PojoClass pojoClass = PojoClassFactory.getPojoClass(clazz);
  if (!pojoClass.isInterface()) {
    throw ReflectionException.getInstance(
        String.format("[%s] is not an interface, can't create a proxy for concrete or abstract types.", pojoClass.getName()));
  }

  InvocationHandler handler = RandomReturnInvocationHandler.getInstance();

  return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
      new Class<?>[] { pojoClass.getClazz() }, handler);
}
 
Example 23
Source Project: openpojo   Source File: EnumRandomGenerator.java    License: Apache License 2.0 5 votes vote down vote up
public Object doGenerate(final Class<?> type) {
  final PojoClass pojoClass = PojoClassFactory.getPojoClass(type);

  final Enum<?>[] values = getValues(pojoClass);
  if (values.length == 0)
    throw RandomGeneratorException.getInstance("Can't generate random value for Enum class [" + type + "] enum doesn't " +
        "define any values");
  return values[RANDOM.nextInt(values.length)];
}
 
Example 24
Source Project: openpojo   Source File: DefaultIdentityEvaluatorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void SampleClassMustUseBusinessIdentity() {
  Validator pojoValidator = ValidatorBuilder.create()
      .with(new BusinessKeyMustExistRule())
      .with(new BusinessIdentityTester())
      .build();
  pojoValidator.validate(PojoClassFactory.getPojoClass(StringArrayCaseSensitive.class));
  pojoValidator.validate(PojoClassFactory.getPojoClass(StringArrayCaseInsensitive.class));
}
 
Example 25
Source Project: openpojo   Source File: EqualsAndHashCodeMatchRuleTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void mustImplementRule() {
  PojoClass equalsAndHashcodeMatchRule = PojoClassFactory.getPojoClass(EqualsAndHashCodeMatchRule.class);
  List<PojoClass> interfaces = equalsAndHashcodeMatchRule.getInterfaces();
  Assert.assertTrue("Expected interface=[Rule] to be implemented, but was not", interfaces.contains(PojoClassFactory
      .getPojoClass(Rule.class)));
}
 
Example 26
Source Project: openpojo   Source File: EqualsAndHashCodeMatchRuleTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldPassIfNoEqualsOrHashcodeImplemented() {
  PojoClass aClassNotImplementingHashCodeOrEquals = PojoClassFactory.getPojoClass(AClassNotImplementingHashcodeOrEquals.class);
  List<PojoMethod> methods = aClassNotImplementingHashCodeOrEquals.getPojoMethods();


  Assert.assertEquals(1, methods.size());
  Assert.assertTrue(methods.get(0).isConstructor());

  rule.evaluate(aClassNotImplementingHashCodeOrEquals);
}
 
Example 27
Source Project: cloudbreak   Source File: ModelTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetterTypeChangerPojoStructureAndBehavior() {
    List<PojoClass> pojoClasses = PojoClassFactory.getPojoClassesRecursively(DOMAIN_PACKAGE, GETTER_TYPE_CHANGER_CLASS_FILTER);

    Validator validator = ValidatorBuilder.create()
            .with(new SetterMustExistRule())
            .with(new SetterTester(),
                    new GetterTester())
            .with(new NoStaticExceptFinalRule())
            .with(new NoNestedClassRule())
            .build();
    validator.validate(pojoClasses);
}
 
Example 28
Source Project: openpojo   Source File: URLRandomGeneratorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void constructorIsPrivate() {
  PojoClass urlPojoClass = PojoClassFactory.getPojoClass(URLRandomGenerator.class);
  for (PojoMethod constructor : urlPojoClass.getPojoConstructors()) {
    if (!constructor.isSynthetic())
      assertTrue(constructor + " should be private", constructor.isPrivate());
  }
}
 
Example 29
Source Project: openpojo   Source File: NoFieldShadowingRuleTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void ensureAParentClassWithOneFieldSampleClassIsAccurate() {
  PojoClass aParentClassWithOneField = PojoClassFactory.getPojoClass(NoShadowAParentClassWithOneField.class);
  List<PojoField> pojoFields = aParentClassWithOneField.getPojoFields();
  Assert.assertThat(pojoFields.size(), is(1));
  Assert.assertThat(pojoFields.get(0).getName(), is("aField"));
}
 
Example 30
Source Project: openpojo   Source File: NoFieldShadowingRuleTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void ensureAChildWithFieldShadowingIsAccurateWW() {
  PojoClass aChildWithFieldShadowing = PojoClassFactory.getPojoClass(NoShadowAChildWithFieldShadowing.class);
  List<PojoField> pojoFields = aChildWithFieldShadowing.getPojoFields();
  Assert.assertThat(pojoFields.size(), is(1));
  Assert.assertThat(pojoFields.get(0).getName(), is("aField"));
}