All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.genesys.blocks.auditlog.component.AuditTrailInterceptor Maven / Gradle / Ivy

/*
 * Copyright 2017 Global Crop Diversity Trust
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.genesys.blocks.auditlog.component;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.Format;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import org.genesys.blocks.auditlog.annotations.Audited;
import org.genesys.blocks.auditlog.annotations.NotAudited;
import org.genesys.blocks.auditlog.model.AuditAction;
import org.genesys.blocks.auditlog.model.AuditLog;
import org.genesys.blocks.auditlog.model.TransactionAuditLog;
import org.genesys.blocks.auditlog.service.AuditTrailService;
import org.genesys.blocks.model.BasicModel;
import org.genesys.blocks.model.EntityId;
import org.hibernate.CallbackException;
import org.hibernate.EmptyInterceptor;
import org.hibernate.Transaction;
import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.type.Type;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ResolvableType;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

/**
 * Record changed data using {@link AuditLog} entries.
 *
 * @author Matija Obreza
 */
@Component
public class AuditTrailInterceptor extends EmptyInterceptor implements InitializingBean {

	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = 1881637304461659508L;

	/** The Constant LOG. */
	private static final Logger LOG = LoggerFactory.getLogger(AuditTrailInterceptor.class);

	/** The Constant DEFAULT_IGNORED_PROPERTIES. */
	private static final Set DEFAULT_IGNORED_PROPERTIES = Stream.of("serialVersionUID", "id", "password", "createdDate", "lastModifiedDate", "version", "lastModifiedBy")
		.collect(Collectors.toSet());

	/** The ignored properties. */
	private Set ignoredProperties = new HashSet<>(DEFAULT_IGNORED_PROPERTIES);

	/** The audited classes. */
	private Set> auditedClasses = new HashSet<>();

	/** The included classes. */
	// Two caches
	private final Set> ignoredClasses, includedClasses;

	/** The audit trail service. */
	@Autowired
	private AuditTrailService auditTrailService;

	/** The entity manager. */
	@PersistenceContext
	private EntityManager entityManager;

	/** The date format. */
	private final String dateFormat = "dd-MMM-yyyy";

	/** The time format. */
	private final String timeFormat = "HH:mm:ss";

	/** The date time format. */
	private final String dateTimeFormat = "dd-MMM-yyyy HH:mm:ss";

	/** The date formatter. */
	private Format dateFormatter;

	/** The date time formatter. */
	private Format dateTimeFormatter;

	/** The time formatter. */
	private Format timeFormatter;

	/** Place to store audit logs before storing them to db */
	private static final ThreadLocal> auditLogs = new ThreadLocal>() {
		@Override
		protected Set initialValue() {
			return new HashSet<>();
		};
	};

	private static final ThreadLocal transactionStack = new ThreadLocal() {
		@Override
		protected AtomicLong initialValue() {
			return new AtomicLong(0l);
		};
	};

	/**
	 * Instantiates a new audit trail interceptor.
	 */
	public AuditTrailInterceptor() {
		LOG.info("Enabling {}", getClass().getName());
		// make synchronized local caches
		ignoredClasses = Collections.synchronizedSet(new HashSet<>());
		includedClasses = Collections.synchronizedSet(new HashSet<>());
	}

	/*
	 * (non-Javadoc)
	 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
	 */
	@Override
	public void afterPropertiesSet() throws Exception {
		assert ignoredProperties != null;
		assert auditTrailService != null;

		// Make them unmodifiable
		ignoredProperties = Collections.unmodifiableSet(ignoredProperties);
		auditedClasses = Collections.unmodifiableSet(auditedClasses);

		dateFormatter = FastDateFormat.getInstance(dateFormat);
		dateTimeFormatter = FastDateFormat.getInstance(dateTimeFormat);
		timeFormatter = FastDateFormat.getInstance(timeFormat);
	}

	/**
	 * Explicitly set the list of classes that should be audited. Note that any
	 * class with {@link Audited} annotation will be included, even if not on this
	 * list.
	 *
	 * @param auditedClasses entity classes to audit
	 * @see Audited
	 */
	public void setAuditedClasses(final Set> auditedClasses) {
		this.auditedClasses = auditedClasses;
	}

	/**
	 * Gets the audited classes.
	 *
	 * @return the audited classes
	 */
	public Set> getAuditedClasses() {
		return auditedClasses;
	}

	/**
	 * Set the list of properties to ignore on all entities (e.g. "password").
	 * Defaults to {@link #DEFAULT_IGNORED_PROPERTIES}. Note that you can explicitly
	 * exclude fields by annotating them with @NotAudited annotation
	 * (see {@link NotAudited}).
	 *
	 * @param ignoredProperties entity property names to exclude from audit trail
	 * @see NotAudited
	 */
	public void setIgnoredProperties(final Set ignoredProperties) {
		this.ignoredProperties = ignoredProperties;
	}

	/**
	 * Gets the ignored properties.
	 *
	 * @return the ignored properties
	 */
	public Set getIgnoredProperties() {
		return ignoredProperties;
	}

	/**
	 * Sets the audit trail service.
	 *
	 * @param auditTrailService the new audit trail service
	 */
	public void setAuditTrailService(final AuditTrailService auditTrailService) {
		this.auditTrailService = auditTrailService;
	}

	/**
	 * Gets the audit trail service.
	 *
	 * @return the audit trail service
	 */
	public AuditTrailService getAuditTrailService() {
		return auditTrailService;
	}

	/*
	 * (non-Javadoc)
	 * @see org.hibernate.EmptyInterceptor#onFlushDirty(java.lang.Object,
	 * java.io.Serializable, java.lang.Object[], java.lang.Object[],
	 * java.lang.String[], org.hibernate.type.Type[])
	 */
	/* We add more stuff to the transaction if that fails we're still good! */
	@Override
	public boolean onFlushDirty(final Object entity, final Serializable id, final Object[] currentState, final Object[] previousState, final String[] propertyNames,
			final Type[] types) {
		final Class entityClass = entity.getClass();
		if (LOG.isTraceEnabled()) {
			LOG.trace("Inspecting Entity.class={} id={}", entityClass, id);
		}

		if (!isAudited(entityClass)) {
			return false;
		}

		// Identify changed values
		for (int i = 0; i < previousState.length; i++) {
			final String propertyName = propertyNames[i];
			final Object prev = previousState[i];
			final Object curr = currentState[i];

			if (ignoredProperties.contains(propertyName)) {
				continue;
			}

			if (((prev != null) && !prev.equals(curr)) || ((prev == null) && (curr != null))) {
				LOG.trace("prop={} prev={} curr={} type={}", propertyName, prev, curr, types[i].getReturnedClass());

				if (isPrimitiveType(types[i].getReturnedClass())) {
					final String currentValue = formatValue(curr, types[i], entityClass, propertyName);
					final String previousValue = formatValue(prev, types[i], entityClass, propertyName);

					if (!StringUtils.equals(previousValue, currentValue)) {
						// Notice cast to Long here!
						recordChange(entity, (Long) id, propertyName, previousValue, currentValue, null);
					}
				} else if (isEntity(types[i].getReturnedClass())) {
					final EntityId prevEntity = (EntityId) prev, currEntity = (EntityId) curr;
					final String previousValue = prevEntity == null ? null : prevEntity.getId().toString();
					final String currentValue = currEntity == null ? null : currEntity.getId().toString();

					if (!StringUtils.equals(previousValue, currentValue)) {
						// Notice cast to Long here!
						recordChange(entity, (Long) id, propertyName, previousValue, currentValue, types[i].getReturnedClass());
					}
				} else {
					LOG.trace("Entity.{} {} is not a primitive. Ignoring value={}", propertyName, prev == null ? null : prev.getClass(), prev);
					// TODO Capture in audit log
				}
			}
		}
		return false;
	}

	/**
	 * Format value.
	 *
	 * @param someValue the some value
	 * @param type the type
	 * @param entityClass the entity class
	 * @param propertyName the property name
	 * @return the string
	 */
	private String formatValue(final Object someValue, final Type type, final Class entityClass, final String propertyName) {
		if (someValue == null) {
			return null;
		}
		final Class returnedClass = type.getReturnedClass();

		if (Date.class.equals(returnedClass) || Calendar.class.equals(returnedClass)) {
			TemporalType temporalType = TemporalType.TIMESTAMP;

			try {
				final Field field = entityClass.getDeclaredField(propertyName);
				if ((field != null) && field.isAnnotationPresent(Temporal.class)) {
					final Temporal ta = field.getAnnotation(Temporal.class);
					temporalType = ta.value();
				}
			} catch (NoSuchFieldException | SecurityException e) {
				LOG.trace("Could not access field {}#{}", entityClass, propertyName);
			}

			switch (temporalType) {
			case TIMESTAMP:
				return dateTimeFormatter.format(someValue);
			case DATE:
				return dateFormatter.format(someValue);
			case TIME:
				return timeFormatter.format(someValue);
			}
		}

		return someValue.toString();
	}

	/**
	 * Checks if is entity.
	 *
	 * @param clazz the clazz
	 * @return true, if is entity
	 */
	private boolean isEntity(final Class clazz) {
		if (EntityId.class.isAssignableFrom(clazz)) {
			return true;
		}
		LOG.trace("{} is not an EntityId", clazz.getName());
		return false;
	}

	/*
	 * (non-Javadoc)
	 * @see org.hibernate.EmptyInterceptor#onDelete(java.lang.Object,
	 * java.io.Serializable, java.lang.Object[], java.lang.String[],
	 * org.hibernate.type.Type[])
	 */
	@Override
	public void onDelete(final Object entity, final Serializable id, final Object[] states, final String[] propertyNames, final Type[] types) {
		final Class entityClass = entity.getClass();
		if (LOG.isTraceEnabled()) {
			LOG.trace("Inspecting Entity.class={} id={}", entityClass, id);
		}

		if (!isAudited(entityClass)) {
			LOG.trace("{} is not audited", entityClass);
			return;
		}

		for (int i = 0; i < states.length; i++) {
			final String propertyName = propertyNames[i];
			final Object state = states[i];

			if (ignoredProperties.contains(propertyName)) {
				continue;
			}

			if (state != null) {
				LOG.trace("Deleted prop={} state={} type={}", propertyName, state, types[i].getReturnedClass());

				if (isPrimitiveType(types[i].getReturnedClass())) {
					// Notice cast to Long here!
					recordDelete(entity, (Long) id, propertyName, state == null ? null : state.toString(), null);
				} else if (isEntity(types[i].getReturnedClass())) {
					final EntityId prevEntity = (EntityId) state;
					final String previousValue = prevEntity == null ? null : prevEntity.getId().toString();
					// Notice cast to Long here!
					recordDelete(entity, (Long) id, propertyName, previousValue, types[i].getReturnedClass());
				} else {
					LOG.trace("Entity.{} {} is not a primitive. Ignoring value={}", propertyName, state == null ? null : state.getClass(), state);
					// TODO Capture in audit log
					// PersistentBag
				}
			}
		}
	}

	/*
	 * (non-Javadoc)
	 * @see org.hibernate.EmptyInterceptor#onCollectionRecreate(java.lang.Object,
	 * java.io.Serializable)
	 */
	@Override
	public void onCollectionRecreate(final Object collection, final Serializable key) throws CallbackException {
		LOG.trace("Collection recreated: key={} coll={}", key, collection);
	}

	/*
	 * (non-Javadoc)
	 * @see org.hibernate.EmptyInterceptor#onCollectionRemove(java.lang.Object,
	 * java.io.Serializable)
	 */
	@Override
	public void onCollectionRemove(final Object collection, final Serializable key) throws CallbackException {
		final PersistentCollection pc = (PersistentCollection) collection;
		if (!isAudited(pc.getOwner().getClass())) {
			LOG.trace("Class {} is not audited", pc.getOwner().getClass());
			return;
		}
		LOG.trace("Collection remove: key={} coll={}", key, collection);

		final Class ownerClass = pc.getOwner().getClass();
		final String propertyName = pc.getRole().substring(pc.getRole().lastIndexOf('.') + 1);
		final Class propertyType = findPropertyType(ownerClass, propertyName);
		LOG.trace("Property class: {}.{}={}", ownerClass.getName(), propertyName, propertyType);

		Collection deleted = new HashSet<>();

		if (pc.getValue() instanceof Collection) {
			deleted.addAll((Collection) pc.getValue());
		}

		// If remaining is EntityId, convert to ID only
		Class referencedEntity = null;
		if (EntityId.class.isAssignableFrom(propertyType)) {
			LOG.trace("{} is EntityId, converting values.", propertyType.getName());
			referencedEntity = propertyType;
			deleted = convertEntityId(deleted);
		}

		LOG.trace("prev=" + deleted.toString() + " curr=" + null);
		recordDelete(pc.getOwner(), (Long) key, propertyName, deleted.toString(), referencedEntity);
	}

	/*
	 * (non-Javadoc)
	 * @see org.hibernate.EmptyInterceptor#onCollectionUpdate(java.lang.Object,
	 * java.io.Serializable)
	 */
	@Override
	public void onCollectionUpdate(final Object collection, final Serializable key) throws CallbackException {
		final PersistentCollection pc = (PersistentCollection) collection;
		if (!isAudited(pc.getOwner().getClass())) {
			LOG.trace("Class {} is not audited", pc.getOwner().getClass());
			return;
		}
		LOG.trace("Collection update: key={} coll={}", key, collection);

		final Class ownerClass = pc.getOwner().getClass();
		LOG.trace("ownerClass={} role={}", ownerClass.getName(), pc.getRole());
		final String propertyName = pc.getRole().substring(pc.getRole().lastIndexOf('.') + 1);
		final Class propertyType = findPropertyType(ownerClass, propertyName);
		LOG.trace("Property class: {}.{}={}", ownerClass.getName(), propertyName, propertyType);

		Collection remaining = new HashSet<>();

		if (pc.getValue() instanceof Collection) {
			remaining.addAll((Collection) pc.getValue());
		} else {
			LOG.trace("Can't handle pc={} val={}", pc.getValue().getClass(), pc);
		}

		Collection previous = null;
		final Serializable snap = pc.getStoredSnapshot();
		if (snap instanceof Map) {
			final Map snapMap = (Map) snap;
			previous = snapMap.values();
		} else if (snap instanceof Collection) {
			final Collection snapList = (Collection) snap;
			previous = snapList;
		} else {
			LOG.trace("Can't handle snap={} val={}", snap.getClass(), snap);
		}

		// If remaining is EntityId, convert to ID only
		Class referencedEntity = null;
		if (EntityId.class.isAssignableFrom(propertyType)) {
			LOG.trace("{} is EntityId, converting values.", propertyType.getName());
			referencedEntity = propertyType;
			previous = convertEntityId(previous);
			remaining = convertEntityId(remaining);
		}

		LOG.trace("prev=" + previous + " curr=" + remaining);
		recordChange(pc.getOwner(), (Long) key, propertyName, previous.toString(), remaining.toString(), referencedEntity);
	}

	/**
	 * Find property type.
	 *
	 * @param class1 the class 1
	 * @param propertyName the property name
	 * @return the class
	 */
	private Class findPropertyType(final Class class1, final String propertyName) {
		LOG.trace("Finding property type for {}.{}", class1.getName(), propertyName);

		// Field
		final Field field = ReflectionUtils.findField(class1, propertyName);
		if (field != null) {
			LOG.trace("Found field: " + field + "\n\ttype=" + field.getType() + "\n\tgeneric=" + field.getGenericType() + "\n\tgenericTN=" + field.getGenericType().getTypeName());
			final ResolvableType t = ResolvableType.forField(field, class1);
			if (t.hasGenerics()) {
				LOG.trace("\tResoved={} returning={}", t.toString(), t.resolveGeneric(0));
				return t.resolveGeneric(0);
			} else {
				LOG.trace("Returning class itself={}", t.getRawClass());
				return t.getRawClass();
			}
		}

		// Getter
		try {
			final Method method = class1.getMethod("get" + StringUtils.capitalize(propertyName));
			if (method != null) {
				LOG.trace("Didn't find field, found the method: " + method.getReturnType().getTypeParameters()[0]);
			}
		} catch (SecurityException | NoSuchMethodException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * Convert entity id.
	 *
	 * @param previous the previous
	 * @return the collection
	 */
	private Collection convertEntityId(final Collection previous) {
		final Collection converted = new ArrayList<>();
		for (final Object p : previous) {
			if (p instanceof EntityId) {
				converted.add(((EntityId) p).getId());
			} else {
				converted.add(p);
			}
		}
		return converted;
	}

	/**
	 * Checks if class is a "primitive".
	 *
	 * @param class1 the property class
	 * @return true, if is primitive
	 */
	boolean isPrimitiveType(final Class class1) {
		if (class1.isPrimitive()) {
			return true;
		} else if (class1.isEnum()) {
			return true;
		} else if (class1.isArray()) {
			return false;
		} else if (Number.class.isAssignableFrom(class1)) {
			return true;
		} else if (String.class.equals(class1)) {
			return true;
		} else if (Character.class.equals(class1)) {
			return true;
		} else if (Boolean.class.equals(class1)) {
			return true;
		} else if (Date.class.equals(class1)) {
			return true;
		} else if (UUID.class.equals(class1)) {
			return true;
		}
		if (LOG.isDebugEnabled()) {
			LOG.trace("Class {} is not a primitive.", class1);
		}
		return false;
	}

	/**
	 * Record change.
	 *
	 * @param logDate the log date
	 * @param entity the entity
	 * @param id the id
	 * @param propertyName the property name
	 * @param previousState the previous state
	 * @param currentState the current state
	 * @param referencedEntity the referenced entity
	 */
	private void recordChange(final Object entity, final Long id, final String propertyName, final String previousState, final String currentState,
			final Class referencedEntity) {

		TransactionAuditLog change = auditTrailService.auditLogEntry(AuditAction.UPDATE, entity, id, propertyName, previousState, currentState, referencedEntity);
		if (auditLogs.get().remove(change)) {
			LOG.trace("Replacing exising changelog {}", change);
		} else {
			LOG.trace("Adding new changelog {}", change);
		}
		auditLogs.get().add(change);
	}

	/**
	 * Record delete.
	 *
	 * @param logDate the log date
	 * @param entity the entity
	 * @param id the id
	 * @param propertyName the property name
	 * @param state the state
	 * @param referencedEntity the referenced entity
	 */
	private void recordDelete(final Object entity, final Long id, final String propertyName, final String state, final Class referencedEntity) {
		TransactionAuditLog delete = auditTrailService.auditLogEntry(AuditAction.DELETE, entity, id, propertyName, state, null, referencedEntity);
		if (auditLogs.get().remove(delete)) {
			LOG.trace("Replacing exising changelog {}", delete);
		} else {
			LOG.trace("Adding new changelog {}", delete);
		}
		auditLogs.get().add(delete);
	}

	/**
	 * Determines if the entity class should be audited.
	 *
	 * @param entityClass entity class
	 * @return true when changes should be audited
	 */
	boolean isAudited(final Class entityClass) {
		// Cache lookup
		if (includedClasses.contains(entityClass)) {
			return true;
		}
		// Cache lookup
		if (ignoredClasses.contains(entityClass)) {
			return false;
		}

		final NotAudited notAuditedAnnotation = entityClass.getAnnotation(NotAudited.class);
		if (notAuditedAnnotation != null) {
			LOG.trace("{} is exluded from auditing", entityClass);
			// Register ignored class
			ignoredClasses.add(entityClass);
			return false;
		}

		final Audited auditedAnnotation = entityClass.getAnnotation(Audited.class);
		if (auditedAnnotation != null) {
			LOG.trace("{} is annotated for auditing", entityClass);
			// Register included class
			includedClasses.add(entityClass);
			return true;
		}

		for (final Class auditedClass : auditedClasses) {
			if (auditedClass.isAssignableFrom(entityClass)) {
				LOG.trace("{} is audited because it is an instance of {}", entityClass, auditedClass);
				// Register included class
				includedClasses.add(entityClass);
				return true;
			}
		}

		LOG.trace("{} is not audited", entityClass);
		// Register ignored entity class
		ignoredClasses.add(entityClass);
		return false;
	}

	// @Override
	// public boolean onSave(Object entity, Serializable id, Object[] state,
	// String[] propertyNames, Type[] types) {
	// LOG.trace("onSave entity={} id={} props={}", entity, id,
	// Arrays.toString(propertyNames));
	// return super.onSave(entity, id, state, propertyNames, types);
	// }

	@Override
	public void afterTransactionBegin(final Transaction tx) {
		transactionStack.get().getAndIncrement();
		LOG.trace("Starting transaction level={}", transactionStack.get().get());

		// tx.registerSynchronization(new Synchronization() {
		//
		// @Override
		// public void beforeCompletion() {
		// LOG.trace("callback beforeCompletion");
		// }
		//
		// @Override
		// public void afterCompletion(int status) {
		// LOG.trace("callback afterCompletion status={}", status);
		// }
		// });
		super.afterTransactionBegin(tx);
	}

	// Called before a transaction is committed (but not before rollback).
	@Override
	public void beforeTransactionCompletion(final Transaction tx) {
		final long level = transactionStack.get().get();
		LOG.trace("beforeTransactionCompletion transaction level={} auditlogs={}", level, auditLogs.get().size());

		// LOG.trace("Before transaction completion status={} tx={}",
		// tx.getLocalStatus(), tx);

		if (level == 1 && auditLogs.get().size() > 0) {
			LOG.trace("We have {} auditlogs", auditLogs.get().size());
			auditLogs.get().stream().forEach(auditLog -> {
				LOG.debug("Audit log to save: {}", auditLog);
			});
			this.auditTrailService.addAuditLogs(auditLogs.get());
			auditLogs.get().clear();
		}

		super.beforeTransactionCompletion(tx);
	}

	// @SuppressWarnings({ "rawtypes", "unchecked" })
	// @Override
	// public void postFlush(final Iterator entities) {
	// // LOG.trace("postFlush {}", entities);
	// entities.forEachRemaining(entity -> {
	// LOG.trace("postFlush {}", entity);
	// });
	//
	// super.postFlush(entities);
	// }

	// Called after a transaction is committed or rolled back.
	@Override
	public void afterTransactionCompletion(Transaction tx) {
		final long level = transactionStack.get().decrementAndGet();
		LOG.trace("afterTransactionCompletion transaction level={} auditlogs={}", level, auditLogs.get().size());
		if (tx.wasCommitted()) {
			LOG.trace("Transaction was committed, have {} audit logs", auditLogs.get().size());
		} else if (tx.wasRolledBack()) {
			LOG.trace("Transaction was rolled back, have {} audit logs", auditLogs.get().size());
		}

		if (level == 0) {
			// clear pending logs if back to level 0
			auditLogs.get().clear();
		}
		super.afterTransactionCompletion(tx);
	}

	@Override
	public Boolean isTransient(final Object entity) {
		if (entity instanceof BasicModel) {
			return !((BasicModel) entity).isPersisted();
		}
		// TODO Use Spring field access methods?
		try {
			return tryMethod(entity, "getVersion");
		} catch (final NoSuchMethodException e) {
			try {
				return tryMethod(entity, "getId");
			} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e1) {
				throw new RuntimeException(e.getMessage() + " on " + entity.getClass() + " e=" + entity, e);
			}
		} catch (final Throwable e) {
			throw new RuntimeException(e.getMessage() + " on " + entity.getClass() + " e=" + entity, e);
		}
	}

	public Boolean tryMethod(final Object entity, final String methodName) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
		final Method getter = entity.getClass().getMethod(methodName);
		if (getter != null) {
			final Object result = getter.invoke(entity);
			if (result == null) {
				LOG.trace(entity + " is transient, has " + methodName + " == null");
				return true;
			} else if (result instanceof Number) {
				final Number r = (Number) result;
				if (r.longValue() < 0) {
					LOG.trace(entity + " is transient, has " + methodName + " = " + result + " < 0");
					return true;
				} else {
					// LOG.trace(entity + " is not transient, has " + methodName + " = " + result +
					// " >= 0");
					return false;
				}
			} else {
				// LOG.trace(entity + " is not transient, has " + methodName + " = " + result);
				return false;
			}
		} else {
			LOG.trace("No version method.");
			throw new RuntimeException("No version method");
		}
	}
}