Java Code Examples for com.openpojo.reflection.PojoClass

The following examples show how to use com.openpojo.reflection.PojoClass. 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: openpojo   Source File: PojoClassImplTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void multipleAnnotationsShouldBeReturned() {
  final Class<?> aClassWithAnnotations = AClassWithAnnotations.class;

  final PojoClass pojoClass = getPojoClassImplForClass(aClassWithAnnotations);
  Affirm.affirmEquals(String.format("Annotations added/removed from Class=[%s]", aClassWithAnnotations), 2, pojoClass
      .getAnnotations().size());

  final List<Class<?>> expectedAnnotations = new LinkedList<Class<?>>();
  expectedAnnotations.add(SomeAnnotation.class);
  expectedAnnotations.add(AnotherAnnotation.class);
  for (final Annotation annotation : pojoClass.getAnnotations()) {
    Affirm.affirmTrue(String.format("Expected annotations [%s] not found, instead found [%s]", expectedAnnotations,
        annotation.annotationType()), expectedAnnotations.contains(annotation.annotationType()));
  }
}
 
Example 2
Source Project: openpojo   Source File: ValidationHelperTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReportMissingASMProperly() {
  Validator validator = ValidatorBuilder.create()
      .with(new Tester() {
        public void run(PojoClass pojoClass) {
          throw ASMNotLoadedException.getInstance();
        }
      }).build();

  LogHelper.initialize(MockAppenderLog4J.class);
  validator.validate(PojoClassFactory.getPojoClass(this.getClass()));
  List<LogEvent> warnEvents = LogHelper.getWarnEvents(MockAppenderLog4J.class, DefaultValidator.class.getName());
  Assert.assertEquals(1, warnEvents.size());
  String expectedMessage = "ASM not loaded while attempting to execute behavioural tests on non-constructable class["
      + this.getClass() + "], either filter abstract classes or add asm to your classpath.";
  Assert.assertEquals(expectedMessage, warnEvents.get(0).getMessage());
}
 
Example 3
Source Project: openpojo   Source File: FilterNonConcreteTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testInclude() {
  PojoClassFilter pojoClassFilter = new FilterNonConcrete();
  PojoClass stubPojoClass = PojoStubFactory.getStubPojoClass(false);

  Affirm.affirmTrue(String.format("Filter[%s] was supposed to filter OUT non concrete class", pojoClassFilter), stubPojoClass
      .isConcrete() == pojoClassFilter.include(stubPojoClass));

  stubPojoClass = PojoStubFactory.getStubPojoClass(true);
  Affirm.affirmTrue(String.format("Filter[%s] was supposed to filter IN concrete class", pojoClassFilter),
      stubPojoClass.isConcrete() == pojoClassFilter.include(stubPojoClass));

  final StubPojoClassFilter stubPojoClassFilter = new StubPojoClassFilter();
  pojoClassFilter = new FilterChain(new FilterNonConcrete(), stubPojoClassFilter);

  stubPojoClass = PojoStubFactory.getStubPojoClass(true);
  pojoClassFilter.include(stubPojoClass);
  Affirm.affirmTrue(String.format("Filter [%s] didn't invoke next in filter chain", pojoClassFilter), stubPojoClassFilter
      .includeCalled);
}
 
Example 4
Source Project: parallec   Source File: ParallecPojoClassTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Unit Test the POJO classes.
 *
 * @throws ClassNotFoundException
 *             the class not found exception
 * @throws InstantiationException
 *             the instantiation exception
 * @throws IllegalAccessException
 *             the illegal access exception
 */

@Test
public void testPojoStructureAndBehavior() throws ClassNotFoundException,
        InstantiationException, IllegalAccessException {
    final PojoValidator pojoValidator = new PojoValidator();
    for (final Class<? extends Rule> ruleClass : getValidationRules()) {
        final Rule rule = ruleClass.newInstance();
        pojoValidator.addRule(rule);
    }

    // Load tester classes
    for (Class<? extends Tester> testerClass : getTesters()) {
        final Tester testerInstance = testerClass.newInstance();
        pojoValidator.addTester(testerInstance);
    }

    for (final Class<?> c : getPOJOClasses()) {
        final PojoClass pojoClass = PojoClassFactory.getPojoClass(c);

        pojoValidator.runValidation(pojoClass);
    }
}
 
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: PojoParameterImplTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void isParameterized() {
  PojoClass pojoClass = PojoClassFactory.getPojoClass(AClassWithParameterizedConstructors.class);

  Assert.assertTrue(pojoClass.isNestedClass());

  for (PojoMethod constructor : pojoClass.getPojoConstructors()) {
    if (!constructor.isSynthetic()) {
      List<PojoParameter> pojoParameters = constructor.getPojoParameters();
      Assert.assertThat(pojoParameters.size(), is(greaterThan(1)));
      for (int i = 1; i < pojoParameters.size(); i++) {
        PojoParameter parameter = pojoParameters.get(i);
        Assert.assertThat(parameter.isParameterized(), is(Matchers.equalTo(true)));
      }
    }
  }
}
 
Example 7
Source Project: openpojo   Source File: NoFieldShadowingRuleTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void aChildWithFieldShadowingShouldFail() {
  PojoClass aChildWithFieldShadowing = PojoClassFactory.getPojoClass(NoShadowAChildWithFieldShadowing.class);
  try {
    validator.validate(aChildWithFieldShadowing);
    Assert.fail("Expected [NoShadowAChildWithFieldShadowing.class] to fail NoFieldShadowRule but didn't");
  } catch (AssertionError ae) {
    Assert.assertEquals("Field=[PojoFieldImpl " +
        "[field=private java.lang.String com.openpojo.validation.rule.impl.sampleclasses.NoShadowAChildWithFieldShadowing.aField, " +
        "fieldGetter=null, " +
        "fieldSetter=null]] " +
        "shadows field with the same name in " +
        "parent class=[[PojoFieldImpl [" +
        "field=private java.lang.String com.openpojo.validation.rule.impl.sampleclasses.NoShadowAParentClassWithOneField.aField, " +
        "fieldGetter=null," +
        " fieldSetter=null]]]", ae.getMessage());
  }
}
 
Example 8
Source Project: openpojo   Source File: DefaultValidatorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void rulesAndTestersAreTriggeredWhenValidationIsRunRecursively() {
  TesterSpy testerSpy = new TesterSpy();
  List<Tester> testers = new ArrayList<Tester>();
  testers.add(testerSpy);

  RuleSpy ruleSpy = new RuleSpy();
  List<Rule> rules = new ArrayList<Rule>();
  rules.add(ruleSpy);

  FilterSpy filterSpy = new FilterSpy();

  DefaultValidator defaultValidator = new DefaultValidator(rules, testers);
  String packageName = this.getClass().getPackage().getName() + ".sample";
  List<PojoClass> validatedPojoClasses = defaultValidator.validateRecursively(packageName, filterSpy);

  Assert.assertEquals(2, validatedPojoClasses.size());
  Assert.assertTrue(validatedPojoClasses.contains(PojoClassFactory.getPojoClass(DummyClass.class)));
  Assert.assertTrue(validatedPojoClasses.contains(PojoClassFactory.getPojoClass(AnotherDummyClass.class)));

  assertInvokedClasses(testerSpy.getInvocations(), DummyClass.class.getName(), AnotherDummyClass.class.getName());
  assertInvokedClasses(ruleSpy.getInvocations(), DummyClass.class.getName(), AnotherDummyClass.class.getName());
  assertInvokedClasses(filterSpy.getInvocations(), DummyClass.class.getName(), AnotherDummyClass.class.getName());
}
 
Example 9
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 10
Source Project: moleculer-java   Source File: PojoTest.java    License: MIT License 5 votes vote down vote up
public boolean include(PojoClass pojoClass) {
	boolean enable = !pojoClass.getName().contains("Test") && !pojoClass.getName().contains("$");
	if (enable) {
		// System.out.println(pojoClass.getName());
	}
	return enable;
}
 
Example 11
Source Project: openpojo   Source File: CollectionsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testUnmodifiableCollectionsGetterReturned() {
  Validator pojoValidator = ValidatorBuilder.create()
      .with(new GetterTester())
      .with(new SetterTester())
      .build();

  PojoClass pojoClass = PojoClassFactory.getPojoClass(CollectionContainingClass.class);
  pojoValidator.validate(pojoClass);
}
 
Example 12
Source Project: cerberus   Source File: DomainPojoTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test_pojo_structure_and_behavior() {

  List<PojoClass> pojoClasses = PojoClassFactory.getPojoClasses("com.nike.cerberus.domain");

  pojoClasses.remove(PojoClassFactory.getPojoClass(CerberusAuthToken.class));
  pojoClasses.remove(
      PojoClassFactory.getPojoClass(CerberusAuthToken.CerberusAuthTokenBuilder.class));
  pojoClasses.remove(PojoClassFactory.getPojoClass(VaultStyleErrorResponse.Builder.class));
  pojoClasses.remove(PojoClassFactory.getPojoClass(IamPrincipalPermission.Builder.class));
  pojoClasses.remove(PojoClassFactory.getPojoClass(UserGroupPermission.Builder.class));
  pojoClasses.remove(PojoClassFactory.getPojoClass(SafeDepositBoxV2.Builder.class));
  pojoClasses.remove(
      PojoClassFactory.getPojoClass(SecureDataResponse.SecureDataResponseBuilder.class));

  Assert.assertTrue(pojoClasses.size() > 1);

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

  validator.validate(pojoClasses);
}
 
Example 13
Source Project: openpojo   Source File: IssueTest.java    License: 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 14
Source Project: cloudbreak   Source File: ModelTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSetterTypeChangerPojoStructureAndBehavior() {
    List<PojoClass> pojoClasses = PojoClassFactory.getPojoClassesRecursively(DOMAIN_PACKAGE, SETTER_TYPE_CHANGER_CLASS_FILTER);

    Validator validator = ValidatorBuilder.create()
            .with(new GetterMustExistRule())
            .with(new SetterTester(),
                    new GetterTester())
            .with(new NoStaticExceptFinalRule())
            .with(new NoNestedClassRule())
            .build();
    validator.validate(pojoClasses);
}
 
Example 15
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 16
Source Project: openpojo   Source File: GetterTesterAndSetterTesterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldFailSetterTest() {
  List<PojoClass> badPojoClasses = getBadPojoClasses();
  Assert.assertEquals("Classes added/removed?", 1, badPojoClasses.size());
  for (final PojoClass pojoClass : badPojoClasses) {
    try {
      invokeRun(pojoClass, new SetterTester());
      Assert.fail("Should not have passed");
    } catch (AssertionError ignored) {

    }
  }
}
 
Example 17
Source Project: openpojo   Source File: PojoAbstractMethodImplTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldFindNoAbstractMethods() {
  PojoClass pojoClass = PojoClassFactory.getPojoClass(AnAbstractClassEmpty.class);
  for (PojoMethod pojoMethod : pojoClass.getPojoMethods()) {
    Assert.assertTrue(pojoMethod.isConstructor());
    Assert.assertFalse(pojoMethod.isAbstract());
  }

  Assert.assertEquals(1, pojoClass.getPojoMethods().size());
}
 
Example 18
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 19
Source Project: openpojo   Source File: PojoFieldPrefixedFieldsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void unmatchedPrefixesHaveNoEffect() {
  AttributeHelper.registerFieldPrefix("n");
  PojoClass pojoClass = PojoClassFactory.getPojoClass(AClassWithFieldsNotPrefixed.class);
  Rule getterRule = new GetterMustExistRule();
  getterRule.evaluate(pojoClass);
}
 
Example 20
Source Project: openpojo   Source File: PojoFieldImplTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldGetParameterizedType() {
  PojoClass pojoClass = PojoClassFactory.getPojoClass(ClassWithGenericTypes.class);
  Affirm.affirmEquals("Fields added/removed?!", 4, pojoClass.getPojoFields().size());

  int affirmChecks = 0;
  for (PojoField pojoField : pojoClass.getPojoFields()) {
    if (pojoField.getName().equals("parameterizedChildren")) {
      Affirm.affirmTrue("Not Generic?!", pojoField.isParameterized());
      Affirm.affirmTrue("Wrong Parameterization!?", pojoField.getParameterTypes().contains(ClassWithGenericTypes.class));
      affirmChecks++;
    }

    if (pojoField.getName().equals("nonparameterizedList") || pojoField.getName().equals("nonParameterizedString")) {
      Affirm.affirmFalse("Turned generic?!", pojoField.isParameterized());
      Affirm.affirmEquals("Returned non-empty list for nonParameterized type!? [" + pojoField.getParameterTypes() + "]", 0,
          pojoField.getParameterTypes().size());
      affirmChecks++;
    }

    if (pojoField.getName().equals("parameterizedMap")) {
      Affirm.affirmEquals("MultipTypeGeneric failed!!", 2, pojoField.getParameterTypes().size());
      Affirm.affirmTrue(String.format("Type not found [%s]", String.class), pojoField.getParameterTypes().contains(String
          .class));
      Affirm.affirmTrue(String.format("Type not found [%s]", Integer.class), pojoField.getParameterTypes().contains(Integer
          .class));
      affirmChecks++;
    }
  }
  Affirm.affirmEquals("Fields added/removed/renamed? expected 4 checks!!", 4, affirmChecks);
}
 
Example 21
Source Project: openpojo   Source File: TestClassMustBeProperlyNamedRule.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isAnnotatedOrParentAnnotated(PojoClass pojoClass, Class<? extends Annotation> testAnnotation) {
  if (pojoClass == null)
    return false;

  //Class level annotation
  if (pojoClass.getAnnotation(testAnnotation) != null)
    return true;

  for (PojoMethod pojoMethod : pojoClass.getPojoMethods()) {
    if (pojoMethod.getAnnotation(testAnnotation) != null)
      return true;
  }

  return (isAnnotatedOrParentAnnotated(pojoClass.getSuperClass(), testAnnotation));
}
 
Example 22
Source Project: openpojo   Source File: ByteCodeFactoryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void givenAnAbstractClassWithGenericConstructorShouldConstruct() {
  PojoClass pojoClass = PojoClassFactory.getPojoClass(AnAbstractClassWithGenericConstructor.class);
  Class<?> subClass = getSubClass(pojoClass.getClazz());

  assertIsConcreteAndConstructable(subClass);
}
 
Example 23
Source Project: openpojo   Source File: JarFileReaderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void onlyPrivateConstructors() {
  PojoClass pojoClass = PojoClassFactory.getPojoClass(JarFileReader.class);
  for (PojoMethod method : pojoClass.getPojoConstructors()) {
    Assert.assertTrue("Constructor must be private [" + method + "]", method.isPrivate());
  }
}
 
Example 24
Source Project: openpojo   Source File: EqualsAndHashCodeMatchRuleTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldFailOnlyHashcodeIsImplemented() {
  PojoClass aClassImplementingHashcodeOnly = PojoClassFactory.getPojoClass(AClassImplementingHashcodeOnly.class);
  List<PojoMethod> methods = aClassImplementingHashcodeOnly.getPojoMethods();

  Assert.assertEquals(2, methods.size());
  boolean constructorFound = false;
  boolean hashCode = false;
  for (PojoMethod method : methods) {
    if (method.isConstructor())
      constructorFound = true;
    if (!method.isConstructor() && method.getName().equals("hashCode")
        && method.getPojoParameters().size() == 0
        && method.getReturnType().equals(int.class))
      hashCode = true;
  }

  Assert.assertTrue("Constructor not found", constructorFound);
  Assert.assertTrue("hashCode not found", hashCode);

  try {
    rule.evaluate(aClassImplementingHashcodeOnly);
    Assert.fail("Should have failed validation but did not");
  } catch (AssertionError ae) {
    Assert.assertEquals("hashCode implemented but equals isn't in Pojo [" + aClassImplementingHashcodeOnly + "]",
        ae.getMessage());
  }
}
 
Example 25
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 26
Source Project: openpojo   Source File: NoPrimitivesRule.java    License: Apache License 2.0 5 votes vote down vote up
public void evaluate(final PojoClass pojoClass) {
  for (PojoField fieldEntry : pojoClass.getPojoFields()) {
    if (fieldEntry.isPrimitive() && !ValidationHelper.isStaticFinal(fieldEntry)) {
      Affirm.fail(String.format(
          "Primitive fields (byte, short, int, long, float, double, boolean, char) not allowed [%s]", fieldEntry));
    }
  }
}
 
Example 27
Source Project: openpojo   Source File: PojoClassImplTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetClazz() {
  final Class<?> clazz = this.getClass();
  final PojoClass pojoClass = getPojoClassImplForClass(clazz);
  Affirm.affirmTrue(String.format("PojoClass parsing for [%s] returned different class=[%s] in getClazz() call" + " for " +
      "PojoClass implementation=[%s]", clazz, pojoClass.getClazz(), pojoClass), clazz.equals(pojoClass.getClazz()));
}
 
Example 28
@Test
public void shouldGetConstructorWithGenericParameter() {
  PojoClass pojoClass = PojoClassFactory.getPojoClass(AClassWithGenericParameterConstructor.class);
  List<PojoMethod> constructors = pojoClass.getPojoConstructors();
  Affirm.affirmEquals(pojoClass.getName() + " should have only one generic parameterized constructor", 1, constructors.size());

  shouldHaveOneParameterizedParameter(constructors, String.class);
}
 
Example 29
Source Project: openpojo   Source File: ByteCodeFactoryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void givenAnAbstractClassWithAnAbstractMethodShouldReturnAnInstance() {
  PojoClass pojoClass = PojoClassFactory.getPojoClass(AnAbstractClassWithOneAbstraceMethod.class);
  Assert.assertEquals("Should have 1 constructor and 1 abstract method", 2, pojoClass.getPojoMethods().size());

  Class<?> subclass = getSubClass(pojoClass.getClazz());
  assertNotNull(subclass);
  assertIsSubclass(pojoClass.getClazz(), subclass);

}
 
Example 30
Source Project: openpojo   Source File: PojoClassImplTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void isPrivateClass() {
  PojoClass pojoclass = getClass(SAMPLE_CLASSES_PKG + ".AccessibilityClass$PrivateClass");
  Affirm.affirmNotNull("class not found", pojoclass);

  Affirm.affirmTrue("isPrivate() check on class=[" + pojoclass + "] returned true!!", pojoclass.isPrivate());
  Affirm.affirmFalse("isPackagePrivate() check on class=[" + pojoclass + "] returned true!!", pojoclass.isPackagePrivate());
  Affirm.affirmFalse("isProtected() check on class=[" + pojoclass + "] returned true!!", pojoclass.isProtected());
  Affirm.affirmFalse("isPublic() check on class=[" + pojoclass + "] returned true!!", pojoclass.isPublic());
}