com.openpojo.reflection.impl.PojoClassFactory Java Examples

The following examples show how to use com.openpojo.reflection.impl.PojoClassFactory. 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: OpenPojoEntityTest.java    From tessera with Apache License 2.0 7 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 File: AbstractUnitTest.java    From cia with 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 #3
Source File: DefaultRandomGenerator.java    From openpojo with 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 File: BusinessIdentityUtilsTest.java    From openpojo with 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 #5
Source File: ASMServiceEnd2EndTest.java    From openpojo with 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 #6
Source File: ClassReaderFactoryTest.java    From openpojo with 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 #7
Source File: DomainTest.java    From cloudbreak with 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 #8
Source File: ASMServiceEnd2EndTest.java    From openpojo with 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 #9
Source File: AwsStsPojoTest.java    From cerberus with 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 #10
Source File: PojoPackageTestBase.java    From spring-batch-lightmin with Apache License 2.0 5 votes vote down vote up
@Test
public void ensureExpectedPojoCount() {
    if (this.withExpectedCount) {
        final List<PojoClass> pojoClasses = PojoClassFactory.getPojoClasses(this.pojoPackage,
                new FilterPackageInfo());
        Affirm.affirmEquals("Classes added / removed?", this.expectedClassCount, pojoClasses.size());
    } else {
        log.debug("WithExpectedCount is disbabled");
    }
}
 
Example #11
Source File: URIRandomGeneratorTest.java    From openpojo with Apache License 2.0 5 votes vote down vote up
@Test
public void constructorIsPrivate() {
  PojoClass uriPojoClass = PojoClassFactory.getPojoClass(URIRandomGenerator.class);
  for (PojoMethod constructor : uriPojoClass.getPojoConstructors()) {
    if (!constructor.isSynthetic())
      assertTrue(constructor + " should be private", constructor.isPrivate());
  }
}
 
Example #12
Source File: IssueTest.java    From openpojo with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnNullIfMethodParameterIsMissing() throws Exception {
  Class<?> clazz = SampleJar.getURLClassLoader().loadClass("com.failtoload.AClassWithMethodParameterMissing");
  Assert.assertNotNull("expected class not found", clazz);
  Assert.assertNull("Should have failed to load", PojoClassFactory.getPojoClass(clazz));

}
 
Example #13
Source File: ASMServiceEnd2EndTest.java    From openpojo with Apache License 2.0 5 votes vote down vote up
@Test
public void canGenerateSubClassForPrivateConstructor() {
  final Class<AbstractClassWithPrivateConstructor> type = AbstractClassWithPrivateConstructor.class;
  PojoClass pojoClass = PojoClassFactory.getPojoClass(type);
  AbstractClassWithPrivateConstructor randomInstance = RandomFactory.getRandomValue(type);
  assertThat(randomInstance, notNullValue());
  assertThat(randomInstance.toString(), notNullValue());
}
 
Example #14
Source File: IssueTest.java    From openpojo with Apache License 2.0 5 votes vote down vote up
@Test
public void end2endTest() {
  PojoClass pojoClass = PojoClassFactory.getPojoClass(classWithCredentialsDumperClass);
  Validator validator = ValidatorBuilder.create()
      .with(new GetterTester())
      .with(new SetterTester())
      .build();
  validator.validate(pojoClass);
}
 
Example #15
Source File: GenericConstructorsTest.java    From openpojo with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldConstructClassWithGenericSetEnumConstructor() {
  PojoClass pojoClass = PojoClassFactory.getPojoClass(ClassWithGenericSetEnumConstructor.class);
  ClassWithGenericSetEnumConstructor instance =
      (ClassWithGenericSetEnumConstructor) InstanceFactory.getMostCompleteInstance(pojoClass);
  Assert.assertNotNull(instance);
  Assert.assertNotNull(instance.getDaysOfTheWeek());
}
 
Example #16
Source File: CommonCode.java    From openpojo with Apache License 2.0 5 votes vote down vote up
public static void shouldFailTesterValidation(final Tester tester, final Class<?>... failClasses) {
  for (Class<?> clazz : failClasses) {
    try {
      tester.run(PojoClassFactory.getPojoClass(clazz));
      Affirm.fail(String.format("Tester = [%s] failed to detect error while evaluating class= [%s]", tester, clazz));
    } catch (AssertionError ae) {
      if (ae.getMessage().contains("Tester = [")) {
        throw ae;
      }
    }
  }
}
 
Example #17
Source File: JavaClassPathClassLoaderTest.java    From openpojo with Apache License 2.0 5 votes vote down vote up
@Test
public void end2end_shouldLoadAllClassesInJavaLang() {
  List<PojoClass> types = PojoClassFactory.getPojoClassesRecursively("java.lang", null);
  checkListOfPojoClassesContains(types, java.lang.Class.class);
  checkListOfPojoClassesContains(types, java.lang.CharSequence.class);
  checkListOfPojoClassesContains(types, java.lang.Runnable.class);
  checkListOfPojoClassesContains(types, java.lang.Throwable.class);
  checkListOfPojoClassesContains(types, java.lang.Double.class);
  checkListOfPojoClassesContains(types, java.lang.Float.class);
  checkListOfPojoClassesContains(types, java.lang.Object.class);
  checkListOfPojoClassesContains(types, java.lang.Error.class);

  Assert.assertThat(types.size(), greaterThan(minJavaLangClasses));
}
 
Example #18
Source File: TestClassMustEndWithRuleTest.java    From openpojo with Apache License 2.0 5 votes vote down vote up
@Test(expected = AssertionError.class)
public void aTestNGClassThatDoesntEndWithTestShouldFail() {
  final Class<ATestNGClassEndsWithTest> parentClass = ATestNGClassEndsWithTest.class;
  Class<?> aBadTestClass = ASMService.getInstance().createSubclassFor(parentClass,
      new DefaultSubClassDefinition(parentClass, getUniqueClassName("ABadTestClassName")));
  PojoClass aBadTestClassPojo = PojoClassFactory.getPojoClass(aBadTestClass);
  testClassMustEndWithRule.evaluate(aBadTestClassPojo);
}
 
Example #19
Source File: ASMServiceEnd2EndTest.java    From openpojo with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldDefaultForToStringWithPrams() {
  final Class<AbstractClassWithAbstractNonInheritedToString> type = AbstractClassWithAbstractNonInheritedToString.class;
  PojoClass pojoClass = PojoClassFactory.getPojoClass(type);
  final AbstractClassWithAbstractNonInheritedToString randomValue = RandomFactory.getRandomValue(type);
  assertThat(randomValue, notNullValue());
  assertThat(randomValue.toString(),
      startsWith(type.getName() + DefaultSubClassDefinition.GENERATED_CLASS_POSTFIX + "@"));
}
 
Example #20
Source File: NoFieldShadowingRuleTest.java    From openpojo with Apache License 2.0 5 votes vote down vote up
@Test
public void preConfiguredShadowFieldsSkipped() {
  PojoClass aChildWithFieldShadowing = PojoClassFactory.getPojoClass(NoShadowAChildWithFieldShadowing.class);
  validator = ValidatorBuilder
      .create()
      .with(new NoFieldShadowingRule("aField"))
      .build();
  validator.validate(aChildWithFieldShadowing);
}
 
Example #21
Source File: NoFieldShadowingRuleTest.java    From openpojo with 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"));
}
 
Example #22
Source File: NoFieldShadowingRuleTest.java    From openpojo with 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 #23
Source File: URLRandomGeneratorTest.java    From openpojo with 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 #24
Source File: ModelTest.java    From cloudbreak with 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 #25
Source File: IssueTest.java    From openpojo with Apache License 2.0 5 votes vote down vote up
@Test
public void testSetGenerator() {
  Validator pojoValidator = ValidatorBuilder.create()
      .with(new SetterTester())
      .build();

  PojoClass pojoClass = PojoClassFactory.getPojoClass(TestClass.class);

  pojoValidator.validate(pojoClass);
}
 
Example #26
Source File: AbstractUnitTest.java    From cia with Apache License 2.0 5 votes vote down vote up
/**
 * Check all dto classes in package.
 *
 * @param string the string
 * @return true, if successful
 */
protected final boolean checkAllDtoClassesInPackage(final String string) {

	final List<PojoClass> pojoClassesRecursively = PojoClassFactory.getPojoClassesRecursively(string,
			new FilterTestClasses());

	final Validator validator = ValidatorBuilder.create().with(new GetterMustExistRule()).with(new GetterTester())
			.with(new EqualsAndHashCodeMatchRule()).with(new InvokeToStringTester())
			.with(new InvokeHashcodeTester()).with(new DummyEqualsTester()).with(new WithTester()).build();
	validator.validate(pojoClassesRecursively);
	return true;
}
 
Example #27
Source File: EqualsAndHashCodeMatchRuleTest.java    From openpojo with 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 #28
Source File: EqualsAndHashCodeMatchRuleTest.java    From openpojo with 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 #29
Source File: NonceTest.java    From tessera with 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 #30
Source File: ModelTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void testPojoStructureAndBehavior() {
    List<PojoClass> pojoClasses = PojoClassFactory.getPojoClassesRecursively(DOMAIN_PACKAGE, POJO_CLASS_FILTER);

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