changeset 39:86c343109257

more comments and cleanup.
author casties
date Thu, 13 Oct 2016 19:02:24 +0200
parents cb25e343e317
children c181cb6f1761
files src/main/java/org/mpi/openmind/cache/AbstractCacheService.java src/main/java/org/mpi/openmind/cache/WrapperService.java src/main/java/org/mpi/openmind/repository/bo/Entity.java src/main/java/org/mpi/openmind/repository/services/AbstractPersistenceService.java
diffstat 4 files changed, 226 insertions(+), 155 deletions(-) [+]
line wrap: on
line diff
--- a/src/main/java/org/mpi/openmind/cache/AbstractCacheService.java	Wed Oct 12 20:51:35 2016 +0200
+++ b/src/main/java/org/mpi/openmind/cache/AbstractCacheService.java	Thu Oct 13 19:02:24 2016 +0200
@@ -61,34 +61,46 @@
 	}
 	
 	/**
-	 * Returns (a clone of a read-only) entity by id.
+	 * Returns (a clone of) an entity form the cache by id.
 	 * 
 	 * @param id
 	 * @return
 	 */
-	public Entity getEntityById(Long id){
-		Entity ent = getEntityByIdReadOnly(id);
-		if(ent != null){
-			return (Entity)ent.clone();
-		}
-		return null;
-	} 
+    public Entity getEntityById(Long id) {
+        Entity ent = getEntityByIdReadOnly(id);
+        if (ent != null) {
+            return (Entity) ent.clone();
+        }
+        return null;
+    }
 	
+	/**
+	 * Returns an entity from the cache by id.
+	 * 
+	 * Do not modify the entity!
+	 * 
+	 * @param id
+	 * @return
+	 */
 	public Entity getEntityByIdReadOnly(Long id){
 		if (id == null) {
+		    // TODO: WTF?
 			try {
 				throw new Exception("Id of entity can not be null.");
 			} catch (Exception e) {
 				logger.error(e.getMessage(), e);
 			}
 		} else {
+		    // get entity from cache
 			Entity ent = this.entMap.getValuesByOwnKey(id);
 			if (ent == null) {
+			    // load entity from db
 				logger.debug("Entity no found in cache ID=" + id);
 				List<Entity> list =  
 					getPs().getLightweightEntities(Node.SYS_STATUS_CURRENT_VERSION, id, Node.TYPE_ABOX, null, null, true, 1);
 				if (list.size() > 0) {
 		        	ent = list.get(0);
+		        	// load all entities of the same object class
 		        	loadEntitiesByDef(ent.getObjectClass());
 		        }
 			}	
@@ -103,35 +115,36 @@
 	 * @param oc
 	 * @return
 	 */
-	public List<Entity> loadEntitiesByDef(String oc){
-		logger.debug("[" + Thread.currentThread().getId() +  "]\tgetEntitiesByDef=" + oc + "\nHashCode=" + this.hashCode());
+    public List<Entity> loadEntitiesByDef(String oc) {
+        logger.debug(
+                "[" + Thread.currentThread().getId() + "]\tgetEntitiesByDef=" + oc + "\nHashCode=" + this.hashCode());
 
-		if (entLoadedByOC.get(oc) == null || entLoadedByOC.get(oc) == false) {
-			synchronized (entMap) {
-				if (entLoadedByOC.get(oc) == null) {
-					long start = System.currentTimeMillis();
-					
-					logger.debug("[" + Thread.currentThread().getId() + 
-							"]\t Starting loading Entities from DB for OC=" + oc + "\nHashCode=" + this.hashCode());
-					//###################
-					entLoadedByOC.put(oc, false);
-					List<Entity> list = 
-						getPs().getLightweightEntities(Node.SYS_STATUS_CURRENT_VERSION, null, Node.TYPE_ABOX, oc, null, true, -1);
-					for(Entity ent : list){
-						entMap.put(ent.getKey(), ent);
-					}
-					entLoadedByOC.put(oc, true);
-					//###################
-					long end  = System.currentTimeMillis();
-					logger.debug("[" + Thread.currentThread().getId() + 
-							"]\tFinished loading Entities from DB for OC=" + oc + " - time= " + (end-start) + "\nHashCode=" + this.hashCode());	
-				}
-			}
-			
-		}
-		List<Entity> list = entMap.getValuesByAKey(oc);
-		return list;
-	}
+        if (entLoadedByOC.get(oc) == null || entLoadedByOC.get(oc) == false) {
+            synchronized (entMap) {
+                if (entLoadedByOC.get(oc) == null) {
+                    long start = System.currentTimeMillis();
+                    logger.debug("[" + Thread.currentThread().getId() + "]\t Starting loading Entities from DB for OC="
+                            + oc + "\nHashCode=" + this.hashCode());
+                    entLoadedByOC.put(oc, false);
+                    
+                    // load entities from database
+                    List<Entity> list = getPs().getLightweightEntities(Node.SYS_STATUS_CURRENT_VERSION, null,
+                            Node.TYPE_ABOX, oc, null, true, -1);
+                    // put entities in cache map
+                    for (Entity ent : list) {
+                        entMap.put(ent.getKey(), ent);
+                    }
+                    
+                    entLoadedByOC.put(oc, true);
+                    long end = System.currentTimeMillis();
+                    logger.debug("[" + Thread.currentThread().getId() + "]\tFinished loading Entities from DB for OC="
+                            + oc + " - time= " + (end - start) + "\nHashCode=" + this.hashCode());
+                }
+            }
+        }
+        List<Entity> list = entMap.getValuesByAKey(oc);
+        return list;
+    }
 	
 	public void saveEntityListAsNodeWithoutContent(List<Entity> nodeList) throws Exception{
 		this.getPs().saveEntityListAsNodeWithoutContent(nodeList);
--- a/src/main/java/org/mpi/openmind/cache/WrapperService.java	Wed Oct 12 20:51:35 2016 +0200
+++ b/src/main/java/org/mpi/openmind/cache/WrapperService.java	Thu Oct 13 19:02:24 2016 +0200
@@ -988,6 +988,8 @@
 	}
 
 	/**
+	 * Return an entity with the given id from the cache.
+	 * 
 	 * The entity returned could be LW or not, it depends on the cache.
 	 * additionally, it will be always a clone of the version in cache,
 	 * therefore it method is thought for editing's issues.
@@ -1000,6 +1002,14 @@
 		return ent;
 	}
 
+	/**
+	 * Return an entity with the given id from the cache.
+	 * 
+	 * Do not modify the entity!
+	 * 
+	 * @param id
+	 * @return
+	 */
 	public Entity getEntityByIdReadOnly(Long id) {
 		Entity ent = this.cache.getEntityByIdReadOnly(id);
 		return ent;
--- a/src/main/java/org/mpi/openmind/repository/bo/Entity.java	Wed Oct 12 20:51:35 2016 +0200
+++ b/src/main/java/org/mpi/openmind/repository/bo/Entity.java	Thu Oct 13 19:02:24 2016 +0200
@@ -712,13 +712,19 @@
     	return new AttributeMap(this);
     }
     
+    /**
+     * Returns the named attribute.
+     *  
+     * @param name
+     * @return
+     */
     public Attribute getAttributeByName(String name) {
         try {
             if (this.lightweight) {
                 throw new IllegalAccessException("This Entity is lightweight, so its relations and attributes were not loaded from the DB.");
             }
             for (Attribute attribute : this.getAttributes()) {
-                if (attribute.getObjectClass().equals(name) /*|| attribute.getObjectClass().equals(name)*/) {
+                if (attribute.getObjectClass().equals(name)) {
                     return attribute;
                 }
             }
@@ -914,41 +920,51 @@
 		}
 	}
 
+    /* (non-Javadoc)
+     * @see org.mpi.openmind.repository.bo.Node#clone()
+     */
     @Override
     public Object clone() {
         try {
-            Entity clone = (Entity) super.clone(); 
+            // super.clone 
+            Entity clone = (Entity) super.clone();
+            // start with empty attributes and relations
             clone.setAttributes(new ArrayList<Attribute>());
             clone.setSourceRelations(new ArrayList<Relation>());
             clone.setTargetRelations(new ArrayList<Relation>());
             
-            if(!clone.isLightweight()){
-            	for (Attribute attribute : this.attributes) {
+            if (!clone.isLightweight()) {
+                // clone attributes and add to cloned entity
+                for (Attribute attribute : this.attributes) {
                     clone.addAttribute((Attribute) attribute.clone());
                 }
+                // clone source relations and add to cloned entity
                 for (Relation srcRelation : this.sourceRelations) {
-                	Relation clonRelation = (Relation) srcRelation.clone();
-                	clonRelation.setAttributes(new ArrayList<Attribute>());
-                	for(Attribute att : srcRelation.getAttributes()){
-                		clonRelation.getAttributes().add((Attribute)att.clone());
-                	}
-                    clone.addSourceRelation(clonRelation);
+                    Relation cloneRelation = (Relation) srcRelation.clone();
+                    cloneRelation.setAttributes(new ArrayList<Attribute>());
+                    // clone relation attributes
+                    for (Attribute att : srcRelation.getAttributes()) {
+                        cloneRelation.getAttributes().add((Attribute) att.clone());
+                    }
+                    clone.addSourceRelation(cloneRelation);
                 }
+                // clone target relations and add to cloned entity
                 for (Relation targetRelation : this.targetRelations) {
-                	Relation clonRelation = (Relation) targetRelation.clone();
-                	clonRelation.setAttributes(new ArrayList<Attribute>());
-                	for(Attribute att : targetRelation.getAttributes()){
-                		clonRelation.getAttributes().add((Attribute)att.clone());
-                	}
+                    Relation cloneRelation = (Relation) targetRelation.clone();
+                    cloneRelation.setAttributes(new ArrayList<Attribute>());
+                    // clone relation attributes
+                    for (Attribute att : targetRelation.getAttributes()) {
+                        cloneRelation.getAttributes().add((Attribute) att.clone());
+                    }
                     clone.addTargetRelation((Relation) targetRelation.clone());
-                }	
+                }
             }
 
             return clone;
         } catch (Exception e) {
-        	logger.error(e.getMessage(), e);
-            return null;
+            logger.error(e);
         }
+        return null;
     }
 
     /**
--- a/src/main/java/org/mpi/openmind/repository/services/AbstractPersistenceService.java	Wed Oct 12 20:51:35 2016 +0200
+++ b/src/main/java/org/mpi/openmind/repository/services/AbstractPersistenceService.java	Thu Oct 13 19:02:24 2016 +0200
@@ -650,7 +650,7 @@
 	}
 
 	/**
-	 * Update the entity to prepare it for persistence.
+	 * Update the entity to prepare it for persistence using the session.
 	 * 
 	 * If the ID is null new IDs will be assigned for the entity and its 
 	 * attributes and relations.
@@ -824,7 +824,7 @@
 	}
 
 	/**
-	 * Persist a (current) entity and its attributes and relations.
+	 * Persist a (current) entity and its attributes and relations using the session.
 	 * 
 	 * @param session
 	 * @param entity
@@ -891,7 +891,7 @@
 	}
 
 	/**
-	 * Returns entities with their content from the database.
+	 * Returns entities with their content from the database using the session.
 	 * 
 	 * If a parameter is null then the condition is omitted from the query
 	 * returning all entities matching the remaining conditions.
@@ -907,11 +907,10 @@
 	private List<Entity> getEntities(Session session, Long id,
 			String systemStatus, String type, String ownValue, boolean considerTimeModif) {
 
-		if (!(systemStatus.equals(Node.SYS_STATUS_PREVIOUS_VERSION) || systemStatus
-				.equals(Node.SYS_STATUS_CURRENT_VERSION))) {
-			throw new IllegalArgumentException("Invalid input systemStatus: "
-					+ systemStatus);
-		}
+        if (!(systemStatus.equals(Node.SYS_STATUS_PREVIOUS_VERSION)
+                || systemStatus.equals(Node.SYS_STATUS_CURRENT_VERSION))) {
+            throw new IllegalArgumentException("Invalid input systemStatus: " + systemStatus);
+        }
 
 		if (StringUtils.isNotEmpty(type)
 				&& !(type.equals(Node.TYPE_ABOX) || type.equals(Node.TYPE_TBOX))) {
@@ -959,7 +958,7 @@
 	}
 
 	/**
-	 * Returns entities with their content.
+	 * Returns entities with their content from the database.
 	 * 
      * If a parameter is null then the condition is omitted from the query
      * returning all entities matching the remaining conditions.
@@ -1388,112 +1387,145 @@
 		return entity;
 	}
 
-	protected List<Entity> getLightweightEntities(Session session,
-			String systemStatus, Long id, String type, String objectClass,
-			String ownValue, boolean ownValueSubString, int maxResult) {
-
-		String hqlEntities = "from Entity where ";
-		if (StringUtils.isNotEmpty(ownValue)) {
-			if (ownValueSubString)
-				hqlEntities += "ownValue like :ownValue AND ";
-			else
-				hqlEntities += "ownValue = :ownValue AND ";
-		}
-		if (id != null) {
-			hqlEntities += "id = :id AND ";
-		}
-		if (StringUtils.isNotEmpty(objectClass)) {
-			hqlEntities += "objectClass = :objectClass AND ";
-		}
-		if (StringUtils.isNotEmpty(type)) {
-			hqlEntities += "type = :type AND ";
-		}
-
-		hqlEntities += "systemStatus = :systemStatus ";
-
-		// it will be now sorted by openmind
-		// + "order by ownValue";
-
-		Query queryEntities = session.createQuery(hqlEntities);
-		queryEntities.setString("systemStatus", systemStatus);
-		if (StringUtils.isNotEmpty(ownValue)) {
-			if (ownValueSubString) {
-				queryEntities.setString("ownValue", "%" + ownValue + "%");
-				logger.info("ownValue=%" + ownValue + "%");
-			} else {
-				queryEntities.setString("ownValue", ownValue);
-				logger.info("ownValue=" + ownValue);
-			}
-		}
-		if (maxResult > 0) {
-			queryEntities.setMaxResults(maxResult);
-		}
-
-		if (StringUtils.isNotEmpty(type)) {
-			queryEntities.setString("type", type);
-		}
-		if (id != null) {
-			queryEntities.setLong("id", id);
-		}
-		if (StringUtils.isNotEmpty(objectClass)) {
-			queryEntities.setString("objectClass", objectClass);
-		}
-		List<Entity> entities = queryEntities.list();
-		
-		for(Entity ent : entities){
-			ent.setLightweight(true);
-		}
-		
-		return entities;
-	}
-
 	/**
-	 * Own value is searched as substring
-	 * 
+	 * Return all (lightweight) entities matching the query.
+     * 
+     * Any parameter that is null is omitted as a query condition matching
+     * all values in this parameter.
+     * 
+     * Own value is searched as substring if ownValueSubString=true.
+     * 
+	 * @param session
 	 * @param systemStatus
 	 * @param id
 	 * @param type
 	 * @param objectClass
 	 * @param ownValue
+	 * @param ownValueSubString
 	 * @param maxResult
 	 * @return
 	 */
-	public List<Entity> getLightweightEntities(String systemStatus, Long id,
-			String type, String objectClass, String ownValue,
-			boolean ownValueSubString, int maxResult) {
-		logger.debug("GET LW ENTITIES [type=" + type + " id=" + id
-				+ ", objectClass=" + objectClass + ", ownValue=" + ownValue
-				+ "]");
+    protected List<Entity> getLightweightEntities(Session session, String systemStatus, Long id, String type,
+            String objectClass, String ownValue, boolean ownValueSubString, int maxResult) {
+
+        /*
+         * build query string
+         */
+        String hqlEntities = "from Entity where ";
+        if (StringUtils.isNotEmpty(ownValue)) {
+            if (ownValueSubString)
+                hqlEntities += "ownValue like :ownValue AND ";
+            else
+                hqlEntities += "ownValue = :ownValue AND ";
+        }
+        if (id != null) {
+            hqlEntities += "id = :id AND ";
+        }
+        if (StringUtils.isNotEmpty(objectClass)) {
+            hqlEntities += "objectClass = :objectClass AND ";
+        }
+        if (StringUtils.isNotEmpty(type)) {
+            hqlEntities += "type = :type AND ";
+        }
 
-		List<Entity> entities = new ArrayList<Entity>();
-		if (!(systemStatus.equals(Node.SYS_STATUS_PREVIOUS_VERSION) || systemStatus
-				.equals(Node.SYS_STATUS_CURRENT_VERSION))) {
-			throw new IllegalArgumentException("Invalid input systemStatus: "
-					+ systemStatus);
-		}
+        hqlEntities += "systemStatus = :systemStatus ";
+
+        /* 
+         * create query object
+         */
+        Query queryEntities = session.createQuery(hqlEntities);
+        
+        /*
+         * add query parameters
+         */
+        queryEntities.setString("systemStatus", systemStatus);
+        if (StringUtils.isNotEmpty(ownValue)) {
+            if (ownValueSubString) {
+                // substring search
+                queryEntities.setString("ownValue", "%" + ownValue + "%");
+                //logger.debug("ownValue=%" + ownValue + "%");
+            } else {
+                queryEntities.setString("ownValue", ownValue);
+                //logger.debug("ownValue=" + ownValue);
+            }
+        }
+        if (maxResult > 0) {
+            queryEntities.setMaxResults(maxResult);
+        }
 
-		if (StringUtils.isNotEmpty(type)
-				&& !(type.equals(Node.TYPE_ABOX) || type.equals(Node.TYPE_TBOX))) {
-			throw new IllegalArgumentException("Invalid input type: " + type);
-		}
+        if (StringUtils.isNotEmpty(type)) {
+            queryEntities.setString("type", type);
+        }
+        if (id != null) {
+            queryEntities.setLong("id", id);
+        }
+        if (StringUtils.isNotEmpty(objectClass)) {
+            queryEntities.setString("objectClass", objectClass);
+        }
+        
+        /*
+         * run query and return results
+         */
+        List<Entity> entities = queryEntities.list();
 
-		try {
-			// where parent_id = :parent_id AND type = :type
-			Session session = HibernateUtil.getSessionFactory()
-					.getCurrentSession();
-			session.getTransaction().begin();
+        for (Entity ent : entities) {
+            ent.setLightweight(true);
+        }
+
+        return entities;
+    }
 
-			entities = this.getLightweightEntities(session, systemStatus, id,
-					type, objectClass, ownValue, ownValueSubString, maxResult);
-
+	/**
+	 * Return all (lightweight) entities matching the query.
+	 * 
+     * Any parameter that is null is omitted as a query condition matching
+     * all values in this parameter.
+     * 
+	 * Own value is searched as substring if ownValueSubString=true.
+	 * 
+     * @param systemStatus
+     * @param id
+     * @param type
+     * @param objectClass
+     * @param ownValue
+     * @param ownValueSubString
+     * @param maxResult
+     * @return
+     */
+    public List<Entity> getLightweightEntities(String systemStatus, Long id, String type, String objectClass,
+            String ownValue, boolean ownValueSubString, int maxResult) {
+        logger.debug("GET LW ENTITIES [type=" + type + " id=" + id + ", objectClass=" + objectClass + ", ownValue="
+                + ownValue + "]");
 
-			session.getTransaction().commit();
-			return entities;
-		} catch (Exception e) {
-			logger.error(e.getMessage(), e);
-		}
-		return entities;
-	}
+        List<Entity> entities = new ArrayList<Entity>();
+        /*
+         * check inputs
+         */
+        if (!(systemStatus.equals(Node.SYS_STATUS_PREVIOUS_VERSION)
+                || systemStatus.equals(Node.SYS_STATUS_CURRENT_VERSION))) {
+            throw new IllegalArgumentException("Invalid input systemStatus: " + systemStatus);
+        }
+        if (StringUtils.isNotEmpty(type) && !(type.equals(Node.TYPE_ABOX) || type.equals(Node.TYPE_TBOX))) {
+            throw new IllegalArgumentException("Invalid input type: " + type);
+        }
+
+        /*
+         * call getLightweightEntities with transaction
+         */
+        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
+        try {
+            session.getTransaction().begin();
+
+            entities = this.getLightweightEntities(session, systemStatus, id, type, objectClass, ownValue,
+                    ownValueSubString, maxResult);
+
+        } catch (Exception e) {
+            logger.error(e);
+        } finally {
+            session.getTransaction().commit();
+        }
+        return entities;
+    }
 
 	private Sequence getIdSequence(Session session) {
 		Sequence sequence = null;