Java Code Examples for com.openpojo.validation.affirm.Affirm#fail()

The following examples show how to use com.openpojo.validation.affirm.Affirm#fail() . 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: ClassMemberTest.java    From openpojo with Apache License 2.0 6 votes vote down vote up
@Test
public void ensureSampleClassDefinitionIsCorrect() {
  String fieldName = "someMemberClass";
  Affirm.affirmEquals(String.format("Fields added/removed to [%s]?", pojoClass), 1, pojoClass.getPojoFields().size());

  boolean validated = false;
  for (PojoField pojoField : pojoClass.getPojoFields()) {
    if (pojoField.getName().equals(fieldName)) {
      Affirm.affirmEquals("Field type changed?", Class.class.getName(), pojoField.getType().getName());
      Affirm.affirmTrue(String.format("Getter/Setter removed from field[%s]",
          pojoField), pojoField.hasGetter() && pojoField.hasSetter());
      validated = true;
    }
  }
  if (!validated) {
    Affirm.fail(String.format("[%s] field not found on PojoClass [%s]", fieldName, pojoClass));
  }
}
 
Example 3
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 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: SerializableTester.java    From openpojo with Apache License 2.0 6 votes vote down vote up
public void run(PojoClass pojoClass) {
  final Class<?> clazz = pojoClass.getClazz();

  if (Serializable.class.isAssignableFrom(clazz)) {
    Object instance = RandomFactory.getRandomValue(clazz);
    ensureNoFieldsAreNull(pojoClass, instance);

    try {
      byte[] serializedObject = serialize(pojoClass, instance);
      Object instance2 = deSerialize(serializedObject, instance.getClass());
      Affirm.affirmNotNull("Failed to load serialized object [" + instance + "]", instance2);
    } catch (Exception e) {
      Affirm.fail("Failed to run " + this.getClass().getName() + " - Got exception [" + e + "] on PojoClass " + pojoClass);
    }
  } else {
    logger.warn("Class [" + clazz + "] is not serializable, skipping validation");
  }
}
 
Example 6
Source File: StructuralTest.java    From openpojo with Apache License 2.0 6 votes vote down vote up
public void run(PojoClass pojoClass) {
  Affirm.affirmEquals("Should have only one constructor [" + pojoClass.getName() + "]",
      1,
      pojoClass.getPojoConstructors().size());
  PojoMethod constructor = pojoClass.getPojoConstructors().get(0);
  Affirm.affirmTrue("Constructor should be private [" + pojoClass.getName() + "]", constructor.isPrivate());
  try {
    InstanceFactory.getInstance(pojoClass);
    Affirm.fail("Class [" + pojoClass.getName() + "] should have throw exception upon creation");
  } catch (ReflectionException re) {
    Throwable actual = re;
    while (actual != null && !(actual instanceof UnsupportedOperationException))
      actual = actual.getCause();

    if (actual == null)
      Affirm.fail("Expected " + UnsupportedOperationException.class.getName()
          + " to be thrown when constructing [" + pojoClass.getName() + "] but was " + re);
    else
      Affirm.affirmEquals("Expected message miss-match"
          , pojoClass.getName() + " should not be constructed!"
          , actual.getMessage());
  }
}
 
Example 7
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 8
Source File: PojoMethodImplTest.java    From openpojo with Apache License 2.0 5 votes vote down vote up
/**
 * Test method for {@link com.openpojo.reflection.impl.PojoMethodImpl#isFinal()}.
 */
@Test
public void testIsFinal() {
  for (PojoMethod pojoMethod : pojoMethods) {
    if (pojoMethod.getName().equals("finalMethod")) {
      Affirm.affirmTrue("Failed to check final", pojoMethod.isFinal());
      return;
    }
  }
  Affirm.fail("finalMethod missing!!");
}
 
Example 9
Source File: InstanceFactoryTest.java    From openpojo with Apache License 2.0 5 votes vote down vote up
@Test(expected = ReflectionException.class)
public void shouldFailtoCreateUsingDefault() {
  final Class<?> clazz = ClassWithNoDeclaredConstructor.class;
  final String stringParam = RandomFactory.getRandomValue(String.class);
  getInstance(clazz, stringParam);
  Affirm.fail("Should've failed to create");
}
 
Example 10
Source File: InstanceFactoryTest.java    From openpojo with Apache License 2.0 5 votes vote down vote up
@Test(expected = ReflectionException.class)
public void shouldFailtoCreateParametersMissmatch() {
  final Class<?> clazz = ClassWithVariousDeclaredContructorsAndMethods.class;
  final String stringParam = RandomFactory.getRandomValue(String.class);
  getInstance(clazz, stringParam, stringParam);
  Affirm.fail("Should've failed to create");
}
 
Example 11
Source File: JARPackageLoaderTest.java    From openpojo with Apache License 2.0 5 votes vote down vote up
private JARPackageLoader getJarPackageLoader(final String packageName) {
  Enumeration<URL> resources = null;
  try {
    resources = Thread.currentThread().getContextClassLoader().getResources(
        packageName.replace(Java.PACKAGE_DELIMITER, Java.PATH_DELIMITER));
  } catch (IOException e) {
    Affirm.fail(MessageFormatter.format("Failed to get resources for package[{0}] got exception[{1}]", packageName, e));
  }
  URL resource = resources.nextElement();

  Affirm.affirmEquals(MessageFormatter.format("[{0}] not located in a jar file!!", packageName), "jar", resource.getProtocol());

  return new JARPackageLoader(resource, packageName);
}
 
Example 12
Source File: PojoMethodImplTest.java    From openpojo with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsNotSynthetic() {
  for (PojoMethod pojoMethod : pojoMethods) {
    if (pojoMethod.getName().equals("isNotSyntheticMethod")) {
      Affirm.affirmTrue("Failed to check isNotSynthetic method", !pojoMethod.isSynthetic());
      return;
    }
  }
  Affirm.fail("isNotSyntheticMethod missing!!");
}
 
Example 13
Source File: SetterMustExistRule.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.isFinal() && !fieldEntry.hasSetter()) {
      Affirm.fail(String.format("[%s] is missing a setter", fieldEntry));
    }
  }
}
 
Example 14
Source File: PojoMethodImplTest.java    From openpojo with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsNotStatic() {
  for (PojoMethod pojoMethod : pojoMethods) {
    if (pojoMethod.getName().equals("nonStaticMethod")) {
      Affirm.affirmTrue("Failed to check non static method", !pojoMethod.isStatic());
      return;
    }
  }
  Affirm.fail("nonStaticMethod missing!!");
}
 
Example 15
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 16
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 17
Source File: BusinessKeyMustExistRule.java    From openpojo with Apache License 2.0 5 votes vote down vote up
public void evaluate(final PojoClass pojoClass) {
  for (BusinessKeyField businessField : getBusinessKeyFields(pojoClass.getClazz())) {
    if (businessField.isRequired() || businessField.isComposite()) {
      return;
    }
  }

  Affirm.fail(String.format("[%s] doesn't declare any 'required' BusinessKeys!!", pojoClass.getClazz()));
}
 
Example 18
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 19
Source File: PojoMethodImplTest.java    From openpojo with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsSynthetic() {
  PojoClass syntheticPojoClass = PojoClassFactory.getPojoClass(AClassWithSyntheticMethod.class);
  for (PojoMethod pojoMethod : syntheticPojoClass.getPojoMethods()) {
    if (!pojoMethod.getName().equals("doSomethingSneaky") && !pojoMethod.isConstructor()) {
      Affirm.affirmFalse("Failed to check synthetic method [" + pojoMethod + "]", !pojoMethod.isSynthetic());
      return;
    }
  }
  Affirm.fail("failed to find a synthetic method in class");
}
 
Example 20
Source File: TestClassMustBeProperlyNamedRule.java    From openpojo with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public void evaluate(PojoClass pojoClass) {
  if (!pojoClass.isConcrete() || properlyNamed(pojoClass))
    return;

  for (Class<? extends Annotation> annotation : loadedAnnotations) {
    if (isAnnotatedOrParentAnnotated(pojoClass, annotation)) {
      Affirm.fail("Test class [" + pojoClass.getName() + "] does not start with " + prefixes.toString() + " or ends with "
          + suffixes.toString());
    }
  }
}