[jboss-svn-commits] JBL Code SVN: r30734 - in labs/jbossrules/trunk/drools-persistence-jpa/src: main/java/org/drools/persistence/processinstance/variabletypes and 2 other directories.

jboss-svn-commits at lists.jboss.org jboss-svn-commits at lists.jboss.org
Wed Dec 16 15:35:53 EST 2009


Author: baunax
Date: 2009-12-16 15:35:52 -0500 (Wed, 16 Dec 2009)
New Revision: 30734

Added:
   labs/jbossrules/trunk/drools-persistence-jpa/src/test/java/org/drools/persistence/session/MyEntityMethods.java
   labs/jbossrules/trunk/drools-persistence-jpa/src/test/java/org/drools/persistence/session/MyEntityOnlyFields.java
Modified:
   labs/jbossrules/trunk/drools-persistence-jpa/src/main/java/org/drools/persistence/processinstance/persisters/JPAVariablePersister.java
   labs/jbossrules/trunk/drools-persistence-jpa/src/main/java/org/drools/persistence/processinstance/variabletypes/JPAPersistedVariable.java
   labs/jbossrules/trunk/drools-persistence-jpa/src/test/java/org/drools/persistence/session/VariablePersistenceStrategyTest.java
   labs/jbossrules/trunk/drools-persistence-jpa/src/test/resources/META-INF/persistence.xml
Log:
JBRULES-2382 allows classes to have @Id annotation on methods

Modified: labs/jbossrules/trunk/drools-persistence-jpa/src/main/java/org/drools/persistence/processinstance/persisters/JPAVariablePersister.java
===================================================================
--- labs/jbossrules/trunk/drools-persistence-jpa/src/main/java/org/drools/persistence/processinstance/persisters/JPAVariablePersister.java	2009-12-16 20:21:25 UTC (rev 30733)
+++ labs/jbossrules/trunk/drools-persistence-jpa/src/main/java/org/drools/persistence/processinstance/persisters/JPAVariablePersister.java	2009-12-16 20:35:52 UTC (rev 30734)
@@ -1,7 +1,9 @@
 package org.drools.persistence.processinstance.persisters;
 
+import java.io.Serializable;
 import java.lang.reflect.Field;
 import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
 import java.util.logging.Level;
 import java.util.logging.Logger;
 
@@ -14,7 +16,6 @@
 import org.drools.runtime.EnvironmentName;
 
 /**
- * 
  * @author <a href="mailto:kris_verlaenen at hotmail.com">Kris Verlaenen</a>
  * @author salaboy
  */
@@ -22,46 +23,47 @@
 
 	public VariableInstanceInfo persistExternalVariable(String name, Object o,
 			VariableInstanceInfo oldValue, Environment env) {
-                if(o == null || (oldValue != null && oldValue.getPersister().equals(""))){
-                    return null;
-                }
+		if (o == null || (oldValue != null && oldValue.getPersister().equals(""))) {
+			return null;
+		}
 		try {
 			boolean newVariable = false;
-                        EntityManager em = (EntityManager) env.get(EnvironmentName.ENTITY_MANAGER);
+			EntityManager em = (EntityManager) env.get(EnvironmentName.ENTITY_MANAGER);
 			JPAPersistedVariable result = null;
 			if (oldValue instanceof JPAPersistedVariable) {
 				result = (JPAPersistedVariable) oldValue;
 			}
 			if (result == null) {
 				result = new JPAPersistedVariable();
-				
+
 				newVariable = true;
 			}
-			Long idValue = getClassIdValue(o);
+			Serializable idValue = getClassIdValue(o);
 			if (idValue != null) {
-                                System.out.println("Variable "+name +" -> Updating external Entity = "+o);
+				System.out.println("Variable " + name + " -> Updating external Entity = " + o);
 				em.merge(o);
 			} else {
-                                System.out.println("Variable "+name +" -> Persisting external Entity for the first time ="+o);
+				System.out.println("Variable " + name + " -> Persisting external Entity for the first time =" + o);
 				em.persist(o);
 				idValue = getClassIdValue(o);
 			}
 			result.setPersister(this.getClass().getName());
-                        result.setName(name);
-                        // entity might have changed, updating info
+			result.setName(name);
+			// entity might have changed, updating info
 			result.setEntityId(idValue);
 			result.setEntity(o);
 			result.setEntityClass(o.getClass().getCanonicalName());
-                        if(newVariable){
-                            em.persist(result);
-                        }else{
-                            em.merge(result);
-                        }
-			System.out.println("Saving JPAPersistedVariable id=" + result.getId() + " entityId=" + result.getEntityId() + " class=" + result.getEntityClass() + " value=" + result.getEntity());
+			if (newVariable) {
+				em.persist(result);
+			} else {
+				em.merge(result);
+			}
+			System.out.println("Saving JPAPersistedVariable id=" + result.getId() + " entityId=" + result.getEntityId()
+					+ " class=" + result.getEntityClass() + " value=" + result.getEntity());
 			return result;
 		} catch (Throwable t) {
 			Logger.getLogger(JPAVariablePersister.class.getName())
-				.log(Level.SEVERE, null, t);
+					.log(Level.SEVERE, null, t);
 			throw new RuntimeException("Could not persist external variable", t);
 		}
 	}
@@ -69,36 +71,59 @@
 	public Object getExternalPersistedVariable(
 			VariableInstanceInfo variableInstanceInfo, Environment env) {
 		EntityManager em = (EntityManager) env.get(EnvironmentName.ENTITY_MANAGER);
-                if(((JPAPersistedVariable) variableInstanceInfo) == null || ((JPAPersistedVariable) variableInstanceInfo).getEntityId() == null){
-                    return null;
-                }
-		System.out.println("Restoring JPAPersistedVariable id=" + ((JPAPersistedVariable) variableInstanceInfo).getId() + " entityId=" + ((JPAPersistedVariable) variableInstanceInfo).getEntityId() + " class=" + ((JPAPersistedVariable) variableInstanceInfo).getEntityClass() + " value=" + ((JPAPersistedVariable) variableInstanceInfo).getEntity());
+		if (((JPAPersistedVariable) variableInstanceInfo) == null
+				|| ((JPAPersistedVariable) variableInstanceInfo).getEntityId() == null) {
+			return null;
+		}
+		System.out.println("Restoring JPAPersistedVariable id=" + ((JPAPersistedVariable) variableInstanceInfo).getId()
+				+ " entityId=" + ((JPAPersistedVariable) variableInstanceInfo).getEntityId() + " class="
+				+ ((JPAPersistedVariable) variableInstanceInfo).getEntityClass() + " value="
+				+ ((JPAPersistedVariable) variableInstanceInfo).getEntity());
 		try {
 			String varType = ((JPAPersistedVariable) variableInstanceInfo).getEntityClass();
 			return em.find(Class.forName(varType),
-				((JPAPersistedVariable) variableInstanceInfo).getEntityId());
+					((JPAPersistedVariable) variableInstanceInfo).getEntityId());
 		} catch (ClassNotFoundException ex) {
 			Logger.getLogger(JPAVariablePersister.class.getName())
-				.log(Level.SEVERE, null, ex);
+					.log(Level.SEVERE, null, ex);
 			throw new RuntimeException("Could not restore external variable", ex);
 		}
 	}
 
-	private Long getClassIdValue(Object o) throws NoSuchMethodException,
+	private Serializable getClassIdValue(Object o) throws NoSuchMethodException,
 			SecurityException, IllegalAccessException,
 			InvocationTargetException, IllegalArgumentException {
-		Field[] fields = o.getClass().getDeclaredFields();
-		Long idValue = null;
-		for (int i = 0; i < fields.length; i++) {
-			Id id = fields[i].getAnnotation(Id.class);
+		Class<? extends Object> varClass = o.getClass();
+		Field[] fields = varClass.getDeclaredFields();
+		Serializable idValue = null;
+		for (int i = 0; i < fields.length && idValue == null; i++) {
+			Field field = fields[i];
+			Id id = field.getAnnotation(Id.class);
 			if (id != null) {
-				idValue = (Long) o.getClass().getMethod("get"
-					+ Character.toUpperCase(fields[i].getName().charAt(0))
-					+ fields[i].getName().substring(1),
-					new Class<?>[] {}).invoke(o, new Object[] {});
-				break;
+				try {
+					idValue = callIdMethod(o, "get"
+							+ Character.toUpperCase(field.getName().charAt(0))
+							+ field.getName().substring(1));
+				} catch (NoSuchMethodException e) {
+					idValue = (Serializable) field.get(o);
+				}
 			}
 		}
+		if (idValue == null) {
+			Method[] methods = varClass.getMethods();
+			for (int i = 0; i < methods.length && idValue == null; i++) {
+				Method method = methods[i];
+				Id id = method.getAnnotation(Id.class);
+				if (id != null) {
+					idValue = (Serializable) method.invoke(o);
+				}
+			}
+		}
 		return idValue;
 	}
+
+	private Serializable callIdMethod(Object target, String methodName) throws IllegalArgumentException,
+			SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
+		return (Serializable) target.getClass().getMethod(methodName, (Class[]) null).invoke(target, new Object[] {});
+	}
 }

Modified: labs/jbossrules/trunk/drools-persistence-jpa/src/main/java/org/drools/persistence/processinstance/variabletypes/JPAPersistedVariable.java
===================================================================
--- labs/jbossrules/trunk/drools-persistence-jpa/src/main/java/org/drools/persistence/processinstance/variabletypes/JPAPersistedVariable.java	2009-12-16 20:21:25 UTC (rev 30733)
+++ labs/jbossrules/trunk/drools-persistence-jpa/src/main/java/org/drools/persistence/processinstance/variabletypes/JPAPersistedVariable.java	2009-12-16 20:35:52 UTC (rev 30734)
@@ -1,5 +1,7 @@
 package org.drools.persistence.processinstance.variabletypes;
 
+import java.io.Serializable;
+
 import javax.persistence.Entity;
 import javax.persistence.Transient;
 
@@ -16,7 +18,7 @@
 	@Transient
 	private Object entity;
 	private String entityClass;
-	private Long entityId;
+	private Serializable entityId;
 
 	public String getEntityClass() {
 		return entityClass;
@@ -26,11 +28,11 @@
 		this.entityClass = entityClass;
 	}
 
-	public Long getEntityId() {
+	public Serializable getEntityId() {
 		return entityId;
 	}
 
-	public void setEntityId(Long varid) {
+	public void setEntityId(Serializable varid) {
 		this.entityId = varid;
 	}
 

Added: labs/jbossrules/trunk/drools-persistence-jpa/src/test/java/org/drools/persistence/session/MyEntityMethods.java
===================================================================
--- labs/jbossrules/trunk/drools-persistence-jpa/src/test/java/org/drools/persistence/session/MyEntityMethods.java	                        (rev 0)
+++ labs/jbossrules/trunk/drools-persistence-jpa/src/test/java/org/drools/persistence/session/MyEntityMethods.java	2009-12-16 20:35:52 UTC (rev 30734)
@@ -0,0 +1,86 @@
+package org.drools.persistence.session;
+
+import java.io.Serializable;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+
+/**
+ *
+ * @author salaboy
+ */
+ at Entity
+public class MyEntityMethods implements Serializable {
+	private static final long serialVersionUID = 1L;
+	
+	
+    private Long id;
+    private String test;
+
+    public MyEntityMethods(){}
+
+    public MyEntityMethods(String string) {
+        this.test= string;
+    }
+
+    /**
+     * @return the id
+     */
+    @Id @GeneratedValue(strategy=GenerationType.AUTO)
+    public Long getId() {
+        return id;
+    }
+
+    /**
+     * @param id the id to set
+     */
+    public void setId(Long id) {
+        this.id = id;
+    }
+
+    /**
+     * @return the test
+     */
+    public String getTest() {
+        return test;
+    }
+
+    /**
+     * @param test the test to set
+     */
+    public void setTest(String test) {
+        this.test = test;
+    }
+    public String toString(){
+        return "VARIABLE: " +this.getId() + " - " + this.getTest();
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (obj == null) {
+            return false;
+        }
+        if (getClass() != obj.getClass()) {
+            return false;
+        }
+        final MyEntityMethods other = (MyEntityMethods) obj;
+        if (this.id != other.id && (this.id == null || !this.id.equals(other.id))) {
+            return false;
+        }
+        if ((this.test == null) ? (other.test != null) : !this.test.equals(other.test)) {
+            return false;
+        }
+        return true;
+    }
+
+    @Override
+    public int hashCode() {
+        int hash = 5;
+        hash = 41 * hash + (this.id != null ? this.id.hashCode() : 0);
+        hash = 41 * hash + (this.test != null ? this.test.hashCode() : 0);
+        return hash;
+    }
+    
+}


Property changes on: labs/jbossrules/trunk/drools-persistence-jpa/src/test/java/org/drools/persistence/session/MyEntityMethods.java
___________________________________________________________________
Name: svn:keywords
   + Id Revision
Name: svn:eol-style
   + LF

Added: labs/jbossrules/trunk/drools-persistence-jpa/src/test/java/org/drools/persistence/session/MyEntityOnlyFields.java
===================================================================
--- labs/jbossrules/trunk/drools-persistence-jpa/src/test/java/org/drools/persistence/session/MyEntityOnlyFields.java	                        (rev 0)
+++ labs/jbossrules/trunk/drools-persistence-jpa/src/test/java/org/drools/persistence/session/MyEntityOnlyFields.java	2009-12-16 20:35:52 UTC (rev 30734)
@@ -0,0 +1,60 @@
+package org.drools.persistence.session;
+
+import java.io.Serializable;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+
+/**
+ *
+ * @author salaboy
+ */
+ at Entity
+public class MyEntityOnlyFields implements Serializable {
+
+
+	private static final long serialVersionUID = 1L;
+	
+	@Id @GeneratedValue(strategy=GenerationType.AUTO)
+    public Long id;
+    public String test;
+
+    public MyEntityOnlyFields(){}
+
+    public MyEntityOnlyFields(String string) {
+        this.test= string;
+    }
+    
+    public String toString(){
+        return "VARIABLE: " + id + " - " + test;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (obj == null) {
+            return false;
+        }
+        if (getClass() != obj.getClass()) {
+            return false;
+        }
+        final MyEntityOnlyFields other = (MyEntityOnlyFields) obj;
+        if (this.id != other.id && (this.id == null || !this.id.equals(other.id))) {
+            return false;
+        }
+        if ((this.test == null) ? (other.test != null) : !this.test.equals(other.test)) {
+            return false;
+        }
+        return true;
+    }
+
+    @Override
+    public int hashCode() {
+        int hash = 5;
+        hash = 41 * hash + (this.id != null ? this.id.hashCode() : 0);
+        hash = 41 * hash + (this.test != null ? this.test.hashCode() : 0);
+        return hash;
+    }
+    
+}


Property changes on: labs/jbossrules/trunk/drools-persistence-jpa/src/test/java/org/drools/persistence/session/MyEntityOnlyFields.java
___________________________________________________________________
Name: svn:keywords
   + Id Revision
Name: svn:eol-style
   + LF

Modified: labs/jbossrules/trunk/drools-persistence-jpa/src/test/java/org/drools/persistence/session/VariablePersistenceStrategyTest.java
===================================================================
--- labs/jbossrules/trunk/drools-persistence-jpa/src/test/java/org/drools/persistence/session/VariablePersistenceStrategyTest.java	2009-12-16 20:21:25 UTC (rev 30733)
+++ labs/jbossrules/trunk/drools-persistence-jpa/src/test/java/org/drools/persistence/session/VariablePersistenceStrategyTest.java	2009-12-16 20:35:52 UTC (rev 30734)
@@ -81,7 +81,9 @@
         System.out.println("### Starting process ###");
         Map<String, Object> parameters = new HashMap<String, Object>();
         parameters.put("x", "SomeString");
-        parameters.put("y", new MyEntity("This is a test Entity"));
+        parameters.put("y", new MyEntity("This is a test Entity with annotation in fields"));
+        parameters.put("m", new MyEntityMethods("This is a test Entity with annotations in methods"));
+        parameters.put("f", new MyEntityOnlyFields("This is a test Entity with annotations in fields and without accesors methods"));
         parameters.put("z", new MyVariableSerializable("This is a test SerializableObject"));
         WorkflowProcessInstance processInstance = (WorkflowProcessInstance)
         	ksession.startProcess( "com.sample.ruleflow", parameters );
@@ -91,7 +93,7 @@
         assertNotNull( workItem );
         
         List<?> result = emf.createEntityManager().createQuery("select i from VariableInstanceInfo i").getResultList();
-        assertEquals(3, result.size());
+        assertEquals(5, result.size());
 
         System.out.println("### Retrieving process instance ###");
         ksession = JPAKnowledgeService.loadStatefulKnowledgeSession( id, kbase, null, env );
@@ -99,7 +101,9 @@
         	ksession.getProcessInstance( processInstance.getId() );
         assertNotNull( processInstance );
         assertEquals("SomeString", processInstance.getVariable("x"));
-        assertEquals("This is a test Entity", ((MyEntity) processInstance.getVariable("y")).getTest());
+        assertEquals("This is a test Entity with annotation in fields", ((MyEntity) processInstance.getVariable("y")).getTest());
+        assertEquals("This is a test Entity with annotations in methods", ((MyEntityMethods) processInstance.getVariable("m")).getTest());
+        assertEquals("This is a test Entity with annotations in fields and without accesors methods", ((MyEntityOnlyFields) processInstance.getVariable("f")).test);
         assertEquals("This is a test SerializableObject", ((MyVariableSerializable) processInstance.getVariable("z")).getText());
         assertNull(processInstance.getVariable("a"));
         assertNull(processInstance.getVariable("b"));
@@ -112,9 +116,10 @@
         
         System.out.println("### Retrieving variable instance infos ###");
         result = emf.createEntityManager().createQuery("select i from VariableInstanceInfo i").getResultList();
-        assertEquals(6, result.size());
+        assertEquals(8, result.size());
         for (Object o: result) {
-        	System.out.println(((VariableInstanceInfo) o));
+        	assertTrue(VariableInstanceInfo.class.isAssignableFrom(o.getClass()));
+        	System.out.println(o);
         }
         
         System.out.println("### Retrieving process instance ###");
@@ -123,7 +128,9 @@
 			ksession.getProcessInstance(processInstance.getId());
 		assertNotNull(processInstance);
         assertEquals("SomeString", processInstance.getVariable("x"));
-        assertEquals("This is a test Entity", ((MyEntity) processInstance.getVariable("y")).getTest());
+        assertEquals("This is a test Entity with annotation in fields", ((MyEntity) processInstance.getVariable("y")).getTest());
+        assertEquals("This is a test Entity with annotations in methods", ((MyEntityMethods) processInstance.getVariable("m")).getTest());
+        assertEquals("This is a test Entity with annotations in fields and without accesors methods", ((MyEntityOnlyFields) processInstance.getVariable("f")).test);
         assertEquals("This is a test SerializableObject", ((MyVariableSerializable) processInstance.getVariable("z")).getText());
         assertEquals("Some new String", processInstance.getVariable("a"));
         assertEquals("This is a new test Entity", ((MyEntity) processInstance.getVariable("b")).getTest());
@@ -135,7 +142,7 @@
         assertNotNull(workItem);
         
         result = emf.createEntityManager().createQuery("select i from VariableInstanceInfo i").getResultList();
-        assertEquals(6, result.size());
+        assertEquals(8, result.size());
         
         System.out.println("### Retrieving process instance ###");
         ksession = JPAKnowledgeService.loadStatefulKnowledgeSession(id, kbase, null, env);
@@ -143,7 +150,9 @@
         	ksession.getProcessInstance(processInstance.getId());
         assertNotNull(processInstance);
         assertEquals("SomeString", processInstance.getVariable("x"));
-        assertEquals("This is a test Entity", ((MyEntity) processInstance.getVariable("y")).getTest());
+        assertEquals("This is a test Entity with annotation in fields", ((MyEntity) processInstance.getVariable("y")).getTest());
+        assertEquals("This is a test Entity with annotations in methods", ((MyEntityMethods) processInstance.getVariable("m")).getTest());
+        assertEquals("This is a test Entity with annotations in fields and without accesors methods", ((MyEntityOnlyFields) processInstance.getVariable("f")).test);
         assertEquals("This is a test SerializableObject", ((MyVariableSerializable) processInstance.getVariable("z")).getText());
         assertEquals("Some changed String", processInstance.getVariable("a"));
         assertEquals("This is a changed test Entity", ((MyEntity) processInstance.getVariable("b")).getTest());
@@ -185,7 +194,9 @@
 
         Map<String, Object> parameters = new HashMap<String, Object>();
         parameters.put("x", "SomeString");
-        parameters.put("y", new MyEntity("This is a test Entity"));
+        parameters.put("y", new MyEntity("This is a test Entity with annotation in fields"));
+        parameters.put("m", new MyEntityMethods("This is a test Entity with annotations in methods"));
+        parameters.put("f", new MyEntityOnlyFields("This is a test Entity with annotations in fields and without accesors methods"));
         parameters.put("z", new MyVariableSerializable("This is a test SerializableObject"));
         ProcessInstance processInstance = ksession.startProcess( "com.sample.ruleflow", parameters );
 
@@ -234,7 +245,9 @@
 
         Map<String, Object> parameters = new HashMap<String, Object>();
         parameters.put("x", "SomeString");
-        parameters.put("y", new MyEntity("This is a test Entity"));
+        parameters.put("y", new MyEntity("This is a test Entity with annotation in fields"));
+        parameters.put("m", new MyEntityMethods("This is a test Entity with annotations in methods"));
+        parameters.put("f", new MyEntityOnlyFields("This is a test Entity with annotations in fields and without accesors methods"));
         parameters.put("z", new MyVariableSerializable("This is a test SerializableObject"));
         ProcessInstance processInstance = ksession.startProcess( "com.sample.ruleflow", parameters );
 

Modified: labs/jbossrules/trunk/drools-persistence-jpa/src/test/resources/META-INF/persistence.xml
===================================================================
--- labs/jbossrules/trunk/drools-persistence-jpa/src/test/resources/META-INF/persistence.xml	2009-12-16 20:21:25 UTC (rev 30733)
+++ labs/jbossrules/trunk/drools-persistence-jpa/src/test/resources/META-INF/persistence.xml	2009-12-16 20:35:52 UTC (rev 30734)
@@ -12,6 +12,8 @@
         <class>org.drools.persistence.session.SessionInfo</class>
     <class>org.drools.persistence.processinstance.ProcessInstanceInfo</class>
     <class>org.drools.persistence.session.MyEntity</class>
+    <class>org.drools.persistence.session.MyEntityMethods</class>
+    <class>org.drools.persistence.session.MyEntityOnlyFields</class>
     <class>org.drools.persistence.processinstance.variabletypes.JPAPersistedVariable</class>
     <class>org.drools.persistence.processinstance.variabletypes.VariableInstanceInfo</class>
     <class>org.drools.persistence.processinstance.variabletypes.SerializablePersistedVariable</class>



More information about the jboss-svn-commits mailing list