loc.setState("MN");
loc.setZipCode("55901");
loc.setCountry("USA");
// Create an Image with non-matching type and file extension
Image img = new Image();
img.setType(ImageType.JPEG);
img.setFileName("Winter_01.gif");
loadImage(img);
img.setLocation(loc);
// *** PERSIST ***
try {
em.getTransaction().begin();
System.out.println("Persisting an entity with non-matching extension and type");
em.persist(img);
fail();
} catch (ConstraintViolationException cve) {
// Transaction was marked for rollback, roll it back and
// start a new TX
em.getTransaction().rollback();
handleConstraintViolation(cve);
em.getTransaction().begin();
System.out.println("Fixing the file type and re-attempting the persist.");
img.setType(ImageType.GIF);
em.persist(img);
em.getTransaction().commit();
System.out.println("Persist was successful");
}
// *** UPDATE ***
try {
em.getTransaction().begin();
// Modify the file name to a non-matching file name
// and commit to trigger an update
System.out.println("Modifying file name to use an extension that does not");
System.out.println("match the file type. This will cause a CVE.");
img.setFileName("Winter_01.jpg");
em.getTransaction().commit();
fail();
} catch (ConstraintViolationException cve) {
// Handle the exception. The commit failed so the transaction
// was already rolled back.
System.out.println("Update failed as expected");
handleConstraintViolation(cve);
}
// The update failure caused img to be detached. It must be merged back
// into the persistence context.
img = em.merge(img);
// *** REMOVE ***
em.getTransaction().begin();
try {
// Remove the type and commit to trigger removal
System.out.println("Setting the type to an invalid type. This will cause a");
System.out.println("validation exception upon removal");
img.setType(null);
em.remove(img);
em.getTransaction().commit(); // never gets this far... fails on the remove()
fail();
} catch (ConstraintViolationException cve) {
// Rollback the active transaction and handle the exception