forgot the test files in the last commit
authorCherian Mathew <c.mathew@bgbm.org>
Tue, 9 Dec 2014 16:56:03 +0000 (16:56 +0000)
committerCherian Mathew <c.mathew@bgbm.org>
Tue, 9 Dec 2014 16:56:03 +0000 (16:56 +0000)
19 files changed:
.gitattributes
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/cdm/api/cache/CdmClientCachingTest.java [new file with mode: 0644]
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/cdm/api/cache/CdmModelGetMethodCacherTest.java [new file with mode: 0644]
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/cdm/polytomouskey/PolytomousKeyTest.java [new file with mode: 0644]
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/exception/CDMServerException.java [new file with mode: 0644]
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/httpinvoker/BaseRemotingTest.java [new file with mode: 0644]
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/httpinvoker/CDMServer.java [new file with mode: 0644]
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/httpinvoker/CdmPersistentRemoteSourceTest.java [new file with mode: 0644]
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/httpinvoker/CdmRemoteSourceTest.java [new file with mode: 0644]
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/httpinvoker/CdmServerTest.java [new file with mode: 0644]
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/httpinvoker/CdmServerTestManager.java [new file with mode: 0644]
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/httpinvoker/HttpInvokerServicesTest.java [new file with mode: 0644]
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/lazyloading/AbstractLazyInitializerTest.java [new file with mode: 0644]
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/lazyloading/CdmEntityCacherTest.java [new file with mode: 0644]
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/lazyloading/CdmServiceCacherTest.java [new file with mode: 0644]
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/lazyloading/RemoteLazyLoadingTest.java [new file with mode: 0644]
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/lazyloading/RemotePersistentCollectionTest.java [new file with mode: 0644]
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/session/CdmEntitySessionManagerTest.java [new file with mode: 0644]
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/session/MockSessionOwner.java [new file with mode: 0644]

index 5a0cee814abf26a3fa7401a267ef0101d2181816..761d35ad762a30591bb49eb041be90fc5e1dd9be 100644 (file)
@@ -367,6 +367,24 @@ eu.etaxonomy.taxeditor.cdmlib/src/main/resources/eu/etaxonomy/cdm/remotingApplic
 eu.etaxonomy.taxeditor.cdmlib/src/main/resources/eu/etaxonomy/cdm/remoting_persistence_security.xml -text
 eu.etaxonomy.taxeditor.cdmlib/src/main/resources/eu/etaxonomy/cdm/remoting_services_security.xml -text
 eu.etaxonomy.taxeditor.cdmlib/src/main/resources/log4j.properties -text
+eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/cdm/api/cache/CdmClientCachingTest.java -text
+eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/cdm/api/cache/CdmModelGetMethodCacherTest.java -text
+eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/cdm/polytomouskey/PolytomousKeyTest.java -text
+eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/exception/CDMServerException.java -text
+eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/httpinvoker/BaseRemotingTest.java -text
+eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/httpinvoker/CDMServer.java -text
+eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/httpinvoker/CdmPersistentRemoteSourceTest.java -text
+eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/httpinvoker/CdmRemoteSourceTest.java -text
+eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/httpinvoker/CdmServerTest.java -text
+eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/httpinvoker/CdmServerTestManager.java -text
+eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/httpinvoker/HttpInvokerServicesTest.java -text
+eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/lazyloading/AbstractLazyInitializerTest.java -text
+eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/lazyloading/CdmEntityCacherTest.java -text
+eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/lazyloading/CdmServiceCacherTest.java -text
+eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/lazyloading/RemoteLazyLoadingTest.java -text
+eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/lazyloading/RemotePersistentCollectionTest.java -text
+eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/session/CdmEntitySessionManagerTest.java -text
+eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/session/MockSessionOwner.java -text
 eu.etaxonomy.taxeditor.cdmlib/src/test/resources/cdmlib-ehcache.xml -text
 eu.etaxonomy.taxeditor.cdmlib/src/test/resources/datasources.xml -text
 eu.etaxonomy.taxeditor.cdmlib/src/test/resources/eu/etaxonomy/cdm/api/cache/CdmClientCachingTest.xml -text
diff --git a/eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/cdm/api/cache/CdmClientCachingTest.java b/eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/cdm/api/cache/CdmClientCachingTest.java
new file mode 100644 (file)
index 0000000..5e5dcb5
--- /dev/null
@@ -0,0 +1,430 @@
+// $Id$
+/**
+* Copyright (C) 2014 EDIT
+* European Distributed Institute of Taxonomy
+* http://www.e-taxonomy.eu
+*
+* The contents of this file are subject to the Mozilla Public License Version 1.1
+* See LICENSE.TXT at the top of this package for the full license terms.
+*/
+package eu.etaxonomy.cdm.api.cache;
+
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+
+import org.apache.log4j.Level;
+import org.apache.log4j.Logger;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.unitils.dbunit.annotation.DataSet;
+
+import eu.etaxonomy.cdm.api.service.ICommonService;
+import eu.etaxonomy.cdm.api.service.IPolytomousKeyNodeService;
+import eu.etaxonomy.cdm.api.service.IPolytomousKeyService;
+import eu.etaxonomy.cdm.api.service.ITaxonService;
+import eu.etaxonomy.cdm.model.common.CdmBase;
+import eu.etaxonomy.cdm.model.common.Language;
+import eu.etaxonomy.cdm.model.common.LanguageString;
+import eu.etaxonomy.cdm.model.description.KeyStatement;
+import eu.etaxonomy.cdm.model.description.PolytomousKey;
+import eu.etaxonomy.cdm.model.description.PolytomousKeyNode;
+import eu.etaxonomy.taxeditor.httpinvoker.BaseRemotingTest;
+import eu.etaxonomy.taxeditor.httpinvoker.CDMServer;
+import eu.etaxonomy.taxeditor.session.ISessionEventListener;
+import eu.etaxonomy.taxeditor.session.MockSessionOwner;
+
+/**
+ * @author cmathew
+ * @date 7 Oct 2014
+ *
+ */
+@DataSet
+public class CdmClientCachingTest extends BaseRemotingTest {
+
+    private static final Logger logger = Logger.getLogger(CdmClientCachingTest.class);
+
+    private UUID polytomousKeyUuid = UUID.fromString("0d53ba20-7de4-4baa-bd8a-401048447d66");
+    private UUID taxon1Uuid = UUID.fromString("2b336df7-29e8-4f79-985f-66502739d22f");
+    private UUID polytomousKeyNodeUuid1 = UUID.fromString("75e4c924-ff58-4ee7-a59d-fd9173517d08");
+    private UUID polytomousKeyNodeUuid2 = UUID.fromString("b775c027-13c0-4b87-8aa9-712faeaafbdc");
+
+
+    private IPolytomousKeyService polytomousKeyService = getRemoteApplicationController().getPolytomousKeyService();
+    private IPolytomousKeyNodeService polytomousKeyNodeService = getRemoteApplicationController().getPolytomousKeyNodeService();
+    private ICommonService commonService = getRemoteApplicationController().getCommonService();
+    private ITaxonService taxonService = getRemoteApplicationController().getTaxonService();    
+    
+    
+       private CdmTransientEntityCacher cacher;
+    private ISessionEventListener sessionOwner;
+       
+    private static final List<String> PKEY_DEPTH1_INIT_STRATEGY = Arrays.asList(new String[] {
+                       });
+    
+    private static final List<String> PKEY_DEPTH2_INIT_STRATEGY = Arrays.asList(new String[] {
+               "root"});
+    
+    private static final List<String> PKEY_DEPTH3_INIT_STRATEGY = Arrays.asList(new String[] {                 
+               "root.statement"});
+    
+
+    
+    @BeforeClass
+    public static void initializePolytomousKeyTest() {
+        logger.setLevel(Level.INFO);
+        CDMServer.getInstance().setKeepServerRunning(true);                    
+    }
+
+    @Before
+    public void initializeSession() {
+       sessionOwner = new MockSessionOwner();    
+       cdmEntitySessionManager.bind(sessionOwner);
+       cacher = getCacher(sessionOwner);
+    }    
+
+
+    
+    @Test
+    public void recursiveLoadSubGraphDepth1Test() {
+
+       // this call will load into the session cache the graph 
+       // polytomous key  
+       //      |- root : polytomous key node 
+       // in a recursive call          
+        PolytomousKey pkey1 = CdmBase.deproxy(polytomousKeyService.load(polytomousKeyUuid, PKEY_DEPTH1_INIT_STRATEGY),PolytomousKey.class);
+        pkey1 = cdmEntitySessionManager.load(sessionOwner, pkey1);
+        
+        // checking to make sure the root object is in the session cache
+        Assert.assertSame(pkey1.getRoot(), cacher.getFromCache(pkey1.getRoot()));
+        
+    }
+
+    
+    @Test
+    public void recursiveLoadSubGraphDepth2Test() {
+
+       // this call will load into the session cache the graph 
+       // polytomous key  
+       //      |- root : polytomous key node 
+       //              |- question : KeyStatement
+       //              |- statement : KeyStatement     
+       // in a recursive call          
+        PolytomousKey pkey = CdmBase.deproxy(polytomousKeyService.load(polytomousKeyUuid, PKEY_DEPTH2_INIT_STRATEGY),PolytomousKey.class);
+        pkey = cdmEntitySessionManager.load(sessionOwner, pkey);
+        CdmTransientEntityCacher cacher = getCacher(sessionOwner);
+        // checking to make sure the root object is in the session cache
+        Assert.assertSame(pkey.getRoot(), cacher.getFromCache(pkey.getRoot()));
+        Assert.assertSame(pkey.getRoot().getStatement(), cacher.getFromCache(pkey.getRoot().getStatement()));
+        Assert.assertSame(pkey.getRoot().getQuestion(), cacher.getFromCache(pkey.getRoot().getQuestion()));
+        
+    }
+        
+    /**
+     * when : retrieving objects using recursive caching of object graphs with different depths 
+     * then : the objects in the sub-graph having the same persistence id should be the same
+     */
+    @Test
+    public void lazyLoadRecursiveTest() {
+
+       // this call will load into the session cache the graph and update the objects in the sub-graph for a
+       // polytomous key  
+       //      |- root : polytomous key node 
+       //              |- question : KeyStatement
+       //              |- statement : KeyStatement     
+        PolytomousKey pkey1 = CdmBase.deproxy(polytomousKeyService.find(polytomousKeyUuid),PolytomousKey.class);
+        pkey1 = cdmEntitySessionManager.load(sessionOwner, pkey1);
+        CdmTransientEntityCacher cacher = getCacher(sessionOwner);
+               
+    }
+    
+
+    /**
+     * when : retrieving objects using recursive caching of object graphs with different depths      
+     * then : the objects in the sub-graph having the same persistence id should be the same
+     */
+    @Test
+    public void differentSubGraphDepthTest1() {
+       
+       // this call will load into the session cache the graph and update the objects in the sub-graph for a
+       // polytomous key  
+       //      |- root : polytomous key node 
+       // in a recursive call    
+        PolytomousKey pkey1 = CdmBase.deproxy(polytomousKeyService.load(polytomousKeyUuid, PKEY_DEPTH1_INIT_STRATEGY),PolytomousKey.class);
+        pkey1 = cdmEntitySessionManager.load(sessionOwner, pkey1);
+        CdmTransientEntityCacher cacher = getCacher(sessionOwner);
+               
+       // this call will load into the session cache the graph and update the objects in the sub-graph for a
+       // polytomous key  
+       //      |- root : polytomous key node 
+       //              |- question : KeyStatement
+       //              |- statement : KeyStatement            
+        PolytomousKey pkey2 = CdmBase.deproxy(polytomousKeyService.load(polytomousKeyUuid, PKEY_DEPTH2_INIT_STRATEGY),PolytomousKey.class);
+        pkey2 = cdmEntitySessionManager.load(sessionOwner, pkey2);
+
+        Assert.assertSame(pkey2.getRoot().getStatement(), cacher.getFromCache(pkey2.getRoot().getStatement()));
+        Assert.assertSame(pkey1.getRoot().getStatement(), pkey2.getRoot().getStatement());
+        Assert.assertSame(cacher.getFromCache(pkey1.getRoot().getStatement()), cacher.getFromCache(pkey2.getRoot().getStatement()));
+        
+    }
+    
+    /**
+     * when : retrieving objects using recursive caching of object graphs with different depths 
+     * then : the objects in the sub-graph having the same persistence id should be the same
+     */
+    @Test
+    public void differentSubGraphDepthTest2() {
+
+       // this call will load into the session cache the graph and update the objects in the sub-graph for a
+       // polytomous key  
+       //      |- root : polytomous key node 
+       //              |- question : KeyStatement
+       //              |- statement : KeyStatement     
+        PolytomousKey pkey1 = CdmBase.deproxy(polytomousKeyService.load(polytomousKeyUuid, PKEY_DEPTH2_INIT_STRATEGY),PolytomousKey.class);
+        pkey1 = cdmEntitySessionManager.load(sessionOwner, pkey1);
+        CdmTransientEntityCacher cacher = getCacher(sessionOwner);
+               
+       // this call will load into the session cache the graph and update the objects in the sub-graph for a
+       // polytomous key  
+       //      |- root : polytomous key node  
+        PolytomousKey pkey2 = CdmBase.deproxy(polytomousKeyService.load(polytomousKeyUuid, PKEY_DEPTH1_INIT_STRATEGY),PolytomousKey.class);
+        pkey2 = cdmEntitySessionManager.load(sessionOwner, pkey2);
+
+        Assert.assertSame(pkey2.getRoot().getStatement(), cacher.getFromCache(pkey2.getRoot().getStatement()));
+        Assert.assertSame(pkey1.getRoot().getStatement(), pkey2.getRoot().getStatement());
+        Assert.assertSame(cacher.getFromCache(pkey1.getRoot().getStatement()), cacher.getFromCache(pkey2.getRoot().getStatement()));
+    }
+    
+    /**
+     * when : retrieving objects using (first) recursive load directly and (second) lazy loading in the same session
+     * then : the objects in the sub-graph having the same persistence id should be the same
+     */
+    @Test
+    public void recursiveLoadAndLazyLoadTest() {
+       
+       // this call will load into the session cache the graph and update the objects in the sub-graph for a
+       // polytomous key  
+       //      |- root : polytomous key node 
+       //              |- question : KeyStatement
+       //              |- statement : KeyStatement     
+        PolytomousKey pkey1 = CdmBase.deproxy(polytomousKeyService.load(polytomousKeyUuid, PKEY_DEPTH2_INIT_STRATEGY),PolytomousKey.class);
+        pkey1 = cdmEntitySessionManager.load(sessionOwner, pkey1);
+        CdmTransientEntityCacher cacher = getCacher(sessionOwner);
+               
+        // checking that the root is not null and 
+        // that it exists in the cache and
+        // that both the original object and the 
+        // cached object are the same
+        Assert.assertNotNull(pkey1.getRoot().getStatement());
+        Assert.assertNotNull(cacher.getFromCache(pkey1.getRoot().getStatement()));
+        
+       // this call will load into the session cache the graph and update the objects in the sub-graph for a
+       // polytomous key  
+       //      |- root : polytomous key node  
+        PolytomousKey pkey2 = CdmBase.deproxy(polytomousKeyService.find(polytomousKeyUuid),PolytomousKey.class);
+        pkey2 = cdmEntitySessionManager.load(sessionOwner, pkey2);
+
+        
+        Assert.assertSame(pkey2.getRoot().getStatement(), cacher.getFromCache(pkey2.getRoot().getStatement()));
+        Assert.assertSame(pkey1.getRoot().getStatement(), pkey2.getRoot().getStatement());
+        Assert.assertSame(cacher.getFromCache(pkey1.getRoot().getStatement()), cacher.getFromCache(pkey2.getRoot().getStatement()));
+    }
+    
+    /**
+     * when : retrieving objects using (first) lazy loading  and (second) recursive load directly in the same session
+     * then : the objects in the sub-graph having the same persistence id should be the same
+     */
+    @Test
+    public void lazyLoadAndRecursiveLoadTest() {
+
+
+       // this call will load into the session cache the graph and update the objects in the sub-graph for a
+       // polytomous key  
+       //      |- root : polytomous key node  
+       
+       PolytomousKey pkey1 = CdmBase.deproxy(polytomousKeyService.find(polytomousKeyUuid),PolytomousKey.class);
+        pkey1 = cdmEntitySessionManager.load(sessionOwner, pkey1);
+        
+        // lazy initialising root.statement
+        KeyStatement st = CdmBase.deproxy(pkey1.getRoot().getStatement(), KeyStatement.class); 
+        st.getLabel();
+        
+        // checking that the root is not null and 
+        // that it exists in the cache and
+        // that both the original object and the 
+        // cached object are the same
+       Assert.assertNotNull(pkey1.getRoot().getStatement());
+       Assert.assertSame(CdmBase.deproxy(pkey1.getRoot().getStatement(), KeyStatement.class),
+                       cacher.getFromCache(pkey1.getRoot().getStatement(), KeyStatement.class));
+       
+       // this call will load into the session cache the graph and update the objects in the sub-graph for a
+       // polytomous key  
+       //      |- root : polytomous key node 
+       //              |- question : KeyStatement
+       //              |- statement : KeyStatement     
+        
+       PolytomousKey pkey2 = CdmBase.deproxy(polytomousKeyService.load(polytomousKeyUuid, PKEY_DEPTH2_INIT_STRATEGY),PolytomousKey.class);
+       pkey2 = cdmEntitySessionManager.load(sessionOwner, pkey2);
+
+       Assert.assertSame(pkey2.getRoot().getStatement(), cacher.getFromCache(pkey2.getRoot().getStatement(), KeyStatement.class));
+       Assert.assertSame(st, pkey2.getRoot().getStatement());
+       Assert.assertSame(cacher.getFromCache(st), cacher.getFromCache(pkey2.getRoot().getStatement(), KeyStatement.class));
+    }
+    
+
+
+
+    
+    /**
+     * when : loading an object (first) and then (second) loading a graph the object is contained in, in the same session
+     * then : the object should be the same
+     */
+    @Test
+    public void subGraphObjectLoadTest1() {
+
+       // this call will load into the session cache a polytomous key node object              
+       PolytomousKeyNode rootPKNode = CdmBase.deproxy(polytomousKeyNodeService.find(polytomousKeyNodeUuid1),PolytomousKeyNode.class);
+       rootPKNode = cdmEntitySessionManager.load(sessionOwner, rootPKNode);
+
+       Assert.assertNotNull(rootPKNode);
+       Assert.assertSame(rootPKNode, cacher.getFromCache(rootPKNode));
+       
+       PolytomousKeyNode childOfRootPKNode = CdmBase.deproxy(polytomousKeyNodeService.find(polytomousKeyNodeUuid2),PolytomousKeyNode.class);
+       childOfRootPKNode = cdmEntitySessionManager.load(sessionOwner, childOfRootPKNode);
+       
+       Assert.assertNotNull(childOfRootPKNode);
+       Assert.assertSame(childOfRootPKNode, cacher.getFromCache(childOfRootPKNode));
+       
+       // this call will load into the session cache the graph and update the objects in the sub-graph for a
+       // polytomous key  
+       //      |- root : polytomous key node 
+       //              |- question : KeyStatement
+       //              |- statement : KeyStatement     
+        
+       PolytomousKey pkey = CdmBase.deproxy(polytomousKeyService.load(polytomousKeyUuid, PKEY_DEPTH2_INIT_STRATEGY),PolytomousKey.class);
+       pkey = cdmEntitySessionManager.load(sessionOwner, pkey);
+       
+       Assert.assertSame(childOfRootPKNode, cacher.getFromCache(childOfRootPKNode));
+       Assert.assertSame(pkey.getRoot().getChildAt(1), childOfRootPKNode);
+    }
+
+    /**
+     * when : loading a graph (first) and then (second) loading an object contained in in the graph, in the same session
+     * then : the object should be the same
+     */
+    @Test
+    public void subGraphObjectLoadTest2() {
+
+       // this call will load into the session cache the graph and update the objects in the sub-graph for a
+       // polytomous key  
+       //      |- root : polytomous key node 
+       //              |- question : KeyStatement
+       //              |- statement : KeyStatement     
+        
+       PolytomousKey pkey = CdmBase.deproxy(polytomousKeyService.load(polytomousKeyUuid, PKEY_DEPTH2_INIT_STRATEGY),PolytomousKey.class);
+       pkey = cdmEntitySessionManager.load(sessionOwner, pkey);
+       
+       // this call will load into the session cache a polytomous key node object              
+       PolytomousKeyNode rootPKNode = CdmBase.deproxy(polytomousKeyNodeService.find(polytomousKeyNodeUuid1),PolytomousKeyNode.class);
+       rootPKNode = cdmEntitySessionManager.load(sessionOwner, rootPKNode);
+
+       Assert.assertNotNull(rootPKNode);
+       Assert.assertSame(rootPKNode, cacher.getFromCache(rootPKNode));
+       
+       PolytomousKeyNode childOfRootPKNode = CdmBase.deproxy(polytomousKeyNodeService.find(polytomousKeyNodeUuid2),PolytomousKeyNode.class);
+       childOfRootPKNode = cdmEntitySessionManager.load(sessionOwner, childOfRootPKNode);
+       
+       Assert.assertNotNull(childOfRootPKNode);
+       Assert.assertSame(childOfRootPKNode, cacher.getFromCache(childOfRootPKNode));           
+       
+       Assert.assertSame(childOfRootPKNode, cacher.getFromCache(childOfRootPKNode));
+       Assert.assertSame(pkey.getRoot().getChildAt(1), childOfRootPKNode);
+    }
+
+    
+    /**
+     * when : loading objects from a collection 
+     * then : the object stored in the cache should be the same
+     */
+    @Test
+    public void subGraphCollectionLoadTest() {
+       
+       // this call will load into the session cache the graph and update the objects in the sub-graph for a
+       // polytomous key  
+       //      |- root : polytomous key node 
+       //              |- question : KeyStatement
+       //              |- statement : KeyStatement     
+        
+       PolytomousKey pkey = CdmBase.deproxy(polytomousKeyService.load(polytomousKeyUuid, PKEY_DEPTH2_INIT_STRATEGY),PolytomousKey.class);
+       pkey = cdmEntitySessionManager.load(sessionOwner, pkey);
+       
+       PolytomousKeyNode childOfRootPKNode = pkey.getRoot().getChildAt(1);
+       
+       Assert.assertSame(childOfRootPKNode, cacher.getFromCache(childOfRootPKNode));
+       Assert.assertSame(pkey.getRoot().getChildAt(1), childOfRootPKNode);
+       
+    }
+    
+    /**
+     * when : loading a non-lazy collection in a subgraph and loading the collection directly
+     * then : the object stored in the cache should be the same as the object in the sub-graph collection and 
+     *        the object in the directly loaded collection
+     */
+    @Test
+    public void nonLazyCollectionLoadTest() {
+       // need to find an example of this
+    }
+    
+    /**
+     * when : loading objects from a map
+     * then : the object stored in the cache should be the same
+     */
+    @Test
+    public void subGraphMapLoadTest() {
+       
+       Language english = Language.getLanguageFromUuid(Language.uuidEnglish);
+        Language hindi = Language.getLanguageFromUuid(UUID.fromString("0a1d9d1d-135d-4575-b172-669b51673c39"));
+        
+        
+       // this call will load into the session cache the graph and update the objects in the sub-graph for a
+       // polytomous key  
+       //      |- root : polytomous key node 
+       //              |- question : KeyStatement
+       //              |- statement : KeyStatement     
+        
+       PolytomousKey pkey = CdmBase.deproxy(polytomousKeyService.load(polytomousKeyUuid, PKEY_DEPTH3_INIT_STRATEGY),PolytomousKey.class);
+       pkey = cdmEntitySessionManager.load(sessionOwner, pkey);
+       
+       Map<Language, LanguageString> labelMap = pkey.getRoot().getStatement().getLabel();
+       Set<Language> languages = labelMap.keySet();
+       Iterator<Language> languagesItr = languages.iterator();
+       while(languagesItr.hasNext()) {
+               Language lang = languagesItr.next();
+               if(lang.equals(english)) {
+                       Assert.assertSame(lang, english);                       
+               }
+               if(lang.equals(hindi)) {
+                       Assert.assertSame(lang, hindi);
+               }
+               Assert.assertSame(lang, cacher.getFromCache(lang));
+       }       
+    }
+    
+    /**
+     * when : loading a non-lazy map in a subgraph and loading the map directly
+     * then : the object stored in the cache should be the same as the object in the sub-graph map and 
+     *        the object in the directly loaded map
+     */
+    @Test
+    public void nonLazyMapLoadTest() {
+       // need to find an example of this
+    }
+    
+
+
+}
diff --git a/eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/cdm/api/cache/CdmModelGetMethodCacherTest.java b/eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/cdm/api/cache/CdmModelGetMethodCacherTest.java
new file mode 100644 (file)
index 0000000..44bced2
--- /dev/null
@@ -0,0 +1,62 @@
+package eu.etaxonomy.cdm.api.cache;
+
+import java.io.IOException;
+import java.util.List;
+
+import net.sf.ehcache.Cache;
+
+import org.apache.log4j.Level;
+import org.apache.log4j.Logger;
+import org.junit.Assert;
+import org.junit.Test;
+import org.springframework.core.io.ClassPathResource;
+import org.springframework.core.io.Resource;
+
+import eu.etaxonomy.cdm.api.cache.CdmRemoteCacheManager.CdmCacheManagerType;
+
+
+public class CdmModelGetMethodCacherTest {
+
+       private static final Logger logger = Logger.getLogger(CdmModelGetMethodCacherTest.class);
+
+    public static final Resource CDMLIB_DISK_STORE_RESOURCE =
+            new ClassPathResource("/eu/etaxonomy/cache");
+    
+    
+
+       @Test
+       public void cacheGettersTest() {
+               
+               Logger.getRootLogger().setLevel(Level.INFO);
+               try {
+                       System.setProperty("ehcache.disk.store.dir", CDMLIB_DISK_STORE_RESOURCE.getFile().getAbsolutePath());
+               } catch (IOException e) {
+                       throw new CdmClientCacheException(e);
+               }               
+               CdmModelCacher cmdmc = new CdmModelCacher();
+               
+               //cmdmc.checkGetterMethods();
+               
+               cmdmc.cacheGetterFields();
+
+                                               
+               Cache cdmlibCache = CdmRemoteCacheManager.getInstance().getCdmModelGetMethodsCache();
+               List<CdmModelFieldPropertyFromClass> cmgmfcList = cmdmc.getCdmModelGetMethodFromClassList();
+               
+               List<Object> keys = cdmlibCache.getKeys();
+               Assert.assertEquals(cmgmfcList.size(), keys.size());
+                               
+               for(CdmModelFieldPropertyFromClass cmgmfc: cmgmfcList) {
+                       String className = cmgmfc.getClassName();
+                       Assert.assertTrue(keys.contains(className));
+                       logger.info("Class Name : " + className + " has been cached");
+               }
+               cdmlibCache.removeAll();
+               cdmlibCache.flush();
+               CdmRemoteCacheManager.getInstance().shutdown(CdmCacheManagerType.CDMLIB_MODEL);
+       }
+
+       
+        
+
+}
diff --git a/eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/cdm/polytomouskey/PolytomousKeyTest.java b/eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/cdm/polytomouskey/PolytomousKeyTest.java
new file mode 100644 (file)
index 0000000..dfdf793
--- /dev/null
@@ -0,0 +1,301 @@
+// $Id$
+/**
+* Copyright (C) 2014 EDIT
+* European Distributed Institute of Taxonomy
+* http://www.e-taxonomy.eu
+*
+* The contents of this file are subject to the Mozilla Public License Version 1.1
+* See LICENSE.TXT at the top of this package for the full license terms.
+*/
+package eu.etaxonomy.cdm.polytomouskey;
+
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+
+import org.apache.log4j.Level;
+import org.apache.log4j.Logger;
+import org.hibernate.collection.spi.PersistentCollection;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.unitils.dbunit.annotation.DataSet;
+
+import eu.etaxonomy.cdm.api.cache.CdmTransientEntityCacher;
+import eu.etaxonomy.cdm.api.service.ICommonService;
+import eu.etaxonomy.cdm.api.service.IPolytomousKeyService;
+import eu.etaxonomy.cdm.api.service.ITaxonService;
+import eu.etaxonomy.cdm.model.agent.AgentBase;
+import eu.etaxonomy.cdm.model.common.CdmBase;
+import eu.etaxonomy.cdm.model.common.Credit;
+import eu.etaxonomy.cdm.model.common.Extension;
+import eu.etaxonomy.cdm.model.common.IdentifiableSource;
+import eu.etaxonomy.cdm.model.common.Language;
+import eu.etaxonomy.cdm.model.common.LanguageString;
+import eu.etaxonomy.cdm.model.description.KeyStatement;
+import eu.etaxonomy.cdm.model.description.PolytomousKey;
+import eu.etaxonomy.cdm.model.description.PolytomousKeyNode;
+import eu.etaxonomy.cdm.model.media.Rights;
+import eu.etaxonomy.cdm.model.taxon.Taxon;
+import eu.etaxonomy.taxeditor.httpinvoker.BaseRemotingTest;
+import eu.etaxonomy.taxeditor.httpinvoker.CDMServer;
+import eu.etaxonomy.taxeditor.session.ISessionEventListener;
+import eu.etaxonomy.taxeditor.session.MockSessionOwner;
+
+/**
+ * @author cmathew
+ * @date 7 Oct 2014
+ *
+ */
+@DataSet
+public class PolytomousKeyTest extends BaseRemotingTest {
+
+    private static final Logger logger = Logger.getLogger(PolytomousKeyTest.class);
+
+    UUID polytomousKeyUuid = UUID.fromString("0d53ba20-7de4-4baa-bd8a-401048447d66");
+    UUID taxon1Uuid = UUID.fromString("2b336df7-29e8-4f79-985f-66502739d22f");
+
+
+    IPolytomousKeyService polytomousKeyService = getRemoteApplicationController().getPolytomousKeyService();
+    ICommonService commonService = getRemoteApplicationController().getCommonService();
+    ITaxonService taxonService = getRemoteApplicationController().getTaxonService();
+
+    
+       private CdmTransientEntityCacher cacher;
+    private ISessionEventListener sessionOwner;
+    
+    Language english = Language.getLanguageFromUuid(Language.uuidEnglish);
+
+    
+    
+    @BeforeClass
+    public static void initializePolytomousKeyTest() {
+        logger.setLevel(Level.INFO);
+        CDMServer.getInstance().setKeepServerRunning(true);       
+    }
+
+    @Before
+    public void initializeSession() {
+       sessionOwner = new MockSessionOwner();    
+       cdmEntitySessionManager.bind(sessionOwner);
+       cacher = getCacher(sessionOwner);
+    }
+    
+    @Test
+    public void readAllPolytomousKeys() {
+        List<PolytomousKey> pKeys = polytomousKeyService.list(PolytomousKey.class, null, null, null, null);
+        Iterator<PolytomousKey> pKeysItr = pKeys.iterator();
+        Assert.assertEquals(pKeysItr.next().getUuid(),UUID.fromString("9d8bf4f6-a70a-4b80-8556-2ccfb436ff01"));
+        Assert.assertEquals(pKeysItr.next().getUuid(),UUID.fromString("0d53ba20-7de4-4baa-bd8a-401048447d66"));        
+    }
+
+
+    @Test
+    //@DataSet("PolytomousKeyTest.readPolytmousKeyData.xml")
+    public void readPolytmousKeyData() {
+        PolytomousKey pKey = CdmBase.deproxy(polytomousKeyService.find(polytomousKeyUuid),PolytomousKey.class);
+        Set<Taxon> taxonomicScope = pKey.getTaxonomicScope();
+        Iterator<Taxon> tsItr = taxonomicScope.iterator();
+        Taxon taxon = tsItr.next();
+        
+        Assert.assertEquals("Achillea sec. Cyprus", taxon.getTitleCache());
+        Assert.assertEquals(tsItr.hasNext(), false);
+
+        List<Credit> credits = pKey.getCredits();
+        AgentBase agent = credits.get(0).getAgent();
+        Assert.assertEquals(agent.getId(),4809);
+        Assert.assertEquals(agent.getTitleCache(),"R. A. Graham");
+        Assert.assertEquals(credits.get(0).getText(),"Credits Text Test");
+
+        Set<Extension> exts = pKey.getExtensions();
+        Iterator<Extension> extItr = exts.iterator();
+        Extension ext = extItr.next();
+        Assert.assertEquals(ext.getValue(), "http://test.com");
+
+        Set<Rights> rights = pKey.getRights();
+        Iterator<Rights> rightsItr = rights.iterator();
+        Rights right = rightsItr.next();
+        Assert.assertEquals(right.getText(),"Rights Text Test");
+
+        Set<IdentifiableSource> sources = pKey.getSources();
+        Iterator<IdentifiableSource> sourcesItr = sources.iterator();
+        IdentifiableSource source = sourcesItr.next();
+        Assert.assertEquals(source.getId(), 23710);
+        source = sourcesItr.next();
+        Assert.assertEquals(source.getId(), 23711);
+
+        // TO DO : Added tests for Annotations , Markers
+    }
+
+    @Test
+    public void readPolytomousKeyDataFromNodes() {
+        PolytomousKey pKey = CdmBase.deproxy(polytomousKeyService.find(polytomousKeyUuid),PolytomousKey.class);
+        PolytomousKeyNode rootNode = pKey.getRoot();
+
+
+        Assert.assertEquals(rootNode.getId(), 2750);
+
+        Assert.assertEquals(rootNode.getChildAt(0).getId(), 2751);
+        Assert.assertEquals(rootNode.getChildAt(0).getParent().getId(), rootNode.getId());
+        Assert.assertEquals(rootNode.getKey().getId(), pKey.getId());
+        Integer sortIndex = (Integer)getFieldValueViaReflection(rootNode.getChildAt(0), "sortIndex");
+        Assert.assertEquals(sortIndex, new Integer(0));
+        String statement = "Capitula without ligulate ray-florets; leaves entire or subentire";
+        Assert.assertEquals(rootNode.getChildAt(0).getStatement().getLabelText(english), statement);
+
+        Assert.assertEquals(rootNode.getChildAt(1).getId(), 2753);
+        Assert.assertEquals(rootNode.getChildAt(1).getParent().getId(), rootNode.getId());
+        Assert.assertEquals(rootNode.getChildAt(1).getKey().getId(), pKey.getId());
+        sortIndex = (Integer)getFieldValueViaReflection(rootNode.getChildAt(1), "sortIndex");
+        Assert.assertEquals(sortIndex, new Integer(1));
+        statement = "Capitula with ligulate ray-florets; leaves pinnatisect";
+        Assert.assertEquals(rootNode.getChildAt(1).getStatement().getLabelText(english), statement);
+
+        Assert.assertEquals(rootNode.getChildAt(1).getChildAt(0).getId(), 2754);
+        Assert.assertEquals(rootNode.getChildAt(1).getChildAt(0).getParent().getId(), rootNode.getChildAt(1).getId());
+        Assert.assertEquals(rootNode.getChildAt(1).getChildAt(0).getKey().getId(), pKey.getId());
+        sortIndex = (Integer)getFieldValueViaReflection(rootNode.getChildAt(1).getChildAt(0), "sortIndex");
+        Assert.assertEquals(sortIndex, new Integer(0));
+        statement = "Ray-florets yellow";
+        Assert.assertEquals(rootNode.getChildAt(1).getChildAt(0).getStatement().getLabelText(english), statement);
+        Assert.assertEquals(rootNode.getChildAt(1).getChildAt(0).getChildAt(0).getTaxon().getTitleCache(), "Achillea arabica Kotschy sec. Cyprus");
+    }
+
+    @Test
+    public void savePolytomousKeyNodeData() {
+        PolytomousKey pkey = CdmBase.deproxy(polytomousKeyService.find(polytomousKeyUuid),PolytomousKey.class);
+        pkey = cdmEntitySessionManager.load(sessionOwner, pkey);
+        PolytomousKeyNode pkeynode = pkey.getRoot();
+        String newQuestion = "New Question";
+        String newStatement = "New Statement";
+
+        Assert.assertEquals("Question 1",pkeynode.getQuestion().getLabel().get(english).getText());
+        for(PolytomousKeyNode node : pkeynode.getChildren()) {
+
+            node.setQuestion(null);
+            node.setStatement(null);
+        }
+        //FIXME:Remoting Add tests for feature after fixing problem
+
+        //Feature feature = pkeynode.getFeature();
+        //Assert.assertEquals(feature.getTitleCache(),"Systematics");
+        //pkeynode.setFeature(null);
+
+        Assert.assertEquals(pkeynode.getChildAt(0).getModifyingText().get(english).getText(),"Modifying Text 1a");
+        String modifyingText = "Modifying Text 1a updated";
+
+        //pkeynode.getChildAt(0).putModifyingText(english, modifyingText);
+
+        Assert.assertEquals(pkeynode.getChildAt(0).getSubkey().getId(),1550);
+        Assert.assertEquals("Achillea", pkeynode.getChildAt(0).getSubkey().getTitleCache());
+        Assert.assertNull(pkeynode.getChildAt(1).getTaxon());
+        Taxon taxon = CdmBase.deproxy(taxonService.find(taxon1Uuid),Taxon.class);
+        pkeynode.getChildAt(1).setTaxon(taxon);
+
+        polytomousKeyService.merge(pkey);
+
+        pkey = CdmBase.deproxy(polytomousKeyService.find(polytomousKeyUuid),PolytomousKey.class);
+        sessionOwner = new MockSessionOwner();
+        pkey = cdmEntitySessionManager.load(sessionOwner, pkey);
+        
+        pkeynode = pkey.getRoot();
+        for(PolytomousKeyNode node : pkeynode.getChildren()) {
+            Assert.assertNull(node.getQuestion());
+            node.setQuestion(KeyStatement.NewInstance(english,newQuestion));
+            Assert.assertNull(node.getStatement());
+            node.setStatement(KeyStatement.NewInstance(english,newStatement));
+        }
+
+        
+        Assert.assertEquals(pkeynode.getChildAt(1).getTaxon(), taxon);
+
+        polytomousKeyService.merge(pkey);
+
+        pkey = CdmBase.deproxy(polytomousKeyService.find(polytomousKeyUuid),PolytomousKey.class);
+        sessionOwner = new MockSessionOwner();
+        pkey = cdmEntitySessionManager.load(sessionOwner, pkey);
+        
+        pkeynode = pkey.getRoot();
+        for(PolytomousKeyNode node : pkeynode.getChildren()) {
+            Assert.assertNotNull(node.getQuestion());
+            Map<Language, LanguageString> label = node.getQuestion().getLabel();
+            Assert.assertEquals(newQuestion, label.get(english).getText());
+            Assert.assertNotNull(node.getStatement());
+            Assert.assertEquals(newStatement, node.getStatement().getLabel(english).getText());
+        }
+        //Assert.assertEquals(pkeynode.getFeature().getId(), feature.getId());
+
+    }
+
+    @Test
+    public void savePolytomousKeyNodeDataWithSameSubKey() {
+        
+       ISessionEventListener sessionOwner = new MockSessionOwner();
+       cdmEntitySessionManager.bind(sessionOwner);
+        PolytomousKey pkey = CdmBase.deproxy(polytomousKeyService.find(polytomousKeyUuid),PolytomousKey.class);
+        pkey = cdmEntitySessionManager.load(sessionOwner, pkey);
+        
+        PolytomousKeyNode pkeynode = pkey.getRoot();
+
+        PolytomousKey subkey1 = CdmBase.deproxy(pkeynode.getChildAt(0).getSubkey(), PolytomousKey.class);
+        String subkey1title = subkey1.getTitleCache();
+        subkey1.setTitleCache(subkey1title + "test", true);
+
+
+        PolytomousKey subkey2 = CdmBase.deproxy(pkeynode.getChildAt(1).getChildAt(0).getSubkey(), PolytomousKey.class);
+        String subkey2title = subkey2.getTitleCache();
+        subkey2.setTitleCache(subkey2title + "test", true);
+
+        Assert.assertSame(subkey1, subkey2);
+
+        polytomousKeyService.merge(pkey);
+    }
+
+    @Test
+    public void savePolytomousKeyNodeDataWithSameSubKeyUsingService() {
+       
+        PolytomousKey pkey = CdmBase.deproxy(polytomousKeyService.find(polytomousKeyUuid),PolytomousKey.class);
+        pkey = cdmEntitySessionManager.load(sessionOwner, pkey);
+        
+        PolytomousKeyNode pkeynode = pkey.getRoot();
+
+        PersistentCollection children = (PersistentCollection) pkeynode.getChildren();
+        PolytomousKeyNode childNode0 = (PolytomousKeyNode)commonService.get(children, 0);
+        PolytomousKey subkey1 = CdmBase.deproxy(childNode0.getSubkey(),PolytomousKey.class);
+        String subkey1title = subkey1.getTitleCache();
+        subkey1.setTitleCache(subkey1title + "test", true);
+
+        PolytomousKeyNode childNode1 = (PolytomousKeyNode)commonService.get(children, 1);
+        PolytomousKey subkey2 = CdmBase.deproxy(childNode1.getSubkey(),PolytomousKey.class);
+        String subkey2title = subkey2.getTitleCache();
+        subkey2.setTitleCache(subkey2title + "test", true);
+
+        Assert.assertNotSame(childNode0, childNode1);
+        
+        Assert.assertSame(subkey1, subkey2);
+
+        polytomousKeyService.merge(pkey);
+    }
+
+
+    @Test
+    public void savePolytomousKeyNodeDataWithSameLanguageInLabel() {
+        PolytomousKey pkey = CdmBase.deproxy(polytomousKeyService.find(polytomousKeyUuid),PolytomousKey.class);
+        PolytomousKeyNode pkeynode = pkey.getRoot();
+
+        Map<Language, LanguageString> label1 = pkeynode.getQuestion().getLabel();
+        label1.size();
+
+
+        Map<Language, LanguageString> label2 = pkeynode.getChildAt(0).getStatement().getLabel();
+        label2.size();
+
+
+        polytomousKeyService.merge(pkey);
+    }
+
+
+}
diff --git a/eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/exception/CDMServerException.java b/eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/exception/CDMServerException.java
new file mode 100644 (file)
index 0000000..ed2b691
--- /dev/null
@@ -0,0 +1,31 @@
+// $Id$
+/**
+* Copyright (C) 2014 EDIT
+* European Distributed Institute of Taxonomy
+* http://www.e-taxonomy.eu
+*
+* The contents of this file are subject to the Mozilla Public License Version 1.1
+* See LICENSE.TXT at the top of this package for the full license terms.
+*/
+package eu.etaxonomy.taxeditor.exception;
+
+/**
+ * @author cmathew
+ * @date 23 Sep 2014
+ *
+ */
+public class CDMServerException extends Exception {
+
+    public CDMServerException(String message) {
+        super(message);
+    }
+
+    public CDMServerException(Exception e) {
+        super(e);
+    }
+
+    public CDMServerException(String message,Exception e) {
+        super(message,e);
+    }
+
+}
diff --git a/eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/httpinvoker/BaseRemotingTest.java b/eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/httpinvoker/BaseRemotingTest.java
new file mode 100644 (file)
index 0000000..584c266
--- /dev/null
@@ -0,0 +1,170 @@
+/**
+ * Copyright (C) 2014 EDIT
+ * European Distributed Institute of Taxonomy
+ * http://www.e-taxonomy.eu
+ *
+ * The contents of this file are subject to the Mozilla Public License Version 1.1
+ * See LICENSE.TXT at the top of this package for the full license terms.
+ */
+package eu.etaxonomy.taxeditor.httpinvoker;
+
+import java.io.IOException;
+import java.lang.reflect.Field;
+
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.springframework.core.io.ClassPathResource;
+import org.springframework.core.io.Resource;
+import org.unitils.UnitilsJUnit4;
+import org.unitils.database.DatabaseUnitils;
+import org.unitils.database.annotations.Transactional;
+import org.unitils.database.util.TransactionMode;
+import org.unitils.spring.annotation.SpringApplicationContext;
+
+import eu.etaxonomy.cdm.api.application.CdmApplicationRemoteController;
+import eu.etaxonomy.cdm.api.cache.CdmClientCacheException;
+import eu.etaxonomy.cdm.api.cache.CdmTransientEntityCacher;
+import eu.etaxonomy.cdm.model.name.NomenclaturalCode;
+import eu.etaxonomy.taxeditor.remoting.source.CdmPersistentRemoteSource;
+import eu.etaxonomy.taxeditor.remoting.source.CdmRemoteSource;
+import eu.etaxonomy.taxeditor.remoting.source.CdmRemoteSourceException;
+import eu.etaxonomy.taxeditor.remoting.source.ICdmRemoteSource;
+import eu.etaxonomy.taxeditor.session.ICdmEntitySessionManager;
+import eu.etaxonomy.taxeditor.session.ISessionEventListener;
+
+
+/**
+ * Base class for remoting tests, responsible for
+ * - starting / stop the cdm server
+ * - running some basic connection tests
+ * - setting up the remote configuration.
+ *
+ */
+@Transactional(TransactionMode.DISABLED)
+@SpringApplicationContext("file:./target/test-classes/eu/etaxonomy/cdm/testRemotingApplicationContext.xml")
+public class BaseRemotingTest extends UnitilsJUnit4 {
+    //private static final Logger logger = Logger.getLogger(BaseRemotingTest.class);
+
+    private static final Resource TEST_REMOTE_APPLICATION_CONTEXT_RESOURCE =
+            new ClassPathResource("/eu/etaxonomy/cdm/testRemotingApplicationContext.xml");
+
+    private static CdmApplicationRemoteController remoteApplicationController;
+    private static ICdmRemoteSource cdmRemoteSource;
+    private static CdmPersistentRemoteSource remotePersistentSource;
+
+    public static boolean useManagedServer = true;
+
+    public static final Resource CDMLIB_DISK_STORE_RESOURCE =
+            new ClassPathResource("/eu/etaxonomy/cache");
+    
+    protected static ICdmEntitySessionManager cdmEntitySessionManager;
+    
+    @BeforeClass
+    public static void initializeBaseRemotingTest() {
+        //NOTE: Run this the cdmTest H2 DB whenever it needs to be
+       //      recreated e.g. after a model change
+       //DatabaseUnitils.disableConstraints();
+
+               try {
+                       System.setProperty("ehcache.disk.store.dir", CDMLIB_DISK_STORE_RESOURCE.getFile().getAbsolutePath());
+               } catch (IOException e) {
+                       throw new CdmClientCacheException(e);
+               }
+        
+        useManagedServer = (System.getProperty("use.managed.server") == null) ? useManagedServer : Boolean.valueOf(System.getProperty("use.managed.server"));
+        if(useManagedServer) {
+            try {
+                CDMServer.getInstance().start();
+            } catch (Exception e) {
+                e.printStackTrace();
+                Assert.fail("Server failed to start. Reason : " + e.getMessage());
+            }
+
+        initializeController(CDMServer.getInstance().getName(),
+                CDMServer.getInstance().getHost(),
+                CDMServer.getInstance().getPort(),
+                CDMServer.getInstance().getContextPath(),
+                NomenclaturalCode.ICNAFP);
+        }
+    }
+
+    
+    @Test
+    public void disableConstraints() {
+       // To be run on the src/test/resources/h2/cdmTest h2 db after
+       // updating the unitils.properties 'database.url' property
+       DatabaseUnitils.disableConstraints();
+    }
+    public static void initializeController(String sourceName, String host, int port, String contextPath, NomenclaturalCode ncode) {
+
+        cdmRemoteSource = CdmRemoteSource.NewInstance(sourceName, host, port, contextPath, ncode);
+        remoteApplicationController =
+                CdmApplicationRemoteController.NewInstance(cdmRemoteSource,
+                        false,
+                        null,
+                        null);
+
+        try {
+            remotePersistentSource = CdmPersistentRemoteSource.NewInstance(sourceName);
+        } catch (CdmRemoteSourceException e) {
+            Assert.fail("Default Remote Persistent Source failed to load. Reason : " + e.getMessage());
+        }
+        cdmEntitySessionManager = getRemoteApplicationController().getCdmEntitySessionManager();
+    }
+
+
+
+    protected static CdmApplicationRemoteController getRemoteApplicationController() {
+        return remoteApplicationController;
+    }
+
+    protected static ICdmRemoteSource getCdmRemoteSource() {
+        return cdmRemoteSource;
+    }
+
+    protected static CdmPersistentRemoteSource getCdmPersistentRemoteSource() {
+        return remotePersistentSource;
+    }
+    
+    protected static ICdmEntitySessionManager getCdmEntitySessionManager() {
+       return cdmEntitySessionManager;
+    }
+    
+    protected static CdmTransientEntityCacher getCacher(ISessionEventListener sessionOwner) {
+       return (CdmTransientEntityCacher) getFieldValueViaReflection(cdmEntitySessionManager.getSession(sessionOwner), "cdmTransientEntityCacher");
+    }
+
+    @AfterClass
+    public static void cleanup() {
+        try {
+            CDMServer.getInstance().stop();
+        } catch (Exception e) {
+            Assert.fail("Server could not be stopped. Reason : " + e.getMessage());
+        }
+    }
+
+
+    protected static Object getFieldValueViaReflection(Object object, String fieldName) {
+        Class<?> clazz = object.getClass();
+        try {
+            Field field = clazz.getDeclaredField(fieldName);
+            field.setAccessible(true);
+            return field.get(object);
+        } catch (NoSuchFieldException e) {
+            e.printStackTrace();
+        } catch (SecurityException e) {
+            e.printStackTrace();
+        } catch (IllegalArgumentException e) {
+            e.printStackTrace();
+        } catch (IllegalAccessException e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+
+
+
+}
diff --git a/eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/httpinvoker/CDMServer.java b/eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/httpinvoker/CDMServer.java
new file mode 100644 (file)
index 0000000..69d2a9f
--- /dev/null
@@ -0,0 +1,350 @@
+// $Id$
+/**
+ * Copyright (C) 2014 EDIT
+ * European Distributed Institute of Taxonomy
+ * http://www.e-taxonomy.eu
+ *
+ * The contents of this file are subject to the Mozilla Public License Version 1.1
+ * See LICENSE.TXT at the top of this package for the full license terms.
+ */
+package eu.etaxonomy.taxeditor.httpinvoker;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.net.Socket;
+
+
+import javax.sql.DataSource;
+
+import org.apache.log4j.Level;
+import org.apache.log4j.Logger;
+import org.springframework.core.io.ClassPathResource;
+import org.springframework.core.io.Resource;
+import org.unitils.database.annotations.TestDataSource;
+import org.unitils.spring.annotation.SpringApplicationContext;
+
+import eu.etaxonomy.taxeditor.exception.CDMServerException;
+import eu.etaxonomy.taxeditor.remoting.source.CdmRemoteSourceBase;
+
+/**
+ *
+ * (Singleton) Server instance which manages a compatible cdmlib-webapp-war.
+ * This is done by launching a jetty instance (using jetty-runner) as an
+ * executed process. The choice of the external process over a more
+ * preferable 'embedded jetty' instance is due to problems arising from the
+ * class loading of classes (e.g. from hibernate core) which are needed
+ * for both the webapp as well as the remoting client.
+ *
+ * @author cmathew
+ * @date 23 Sep 2014
+ *
+ */
+
+public class CDMServer {
+
+    public static final Logger logger = Logger.getLogger(CDMServer.class);
+
+    @TestDataSource
+    protected DataSource dataSource;
+
+    private final String name = "default";
+    private final String host = "127.0.0.1";
+    private final int port = 9090;
+    private final int stopPort = 9191;
+    private final String stopKey = "jetty-cdm-server";
+    private final String contextPath = "";
+
+    private boolean keepServerRunning = false;
+
+    public static final Resource DEFAULT_CDM_WEBAPP_RESOURCE =
+            new ClassPathResource("/etc/jetty/cdmlib-remote-webapp.war");
+
+    public static final Resource DEFAULT_JETTY_CONFIG_RESOURCE =
+            new ClassPathResource("/etc/jetty/jetty.xml");
+
+    public static final Resource DEFAULT_JETTY_TEMP_RESOURCE =
+            new ClassPathResource("/etc/jetty/temp");
+
+    public static final Resource DEFAULT_JETTY_TEMP_WAR_LIB_RESOURCE =
+            new ClassPathResource("/etc/jetty/temp/webapp/WEB-INF/lib");
+
+    public static final Resource DEFAULT_DATASOURCE_FILE =
+            new ClassPathResource("datasources.xml");
+
+    public static final Resource DEFAULT_JETTY_RUNNER_RESOURCE =
+            new ClassPathResource("/etc/jetty/jetty-runner-9.2.3.v20140905.jar");
+
+    public static final Resource DEFAULT_JETTY_RESOURCE =
+            new ClassPathResource("/etc/jetty/start-9.2.3.v20140905.jar");
+
+
+
+    private static CDMServer cdmServer = null;
+    private static CDMServerException cdmse = null;
+
+    private void CDMServer() {
+        logger.setLevel(Level.INFO);
+    }
+
+    public static CDMServer getInstance() {
+        if(cdmServer == null) {
+            cdmServer = new CDMServer();
+        }
+        return cdmServer;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public String getHost() {
+        return host;
+    }
+
+    public int getPort() {
+        return port;
+    }
+
+    public String getContextPath() {
+        return contextPath;
+    }
+
+    public boolean getKeepServerRunning() {
+        return keepServerRunning;
+    }
+
+    public void setKeepServerRunning(boolean keepServerRunning) {
+        this.keepServerRunning = keepServerRunning;
+    }
+
+    public static boolean isRunningInEclipse() {
+        return (System.getProperty("sun.java.command") != null &&
+                System.getProperty("sun.java.command").startsWith("org.eclipse.jdt.internal.junit.runner.RemoteTestRunner"));
+    }
+
+    private String getVMArgs() throws IOException {
+        StringBuilder sb = new StringBuilder();
+        sb.append(" -Dspring.profiles.active=remoting");
+        sb.append(" -Dcdm.beanDefinitionFile=" + DEFAULT_DATASOURCE_FILE.getFile().getAbsolutePath());
+        sb.append(" -Dcdm.datasource=cdmTest");
+        return sb.toString();
+    }
+
+    private String getStartServerArgs() {
+        StringBuilder sb = new StringBuilder();
+        sb.append(" --port ");
+        sb.append(port);
+        return sb.toString();
+    }
+
+    private String getStopServerSettings() {
+        StringBuilder sb = new StringBuilder();
+        sb.append(" --stop-port ");
+        sb.append(stopPort);
+        sb.append(" --stop-key ");
+        sb.append(stopKey);
+        return sb.toString();
+    }
+
+    private String getStopServerArgs() {
+        StringBuilder sb = new StringBuilder();
+        sb.append(" STOP.PORT=");
+        sb.append(stopPort);
+        sb.append(" STOP.KEY=");
+        sb.append(stopKey);
+        return sb.toString();
+    }
+
+    public void start() throws CDMServerException {
+
+        /**
+         * First check if the CDM server responds to a service request, which implies that
+         * the server has started properly. If no response is received then check if the
+         * server is listening on specific host / port, which implies that the server
+         * has started but incorrectly, in which case we try to force stop it (if we can)
+         * and start a new server.
+         */
+        if(isRunning(1)) {
+            logger.info("[CDM-Server] Server already running @ " + host + ":" + port );
+            return;
+        } else if (isAvailable(1)){
+            logger.info("[CDM-Server] Server available, but not started correctly @ " + host + ":" + port );
+            logger.info("[CDM-Server] .... trying to force stop server @ " + host + ":" + port );
+            try {
+                stop(true);
+            } catch (Exception e) {
+                throw new CDMServerException("CDM Server could not be stopped : " + e.getMessage());
+            }
+        }
+
+        Thread t = new Thread() {
+            @Override
+            public void run() {
+                StringBuffer output = new StringBuffer();
+                try{
+                    Process p;
+                    String command = "java "
+                            + getVMArgs()
+                            + " -jar "
+                            + DEFAULT_JETTY_RUNNER_RESOURCE.getFile().getAbsolutePath()
+                            + getStartServerArgs()
+                            + getStopServerSettings()
+                            + " "
+                            + DEFAULT_CDM_WEBAPP_RESOURCE.getFile().getAbsolutePath();
+                    logger.info("[CDM-Server] Starting server with Command : " + command);
+                    p = Runtime.getRuntime().exec(command);
+
+                    BufferedReader reader =
+                            new BufferedReader(new InputStreamReader(p.getInputStream()));
+
+                    String line = "";
+                    while ((line = reader.readLine())!= null) {
+                        logger.info("[CDM-Server] Start : " + line);
+                    }
+
+                } catch (Exception e) {
+                    e.printStackTrace();
+                    cdmse = new CDMServerException(e);
+                }
+
+            }
+        };
+
+        t.setDaemon(true);
+        cdmse = null;
+        t.start();
+
+        if(isRunning(50)) {
+            logger.info("[CDM-Server] Started Server @ " + host + ":" + port );
+        } else {
+            logger.info("[CDM-Server] Server not started within given interval");
+            // making sure to kill server if it is not started correctly
+            try {
+                stop(true);
+            } catch (Exception e) {
+                throw new CDMServerException("CDM Server could not be stopped : " + e.getMessage());
+            }
+            throw new CDMServerException("CDM Server not started : ");
+        }
+
+    }
+
+    public boolean isAvailable(int checkingIntervals) throws CDMServerException {
+        int intervalsCount = 0;
+        do {
+            try {
+                Socket s = new Socket(host, port);
+                logger.info("[CDM-Server] Available @ " + host + ":" + port );
+                return true;
+            } catch (IOException ioe) {
+
+            }
+            try {
+                Thread.sleep(1000);
+            } catch (InterruptedException ie) {
+                throw new CDMServerException("Error checking CDM Server status", ie);
+            }
+            intervalsCount++;
+        } while (intervalsCount < checkingIntervals);
+
+        return false;
+    }
+
+    public boolean isStopped(int checkingIntervals) throws CDMServerException {
+        int intervalsCount = 0;
+        do {
+            try {
+                Socket s = new Socket(host, port);
+            } catch (IOException ioe) {               
+                return true;
+            }
+            try {
+                Thread.sleep(1000);
+            } catch (InterruptedException ie) {
+                throw new CDMServerException("Error checking CDM Server status", ie);
+            }
+            intervalsCount++;
+        } while (intervalsCount < checkingIntervals);
+
+        return false;
+    }
+
+    public boolean isRunning(int checkingIntervals) throws CDMServerException  {
+        CdmRemoteSourceBase crsb = new CdmRemoteSourceBase("local-cdm-server",
+                host,
+                port,
+                contextPath,
+                null);
+        int intervalsCount = 0;
+        do {
+            try {
+                if(cdmse != null) {
+                    return false;
+                }
+                if(crsb.checkConnection()) {
+                    logger.info("[CDM-Server] Running @ " + host + ":" + port );
+                    return true;
+                }
+            } catch (Exception e) {
+            }
+            try {
+                Thread.sleep(1000);
+            } catch (InterruptedException ie) {
+                throw new CDMServerException("Error checking CDM Server status", ie);
+            }
+            intervalsCount++;
+        } while (intervalsCount < checkingIntervals);
+        return false;
+    }
+
+    public void stop() throws Exception {
+        stop(false);
+    }
+    public void stop(boolean force) throws Exception {
+
+        if(!force) {
+            if(!getInstance().isAvailable(1)) {
+                logger.info("[CDM-Server] Server already stopped @ " + host + ":" + port );
+                return;
+            }
+
+            if(getInstance().getKeepServerRunning()) {
+                logger.info("[CDM-Server] Server @ " + host + ":" + port + " is set to keep running");
+                return;
+            }
+        }
+        Thread t = new Thread() {
+            @Override
+            public void run() {
+                StringBuffer output = new StringBuffer();
+                try{
+                    Process p;
+                    String command = "java -jar " + DEFAULT_JETTY_RESOURCE.getFile().getAbsolutePath()
+                            + getStopServerArgs() + " --stop ";
+                    logger.info("[CDM-Server] Stop Command : " + command);
+                    p = Runtime.getRuntime().exec(command);
+                    p.waitFor();
+                    BufferedReader reader =
+                            new BufferedReader(new InputStreamReader(p.getInputStream()));
+                    String line = "";
+                    while ((line = reader.readLine())!= null) {
+                        logger.info("CDM-Server Stop : " + line + "\n");
+                    }
+                } catch (Exception e) {
+                    e.printStackTrace();
+                }
+
+            }
+        };
+
+        t.setDaemon(true);
+        t.start();
+
+        if(isStopped(5)) {
+            logger.info("[CDM-Server] Stopped Server @ " + host + ":" + port );
+        } else {
+            logger.info("[CDM-Server] Could not stop @ " + host + ":" + port + ". Please kill it manually");
+        }
+    }
+}
diff --git a/eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/httpinvoker/CdmPersistentRemoteSourceTest.java b/eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/httpinvoker/CdmPersistentRemoteSourceTest.java
new file mode 100644 (file)
index 0000000..ba58bd2
--- /dev/null
@@ -0,0 +1,221 @@
+/**
+ * Copyright (C) 2014 EDIT
+ * European Distributed Institute of Taxonomy
+ * http://www.e-taxonomy.eu
+ *
+ * The contents of this file are subject to the Mozilla Public License Version 1.1
+ * See LICENSE.TXT at the top of this package for the full license terms.
+ */
+package eu.etaxonomy.taxeditor.httpinvoker;
+
+
+import static org.hamcrest.CoreMatchers.containsString;
+
+import java.util.Map;
+
+import org.apache.log4j.Level;
+import org.apache.log4j.Logger;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import eu.etaxonomy.cdm.config.CdmPersistentSourceUtils;
+import eu.etaxonomy.cdm.config.CdmPersistentXMLSource.CdmSourceProperties;
+import eu.etaxonomy.cdm.config.CdmSourceException;
+import eu.etaxonomy.cdm.model.metadata.CdmMetaData.MetaDataPropertyName;
+import eu.etaxonomy.cdm.model.name.NomenclaturalCode;
+import eu.etaxonomy.taxeditor.remoting.source.CdmPersistentRemoteSource;
+import eu.etaxonomy.taxeditor.remoting.source.CdmRemoteSource;
+import eu.etaxonomy.taxeditor.remoting.source.CdmRemoteSourceException;
+import eu.etaxonomy.taxeditor.remoting.source.ICdmRemoteSource;
+
+/**
+ * Class to test the cdm persistent source functionality, including
+ * initialising / saving / updating and deleting
+ *
+ * Corresponding test sources settings can be found at
+ * /src/text/resources/eu.etaxonomy.cdm/cdm.datasources.xml
+ *
+ */
+public class CdmPersistentRemoteSourceTest extends BaseRemotingTest {
+    private static final Logger logger = Logger.getLogger(CdmPersistentRemoteSourceTest.class);
+
+    private CdmPersistentRemoteSource remotePersistentSource;
+
+    @BeforeClass
+    public static void initialize() {
+        Logger.getRootLogger().setLevel(Level.INFO);
+    }
+
+    @Test
+    public void whenLoadingExistingCompleteRemoteSourceThenLoadIsSuccessful() {
+
+        remotePersistentSource = getCdmPersistentRemoteSource();
+
+        String expectedServer = "127.0.0.1";
+        String expectedPort = "9090";
+        String expectedContextPath = "";
+        logger.info("Default remote source server : " + remotePersistentSource.getServer());
+        Assert.assertTrue("Default server should be " + expectedServer,
+                expectedServer.equals(remotePersistentSource.getServer()));
+
+        logger.info("Default remote source port : " + remotePersistentSource.getPort());
+        Assert.assertTrue("Default port should be 9090",
+                expectedPort.equals(String.valueOf(remotePersistentSource.getPort())));
+
+        logger.info("Default remote source context path : " + remotePersistentSource.getContextPath());
+        Assert.assertTrue("Default remote source context path should be " + expectedContextPath,
+                expectedContextPath.equals(remotePersistentSource.getContextPath()));
+
+        logger.info("Default remote source nomenclatural code : " + remotePersistentSource.getNomenclaturalCode().toString());
+        Assert.assertTrue("Default NomenclaturalCode should be ICNAFP",
+                NomenclaturalCode.ICNAFP.equals(remotePersistentSource.getNomenclaturalCode()));
+    }
+
+
+
+
+    @Test
+    public void whenConnectingToAnActiveServerThenConnectSuccessfully() {
+        // check if active server throws the right exception
+
+        remotePersistentSource = getCdmPersistentRemoteSource();
+
+        String dbSchemaVersion = "";
+        try {
+            dbSchemaVersion = remotePersistentSource.getDbSchemaVersion();
+        } catch (CdmSourceException e) {
+            Assert.fail("getDbSchemaVersion() on active cdm server should not have thrown CdmSourceException");
+        }
+        logger.info("dbSchemaVersion is " + dbSchemaVersion);
+
+
+        boolean isDbEmpty = false;
+        try {
+            isDbEmpty = remotePersistentSource.isDbEmpty();
+        } catch (CdmSourceException e) {
+            Assert.fail("isDbEmpty() on active cdm server should not have thrown CdmSourceException");
+        }
+        Assert.assertFalse(isDbEmpty);
+
+
+        boolean check = false;
+        try {
+            check = remotePersistentSource.checkConnection();
+        } catch (CdmSourceException e) {
+            Assert.fail("checkConnection() on active cdm server should not have thrown CdmSourceException");
+        }
+        Assert.assertTrue(check);
+
+
+    }
+
+    @Test
+    public void whenRequestingMetadatFromRemoteSourceThenMetaDataIsRetrieved() {
+        try {
+            remotePersistentSource = getCdmPersistentRemoteSource();
+            Map<MetaDataPropertyName, String> cdmMetaDataMap = remotePersistentSource.getMetaDataMap();
+            for(MetaDataPropertyName mdpn : cdmMetaDataMap.keySet()) {
+                String value = cdmMetaDataMap.get(mdpn);
+                logger.info("MetaData Property " + mdpn.name() + " has value " + value);
+                Assert.assertNotNull("Meta Data Value for property for " + mdpn.name() + " should not be null", value);
+            }
+        } catch (CdmSourceException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+    }
+
+    @Test
+    public void whenLoadingNonExistingRemoteSourceThenThrowException() {
+        try {
+            remotePersistentSource = CdmPersistentRemoteSource.NewInstance("nonExistingSource");
+            Assert.fail("Initialising a non-existing remote source should throw an exception");
+        } catch (CdmRemoteSourceException e) {
+            logger.info(e.getMessage());
+        }
+    }
+
+    @Test
+    public void whenLoadingExistingIncompleteRemoteSourceThenThrowException() {
+        try {
+            remotePersistentSource = CdmPersistentRemoteSource.NewInstance("incomplete");
+            Assert.fail("Initialising an incomplete remote source should throw an exception");
+        } catch (CdmRemoteSourceException e) {
+            Assert.assertThat(e.getMessage(), containsString("Required property '" + CdmSourceProperties.SERVER.toString() + "' is missing"));
+        }
+    }
+
+    @Test
+    public void whenSavingUpdatingDeletingNewCompleteRemoteSourceThenSaveUpdateDeleteIsSuccessful() {
+        String strRemoteSource = "local";
+        Assert.assertFalse("New remote source '" + strRemoteSource + "' should not yet exist in source settings file",
+                CdmPersistentRemoteSource.exists(strRemoteSource));
+        try {
+            ICdmRemoteSource remoteSource =
+                    CdmRemoteSource.NewInstance(strRemoteSource,
+                            "127.0.0.1",
+                            8080,
+                            "col",
+                            NomenclaturalCode.ICNAFP);
+            remotePersistentSource = CdmPersistentRemoteSource.save(strRemoteSource,remoteSource);
+
+            logger.info("Server : " + remotePersistentSource.getServer());
+            Assert.assertTrue("Server value should be equal",
+                    remoteSource.getServer().equals(remotePersistentSource.getServer()));
+
+            logger.info("Port : " + remotePersistentSource.getPort());
+            Assert.assertTrue("Port value should be equal",
+                    remoteSource.getPort() == remotePersistentSource.getPort());
+
+            logger.info("Context Path : " + remotePersistentSource.getContextPath());
+            Assert.assertTrue("Context Path value should be equal",
+                    remoteSource.getContextPath().equals(remotePersistentSource.getContextPath()));
+
+            logger.info("Nomenclatural Code : " + remotePersistentSource.getNomenclaturalCode().name());
+            Assert.assertTrue("Nomenclatural Code value should be equal",
+                    remoteSource.getNomenclaturalCode().name().equals(remotePersistentSource.getNomenclaturalCode().name()));
+
+            Assert.assertTrue("New remote source '" + strRemoteSource + "' should be saved in source settings file",
+                    CdmPersistentRemoteSource.exists(strRemoteSource));
+
+            remoteSource = CdmRemoteSource.NewInstance(strRemoteSource,
+                    "127.0.0.55",
+                    9090,
+                    "cyprus",
+                    NomenclaturalCode.ICNB);
+            remotePersistentSource = CdmPersistentRemoteSource.update(strRemoteSource,remoteSource);
+
+            logger.info("Server : " + remotePersistentSource.getServer());
+            Assert.assertTrue("Server value should be equal",
+                    remoteSource.getServer().equals(remotePersistentSource.getServer()));
+
+            logger.info("Port : " + remotePersistentSource.getPort());
+            Assert.assertTrue("Port value should be equal",
+                    remoteSource.getPort() == remotePersistentSource.getPort());
+
+            logger.info("Context Path : " + remotePersistentSource.getContextPath());
+            Assert.assertTrue("Context Path value should be equal",
+                    remoteSource.getContextPath().equals(remotePersistentSource.getContextPath()));
+
+            logger.info("Nomenclatural Code : " + remotePersistentSource.getNomenclaturalCode().name());
+            Assert.assertTrue("Nomenclatural Code value should be equal",
+                    remoteSource.getNomenclaturalCode().name().equals(remotePersistentSource.getNomenclaturalCode().name()));
+
+            Assert.assertTrue("New remote source '" + strRemoteSource + "' should be saved in source settings file",
+                    CdmPersistentRemoteSource.exists(strRemoteSource));
+
+            CdmPersistentSourceUtils.delete(remotePersistentSource);
+
+            Assert.assertFalse("New remote source '" + strRemoteSource + "' should no longer exist in source settings file",
+                    CdmPersistentRemoteSource.exists(strRemoteSource));
+
+        } catch (CdmRemoteSourceException e) {
+            Assert.fail("Saving a new complete remote source should not throw an exception");
+            logger.info(e.getMessage());
+        }
+    }
+
+
+
+}
diff --git a/eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/httpinvoker/CdmRemoteSourceTest.java b/eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/httpinvoker/CdmRemoteSourceTest.java
new file mode 100644 (file)
index 0000000..3a8a786
--- /dev/null
@@ -0,0 +1,112 @@
+/**
+* Copyright (C) 2014 EDIT
+* European Distributed Institute of Taxonomy
+* http://www.e-taxonomy.eu
+*
+* The contents of this file are subject to the Mozilla Public License Version 1.1
+* See LICENSE.TXT at the top of this package for the full license terms.
+*/
+package eu.etaxonomy.taxeditor.httpinvoker;
+
+import org.apache.log4j.Level;
+import org.apache.log4j.Logger;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.springframework.remoting.RemoteAccessException;
+
+import eu.etaxonomy.cdm.config.CdmSourceException;
+import eu.etaxonomy.cdm.model.name.NomenclaturalCode;
+import eu.etaxonomy.taxeditor.lazyloading.RemotePersistentCollectionTest;
+import eu.etaxonomy.taxeditor.remoting.source.CdmRemoteSource;
+
+public class CdmRemoteSourceTest extends BaseRemotingTest {
+       private static final Logger logger = Logger.getLogger(RemotePersistentCollectionTest.class);
+
+
+       @BeforeClass
+       public static void initialize() {
+
+               Logger.getRootLogger().setLevel(Level.INFO);
+
+       }
+
+       @Test
+       public void whenConnectingToInactiveServerThenFailToConnect() {
+               // check if non-active server throws the right exception
+               CdmRemoteSource inactiveCrs = CdmRemoteSource.NewInstance(CDMServer.getInstance().getName(),
+                       CDMServer.getInstance().getHost(),
+                       808080,
+                       CDMServer.getInstance().getContextPath(),
+                       NomenclaturalCode.ICNAFP);
+               try {
+                       inactiveCrs.getDbSchemaVersion();
+                       Assert.fail("getDbSchemaVersion() on inactive cdm server should have thrown RemoteAccessException");
+               } catch(CdmSourceException cse) {
+                       Assert.fail("getDbSchemaVersion() on inactive cdm server should have thrown RemoteAccessException and not CdmSourceException");
+               } catch(RemoteAccessException rae){
+
+               }
+
+               try {
+                       inactiveCrs.isDbEmpty();
+                       Assert.fail("isDbEmpty() on inactive cdm server should have thrown RemoteAccessException");
+               } catch(CdmSourceException cse) {
+                       Assert.fail("isDbEmpty() on inactive cdm server should have thrown RemoteAccessException and not CdmSourceException");
+               } catch(RemoteAccessException rae){
+
+               }
+
+               try {
+                       inactiveCrs.checkConnection();
+                       Assert.fail("checkConnection() on inactive cdm server should have thrown RemoteAccessException");
+               } catch(CdmSourceException cse) {
+                       Assert.fail("checkConnection() on inactive cdm server should have thrown RemoteAccessException and not CdmSourceException");
+               } catch(RemoteAccessException rae){
+
+               }
+
+       }
+
+       @Test
+       public void whenConnectingToAnActiveServerWithServicesBlockedThenFailToAccessServices() {
+
+       }
+
+       @Test
+       public void whenConnectingToAnActiveServerThenConnectSuccessfully() {
+               // check if active server throws the right exception
+               CdmRemoteSource activeCrs = CdmRemoteSource.NewInstance(CDMServer.getInstance().getName(),
+                CDMServer.getInstance().getHost(),
+                CDMServer.getInstance().getPort(),
+                CDMServer.getInstance().getContextPath(),
+                NomenclaturalCode.ICNAFP);
+               String dbSchemaVersion = "";
+               try {
+                       dbSchemaVersion = activeCrs.getDbSchemaVersion();
+               } catch (CdmSourceException e) {
+                       Assert.fail("getDbSchemaVersion() on active cdm server should not have thrown CdmSourceException");
+               }
+               logger.info("dbSchemaVersion is " + dbSchemaVersion);
+
+
+               boolean isDbEmpty = false;
+               try {
+                       isDbEmpty = activeCrs.isDbEmpty();
+               } catch (CdmSourceException e) {
+                       Assert.fail("isDbEmpty() on active cdm server should not have thrown CdmSourceException");
+               }
+               Assert.assertFalse(isDbEmpty);
+
+
+               boolean check = true;
+               try {
+                       isDbEmpty = activeCrs.checkConnection();
+               } catch (CdmSourceException e) {
+                       Assert.fail("checkConnection() on active cdm server should not have thrown CdmSourceException");
+               }
+               Assert.assertTrue(check);
+
+       }
+
+}
diff --git a/eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/httpinvoker/CdmServerTest.java b/eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/httpinvoker/CdmServerTest.java
new file mode 100644 (file)
index 0000000..816b18b
--- /dev/null
@@ -0,0 +1,41 @@
+// $Id$
+/**
+* Copyright (C) 2014 EDIT
+* European Distributed Institute of Taxonomy
+* http://www.e-taxonomy.eu
+*
+* The contents of this file are subject to the Mozilla Public License Version 1.1
+* See LICENSE.TXT at the top of this package for the full license terms.
+*/
+package eu.etaxonomy.taxeditor.httpinvoker;
+
+import org.apache.log4j.Level;
+import org.apache.log4j.Logger;
+import org.junit.Assert;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.unitils.UnitilsJUnit4;
+
+import eu.etaxonomy.taxeditor.lazyloading.AbstractLazyInitializerTest;
+
+/**
+ * @author cmathew
+ * @date 6 Oct 2014
+ *
+ */
+public class CdmServerTest extends UnitilsJUnit4 {
+    private static final Logger logger = Logger.getLogger(CdmServerTest.class);
+
+
+    @Test
+    public void stopCdmServer() {
+        Logger.getRootLogger().setLevel(Level.INFO);
+        CDMServer.getInstance().setKeepServerRunning(false);
+        try {
+            CDMServer.getInstance().stop(true);
+        } catch (Exception e) {
+            Assert.fail("Server could not be stopped. Reason : " + e.getMessage());
+        }
+    }
+
+}
diff --git a/eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/httpinvoker/CdmServerTestManager.java b/eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/httpinvoker/CdmServerTestManager.java
new file mode 100644 (file)
index 0000000..64261d2
--- /dev/null
@@ -0,0 +1,41 @@
+// $Id$
+/**
+* Copyright (C) 2014 EDIT
+* European Distributed Institute of Taxonomy
+* http://www.e-taxonomy.eu
+*
+* The contents of this file are subject to the Mozilla Public License Version 1.1
+* See LICENSE.TXT at the top of this package for the full license terms.
+*/
+package eu.etaxonomy.taxeditor.httpinvoker;
+
+import org.apache.log4j.Level;
+import org.apache.log4j.Logger;
+import org.junit.Assert;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.unitils.UnitilsJUnit4;
+
+import eu.etaxonomy.taxeditor.lazyloading.AbstractLazyInitializerTest;
+
+/**
+ * @author cmathew
+ * @date 6 Oct 2014
+ *
+ */
+public class CdmServerTestManager extends UnitilsJUnit4 {
+    private static final Logger logger = Logger.getLogger(CdmServerTestManager.class);
+
+
+    @Test
+    public void stopCdmServer() {
+        Logger.getRootLogger().setLevel(Level.INFO);
+        
+        try {
+            CDMServer.getInstance().stop();
+        } catch (Exception e) {
+            Assert.fail("Server could not be stopped. Reason : " + e.getMessage());
+        }
+    }
+
+}
diff --git a/eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/httpinvoker/HttpInvokerServicesTest.java b/eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/httpinvoker/HttpInvokerServicesTest.java
new file mode 100644 (file)
index 0000000..b05d362
--- /dev/null
@@ -0,0 +1,34 @@
+/**
+* Copyright (C) 2014 EDIT
+* European Distributed Institute of Taxonomy
+* http://www.e-taxonomy.eu
+*
+* The contents of this file are subject to the Mozilla Public License Version 1.1
+* See LICENSE.TXT at the top of this package for the full license terms.
+*/
+package eu.etaxonomy.taxeditor.httpinvoker;
+
+import org.apache.log4j.Logger;
+import org.junit.Assert;
+import org.junit.Test;
+
+import eu.etaxonomy.cdm.config.CdmSourceException;
+
+/**
+ * Class to test the HttpInvoker services exposed by the CDM Sever
+ *
+ */
+public class HttpInvokerServicesTest extends BaseRemotingTest {
+       private static final Logger logger = Logger.getLogger(HttpInvokerServicesTest.class);
+
+       @Test
+       public void whenCallingMethodsOnRemoteServicesThenSuceed() {
+               try {
+                       String dbSchemaVersion = getRemoteApplicationController().getDatabaseService().getDbSchemaVersion();
+                       logger.info("dbSchemaVersion is " + dbSchemaVersion);
+               } catch (CdmSourceException e) {
+                       Assert.fail("pinging database service on active cdm server should not have thrown CdmSourceException");
+               }
+       }
+
+}
diff --git a/eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/lazyloading/AbstractLazyInitializerTest.java b/eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/lazyloading/AbstractLazyInitializerTest.java
new file mode 100644 (file)
index 0000000..9bfdc0d
--- /dev/null
@@ -0,0 +1,214 @@
+/**
+ * Copyright (C) 2014 EDIT
+ * European Distributed Institute of Taxonomy
+ * http://www.e-taxonomy.eu
+ *
+ * The contents of this file are subject to the Mozilla Public License Version 1.1
+ * See LICENSE.TXT at the top of this package for the full license terms.
+ */
+package eu.etaxonomy.taxeditor.lazyloading;
+
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+
+import org.apache.log4j.Level;
+import org.apache.log4j.Logger;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.unitils.dbunit.annotation.DataSet;
+
+import eu.etaxonomy.cdm.api.application.CdmApplicationRemoteController;
+import eu.etaxonomy.cdm.api.service.IClassificationService;
+import eu.etaxonomy.cdm.api.service.ITaxonService;
+import eu.etaxonomy.cdm.model.agent.Person;
+import eu.etaxonomy.cdm.model.agent.Team;
+import eu.etaxonomy.cdm.model.common.CdmBase;
+import eu.etaxonomy.cdm.model.name.BotanicalName;
+import eu.etaxonomy.cdm.model.name.NonViralName;
+import eu.etaxonomy.cdm.model.name.TaxonNameBase;
+import eu.etaxonomy.cdm.model.taxon.Classification;
+import eu.etaxonomy.cdm.model.taxon.SynonymRelationship;
+import eu.etaxonomy.cdm.model.taxon.Taxon;
+import eu.etaxonomy.cdm.model.taxon.TaxonNode;
+import eu.etaxonomy.taxeditor.httpinvoker.BaseRemotingTest;
+
+
+
+
+/**
+ * Class to test the {@link CdmApplicationRemoteController}
+ *
+ */
+@DataSet
+public class AbstractLazyInitializerTest extends BaseRemotingTest {
+    private static final Logger logger = Logger.getLogger(AbstractLazyInitializerTest.class);
+
+    private static IClassificationService classificationService;
+    private static ITaxonService taxonService;
+
+    private static List<TaxonNode> taxonNodes;
+
+    private final UUID taxonUuid1 = UUID.fromString("8217ef77-2ab1-4318-bd67-ccd0cdef07c4");
+    private final UUID taxonUuid2 = UUID.fromString("ef96fafa-7750-4141-b31b-1ad1daab3e76");
+
+
+    @BeforeClass
+    public void initializeRemoteLazyLoading() {
+
+        Logger.getRootLogger().setLevel(Level.DEBUG);
+
+        taxonService = getRemoteApplicationController().getTaxonService();
+        classificationService= getRemoteApplicationController().getClassificationService();
+        List<Classification> classifications = classificationService.listClassifications(1,0,null,null);
+        Assert.assertFalse(classifications.isEmpty());
+
+        Classification classification = classifications.get(0);
+        Assert.assertNotNull(classification);
+        taxonNodes = classificationService.getAllNodes();
+        Assert.assertFalse(taxonNodes.isEmpty());
+
+    }
+
+
+
+    @Test
+    public void testCDMEntityGet() {
+        //ITaxonService taxonService = getRemoteApplicationController().getTaxonService();
+        Iterator<TaxonNode> taxonNodeItr = taxonNodes.iterator();
+        int maxcount = 30;
+        int count = 0;
+        while(taxonNodeItr.hasNext() && count <= maxcount) {
+            TaxonNode taxonNode = taxonNodeItr.next();
+            Assert.assertNotNull(taxonNode);
+
+            Taxon taxon = taxonNode.getTaxon();
+            Assert.assertNotNull(taxon);
+
+            String taxonTitle = taxon.getTitleCache();
+            logger.info("Taxon : " + taxonTitle);
+
+            TaxonNameBase name = taxon.getName();
+            Assert.assertNotNull(name);
+
+            String nameTitle = name.getTitleCache();
+            logger.info("Taxon Name : " + nameTitle);
+
+            count++;
+        }
+    }
+
+    @Test
+    public void taxonReadTest() {
+        Taxon taxon = (Taxon)taxonService.find(taxonUuid1);
+
+    }
+
+
+    @Test
+    public void testCDMEntitySave() {
+        Taxon taxon = (Taxon)taxonService.find(taxonUuid1);
+        String oldTitleCache = taxon.getTitleCache();
+
+        System.out.println("Taxon title : " + oldTitleCache);
+
+        taxon.setTitleCache(oldTitleCache + ":updated", true);
+        taxonService.merge(taxon);
+
+        Taxon taxonNew = (Taxon)taxonService.find(taxonUuid1);
+        System.out.println("New Taxon Title : " + taxonNew.getTitleCache());
+
+        Assert.assertNotEquals("Title caches should not be equal",oldTitleCache,taxonNew.getTitleCache());
+
+        taxonNew.setTitleCache(oldTitleCache, true);
+        taxonService.merge(taxonNew);
+
+        Taxon taxonOld = (Taxon)taxonService.find(taxonUuid1);
+        System.out.println("Old Taxon Title : " + taxonOld.getTitleCache());
+
+        Assert.assertEquals("Title caches should be equal",oldTitleCache,taxonOld.getTitleCache());
+
+    }
+
+
+        @Test
+        public void testCDMEntitySaveLazyNew() {
+            Team combAuthor = Team.NewInstance();
+            combAuthor.addTeamMember(Person.NewTitledInstance("test member"));
+            BotanicalName name = BotanicalName.NewInstance(null, "Test1", null, null, null, null, null, null, null);
+            name.setCombinationAuthorTeam(combAuthor);
+            Taxon tax1 = Taxon.NewInstance(name, null);
+            UUID taxonUuid1 = taxonService.save(tax1);
+
+            Taxon taxon = (Taxon)taxonService.find(taxonUuid1);
+
+            NonViralName nvn = CdmBase.deproxy(taxon.getName(),NonViralName.class);
+            String oldTitleCache = nvn.getTitleCache();
+            logger.info("Taxon Name Title : " + oldTitleCache);
+            nvn.setTitleCache(oldTitleCache + ":updated",false);
+            taxonService.update(taxon);
+
+            Taxon taxonNew = (Taxon)taxonService.find(taxonUuid1);
+            NonViralName nvnNew = CdmBase.deproxy(taxon.getName(),NonViralName.class);
+            logger.info("New Taxon Name Title : " + nvnNew.getTitleCache());
+
+            Assert.assertNotEquals("Title caches should not be equal",oldTitleCache,nvnNew.getTitleCache());
+
+            nvnNew.setTitleCache(oldTitleCache, true);
+            taxonService.update(taxon);
+
+            Taxon taxonOld = (Taxon)taxonService.find(taxonUuid1);
+            NonViralName nvnOld = CdmBase.deproxy(taxon.getName(),NonViralName.class);
+            logger.info("Old Taxon Name Title : " + nvnNew.getTitleCache());
+
+            Assert.assertEquals("Title caches should be equal",oldTitleCache,nvnOld.getTitleCache());
+        }
+
+        @Ignore
+        @Test
+        public void testCDMEntitySaveCollection() {
+            Taxon taxon = (Taxon)taxonService.find(taxonUuid1);
+
+            Set<SynonymRelationship> synRelations = taxon.getSynonymRelations();
+            Set<String> relToTitles = new HashSet<String>();
+            Iterator<SynonymRelationship> srItr = synRelations.iterator();
+            while(srItr.hasNext()) {
+                SynonymRelationship sr = srItr.next();
+                System.out.println("Synonym Title Cache : " + sr.getSynonym().getTitleCache());
+                relToTitles.add(sr.getSynonym().getTitleCache());
+                sr.getSynonym().setTitleCache(sr.getSynonym().getTitleCache() + ":updated");
+
+            }
+            taxonService.merge(taxon);
+
+            Taxon taxonNew = (Taxon)taxonService.find(taxonUuid1);
+            Set<SynonymRelationship> synRelationsNew = taxonNew.getSynonymRelations();
+
+            Iterator<SynonymRelationship> srItrNew = synRelationsNew.iterator();
+            Iterator<String> relToTitlesItr = relToTitles.iterator();
+            while(srItrNew.hasNext() && relToTitlesItr.hasNext()) {
+                SynonymRelationship srNew = srItrNew.next();
+                String relToTitle = relToTitlesItr.next();
+                System.out.println("New Synonym Title Cache: " + srNew.getSynonym().getTitleCache());
+                Assert.assertNotEquals("Synonym Title caches should not be equal", srNew.getSynonym().getTitleCache(), relToTitle);
+                srNew.getSynonym().setTitleCache(relToTitle);
+            }
+
+            Taxon taxonOld = (Taxon)taxonService.find(taxonUuid1);
+
+            Set<SynonymRelationship> synRelationsOld = taxonNew.getSynonymRelations();
+            Iterator<SynonymRelationship> srItrOld = synRelationsOld.iterator();
+            relToTitlesItr = relToTitles.iterator();
+            while(srItrOld.hasNext() && relToTitlesItr.hasNext()) {
+                SynonymRelationship srOld = srItrOld.next();
+                String relToTitle = relToTitlesItr.next();
+                System.out.println("New Synonym Title Cache: " + srOld.getSynonym().getTitleCache());
+                Assert.assertEquals("Synonym Title caches should be equal", srOld.getSynonym().getTitleCache(), relToTitle);
+
+            }
+        }
+}
diff --git a/eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/lazyloading/CdmEntityCacherTest.java b/eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/lazyloading/CdmEntityCacherTest.java
new file mode 100644 (file)
index 0000000..f995499
--- /dev/null
@@ -0,0 +1,89 @@
+// $Id$
+/**
+* Copyright (C) 2014 EDIT
+* European Distributed Institute of Taxonomy
+* http://www.e-taxonomy.eu
+*
+* The contents of this file are subject to the Mozilla Public License Version 1.1
+* See LICENSE.TXT at the top of this package for the full license terms.
+*/
+package eu.etaxonomy.taxeditor.lazyloading;
+
+import java.util.UUID;
+
+import org.apache.log4j.Level;
+import org.apache.log4j.Logger;
+import org.hibernate.collection.spi.PersistentCollection;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import eu.etaxonomy.cdm.api.service.ICommonService;
+import eu.etaxonomy.cdm.api.service.IPolytomousKeyService;
+import eu.etaxonomy.cdm.api.service.ITaxonService;
+import eu.etaxonomy.cdm.model.common.CdmBase;
+import eu.etaxonomy.cdm.model.common.Language;
+import eu.etaxonomy.cdm.model.description.PolytomousKey;
+import eu.etaxonomy.cdm.model.description.PolytomousKeyNode;
+import eu.etaxonomy.cdm.model.name.NomenclaturalCode;
+import eu.etaxonomy.taxeditor.httpinvoker.BaseRemotingTest;
+import eu.etaxonomy.taxeditor.httpinvoker.CDMServer;
+
+/**
+ * @author cmathew
+ * @date 16 Oct 2014
+ *
+ */
+public class CdmEntityCacherTest extends BaseRemotingTest {
+
+    private static final Logger logger = Logger.getLogger(CdmEntityCacherTest.class);
+
+    UUID polytomousKeyUuid = UUID.fromString("0d53ba20-7de4-4baa-bd8a-401048447d66");
+    UUID taxon1Uuid = UUID.fromString("2b336df7-29e8-4f79-985f-66502739d22f");
+
+
+    IPolytomousKeyService polytomousKeyService = getRemoteApplicationController().getPolytomousKeyService();
+    ICommonService commonService = getRemoteApplicationController().getCommonService();
+    ITaxonService taxonService = getRemoteApplicationController().getTaxonService();
+
+    Language english = Language.getLanguageFromUuid(Language.uuidEnglish);
+
+    @BeforeClass
+    public static void initializePolytomousKeyTest() {
+        logger.setLevel(Level.INFO);
+        CDMServer.getInstance().setKeepServerRunning(true);
+
+        initializeController("default", "127.0.0.1", 8080, "", NomenclaturalCode.ICNAFP);
+    }
+
+    @Test
+    public void testSimpleCache() {
+
+
+    }
+
+    @Test
+    public void testCachingCdmEntities() {
+        PolytomousKey pkey = CdmBase.deproxy(polytomousKeyService.find(polytomousKeyUuid),PolytomousKey.class);
+        PolytomousKeyNode pkeynode = pkey.getRoot();
+
+        PersistentCollection children = (PersistentCollection) pkeynode.getChildren();
+        PolytomousKeyNode childNode0 = (PolytomousKeyNode)commonService.get(children, 0);
+        PolytomousKey subkey1 = CdmBase.deproxy(childNode0.getSubkey(),PolytomousKey.class);
+        String subkey1title = subkey1.getTitleCache();
+        subkey1.setTitleCache(subkey1title + "test", true);
+
+        PolytomousKeyNode childNode1 = (PolytomousKeyNode)commonService.get(children, 1);
+        PolytomousKey subkey2 = CdmBase.deproxy(childNode1.getSubkey(),PolytomousKey.class);
+        String subkey2title = subkey2.getTitleCache();
+        subkey2.setTitleCache(subkey2title + "test", true);
+
+        Assert.assertNotSame(subkey1, subkey2);
+
+        polytomousKeyService.merge(pkey);
+
+
+    }
+
+
+}
diff --git a/eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/lazyloading/CdmServiceCacherTest.java b/eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/lazyloading/CdmServiceCacherTest.java
new file mode 100644 (file)
index 0000000..be649ba
--- /dev/null
@@ -0,0 +1,38 @@
+package eu.etaxonomy.taxeditor.lazyloading;
+
+import org.apache.log4j.Level;
+import org.apache.log4j.Logger;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import eu.etaxonomy.cdm.api.cache.CdmServiceCacher;
+import eu.etaxonomy.cdm.model.common.Language;
+import eu.etaxonomy.taxeditor.httpinvoker.BaseRemotingTest;
+
+public class CdmServiceCacherTest extends BaseRemotingTest {
+       private static final Logger logger = Logger.getLogger(CdmServiceCacherTest.class);
+
+
+       private static CdmServiceCacher cdmServiceCacher;
+
+       @BeforeClass
+       public void initialize() {
+               Logger.getRootLogger().setLevel(Level.INFO);
+               cdmServiceCacher = (CdmServiceCacher)getRemoteApplicationController().getBean("cdmServiceCacher");
+       }
+
+       @Test
+       public void testLanguageCache() {
+               Language defaultLanguage = Language.getDefaultLanguage();
+
+               Language defaultLanguageInCache = (Language)cdmServiceCacher.getFromCache(defaultLanguage.getUuid());
+               Assert.assertEquals("Loaded Language Term should match Language Term in Cache",defaultLanguage,defaultLanguageInCache);
+
+               Language language = Language.getLanguageFromUuid(Language.uuidFrench);
+               Language languageInCache = (Language)cdmServiceCacher.getFromCache(language.getUuid());
+               Assert.assertEquals("Loaded Language Term should match Language Term in Cache",language,languageInCache);
+
+       }
+
+}
diff --git a/eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/lazyloading/RemoteLazyLoadingTest.java b/eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/lazyloading/RemoteLazyLoadingTest.java
new file mode 100644 (file)
index 0000000..30fe70b
--- /dev/null
@@ -0,0 +1,278 @@
+/**
+ * Copyright (C) 2014 EDIT
+ * European Distributed Institute of Taxonomy
+ * http://www.e-taxonomy.eu
+ *
+ * The contents of this file are subject to the Mozilla Public License Version 1.1
+ * See LICENSE.TXT at the top of this package for the full license terms.
+ */
+
+package eu.etaxonomy.taxeditor.lazyloading;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+
+import org.apache.log4j.Level;
+import org.apache.log4j.Logger;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Ignore;
+import org.junit.Test;
+
+import eu.etaxonomy.cdm.api.service.IClassificationService;
+import eu.etaxonomy.cdm.api.service.ITaxonService;
+import eu.etaxonomy.cdm.model.agent.Person;
+import eu.etaxonomy.cdm.model.agent.Team;
+import eu.etaxonomy.cdm.model.common.CdmBase;
+import eu.etaxonomy.cdm.model.name.BotanicalName;
+import eu.etaxonomy.cdm.model.name.NonViralName;
+import eu.etaxonomy.cdm.model.name.TaxonNameBase;
+import eu.etaxonomy.cdm.model.taxon.Classification;
+import eu.etaxonomy.cdm.model.taxon.SynonymRelationship;
+import eu.etaxonomy.cdm.model.taxon.Taxon;
+import eu.etaxonomy.cdm.model.taxon.TaxonNode;
+import eu.etaxonomy.taxeditor.httpinvoker.BaseRemotingTest;
+
+
+
+/**
+ * Test class which tests remoting for persistent cdm entities.
+ *
+ * FIXME:Remoting saving tests are ignored until the merge development is underway
+ * @author c.mathew
+ *
+ */
+//@DataSet
+public class RemoteLazyLoadingTest extends BaseRemotingTest {
+
+    private static final Logger logger = Logger.getLogger(RemoteLazyLoadingTest.class);
+
+    private static IClassificationService classificationService;
+    private static ITaxonService taxonService;
+
+    private static List<TaxonNode> taxonNodes;
+
+    private final UUID taxonUuid1 = UUID.fromString("8217ef77-2ab1-4318-bd67-ccd0cdef07c4");
+    private final UUID taxonUuid2 = UUID.fromString("ef96fafa-7750-4141-b31b-1ad1daab3e76");
+
+
+    @BeforeClass
+    public static void initializeRemoteLazyLoading() {
+
+        Logger.getRootLogger().setLevel(Level.DEBUG);
+        taxonService = getRemoteApplicationController().getTaxonService();
+
+        classificationService= getRemoteApplicationController().getClassificationService();
+        //List<Classification> classifications = classificationService.listClassifications(1,0,null,null);
+//        Assert.assertFalse(classifications.isEmpty());
+//
+//        Classification classification = classifications.get(0);
+//        Assert.assertNotNull(classification);
+        taxonNodes = classificationService.getAllNodes();
+        Assert.assertFalse(taxonNodes.isEmpty());
+
+    }
+
+
+
+    @Test
+    public void testCDMEntityGet() {
+        Iterator<TaxonNode> taxonNodeItr = taxonNodes.iterator();
+        int maxcount = 30;
+        int count = 0;
+        while(taxonNodeItr.hasNext() && count <= maxcount) {
+            TaxonNode taxonNode = taxonNodeItr.next();
+            Assert.assertNotNull(taxonNode);
+
+            Taxon taxon = taxonNode.getTaxon();
+            Assert.assertNotNull(taxon);
+
+            String taxonTitle = taxon.getTitleCache();
+            logger.info("Taxon : " + taxonTitle);
+
+            TaxonNameBase name = taxon.getName();
+            Assert.assertNotNull(name);
+
+            String nameTitle = name.getTitleCache();
+            logger.info("Taxon Name : " + nameTitle);
+
+            count++;
+        }
+
+
+    }
+
+    @Test
+    public void test() {
+
+    }
+
+    @Test
+    public void testCDMEntitySaveEager() {
+        Taxon taxon = (Taxon)taxonService.find(taxonUuid1);
+        String oldTitleCache = taxon.getTitleCache();
+
+        System.out.println("Taxon title : " + oldTitleCache);
+
+        taxon.setTitleCache(oldTitleCache + ":updated");
+        taxonService.merge(taxon);
+
+        Taxon taxonNew = (Taxon)taxonService.find(taxonUuid1);
+        System.out.println("New Taxon Title : " + taxonNew.getTitleCache());
+
+        Assert.assertNotEquals("Title caches should not be equal",oldTitleCache,taxonNew.getTitleCache());
+
+        taxonNew.setTitleCache(oldTitleCache);
+        taxonService.merge(taxonNew);
+
+        Taxon taxonOld = (Taxon)taxonService.find(taxonUuid1);
+        System.out.println("Old Taxon Title : " + taxonOld.getTitleCache());
+
+        Assert.assertEquals("Title caches should be equal",oldTitleCache,taxonOld.getTitleCache());
+
+    }
+
+
+    @Test
+    public void testCDMEntityUpdate() {
+
+        Team combAuthor = Team.NewInstance();
+        combAuthor.addTeamMember(Person.NewTitledInstance("test member"));
+        BotanicalName name = BotanicalName.NewInstance(null, "Test1", null, null, null, null, null, null, null);
+        name.setCombinationAuthorTeam(combAuthor);
+        Taxon taxon = Taxon.NewInstance(name, null);
+        UUID taxonUuid = taxonService.save(taxon);
+
+        //        Taxon taxon = (Taxon)taxonService.find(taxonUuid1);
+        //        NonViralName nvn = CdmBase.deproxy(taxon.getName(),NonViralName.class);
+        //        String oldTitleCache = nvn.getTitleCache();
+        //        System.out.println("Taxon Name Title : " + oldTitleCache);
+        //        nvn.setTitleCache(oldTitleCache + ":updated", true);
+        //
+        //        taxon.setTitleCache(oldTitleCache + ":updated",true);
+        //        try {
+        //            taxonService.update(taxon);
+        //        } catch (LazyInitializationException lie) {
+        //            lie.printStackTrace();
+        //        }
+
+        List<String> TAXON_INIT_STRATEGY = Arrays.asList(new String[] {
+                "name"
+        });
+        Taxon taxonNew = (Taxon)taxonService.findTaxonByUuid(taxonUuid,TAXON_INIT_STRATEGY);
+        NonViralName nvn = CdmBase.deproxy(taxonNew.getName(),NonViralName.class);
+        Team team = CdmBase.deproxy(nvn.getCombinationAuthorTeam(),Team.class);
+        String oldTitleCache = nvn.getTitleCache();
+        System.out.println("Taxon Name Title : " + oldTitleCache);
+        nvn.setTitleCache(oldTitleCache + ":updated", true);
+        taxonService.update(taxonNew);
+
+    }
+
+
+    @Test
+    public void testCDMEntitySaveLazy() {
+        Taxon taxon = (Taxon)taxonService.find(taxonUuid1);
+
+        NonViralName nvn = CdmBase.deproxy(taxon.getName(),NonViralName.class);
+        String oldTitleCache = nvn.getTitleCache();
+        System.out.println("Taxon Name Title : " + oldTitleCache);
+        nvn.setTitleCache(oldTitleCache + ":updated", true);
+        taxonService.update(taxon);
+
+        //             Taxon taxonNew = (Taxon)taxonService.find(taxonUuid1);
+        //             NonViralName nvnNew = CdmBase.deproxy(taxon.getName(),NonViralName.class);
+        //             System.out.println("New Taxon Name Title : " + nvnNew.getTitleCache());
+        //
+        //             Assert.assertNotEquals("Title caches should not be equal",oldTitleCache,nvnNew.getTitleCache());
+        //
+        //             nvnNew.setTitleCache(oldTitleCache, true);
+        //             taxonService.update(taxon);
+        //
+        //             Taxon taxonOld = (Taxon)taxonService.find(taxonUuid1);
+        //             NonViralName nvnOld = CdmBase.deproxy(taxon.getName(),NonViralName.class);
+        //             System.out.println("Old Taxon Name Title : " + nvnNew.getTitleCache());
+        //
+        //             Assert.assertEquals("Title caches should be equal",oldTitleCache,nvnOld.getTitleCache());
+    }
+
+    @Test
+    public void testCDMEntitySaveLazyNew() {
+        Team combAuthor = Team.NewInstance();
+        combAuthor.addTeamMember(Person.NewTitledInstance("test member"));
+        BotanicalName name = BotanicalName.NewInstance(null, "Test1", null, null, null, null, null, null, null);
+        name.setCombinationAuthorTeam(combAuthor);
+        Taxon tax1 = Taxon.NewInstance(name, null);
+        UUID taxonUuid1 = taxonService.save(tax1);
+
+        Taxon taxon = (Taxon)taxonService.find(taxonUuid1);
+
+        NonViralName nvn = CdmBase.deproxy(taxon.getName(),NonViralName.class);
+        String oldTitleCache = nvn.getTitleCache();
+        logger.info("Taxon Name Title : " + oldTitleCache);
+        nvn.setTitleCache(oldTitleCache + ":updated",false);
+        taxonService.update(taxon);
+
+        Taxon taxonNew = (Taxon)taxonService.find(taxonUuid1);
+        NonViralName nvnNew = CdmBase.deproxy(taxon.getName(),NonViralName.class);
+        logger.info("New Taxon Name Title : " + nvnNew.getTitleCache());
+
+        Assert.assertNotEquals("Title caches should not be equal",oldTitleCache,nvnNew.getTitleCache());
+
+        nvnNew.setTitleCache(oldTitleCache, true);
+        taxonService.update(taxon);
+
+        Taxon taxonOld = (Taxon)taxonService.find(taxonUuid1);
+        NonViralName nvnOld = CdmBase.deproxy(taxon.getName(),NonViralName.class);
+        logger.info("Old Taxon Name Title : " + nvnNew.getTitleCache());
+
+        Assert.assertEquals("Title caches should be equal",oldTitleCache,nvnOld.getTitleCache());
+    }
+    @Ignore
+    @Test
+    public void testCDMEntitySaveCollection() {
+        Taxon taxon = (Taxon)taxonService.find(taxonUuid1);
+
+        Set<SynonymRelationship> synRelations = taxon.getSynonymRelations();
+        Set<String> relToTitles = new HashSet<String>();
+        Iterator<SynonymRelationship> srItr = synRelations.iterator();
+        while(srItr.hasNext()) {
+            SynonymRelationship sr = srItr.next();
+            System.out.println("Synonym Title Cache : " + sr.getSynonym().getTitleCache());
+            relToTitles.add(sr.getSynonym().getTitleCache());
+            sr.getSynonym().setTitleCache(sr.getSynonym().getTitleCache() + ":updated");
+
+        }
+        taxonService.merge(taxon);
+
+        Taxon taxonNew = (Taxon)taxonService.find(taxonUuid1);
+        Set<SynonymRelationship> synRelationsNew = taxonNew.getSynonymRelations();
+
+        Iterator<SynonymRelationship> srItrNew = synRelationsNew.iterator();
+        Iterator<String> relToTitlesItr = relToTitles.iterator();
+        while(srItrNew.hasNext() && relToTitlesItr.hasNext()) {
+            SynonymRelationship srNew = srItrNew.next();
+            String relToTitle = relToTitlesItr.next();
+            System.out.println("New Synonym Title Cache: " + srNew.getSynonym().getTitleCache());
+            Assert.assertNotEquals("Synonym Title caches should not be equal", srNew.getSynonym().getTitleCache(), relToTitle);
+            srNew.getSynonym().setTitleCache(relToTitle);
+        }
+
+        Taxon taxonOld = (Taxon)taxonService.find(taxonUuid1);
+
+        Set<SynonymRelationship> synRelationsOld = taxonNew.getSynonymRelations();
+        Iterator<SynonymRelationship> srItrOld = synRelationsOld.iterator();
+        relToTitlesItr = relToTitles.iterator();
+        while(srItrOld.hasNext() && relToTitlesItr.hasNext()) {
+            SynonymRelationship srOld = srItrOld.next();
+            String relToTitle = relToTitlesItr.next();
+            System.out.println("New Synonym Title Cache: " + srOld.getSynonym().getTitleCache());
+            Assert.assertEquals("Synonym Title caches should be equal", srOld.getSynonym().getTitleCache(), relToTitle);
+
+        }
+    }
+}
diff --git a/eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/lazyloading/RemotePersistentCollectionTest.java b/eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/lazyloading/RemotePersistentCollectionTest.java
new file mode 100644 (file)
index 0000000..a3c94b9
--- /dev/null
@@ -0,0 +1,226 @@
+/**
+* Copyright (C) 2014 EDIT
+* European Distributed Institute of Taxonomy
+* http://www.e-taxonomy.eu
+*
+* The contents of this file are subject to the Mozilla Public License Version 1.1
+* See LICENSE.TXT at the top of this package for the full license terms.
+*/
+package eu.etaxonomy.taxeditor.lazyloading;
+
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.log4j.Level;
+import org.apache.log4j.Logger;
+import org.hibernate.collection.internal.AbstractPersistentCollection;
+import org.hibernate.collection.spi.PersistentCollection;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import eu.etaxonomy.cdm.api.service.IClassificationService;
+import eu.etaxonomy.cdm.api.service.ICommonService;
+import eu.etaxonomy.cdm.model.common.Language;
+import eu.etaxonomy.cdm.model.common.LanguageString;
+import eu.etaxonomy.cdm.model.description.DescriptionElementBase;
+import eu.etaxonomy.cdm.model.description.TaxonDescription;
+import eu.etaxonomy.cdm.model.description.TextData;
+import eu.etaxonomy.cdm.model.name.TaxonNameBase;
+import eu.etaxonomy.cdm.model.taxon.Classification;
+import eu.etaxonomy.cdm.model.taxon.Taxon;
+import eu.etaxonomy.cdm.model.taxon.TaxonNode;
+import eu.etaxonomy.taxeditor.httpinvoker.BaseRemotingTest;
+
+/**
+ * Test class which tests remoting for persistent collections.
+ *
+ * @author c.mathew
+ * @created 13.03.2014
+ */
+public class RemotePersistentCollectionTest extends BaseRemotingTest {
+       private static final Logger logger = Logger.getLogger(RemotePersistentCollectionTest.class);
+
+       private static IClassificationService classificationService;
+       private static ICommonService commonService;
+
+       @BeforeClass
+       public void initializeServices() {
+               Logger.getRootLogger().setLevel(Level.INFO);
+               classificationService = getRemoteApplicationController().getClassificationService();
+               commonService = getRemoteApplicationController().getCommonService();
+       }
+
+       /**
+        * Test method which checks remoting for persistent lists.
+        *
+        */
+       @Test
+       public void persistentListTest() {
+
+               List<TaxonNode> taxonNodes = classificationService.getAllNodes();
+               int size = taxonNodes.size();
+               logger.debug("classificationService.getAllNodes() size : " + size);
+               TaxonNode taxonNode = null;
+               if(size > 0) {
+                       Assert.assertFalse(taxonNodes.isEmpty());
+
+                       taxonNode = taxonNodes.get(0);
+                       Assert.assertNotNull(taxonNode);
+                       Assert.assertTrue(taxonNodes.contains(taxonNode));
+
+                       // get the list of child nodes, which will give a
+                       // proxy list which is not yet initialised
+                       List<TaxonNode> childNodes = taxonNode.getChildNodes();
+                       // this size call will first initialise the list locally by internally
+                       // calling the ICommonService.initializeCollection method and then
+                       // call size on the initialised list
+                       int childCount = childNodes.size();
+
+                       // this size call will initialise the list remotely and only return the
+                       // size of the list
+                       int remoteChildCount = commonService.size((PersistentCollection)childNodes);
+                       Assert.assertEquals(childCount, remoteChildCount);
+
+                       String firstNodeTaxonTitle = taxonNode.getTaxon().getTitleCache();
+                       Assert.assertNotNull(firstNodeTaxonTitle);
+
+                       if(childCount > 0) {
+                               Assert.assertFalse(childNodes.isEmpty());
+                               // this get call will use the already initialised list to get the
+                               // 0th element
+                               TaxonNode localTaxonNode = childNodes.get(0);
+
+                               // this get call will initialise the list remotely and only return the
+                               // 0th element from the list
+                               TaxonNode remoteTaxonNode = (TaxonNode)commonService.get((PersistentCollection)childNodes,0);
+
+                               // the locally and remotely retrieved taxon node should exist in the
+                               // (local and remote) child nodes list, should be not-null and should be equal to each other
+                               Assert.assertTrue(taxonNode.getChildNodes().contains(localTaxonNode));
+                               Assert.assertTrue(taxonNode.getChildNodes().contains(remoteTaxonNode));
+                               Assert.assertTrue(commonService.contains((PersistentCollection)childNodes, localTaxonNode));
+                               Assert.assertTrue(commonService.contains((PersistentCollection)childNodes, remoteTaxonNode));
+                               Assert.assertNotNull(remoteTaxonNode);
+                               Assert.assertNotNull(localTaxonNode);
+                               Assert.assertEquals(remoteTaxonNode,localTaxonNode);
+                       }
+               }
+       }
+
+//     @Test
+//     public void persistentSetTest() {
+//             List<Classification> classifications = classificationService.listClassifications(1,0,null,null);
+//             int size = classifications.size();
+//             if(size > 0) {
+//                     Assert.assertFalse(classifications.isEmpty());
+//
+//                     Classification classification = classifications.get(0);
+//                     Assert.assertNotNull(classification);
+//                     Assert.assertTrue(classifications.contains(classification));
+//
+//                     TaxonNode rootTaxonNode = classification.getRootNode();
+//                     // get the list of child nodes, which will give a
+//                     // proxy list which is not yet initialised
+//                     List<TaxonNode> childNodes = rootTaxonNode.getChildNodes();
+//
+//                     // this size call will initialise the list locally by internally
+//                     // calling the ICommonService.initializeCollection method
+//                     int childCount = childNodes.size();
+//
+//                     if(childCount > 0) {
+//                             Assert.assertFalse(childNodes.isEmpty());
+//
+//                             // this get call will use the already initialised list to get the
+//                             // 0th element
+//                             Taxon localTaxon = childNodes.get(0).getTaxon();
+//                             Assert.assertNotNull(localTaxon);
+//
+//                             TaxonNameBase taxonName = localTaxon.getName();
+//                             Assert.assertNotNull(taxonName);
+//
+//                             // get the list of taxa, which will give a
+//                             // proxy set which is not yet initialised
+//                             Set<Taxon> taxa = taxonName.getTaxonBases();
+//
+//                             // this size call will initialise the list locally by internally
+//                             // calling the ICommonService.initializeCollection method
+//                             int taxaCount = taxa.size();
+//                             Assert.assertNotEquals(taxaCount,-1);
+//
+//                             if(taxaCount > 0) {
+//                                     Assert.assertFalse(taxa.isEmpty());
+//                                     // the locally retrieved taxon should exist in the
+//                                     // (local and remote) taxon list and should be not-null
+//                                     Assert.assertTrue(taxa.contains(localTaxon));
+//                                     Assert.assertNotNull(localTaxon);
+//                                     Assert.assertTrue(commonService.contains((PersistentCollection)taxa, localTaxon));
+//                             }
+//                     }
+//             }
+//     }
+
+       @Test
+       public void persistentMapTest() {
+               List<TaxonNode> taxonNodes = classificationService.getAllNodes();
+               // calling iterator will initialise the collection
+               Iterator<TaxonNode> taxonNodesItr = taxonNodes.iterator();
+               while(taxonNodesItr.hasNext()) {
+                       TaxonNode taxonNode = taxonNodesItr.next();
+                       Taxon taxon = taxonNode.getTaxon();
+
+                       if(taxon != null) {
+                               Set<TaxonDescription> descriptions = taxon.getDescriptions();
+                               Iterator<TaxonDescription> descriptionsItr = descriptions.iterator();
+                               while(descriptionsItr.hasNext()) {
+                                       TaxonDescription desc = descriptionsItr.next();
+                                       if(desc != null) {
+                                               for (DescriptionElementBase element : desc.getElements()){
+                                                       if (element.isInstanceOf(TextData.class)){
+                                                               // usually a call to 'get' collections should not initialise the collection,
+                                                               // but the 'getMultilanguageText' call internally calls readSize on the collection
+                                                               // which triggers the initialisation
+                                                               Map<Language, LanguageString> multilanguagetextMap = ((TextData)element).getMultilanguageText();
+                                                               //boolean init = AbstractPersistentCollection.isInitialized(multilanguagetextMap);
+                                                               //Assert.assertTrue(init);
+
+                                                               if(!multilanguagetextMap.isEmpty()) {
+                                                                       // found a map whcih we can test!
+                                                                       logger.info("Found Non-empty multilanguagetextMap");
+                                                                       boolean empty = commonService.isEmpty((PersistentCollection)multilanguagetextMap);
+                                                                       Assert.assertFalse(empty);
+                                                                       // test retrieval of key set, which should already by initialised
+                                                                       Set<Language> langKeySet = multilanguagetextMap.keySet();
+                                                                       Iterator<Language> langKeySetItr = langKeySet.iterator();
+                                                                       while(langKeySetItr.hasNext()) {
+                                                                               Language key = langKeySetItr.next();
+                                                                               // testing 'containsKey' on locally initialised collection
+                                                                               boolean localContainsKey = multilanguagetextMap.containsKey(key);
+                                                                               Assert.assertTrue(localContainsKey);
+                                                                               // testing 'containsKey' on remotely initialised collection
+                                                                               boolean remoteContainsKey =
+                                                                                               commonService.containsKey((PersistentCollection)multilanguagetextMap, key);
+                                                                               Assert.assertTrue(remoteContainsKey);
+
+                                                                               LanguageString value = multilanguagetextMap.get(key);
+                                                                               // testing 'containsValue' on locally initialised collection
+                                                                               boolean localContainsValue = multilanguagetextMap.containsValue(value);
+                                                                               Assert.assertTrue(localContainsValue);
+                                                                               // testing 'containsValue' on remotely initialised collection
+                                                                               boolean remoteContainsValue =
+                                                                                               commonService.containsValue((PersistentCollection)multilanguagetextMap, value);
+                                                                               Assert.assertTrue(remoteContainsValue);
+
+                                                                       }
+                                                                       return;
+                                                               }
+                                                       }
+                                               }
+                                       }
+                               }
+                       }
+               }
+       }
+}
diff --git a/eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/session/CdmEntitySessionManagerTest.java b/eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/session/CdmEntitySessionManagerTest.java
new file mode 100644 (file)
index 0000000..3b7f16c
--- /dev/null
@@ -0,0 +1,98 @@
+package eu.etaxonomy.taxeditor.session;
+
+import java.util.List;
+import java.util.UUID;
+
+import org.apache.log4j.Logger;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+
+import eu.etaxonomy.cdm.api.service.IPolytomousKeyService;
+import eu.etaxonomy.cdm.model.common.CdmBase;
+import eu.etaxonomy.cdm.model.common.Language;
+import eu.etaxonomy.cdm.model.description.PolytomousKey;
+import eu.etaxonomy.taxeditor.httpinvoker.BaseRemotingTest;
+import eu.etaxonomy.taxeditor.httpinvoker.CDMServer;
+import eu.etaxonomy.taxeditor.session.CdmEntitySessionManager;
+import eu.etaxonomy.taxeditor.session.ISessionEventListener;
+
+public class CdmEntitySessionManagerTest extends BaseRemotingTest {
+
+       private static final Logger logger = Logger.getLogger(CdmEntitySessionManagerTest.class);
+       
+       private ISessionEventListener sessionOwner;
+       private ICdmEntitySessionManager cdmEntitySessionManager = getRemoteApplicationController().getCdmEntitySessionManager();
+       IPolytomousKeyService polytomousKeyService = getRemoteApplicationController().getPolytomousKeyService();
+
+       private UUID polytomousKeyUuid = UUID.fromString("0d53ba20-7de4-4baa-bd8a-401048447d66");
+       private Language english = Language.getLanguageFromUuid(Language.uuidEnglish);
+
+       @BeforeClass
+       public static void initializeCdmEntitySessionManagerTest() {        
+               CDMServer.getInstance().setKeepServerRunning(true);             
+       }
+
+       @Before
+       public void initializeSession() {
+               sessionOwner = new MockSessionOwner();    
+               cdmEntitySessionManager.bind(sessionOwner);     
+       }
+
+       @Test
+       public void manageSessionWithObjectTest() {
+               PolytomousKey pKey = CdmBase.deproxy(polytomousKeyService.find(polytomousKeyUuid),PolytomousKey.class);
+               pKey = cdmEntitySessionManager.load(sessionOwner, pKey);
+               Assert.assertNotNull(cdmEntitySessionManager.getActiveSession());
+               List<CdmBase> rootEntities = (List<CdmBase>)getFieldValueViaReflection(cdmEntitySessionManager.getActiveSession(), "rootEntities");
+
+               Assert.assertEquals(rootEntities.size(),1);
+               Assert.assertSame(rootEntities.get(0), pKey);
+
+               String upTitleCache = "Updated Title Cache";
+               String upStatement = "Updated Statement";
+               pKey.setTitleCache(upTitleCache, true);
+
+               pKey.getRoot().getChildAt(0).getStatement().getLabel(english).setText(upStatement);
+               polytomousKeyService.merge(pKey);
+
+               sessionOwner = new MockSessionOwner();    
+               pKey = CdmBase.deproxy(polytomousKeyService.find(polytomousKeyUuid),PolytomousKey.class);
+               pKey = cdmEntitySessionManager.load(sessionOwner, pKey);
+               
+               Assert.assertEquals(pKey.getTitleCache(), upTitleCache);
+               Assert.assertEquals(pKey.getRoot().getChildAt(0).getStatement().getLabel(english).getText(), upStatement);
+       }
+
+       @Test
+       public void manageSessionWithListTest() {
+               List<PolytomousKey> pKeys = polytomousKeyService.list(PolytomousKey.class, null, null, null, null);
+               pKeys = (List<PolytomousKey>) cdmEntitySessionManager.load(sessionOwner, pKeys);
+               Assert.assertNotNull(cdmEntitySessionManager.getActiveSession());
+               List<CdmBase> rootEntities = (List<CdmBase>)getFieldValueViaReflection(cdmEntitySessionManager.getActiveSession(), "rootEntities");
+
+               Assert.assertEquals(rootEntities.size(),2);
+               Assert.assertSame(rootEntities.get(0),pKeys.get(0));
+               Assert.assertEquals(rootEntities.get(0).getUuid(),UUID.fromString("9d8bf4f6-a70a-4b80-8556-2ccfb436ff01"));
+
+               Assert.assertSame(rootEntities.get(1),pKeys.get(1));
+               Assert.assertEquals(rootEntities.get(1).getUuid(),UUID.fromString("0d53ba20-7de4-4baa-bd8a-401048447d66"));
+
+               String upTitleCache = "Updated Title Cache";
+               String upStatement = "Updated Statement";
+               pKeys.get(0).setTitleCache(upTitleCache, true);
+               polytomousKeyService.merge(pKeys.get(0));
+               pKeys.get(1).getRoot().getChildAt(0).getStatement().getLabel(english).setText(upStatement);
+               polytomousKeyService.merge(pKeys.get(1));
+
+               sessionOwner = new MockSessionOwner();    
+               pKeys = polytomousKeyService.list(PolytomousKey.class, null, null, null, null);
+               pKeys = (List<PolytomousKey>) cdmEntitySessionManager.load(sessionOwner, pKeys);
+               Assert.assertEquals(pKeys.get(0).getTitleCache(), upTitleCache);
+               Assert.assertEquals(pKeys.get(1).getRoot().getChildAt(0).getStatement().getLabel(english).getText(), upStatement);
+
+       }
+
+}
diff --git a/eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/session/MockSessionOwner.java b/eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/session/MockSessionOwner.java
new file mode 100644 (file)
index 0000000..24ee0a6
--- /dev/null
@@ -0,0 +1,7 @@
+package eu.etaxonomy.taxeditor.session;
+
+import eu.etaxonomy.taxeditor.session.ISessionEventListener;
+
+public class MockSessionOwner implements ISessionEventListener {
+
+}