Java Code Examples for com.openpojo.reflection.PojoClass#getPojoFields()

The following examples show how to use com.openpojo.reflection.PojoClass#getPojoFields() . 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: SerializableMustHaveSerialVersionUIDRule.java    From openpojo with Apache License 2.0 6 votes vote down vote up
public void evaluate(final PojoClass pojoClass) {
  if (pojoClass.extendz(Serializable.class) && !pojoClass.isInterface()) {
    for (PojoField pojoField : pojoClass.getPojoFields()) {
      if (pojoField.getName().equalsIgnoreCase(SERIAL_VERSION_UID)) {
        if (!pojoField.getName().equals(SERIAL_VERSION_UID)) {
          Affirm.affirmEquals(String.format("Case miss-match on serialVersionUID field on Serializable class [%s]", pojoClass),
              SERIAL_VERSION_UID, pojoField.getName());
        }
        if (!(pojoField.isStatic() && pojoField.isFinal())) {
          Affirm.fail(String.format("[%s] must be defined as [static final] on Serializable class [%s]",
              SERIAL_VERSION_UID, pojoClass));
        }
        if (pojoField.getType() != long.class) {
          Affirm.fail(String.format("[%s] must be defined as [long] on Serializable class [%s]",
              SERIAL_VERSION_UID, pojoClass));
        }
        return;
      }
    }
    Affirm.fail(String.format("No [%s] field defined on Serializable class [%s]", SERIAL_VERSION_UID, pojoClass));
  }
}
 
Example 2
Source File: GetterTester.java    From openpojo with Apache License 2.0 6 votes vote down vote up
public void run(final PojoClass pojoClass) {
  final Object classInstance = ValidationHelper.getBasicInstance(pojoClass);
  for (final PojoField fieldEntry : pojoClass.getPojoFields()) {
    if (fieldEntry.hasGetter()) {
      Object value = fieldEntry.get(classInstance);

      if (!fieldEntry.isFinal()) {
        value = RandomFactory.getRandomValue(fieldEntry);
        fieldEntry.set(classInstance, value);
      }

      SameInstanceIdentityHandlerStub.registerIdentityHandlerStubForValue(value);

      LoggerFactory.getLogger(this.getClass()).debug("Testing Field [{0}] with value [{1}]", fieldEntry, safeToString(value));

      Affirm.affirmEquals("Getter returned non equal value for field=[" + fieldEntry + "]", value, fieldEntry.invokeGetter(classInstance));
      SameInstanceIdentityHandlerStub.unregisterIdentityHandlerStubForValue(value);
    } else {
      LoggerFactory.getLogger(this.getClass()).debug("Field [{0}] has no getter skipping", fieldEntry);
    }
  }
}
 
Example 3
Source File: SetterTester.java    From openpojo with Apache License 2.0 6 votes vote down vote up
public void run(final PojoClass pojoClass) {
  final Object classInstance = ValidationHelper.getBasicInstance(pojoClass);
  for (final PojoField fieldEntry : pojoClass.getPojoFields()) {
    if (fieldEntry.hasSetter()) {
      final Object value;

      value = RandomFactory.getRandomValue(fieldEntry);

      SameInstanceIdentityHandlerStub.registerIdentityHandlerStubForValue(value);
      LoggerFactory.getLogger(this.getClass()).debug("Testing Field [{0}] with value [{1}]",
          fieldEntry, safeToString(value));

      fieldEntry.invokeSetter(classInstance, value);

      Affirm.affirmEquals("Setter test failed, non equal value for field=[" + fieldEntry + "]", value,
          fieldEntry.get(classInstance));

      SameInstanceIdentityHandlerStub.unregisterIdentityHandlerStubForValue(value);
    } else {
      LoggerFactory.getLogger(this.getClass()).debug("Field [{0}] has no setter skipping", fieldEntry);
    }
  }
}
 
Example 4
Source File: SerializableTester.java    From openpojo with Apache License 2.0 6 votes vote down vote up
private void ensureNoFieldsAreNull(PojoClass pojoClass, Object instance) {
  PojoClass currentPojo = pojoClass;
  while (currentPojo != null) {
    for (PojoField field : currentPojo.getPojoFields()) {
      PojoClass fieldClass = PojoClassFactory.getPojoClass(field.getType());
      if (useStrictValidation && !fieldClass.extendz(Serializable.class) && fieldClass.isInterface() && !field.isTransient()) {
        Affirm.fail("Field ["
                + field.getName()
                + "] is an interface that allows non-Serializable types on a Serializable ["
                + pojoClass.getClazz()
                + "]"
            );
      }
      if (field.get(instance) == null)
        field.set(instance, RandomFactory.getRandomValue(field));
    }
    currentPojo = currentPojo.getSuperClass();
  }
}
 
Example 5
Source File: PojoFieldImplTest.java    From openpojo with Apache License 2.0 6 votes vote down vote up
@Test
public void multipleAnnotationsShouldBeReturned() {
  PojoClass pojoClass = PojoClassFactory.getPojoClass(AClassWithVariousAnnotatedFields.class);
  List<PojoField> allFields = pojoClass.getPojoFields();

  for (PojoField pojoField : allFields) {
    if (pojoField.getName().equals("multipleAnnotationField")) {
      Affirm.affirmEquals(String.format("Annotations added/removed from field=[%s]", pojoField), 2, pojoField.getAnnotations
          ().size());
      List<Class<?>> expectedAnnotations = new LinkedList<Class<?>>();
      expectedAnnotations.add(SomeAnnotation.class);
      expectedAnnotations.add(BusinessKey.class);
      for (Annotation annotation : pojoField.getAnnotations()) {
        Affirm.affirmTrue(String.format("Expected annotations [%s] not found, instead found [%s]", expectedAnnotations,
            annotation.annotationType()), expectedAnnotations.contains(annotation.annotationType()));
      }
      return;
    }
  }
  Affirm.fail(String.format("multipleAnnotationField renamed? expected in [%s]", pojoClass));
}
 
Example 6
Source File: NoPrimitivesRule.java    From openpojo with 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 7
Source File: PojoFieldImplTest.java    From openpojo with Apache License 2.0 5 votes vote down vote up
@Test
public void annotationlessShouldNotReturnNull() {
  PojoClass pojoClass = PojoClassFactory.getPojoClass(AClassWithVariousAnnotatedFields.class);
  List<PojoField> allFields = pojoClass.getPojoFields();

  for (PojoField pojoField : allFields) {
    if (pojoField.getName().equals("nonAnnotatedField")) {
      Affirm.affirmNotNull("getAnnotations should not return null.", pojoField.getAnnotations());
      return;
    }
  }
  Affirm.fail(String.format("nonAnnotatedField renamed? expected in [%s]", pojoClass));
}
 
Example 8
Source File: NoStaticExceptFinalRule.java    From openpojo with Apache License 2.0 5 votes vote down vote up
public void evaluate(final PojoClass pojoClass) {
  for (PojoField fieldEntry : pojoClass.getPojoFields()) {
    if (fieldEntry.isStatic() && !fieldEntry.isFinal()) {
      Affirm.fail(String.format("Static fields=[%s] not marked final are not allowed", fieldEntry));
    }
  }
}
 
Example 9
Source File: PojoFieldImplTest.java    From openpojo with Apache License 2.0 5 votes vote down vote up
@Test
public void canGetEnclosingClass() {
  PojoClass pojoClassWithFields = PojoClassFactory.getPojoClass(AClassWithFields.class);
  Affirm.affirmTrue("Class should have some fields", pojoClassWithFields.getPojoFields().size() > 0);
  for (PojoField field : pojoClassWithFields.getPojoFields()) {
    Affirm.affirmEquals("Failed to get PojoClass from field ["+ field + "]", pojoClassWithFields, field.getDeclaringPojoClass());
  }
}
 
Example 10
Source File: NoPublicFieldsExceptStaticFinalRule.java    From openpojo with Apache License 2.0 5 votes vote down vote up
public void evaluate(final PojoClass pojoClass) {
  for (PojoField fieldEntry : pojoClass.getPojoFields()) {
    if (fieldEntry.isPublic() && !ValidationHelper.isStaticFinal(fieldEntry)) {
      Affirm.fail(String.format("Non 'static final' Public fields=[%s] not allowed", fieldEntry));
    }
  }
}
 
Example 11
Source File: SerializableTester.java    From openpojo with Apache License 2.0 5 votes vote down vote up
private String getFailMessage(PojoClass pojoClass, NotSerializableException notSerializable) {
  String message = "Class [" + pojoClass.getClazz().getName() + "] has non-serializable field type [";
  boolean found = false;
  for (PojoField field : pojoClass.getPojoFields())
    if (field.getType().getName().equals(notSerializable.getMessage())) {
      found = true;
      message += field;
    }
  if (!found)
    message += notSerializable.getMessage() + "] which is inherited from a super class";
  else
    message += "]";
  return message;
}
 
Example 12
Source File: DefaultValuesNullTester.java    From openpojo with Apache License 2.0 5 votes vote down vote up
public void run(final PojoClass pojoClass) {
  final Object classInstance = ValidationHelper.getBasicInstance(pojoClass);

  for (final PojoField fieldEntry : pojoClass.getPojoFields()) {
    if (!fieldEntry.isPrimitive() && !fieldEntry.isFinal() && fieldEntry.getAnnotation(BusinessKey.class) == null) {
      Affirm.affirmNull(String.format("Expected null value for for field=[%s]", fieldEntry), fieldEntry.get(classInstance));
    }
  }
}
 
Example 13
Source File: AbstractUnitTest.java    From cia with Apache License 2.0 5 votes vote down vote up
public void run(final PojoClass pojoClass) {
	final Object classInstance = ValidationHelper.getBasicInstance(pojoClass);
	for (final PojoField fieldEntry : pojoClass.getPojoFields()) {

		if (fieldEntry.hasSetter()) {
			final String name = fieldEntry.getName();

			final List<PojoMethod> methods = pojoClass.getPojoMethods();

			for (final PojoMethod pojoMethod : methods) {
				if (("with" + name).equalsIgnoreCase(pojoMethod.getName())) {

					final Object value = RandomFactory.getRandomValue(fieldEntry);

					SameInstanceIdentityHandlerStub.registerIdentityHandlerStubForValue(value);
					LoggerFactory.getLogger(this.getClass()).debug("Testing Field [{0}] with value [{1}]",
							fieldEntry, safeToString(value));

					pojoMethod.invoke(classInstance, value);

					Affirm.affirmEquals("With test failed, non equal value for field=[" + fieldEntry + "]",
							value, fieldEntry.get(classInstance));

					SameInstanceIdentityHandlerStub.unregisterIdentityHandlerStubForValue(value);
				}
			}
		}
	}
}
 
Example 14
Source File: PojoFieldPrefixedFieldsTest.java    From openpojo with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHaveGettersAndSetters() {
  AttributeHelper.registerFieldPrefix("m");
  PojoClass pojoClass = PojoClassFactory.getPojoClass(AClassWithFieldsPrefixed.class);
  for (PojoField pojoField : pojoClass.getPojoFields()) {
    Affirm.affirmTrue(String.format("Getters / Setters not found on field =[%s]", pojoField), pojoField.hasGetter() &&
        pojoField.hasSetter());
  }
}
 
Example 15
Source File: IssueTest.java    From openpojo with 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 16
Source File: JacocoPojoClassAdapter.java    From openpojo with Apache License 2.0 5 votes vote down vote up
public PojoClass adapt(final PojoClass pojoClass) {
  final List<PojoField> cleansedPojoFields = new LinkedList<PojoField>();
  for (final PojoField pojoField : pojoClass.getPojoFields()) {
    if (!pojoField.getName().equals(JACOCO_FIELD_NAME)) {
      cleansedPojoFields.add(pojoField);
    }
  }
  final List<PojoMethod> cleansedPojoMethods = new LinkedList<PojoMethod>();
  for (final PojoMethod pojoMethod : pojoClass.getPojoMethods()) {
    if (!pojoMethod.getName().equals(JACOCO_METHOD_NAME)) {
      cleansedPojoMethods.add(pojoMethod);
    }
  }
  return new PojoClassImpl(pojoClass.getClazz(), cleansedPojoFields, cleansedPojoMethods);
}
 
Example 17
Source File: ValidationHelperTest.java    From openpojo with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsStaticFinal() {
  PojoClass pojoClass = PojoClassFactory.getPojoClass(StaticFinalData.class);
  List<PojoField> pojoFields = pojoClass.getPojoFields();
  Assert.assertEquals(4, pojoFields.size());
  for (PojoField fieldEntry : pojoFields) {
    if (fieldEntry.getName().equals("staticAndNotFinal")) {
      Assert.assertTrue("Static and not Final test failed!!",
          fieldEntry.isStatic()
              && !fieldEntry.isFinal()
              && !ValidationHelper.isStaticFinal(fieldEntry));
    }
    if (fieldEntry.getName().equals("notStaticAndNotFinal")) {
      Assert.assertTrue("Not static OR final test failed!!",
          !fieldEntry.isStatic()
              && !fieldEntry.isFinal()
              && !ValidationHelper.isStaticFinal(fieldEntry));
    }
    if (fieldEntry.getName().equals("STATIC_AND_FINAL")) {
      Assert.assertTrue("Static AND Final test failed!!!",
          fieldEntry.isStatic()
              && fieldEntry.isFinal()
              && ValidationHelper.isStaticFinal(fieldEntry));
    }
    if (fieldEntry.getName().equals("finalAndNotStatic")) {
      Assert.assertTrue("Final and not Static test failed!!",
          !fieldEntry.isStatic()
              && fieldEntry.isFinal()
              && !ValidationHelper.isStaticFinal(fieldEntry));
    }
  }
}
 
Example 18
Source File: AbstractUnitTest.java    From cia with Apache License 2.0 5 votes vote down vote up
private static void randomValues(final Object instance, final PojoClass pojoClass) {
	if (pojoClass == null) {
		return;
	}

	for (final PojoField fieldEntry : pojoClass.getPojoFields()) {
		if (fieldEntry.hasSetter()) {
			final Object value;

			value = RandomFactory.getRandomValue(fieldEntry);
			fieldEntry.invokeSetter(instance, value);
		}
	}
	randomValues(instance, pojoClass.getSuperClass());
}
 
Example 19
Source File: PojoFieldImplTest.java    From openpojo with 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 20
Source File: AllPimitivesAsArraysDeclaredRule.java    From openpojo with Apache License 2.0 4 votes vote down vote up
public void evaluate(PojoClass pojoClass) {
  boolean foundBytes = false,
          foundChars = false,
          foundShorts = false,
          foundInts = false,
          foundLongs = false,
          foundFloats = false,
          foundDoubles = false,
          foundBooleans = false;

  for (PojoField field : pojoClass.getPojoFields()) {
    if (field.isArray()) {
      Type type = field.getParameterTypes().get(0);
      if (type == byte.class)
        foundBytes = true;
      if (type == char.class)
        foundChars = true;
      if (type == short.class)
        foundShorts = true;
      if (type == int.class)
        foundInts = true;
      if (type == long.class)
        foundLongs = true;
      if (type == float.class)
        foundFloats = true;
      if (type == double.class)
        foundDoubles = true;
      if (type == boolean.class)
        foundBooleans = true;
    }
  }
  Assert.assertTrue("byte array not found", foundBytes);
  Assert.assertTrue("char array not found", foundChars);
  Assert.assertTrue("short array not found", foundShorts);
  Assert.assertTrue("int array not found", foundInts);
  Assert.assertTrue("long array not found", foundLongs);
  Assert.assertTrue("float array not found", foundFloats);
  Assert.assertTrue("double array not found", foundDoubles);
  Assert.assertTrue("boolean array not found", foundBooleans);
  Assert.assertEquals("No other fields allowed, only primitive arrays", 8, pojoClass.getPojoFields().size());
}