# HG changeset patch # User indvdum (gotoindvdum[at]gmail[dot]com) # Date 1352415649 -14400 # Node ID f692598b374238fc81fa4b4fd191f49588c9450b # Parent 452e65d696a36be265d554ea8ed18b0d41b24aa7 Moving reusable JPA DAO code into separate module diff -r 452e65d696a3 -r f692598b3742 pom.xml --- a/pom.xml Thu Nov 08 23:28:16 2012 +0400 +++ b/pom.xml Fri Nov 09 03:00:49 2012 +0400 @@ -52,6 +52,18 @@ + + org.apache.maven.plugins + maven-jar-plugin + ${maven-jar-plugin.version} + + + + test-jar + + + + @@ -77,5 +89,10 @@ ${derby.version} test + + org.codehaus.jackson + jackson-jaxrs + ${jackson-jaxrs.version} + diff -r 452e65d696a3 -r f692598b3742 src/main/java/ru/indvdum/jpa/collections/EntityList.groovy --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/ru/indvdum/jpa/collections/EntityList.groovy Fri Nov 09 03:00:49 2012 +0400 @@ -0,0 +1,35 @@ +package ru.indvdum.jpa.collections + +/** + * @author indvdum (gotoindvdum@gmail.com) + * @since 12.01.2012 17:26:13 + * + * @param + */ +class EntityList extends TriggeredList { + + def ofObject + def getter + def setter + + public EntityList() { + super() + } + + public EntityList(Object ofObject, String getter, String setter) { + this.ofObject = ofObject + this.getter = getter + this.setter = setter + } + + @Override + protected void afterChange() { + if(ofObject == null || getter == null || setter == null) + return + each { + if(it."${getter}"() != ofObject) { + it."${setter}"(ofObject) + } + } + } +} diff -r 452e65d696a3 -r f692598b3742 src/main/java/ru/indvdum/jpa/collections/TriggeredList.groovy --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/ru/indvdum/jpa/collections/TriggeredList.groovy Fri Nov 09 03:00:49 2012 +0400 @@ -0,0 +1,93 @@ +package ru.indvdum.jpa.collections + +import java.util.Collection +import java.util.Iterator +import java.util.List +import java.util.ListIterator + +/** + * E realization of List interface with support of change notifications + * + * @author indvdum (gotoindvdum[at]gmail[dot]com) + * @since 12.01.2012 13:57:48 + * + * @param + */ +abstract class TriggeredList extends ArrayList { + + /** + * Invoked after changes in list + */ + abstract protected void afterChange(); + + // changing methods + + @Override + public boolean add(E e) { + boolean result = super.add(e); + afterChange(); + return result; + } + + @Override + public boolean remove(Object o) { + boolean result = super.remove(o); + afterChange(); + return result; + } + + @Override + public boolean addAll(Collection c) { + boolean result = super.addAll(c); + afterChange(); + return result; + } + + @Override + public boolean addAll(int index, Collection c) { + boolean result = super.addAll(index, c); + afterChange(); + return result; + } + + @Override + public boolean removeAll(Collection c) { + boolean result = super.removeAll(c); + afterChange(); + return result; + } + + @Override + public boolean retainAll(Collection c) { + boolean result = super.retainAll(c); + afterChange(); + return result; + } + + @Override + public void clear() { + super.clear(); + afterChange(); + } + + @Override + public E set(int index, E element) { + E result = super.set(index, element); + afterChange(); + return result; + } + + @Override + public void add(int index, E element) { + super.add(index, element); + afterChange(); + } + + @Override + public E remove(int index) { + E result = super.remove(index); + afterChange(); + return result; + } + +} diff -r 452e65d696a3 -r f692598b3742 src/main/java/ru/indvdum/jpa/dao/JPADataAccessObject.groovy --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/ru/indvdum/jpa/dao/JPADataAccessObject.groovy Fri Nov 09 03:00:49 2012 +0400 @@ -0,0 +1,201 @@ +package ru.indvdum.jpa.dao import java.sql.Connection +import java.sql.SQLException +import java.util.ResourceBundle; import java.util.Map.Entry + +import javax.persistence.EntityManager +import javax.persistence.EntityManagerFactory +import javax.persistence.EntityTransaction +import javax.persistence.NoResultException +import javax.persistence.Persistence +import javax.persistence.Query +import javax.persistence.criteria.CriteriaBuilder +import javax.persistence.criteria.CriteriaQuery +import javax.persistence.criteria.Predicate +import javax.persistence.criteria.Root +import javax.sql.DataSource + +import org.apache.openjpa.conf.OpenJPAConfiguration +import org.apache.openjpa.persistence.OpenJPAEntityManagerFactorySPI +import org.apache.openjpa.persistence.OpenJPAPersistence +import org.slf4j.Logger +import org.slf4j.LoggerFactory + import ru.indvdum.jpa.props.Props; +/** + * @author indvdum (gotoindvdum[at]gmail[dot]com) + * @since 08.11.2012 23:35:04 + * + */ +public class JPADataAccessObject { + protected static String persistenceUnitName = null; + protected static EntityManagerFactory emf = Persistence.createEntityManagerFactory(getPersistenceUnitName(), PropertySelector.select()); + protected EntityManager em = emf.createEntityManager(); + final static Logger log = LoggerFactory.getLogger(JPADataAccessObject.class.getSimpleName()); + + JPADataAccessObject() { + em.isOpen(); + } protected static String getPersistenceUnitName() { if (persistenceUnitName != null) return persistenceUnitName; if (persistenceUnitName == null) persistenceUnitName = System.getProperty(Props.PERSISTANCE_UNIT_NAME_PROPERTY); if (persistenceUnitName == null) persistenceUnitName = ResourceBundle.getBundle(Props.JPADAO_PROPERTY_FILE).getString(Props.PERSISTANCE_UNIT_NAME_PROPERTY); if (persistenceUnitName == null) persistenceUnitName = "database"; return persistenceUnitName; } + + public static Connection getSQLConnection() throws SQLException { + OpenJPAEntityManagerFactorySPI openjpaemf = (OpenJPAEntityManagerFactorySPI) OpenJPAPersistence.cast(emf); + OpenJPAConfiguration conf = openjpaemf.getConfiguration(); + DataSource ds = (DataSource) conf.getConnectionFactory(); + return ds.getConnection(); + } + + void close() { + em.close() + em = null + } + + public T mergeAndRefresh(T object) { + def merged = em.merge(object) + em.refresh(merged) + + merged + } + + public T merge(T object) { + em.merge(object) + } + + void refresh(Object ... refreshObjects) { + for(object in refreshObjects) { + em.refresh(object) + } + } + + boolean persist(Object ... persistanceQueue) { + persistAndRemove(persistanceQueue, new Object[0]) + } + + boolean persist(Collection entities) { + persistAndRemove(entities.toArray(), new Object[0]) + } + + boolean remove(Object ... removeQueue) { + persistAndRemove(new Object[0], removeQueue) + } + + boolean remove(Collection entities) { + persistAndRemove(new Object[0], entities.toArray()) + } + + synchronized boolean persistAndRemove(Object[] persistanceQueue, Object[] removeQueue) { + EntityTransaction tx = null + + try { + tx = em.getTransaction() + tx.begin() + + if(persistanceQueue != null) { + for(object in persistanceQueue) { + if(object != null) { + em.persist(object) + } + } + } + + if(removeQueue != null) { + for(object in removeQueue) { + if(object != null) { + em.remove(object) + } + } + } + + tx.commit() + } + catch(Throwable t) { + log.error("Error while synchronizing with Database: ", t); + + if(tx != null && tx.isActive()) { + tx.rollback() + } + + return false + } + + return true + } + + public T find(Class entityClass, Object primaryKey) { + return em.find(entityClass, primaryKey); + } + + public List list(Class entityClass, Map equalProperties, Map notEqualProperties) { + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaQuery query = cb.createQuery(entityClass); + Root root = query.from(entityClass); + Collection predicates = new HashSet(); + if(equalProperties != null) { + for(Entry entry: equalProperties.entrySet()){ + String property = entry.getKey(); + Object value = entry.getValue(); + predicates.add(cb.equal(root.get(property), value)); + } + } + if(notEqualProperties != null) { + for(Entry entry: equalProperties.entrySet()){ + String property = entry.getKey(); + Object value = entry.getValue(); + predicates.add(cb.notEqual(root.get(property), value)); + } + } + query.where(cb.and(predicates.toArray(new Predicate[predicates.size()]))); + return em.createQuery(query).getResultList(); + } + + public T find(Class entityClass, Map equalProperties, Map notEqualProperties) { + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaQuery query = cb.createQuery(entityClass); + Root root = query.from(entityClass); + Collection predicates = new HashSet(); + if(equalProperties != null) { + for(Entry entry: equalProperties.entrySet()){ + String property = entry.getKey(); + Object value = entry.getValue(); + predicates.add(cb.equal(root.get(property), value)); + } + } + if(notEqualProperties != null) { + for(Entry entry: equalProperties.entrySet()){ + String property = entry.getKey(); + Object value = entry.getValue(); + predicates.add(cb.notEqual(root.get(property), value)); + } + } + query.where(cb.and(predicates.toArray(new Predicate[predicates.size()]))); + T result = null; + try { + result = em.createQuery(query).getSingleResult(); + } catch (NoResultException e) { + log.error("Error while searching object in Database: ", e); + } + return result; + } + + public List list(Class entityClass) { + CriteriaQuery query = em.getCriteriaBuilder().createQuery(entityClass); + query.from(entityClass); + return new ArrayList(em.createQuery(query).getResultList()); + } + + public boolean contains(Collection entities) { + boolean res = true; + entities.each {res &= contains(it)} + return res + } + + public boolean contains(Object entity) { + return em.contains(entity); + } + + private Object getSingleResult(Query query) { + try { + return query.getSingleResult() + } + catch (NoResultException e) { + return null + } + } +} diff -r 452e65d696a3 -r f692598b3742 src/main/java/ru/indvdum/jpa/dao/PropertySelector.groovy --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/ru/indvdum/jpa/dao/PropertySelector.groovy Fri Nov 09 03:00:49 2012 +0400 @@ -0,0 +1,55 @@ +package ru.indvdum.jpa.dao + +/** + * @author indvdum (gotoindvdum[at]gmail[dot]com) + * @since 03.11.2011 13:53:32 + * + */ +class PropertySelector { + public static final String SHOWSQL = "custom.showsql" + public static final String SYNCHRONIZEDB = "custom.synchronize" + public static final String SCHEMANAME = "custom.schemaname" + public static final String DBDICTIONARY = "custom.dbdictionary" + public static final String RUNTIMEENHANCEMENT = "custom.runtimeenhancement" + + private static Properties properties = new Properties() + + private static boolean isProperty(String propertyName) { + return Boolean.valueOf(properties.getProperty(propertyName)).booleanValue() + } + + private static String getSystemProperty(String propertyName) { + properties.getProperty(propertyName) + } + + static void setSystemProperty(String propertyName, String propertyValue) { + properties.setProperty(propertyName, propertyValue) + } + + static Map select() { + Map emfProperties = [:] + + if(isProperty(SHOWSQL)) { + emfProperties["openjpa.Log"] = "DefaultLevel=INFO, Tool=INFO, SQL=TRACE" + emfProperties["openjpa.ConnectionFactoryProperties"] = "PrintParameters=true, PrettyPrint=true" + } + + if(isProperty(SYNCHRONIZEDB)) { + emfProperties["openjpa.jdbc.SynchronizeMappings"] = "buildSchema(ForeignKeys=true)" + } + + if(getSystemProperty(SCHEMANAME) != null) { + emfProperties["openjpa.jdbc.Schema"] = getSystemProperty(SCHEMANAME) + } + + if(getSystemProperty(DBDICTIONARY)) { + emfProperties["openjpa.jdbc.DBDictionary"] = getSystemProperty(DBDICTIONARY) + } + + if(getSystemProperty(RUNTIMEENHANCEMENT)) { + emfProperties["openjpa.RuntimeUnenhancedClasses"] = getSystemProperty(RUNTIMEENHANCEMENT) + } + + return emfProperties + } +} diff -r 452e65d696a3 -r f692598b3742 src/main/java/ru/indvdum/jpa/entities/AbstractEntity.groovy --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/ru/indvdum/jpa/entities/AbstractEntity.groovy Fri Nov 09 03:00:49 2012 +0400 @@ -0,0 +1,132 @@ +package ru.indvdum.jpa.entities + +import java.lang.reflect.Modifier + +import javax.persistence.EmbeddedId +import javax.persistence.Entity +import javax.persistence.Id +import javax.persistence.Transient + +import org.apache.openjpa.util.OpenJPAId +import org.codehaus.jackson.map.ObjectMapper + +import ru.indvdum.jpa.dao.JPADataAccessObject; + +/** + * @author indvdum (gotoindvdum@gmail.com) + * @since 25.12.2011 13:26:57 + * + */ +abstract class AbstractEntity implements Serializable { + + @Transient + protected ObjectMapper mapper = new ObjectMapper() + + @Override + public String toString() { + return getClass().getSimpleName() + ' ' + toJSON() + } + + /** + * JSON-like representation of an object + * + * @return + */ + public String toJSON() { + return mapper.writeValueAsString(this) + } + + /* + * HashCode, based on root class name of entity class hierarchy and id value + * + * (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + Class clazz = getClass() + while ( + clazz.superclass != null + && !Modifier.isAbstract(clazz.superclass.modifiers) + && clazz.superclass.annotations.find {it instanceof Entity} != null + ) + clazz = clazz.superclass + String res = clazz.getName() + ': ' + getIdentifierValue() + return res.hashCode() + } + + /* + * Comparison, based on entities id's + * + * (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if(obj == null) + return false + if(!(obj.class.isAssignableFrom(this.class) || this.class.isAssignableFrom(obj.class))) + return false + def id = getIdentifierValue() + def objId = (obj as AbstractEntity).getIdentifierValue() + return id == objId || id != null && id != this && id.equals(objId) + } + + /** + * @return The identifier value of an entity. + */ + @Transient + public Object getIdentifierValue() { + // an attempt to get id by EntityManagerFactory + Object identifier = JPADataAccessObject.emf.getPersistenceUnitUtil().getIdentifier(this) + if(identifier instanceof OpenJPAId) + return ((OpenJPAId)identifier).getIdObject() + + def result + + // an attempt to find id by annotated fields + Class clazz = getClass() + def self = this + Collection fields = clazz.declaredFields + while(clazz.superclass != null) { + clazz = clazz.superclass + fields.addAll(clazz.declaredFields) + } + fields.grep { + !it.synthetic && + !Modifier.isStatic(it.modifiers) && + !Modifier.isTransient(it.modifiers) + }.grep { + it.annotations.find { + it instanceof Id || it instanceof EmbeddedId + } != null + }.each { + boolean isAccessible = it.accessible + it.accessible = true + result = it.get(self) + it.accessible = isAccessible + } + if(result != null && !(result instanceof Reference && (result as Reference).value == null)) + return result + + // an attempt to represent id as a aggregate of all fields + // TODO check, why toJSON method don't work +// return toJSON() + result = '{' + fields.grep { + !it.synthetic && + !Modifier.isStatic(it.modifiers) && + !Modifier.isTransient(it.modifiers) + }.grep { + it.annotations.find { + it instanceof Transient + } == null + }.each { + boolean isAccessible = it.accessible + it.accessible = true + result += '"' + it.name + '": "' + it.get(self) + '", ' + it.accessible = isAccessible + } + return result + } +} diff -r 452e65d696a3 -r f692598b3742 src/main/java/ru/indvdum/jpa/jndi/SimpleContext.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/ru/indvdum/jpa/jndi/SimpleContext.java Fri Nov 09 03:00:49 2012 +0400 @@ -0,0 +1,173 @@ +package ru.indvdum.jpa.jndi; + +import java.util.HashMap; +import java.util.Hashtable; +import java.util.Map; + +import javax.naming.Binding; +import javax.naming.Context; +import javax.naming.Name; +import javax.naming.NameClassPair; +import javax.naming.NameParser; +import javax.naming.NamingEnumeration; +import javax.naming.NamingException; + +/** + * @author indvdum (gotoindvdum[at]gmail[dot]com) + * @since 03.11.2011 16:37:15 + * + */ +public class SimpleContext implements Context { + private Map _bind_map = new HashMap(); + + public SimpleContext(Hashtable environment) { + } + + @Override + public Object addToEnvironment(String propName, Object propVal) throws NamingException { + throw new UnsupportedOperationException(); + } + + @Override + public void bind(Name name, Object obj) throws NamingException { + bind(String.valueOf(name), obj); + } + + @Override + public void bind(String name, Object obj) throws NamingException { + if (_bind_map.get(name) == null) { + _bind_map.put(name, obj); + } else { + throw new NamingException("Already bond."); + } + } + + @Override + public void close() throws NamingException { + } + + @Override + public Name composeName(Name name, Name prefix) throws NamingException { + throw new UnsupportedOperationException(); + } + + @Override + public String composeName(String name, String prefix) throws NamingException { + throw new UnsupportedOperationException(); + } + + @Override + public Context createSubcontext(Name name) throws NamingException { + throw new UnsupportedOperationException(); + } + + @Override + public Context createSubcontext(String name) throws NamingException { + throw new UnsupportedOperationException(); + } + + @Override + public void destroySubcontext(Name name) throws NamingException { + throw new UnsupportedOperationException(); + } + + @Override + public void destroySubcontext(String name) throws NamingException { + throw new UnsupportedOperationException(); + } + + @Override + public Hashtable getEnvironment() throws NamingException { + throw new UnsupportedOperationException(); + } + + @Override + public String getNameInNamespace() throws NamingException { + throw new UnsupportedOperationException(); + } + + @Override + public NameParser getNameParser(Name name) throws NamingException { + throw new UnsupportedOperationException(); + } + + @Override + public NameParser getNameParser(String name) throws NamingException { + throw new UnsupportedOperationException(); + } + + @Override + public NamingEnumeration list(Name name) throws NamingException { + throw new UnsupportedOperationException(); + } + + @Override + public NamingEnumeration list(String name) throws NamingException { + throw new UnsupportedOperationException(); + } + + @Override + public NamingEnumeration listBindings(Name name) throws NamingException { + throw new UnsupportedOperationException(); + } + + @Override + public NamingEnumeration listBindings(String name) throws NamingException { + throw new UnsupportedOperationException(); + } + + @Override + public Object lookup(Name name) throws NamingException { + return lookup(String.valueOf(name)); + } + + @Override + public Object lookup(String name) throws NamingException { + return _bind_map.get(name); + } + + @Override + public Object lookupLink(Name name) throws NamingException { + throw new UnsupportedOperationException(); + } + + @Override + public Object lookupLink(String name) throws NamingException { + throw new UnsupportedOperationException(); + } + + @Override + public void rebind(Name name, Object obj) throws NamingException { + rebind(String.valueOf(name), obj); + } + + @Override + public void rebind(String name, Object obj) throws NamingException { + _bind_map.put(name, obj); + } + + @Override + public Object removeFromEnvironment(String propName) throws NamingException { + throw new UnsupportedOperationException(); + } + + @Override + public void rename(Name oldName, Name newName) throws NamingException { + throw new UnsupportedOperationException(); + } + + @Override + public void rename(String oldName, String newName) throws NamingException { + throw new UnsupportedOperationException(); + } + + @Override + public void unbind(Name name) throws NamingException { + unbind(String.valueOf(name)); + } + + @Override + public void unbind(String name) throws NamingException { + _bind_map.remove(name); + } +} \ No newline at end of file diff -r 452e65d696a3 -r f692598b3742 src/main/java/ru/indvdum/jpa/jndi/SimpleContextFactory.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/ru/indvdum/jpa/jndi/SimpleContextFactory.java Fri Nov 09 03:00:49 2012 +0400 @@ -0,0 +1,28 @@ +package ru.indvdum.jpa.jndi; + +import java.util.Hashtable; + +import javax.naming.Context; +import javax.naming.NamingException; +import javax.naming.spi.InitialContextFactory; + +/** + * @author indvdum (gotoindvdum[at]gmail[dot]com) + * @since 03.11.2011 16:37:21 + * + */ +public class SimpleContextFactory implements InitialContextFactory { + + private static Context simpleContext = null; + + @Override + public Context getInitialContext(Hashtable environment) throws NamingException { + if (simpleContext == null) { + synchronized (this) { + simpleContext = new SimpleContext(environment); + } + } + + return simpleContext; + } +} \ No newline at end of file diff -r 452e65d696a3 -r f692598b3742 src/main/java/ru/indvdum/jpa/props/Props.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/ru/indvdum/jpa/props/Props.java Fri Nov 09 03:00:49 2012 +0400 @@ -0,0 +1,14 @@ +package ru.indvdum.jpa.props; + +/** + * @author indvdum (gotoindvdum[at]gmail[dot]com) + * @since 09.11.2012 1:14:24 + * + */ +public class Props { + + public static final String PERSISTANCE_UNIT_NAME_PROPERTY = "jpadao.persistenceUnitName"; + public static final String DATA_SOURCE_PROPERTY = "jpadao.datasource"; + public static final String JPADAO_PROPERTY_FILE = "jpadao"; + +} diff -r 452e65d696a3 -r f692598b3742 src/main/resources/jndi.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/resources/jndi.properties Fri Nov 09 03:00:49 2012 +0400 @@ -0,0 +1,1 @@ +java.naming.factory.initial=ru.indvdum.jpa.jndi.SimpleContextFactory \ No newline at end of file diff -r 452e65d696a3 -r f692598b3742 src/test/java/ru/indvdum/jpa/tests/AbstractJPAEntityTest.groovy --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/test/java/ru/indvdum/jpa/tests/AbstractJPAEntityTest.groovy Fri Nov 09 03:00:49 2012 +0400 @@ -0,0 +1,326 @@ +package ru.indvdum.jpa.tests +; + +import static org.junit.Assert.* + +import java.lang.reflect.Field +import java.lang.reflect.Method +import java.lang.reflect.Modifier + +import javax.persistence.EmbeddedId +import javax.persistence.Entity +import javax.persistence.GeneratedValue +import javax.persistence.Id +import javax.persistence.IdClass +import javax.persistence.Transient + +import org.junit.Test + +import ru.indvdum.jpa.dao.JPADataAccessObject +import ru.indvdum.jpa.entities.AbstractEntity; + + +/** + * JUnit test case for testing of a creating, listing, updating and removing + * operations with database of the JPA entities. + * + * @author indvdum (gotoindvdum@gmail.com) + * @since 23.12.2011 22:54:26 + * + */ +abstract class AbstractJPAEntityTest extends AbstractJPATest { + + protected def uniqueValue = 1 + protected JPADataAccessObject dao = null + protected Set toRemove = new HashSet() + + @Test + public void testEntity() { + dao = createDAO() + try { + testEntity(getEntityClass()) + } finally { + dao.close() + } + } + + /** + * @return Your implementation of JPADataAccessObject + */ + protected abstract JPADataAccessObject createDAO(); + + /** + * Test creating, listing, updating, and removing of an {@code entityClass} object + * + * @param entityClass + */ + protected void testEntity(Class entityClass) { + + assert AbstractEntity.class.isAssignableFrom(entityClass) + + Map fieldsValues + def dbEntity + + // creating + def entity = createEntity(entityClass) + testCreatedEntity(entity) + + // listing + toRemove.each { + assert dao.list(it.class).each { it2 -> + assert it.class.isAssignableFrom(it2.class) + }.size() == toRemove.findAll { it2 -> + it.class.isAssignableFrom(it2.class) + }.size() + } + + // updating + fieldsValues = updateFields(entity) + assert dao.persist(entity) + assert dao.contains(entity) + dbEntity = dao.find(entityClass, (entity as AbstractEntity).getIdentifierValue()) + assert dbEntity != null + assert checkEntityFieldValues(dbEntity, fieldsValues) + testUpdatedEntity(entity) + + // removing + assert dao.remove(toRemove) + assert !dao.contains(toRemove) + testRemovedEntity(entity) + } + + /** + * Create and persist to database an {@code entityClass} object + * + * @param entityClass + * @return created entity object + */ + protected Object createEntity(Class entityClass) { + assertNotNull entityClass.annotations.find {it instanceof Entity} + def entity = entityClass.newInstance() + assert entity.class == entityClass + toRemove.add(entity) + + Map fieldsValues = updateFields(entity) + assert dao.persist(entity) + assert dao.contains(entity) + def dbEntity = dao.find(entityClass, (entity as AbstractEntity).getIdentifierValue()) + assert dbEntity != null + assert checkEntityFieldValues(dbEntity, fieldsValues) + + return entity + } + + /** + * Update all fields of an {@code entity} object + * @param entity + * @return generated field values + */ + protected Map updateFields(Object entity) { + Map fieldsValues = new HashMap() + getFields(entity).grep { + it.annotations.find { + it instanceof Transient || it instanceof GeneratedValue + } == null + }.each { + def newValue = generateFieldValue(entity, it) + setFieldValueBySetter(entity, it, newValue) + fieldsValues.put(it.name, newValue) + } + return fieldsValues + } + + /** + * Collections and arrays will not be processed + * + * @param entity + * @param field + * @return generated field value + */ + protected Object generateFieldValue(Object entity, Field field) { + def type = field.getType() + def newValue + if(type.toString() == 'boolean' || type == Boolean.class) { + newValue = (boolean) (uniqueValue++ % 2i == 0i) + } else if(type.toString() == 'byte' || type == Byte) { + newValue = (byte) (uniqueValue++ % Byte.MAX_VALUE + 1i) + } else if(type.toString() == 'char' || type == Character) { + newValue = (char) (uniqueValue++ % (int) Character.MAX_VALUE + 1i) + } else if(type.toString() == 'short' || type == Short) { + newValue = (short) (uniqueValue++ % Short.MAX_VALUE + 1i) + } else if(type.toString() == 'int' || type == Integer) { + newValue = (int) (uniqueValue++ % Integer.MAX_VALUE + 1i) + } else if(type.toString() == 'long' || type == Long) { + newValue = (long) uniqueValue++ % Long.MAX_VALUE + 1L + } else if(type.toString() == 'float' || type == Float) { + newValue = (float) uniqueValue++ % Float.MAX_VALUE + 1f + } else if(type.toString() == 'double' || type == Double) { + newValue = (double) uniqueValue++ % Double.MAX_VALUE + 1d + } else if(type == String.class) { + newValue = (String) "test${uniqueValue++}" + } else if(type instanceof Class && (type as Class).annotations.find {it instanceof Entity} != null) { // modifying of a primary keys is deprecated + // an attempt to use already created entities + def currentValue = getFieldValue(entity, field) + newValue = toRemove.find {it.class == type && it != currentValue} + if(newValue == null) + newValue = createEntity(type as Class) + } else if( + type instanceof Class + && !( + field.clazz.annotations.find {it instanceof IdClass} != null + && field.declaredAnnotations.find {it instanceof Id} != null + ) + && field.declaredAnnotations.find {it instanceof EmbeddedId} == null + && !Collection.class.isAssignableFrom(type) + && !(type as Class).isArray() + ) { // modifying of a primary keys is deprecated + newValue = (type as Class).newInstance() + } else { + newValue = getFieldValue(entity, field) + } + return newValue + } + + /** + * @param entity + * @param rightValues + * @return {@code true}, if all entity fields is equals to {@code rightValues} + */ + protected boolean checkEntityFieldValues(Object entity, Map rightValues) { + def result = true + def fields = getFields(entity) + rightValues.each { key, value -> + fields.find { it.name == key }.each { + if(!getFieldValue(entity, it).equals(value)) { + result = false + } + } + } + return result + } + + /** + * Set a {@code field} to a {@code value} of an entity {@code object} + * + * @param object + * @param field + * @param value + */ + protected void setFieldValue(Object object, Field field, Object value) { + boolean isAccessible = field.accessible + field.accessible = true + field.set(object, value) + field.accessible = isAccessible + } + + /** + * Trying set a {@code field} to a {@code value} of an entity {@code object} + * by using a setter method. If setter not found, field will be set directly + * throw {@code setFieldValue} method. + * + * @param object + * @param field + * @param value + */ + protected void setFieldValueBySetter(Object object, Field field, Object value) { + boolean isSetted = false + getMethods(object).grep { + ( + Modifier.isPublic(it.modifiers) + && it.parameterTypes.size() == 1 + && ( + value == null + || it.parameterTypes[0].isAssignableFrom(value.class) + ) + && it.name =~ /^set(?i:${field.name.charAt(0)})${field.name.replaceFirst("^.{1}", "")}/ + ) + }.each { + object."${it.name}"(value) + isSetted = true + } + if(isSetted) + return + setFieldValue(object, field, value) + } + + /** + * @param object + * @param field + * @return the field value of an object + */ + protected Object getFieldValue(Object object, Field field) { + boolean isAccessible = field.accessible + field.accessible = true + def value = field.get(object) + field.accessible = isAccessible + return value + } + + /** + * @param obj + * @return all object fields, including inherited + */ + protected Collection getFields(obj) { + Class clazz = obj.getClass() + Collection fields = clazz.declaredFields + while(clazz.superclass != null) { + clazz = clazz.superclass + fields.addAll(clazz.declaredFields) + } + fields.grep { + !it.synthetic && + !Modifier.isStatic(it.modifiers) && + !Modifier.isTransient(it.modifiers) + } + } + + /** + * @param obj + * @return all object methods, including inherited + */ + protected Collection getMethods(obj) { + Class clazz = obj.getClass() + Collection methods = clazz.declaredMethods + while(clazz.superclass != null) { + clazz = clazz.superclass + methods.addAll(clazz.declaredMethods) + } + methods.grep { + !it.synthetic && + !Modifier.isStatic(it.modifiers) && + !Modifier.isTransient(it.modifiers) + } + } + + /** + * For implement in successors + * + * @param entity + */ + protected void testCreatedEntity(Object entity) { + + } + + /** + * For implement in successors + * + * @param entity + */ + protected void testUpdatedEntity(Object entity) { + + } + + /** + * For implement in successors + * + * @param entity + */ + protected void testRemovedEntity(Object entity) { + + } + + /** + * @return an {@link AbstractEntity} successor + */ + abstract protected Class getEntityClass() +} diff -r 452e65d696a3 -r f692598b3742 src/test/java/ru/indvdum/jpa/tests/AbstractJPATest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/test/java/ru/indvdum/jpa/tests/AbstractJPATest.java Fri Nov 09 03:00:49 2012 +0400 @@ -0,0 +1,71 @@ +package ru.indvdum.jpa.tests; + +import java.util.ResourceBundle; + +import javax.naming.InitialContext; +import javax.naming.NamingException; + +import org.apache.commons.dbcp.BasicDataSource; +import org.junit.BeforeClass; + +import ru.indvdum.jpa.dao.PropertySelector; +import ru.indvdum.jpa.props.Props; + +/** + * @author indvdum (gotoindvdum[at]gmail[dot]com) + * @since 22.12.2011 16:44:26 + * + */ +public abstract class AbstractJPATest { + + @BeforeClass + public static void setUpClass() throws Exception { + if ("true".equalsIgnoreCase(System.getProperty("JPA.realDatabaseConnection"))) { + initRealDatabase(); + } else { + initDerby(); + } + } + + protected static String dataSource = null; + + protected static String getDataSourceName() { + if (dataSource != null) + return dataSource; + + if (dataSource == null) + dataSource = System.getProperty(Props.DATA_SOURCE_PROPERTY); + if (dataSource == null) + dataSource = ResourceBundle.getBundle(Props.JPADAO_PROPERTY_FILE).getString(Props.DATA_SOURCE_PROPERTY); + if (dataSource == null) + dataSource = "jdbc/database"; + return dataSource; + } + + private static void initDerby() throws NamingException { + System.setProperty("derby.stream.error.field", "java.lang.System.err"); + + InitialContext context = new InitialContext(); + BasicDataSource datasource = (BasicDataSource) context.lookup(getDataSourceName()); + + if (datasource == null) { + datasource = new BasicDataSource(); + datasource.setUrl("jdbc:derby:memory:myDb;create=true"); + datasource.setDriverClassName("org.apache.derby.jdbc.EmbeddedDriver"); + datasource.setUsername(""); + datasource.setPassword(""); + datasource.setMaxActive(2); + + context.bind(getDataSourceName(), datasource); + } + + PropertySelector.setSystemProperty(PropertySelector.RUNTIMEENHANCEMENT, "supported"); + PropertySelector.setSystemProperty(PropertySelector.SHOWSQL, "true"); + PropertySelector.setSystemProperty(PropertySelector.SYNCHRONIZEDB, "true"); + } + + private static void initRealDatabase() throws NamingException { + // TODO: need realize + } + +}