Project

General

Profile

« Previous | Next » 

Revision c8cd88d1

Added by Cherian Mathew over 9 years ago

forgot the test files in the last commit

View differences:

.gitattributes
367 367
eu.etaxonomy.taxeditor.cdmlib/src/main/resources/eu/etaxonomy/cdm/remoting_persistence_security.xml -text
368 368
eu.etaxonomy.taxeditor.cdmlib/src/main/resources/eu/etaxonomy/cdm/remoting_services_security.xml -text
369 369
eu.etaxonomy.taxeditor.cdmlib/src/main/resources/log4j.properties -text
370
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/cdm/api/cache/CdmClientCachingTest.java -text
371
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/cdm/api/cache/CdmModelGetMethodCacherTest.java -text
372
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/cdm/polytomouskey/PolytomousKeyTest.java -text
373
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/exception/CDMServerException.java -text
374
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/httpinvoker/BaseRemotingTest.java -text
375
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/httpinvoker/CDMServer.java -text
376
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/httpinvoker/CdmPersistentRemoteSourceTest.java -text
377
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/httpinvoker/CdmRemoteSourceTest.java -text
378
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/httpinvoker/CdmServerTest.java -text
379
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/httpinvoker/CdmServerTestManager.java -text
380
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/httpinvoker/HttpInvokerServicesTest.java -text
381
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/lazyloading/AbstractLazyInitializerTest.java -text
382
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/lazyloading/CdmEntityCacherTest.java -text
383
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/lazyloading/CdmServiceCacherTest.java -text
384
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/lazyloading/RemoteLazyLoadingTest.java -text
385
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/lazyloading/RemotePersistentCollectionTest.java -text
386
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/session/CdmEntitySessionManagerTest.java -text
387
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/session/MockSessionOwner.java -text
370 388
eu.etaxonomy.taxeditor.cdmlib/src/test/resources/cdmlib-ehcache.xml -text
371 389
eu.etaxonomy.taxeditor.cdmlib/src/test/resources/datasources.xml -text
372 390
eu.etaxonomy.taxeditor.cdmlib/src/test/resources/eu/etaxonomy/cdm/api/cache/CdmClientCachingTest.xml -text
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/cdm/api/cache/CdmClientCachingTest.java
1
// $Id$
2
/**
3
* Copyright (C) 2014 EDIT
4
* European Distributed Institute of Taxonomy
5
* http://www.e-taxonomy.eu
6
*
7
* The contents of this file are subject to the Mozilla Public License Version 1.1
8
* See LICENSE.TXT at the top of this package for the full license terms.
9
*/
10
package eu.etaxonomy.cdm.api.cache;
11

  
12
import java.util.Arrays;
13
import java.util.Iterator;
14
import java.util.List;
15
import java.util.Map;
16
import java.util.Set;
17
import java.util.UUID;
18

  
19
import org.apache.log4j.Level;
20
import org.apache.log4j.Logger;
21
import org.junit.Assert;
22
import org.junit.Before;
23
import org.junit.BeforeClass;
24
import org.junit.Test;
25
import org.unitils.dbunit.annotation.DataSet;
26

  
27
import eu.etaxonomy.cdm.api.service.ICommonService;
28
import eu.etaxonomy.cdm.api.service.IPolytomousKeyNodeService;
29
import eu.etaxonomy.cdm.api.service.IPolytomousKeyService;
30
import eu.etaxonomy.cdm.api.service.ITaxonService;
31
import eu.etaxonomy.cdm.model.common.CdmBase;
32
import eu.etaxonomy.cdm.model.common.Language;
33
import eu.etaxonomy.cdm.model.common.LanguageString;
34
import eu.etaxonomy.cdm.model.description.KeyStatement;
35
import eu.etaxonomy.cdm.model.description.PolytomousKey;
36
import eu.etaxonomy.cdm.model.description.PolytomousKeyNode;
37
import eu.etaxonomy.taxeditor.httpinvoker.BaseRemotingTest;
38
import eu.etaxonomy.taxeditor.httpinvoker.CDMServer;
39
import eu.etaxonomy.taxeditor.session.ISessionEventListener;
40
import eu.etaxonomy.taxeditor.session.MockSessionOwner;
41

  
42
/**
43
 * @author cmathew
44
 * @date 7 Oct 2014
45
 *
46
 */
47
@DataSet
48
public class CdmClientCachingTest extends BaseRemotingTest {
49

  
50
    private static final Logger logger = Logger.getLogger(CdmClientCachingTest.class);
51

  
52
    private UUID polytomousKeyUuid = UUID.fromString("0d53ba20-7de4-4baa-bd8a-401048447d66");
53
    private UUID taxon1Uuid = UUID.fromString("2b336df7-29e8-4f79-985f-66502739d22f");
54
    private UUID polytomousKeyNodeUuid1 = UUID.fromString("75e4c924-ff58-4ee7-a59d-fd9173517d08");
55
    private UUID polytomousKeyNodeUuid2 = UUID.fromString("b775c027-13c0-4b87-8aa9-712faeaafbdc");
56

  
57

  
58
    private IPolytomousKeyService polytomousKeyService = getRemoteApplicationController().getPolytomousKeyService();
59
    private IPolytomousKeyNodeService polytomousKeyNodeService = getRemoteApplicationController().getPolytomousKeyNodeService();
60
    private ICommonService commonService = getRemoteApplicationController().getCommonService();
61
    private ITaxonService taxonService = getRemoteApplicationController().getTaxonService();    
62
    
63
    
64
	private CdmTransientEntityCacher cacher;
65
    private ISessionEventListener sessionOwner;
66
       
67
    private static final List<String> PKEY_DEPTH1_INIT_STRATEGY = Arrays.asList(new String[] {
68
			});
69
    
70
    private static final List<String> PKEY_DEPTH2_INIT_STRATEGY = Arrays.asList(new String[] {
71
    		"root"});
72
    
73
    private static final List<String> PKEY_DEPTH3_INIT_STRATEGY = Arrays.asList(new String[] {    		
74
    		"root.statement"});
75
    
76

  
77
    
78
    @BeforeClass
79
    public static void initializePolytomousKeyTest() {
80
        logger.setLevel(Level.INFO);
81
        CDMServer.getInstance().setKeepServerRunning(true);    	        
82
    }
83

  
84
    @Before
85
    public void initializeSession() {
86
    	sessionOwner = new MockSessionOwner();    
87
    	cdmEntitySessionManager.bind(sessionOwner);
88
    	cacher = getCacher(sessionOwner);
89
    }    
90

  
91

  
92
    
93
    @Test
94
    public void recursiveLoadSubGraphDepth1Test() {
95

  
96
    	// this call will load into the session cache the graph 
97
    	// polytomous key  
98
    	// 	|- root : polytomous key node 
99
    	// in a recursive call    	
100
        PolytomousKey pkey1 = CdmBase.deproxy(polytomousKeyService.load(polytomousKeyUuid, PKEY_DEPTH1_INIT_STRATEGY),PolytomousKey.class);
101
        pkey1 = cdmEntitySessionManager.load(sessionOwner, pkey1);
102
        
103
        // checking to make sure the root object is in the session cache
104
        Assert.assertSame(pkey1.getRoot(), cacher.getFromCache(pkey1.getRoot()));
105
        
106
    }
107

  
108
    
109
    @Test
110
    public void recursiveLoadSubGraphDepth2Test() {
111

  
112
    	// this call will load into the session cache the graph 
113
    	// polytomous key  
114
    	// 	|- root : polytomous key node 
115
    	//		|- question : KeyStatement
116
    	//		|- statement : KeyStatement    	
117
    	// in a recursive call    	
118
        PolytomousKey pkey = CdmBase.deproxy(polytomousKeyService.load(polytomousKeyUuid, PKEY_DEPTH2_INIT_STRATEGY),PolytomousKey.class);
119
        pkey = cdmEntitySessionManager.load(sessionOwner, pkey);
120
        CdmTransientEntityCacher cacher = getCacher(sessionOwner);
121
        // checking to make sure the root object is in the session cache
122
        Assert.assertSame(pkey.getRoot(), cacher.getFromCache(pkey.getRoot()));
123
        Assert.assertSame(pkey.getRoot().getStatement(), cacher.getFromCache(pkey.getRoot().getStatement()));
124
        Assert.assertSame(pkey.getRoot().getQuestion(), cacher.getFromCache(pkey.getRoot().getQuestion()));
125
        
126
    }
127
        
128
    /**
129
     * when : retrieving objects using recursive caching of object graphs with different depths 
130
     * then : the objects in the sub-graph having the same persistence id should be the same
131
     */
132
    @Test
133
    public void lazyLoadRecursiveTest() {
134

  
135
    	// this call will load into the session cache the graph and update the objects in the sub-graph for a
136
    	// polytomous key  
137
    	// 	|- root : polytomous key node 
138
    	//		|- question : KeyStatement
139
    	//		|- statement : KeyStatement    	
140
        PolytomousKey pkey1 = CdmBase.deproxy(polytomousKeyService.find(polytomousKeyUuid),PolytomousKey.class);
141
        pkey1 = cdmEntitySessionManager.load(sessionOwner, pkey1);
142
        CdmTransientEntityCacher cacher = getCacher(sessionOwner);
143
               
144
    }
145
    
146

  
147
    /**
148
     * when : retrieving objects using recursive caching of object graphs with different depths      
149
     * then : the objects in the sub-graph having the same persistence id should be the same
150
     */
151
    @Test
152
    public void differentSubGraphDepthTest1() {
153
    	
154
    	// this call will load into the session cache the graph and update the objects in the sub-graph for a
155
    	// polytomous key  
156
    	// 	|- root : polytomous key node 
157
    	// in a recursive call    
158
        PolytomousKey pkey1 = CdmBase.deproxy(polytomousKeyService.load(polytomousKeyUuid, PKEY_DEPTH1_INIT_STRATEGY),PolytomousKey.class);
159
        pkey1 = cdmEntitySessionManager.load(sessionOwner, pkey1);
160
        CdmTransientEntityCacher cacher = getCacher(sessionOwner);
161
               
162
    	// this call will load into the session cache the graph and update the objects in the sub-graph for a
163
    	// polytomous key  
164
    	// 	|- root : polytomous key node 
165
    	//		|- question : KeyStatement
166
    	//		|- statement : KeyStatement    	       
167
        PolytomousKey pkey2 = CdmBase.deproxy(polytomousKeyService.load(polytomousKeyUuid, PKEY_DEPTH2_INIT_STRATEGY),PolytomousKey.class);
168
        pkey2 = cdmEntitySessionManager.load(sessionOwner, pkey2);
169

  
170
        Assert.assertSame(pkey2.getRoot().getStatement(), cacher.getFromCache(pkey2.getRoot().getStatement()));
171
        Assert.assertSame(pkey1.getRoot().getStatement(), pkey2.getRoot().getStatement());
172
        Assert.assertSame(cacher.getFromCache(pkey1.getRoot().getStatement()), cacher.getFromCache(pkey2.getRoot().getStatement()));
173
        
174
    }
175
    
176
    /**
177
     * when : retrieving objects using recursive caching of object graphs with different depths 
178
     * then : the objects in the sub-graph having the same persistence id should be the same
179
     */
180
    @Test
181
    public void differentSubGraphDepthTest2() {
182

  
183
    	// this call will load into the session cache the graph and update the objects in the sub-graph for a
184
    	// polytomous key  
185
    	// 	|- root : polytomous key node 
186
    	//		|- question : KeyStatement
187
    	//		|- statement : KeyStatement    	
188
        PolytomousKey pkey1 = CdmBase.deproxy(polytomousKeyService.load(polytomousKeyUuid, PKEY_DEPTH2_INIT_STRATEGY),PolytomousKey.class);
189
        pkey1 = cdmEntitySessionManager.load(sessionOwner, pkey1);
190
        CdmTransientEntityCacher cacher = getCacher(sessionOwner);
191
               
192
    	// this call will load into the session cache the graph and update the objects in the sub-graph for a
193
    	// polytomous key  
194
    	// 	|- root : polytomous key node  
195
        PolytomousKey pkey2 = CdmBase.deproxy(polytomousKeyService.load(polytomousKeyUuid, PKEY_DEPTH1_INIT_STRATEGY),PolytomousKey.class);
196
        pkey2 = cdmEntitySessionManager.load(sessionOwner, pkey2);
197

  
198
        Assert.assertSame(pkey2.getRoot().getStatement(), cacher.getFromCache(pkey2.getRoot().getStatement()));
199
        Assert.assertSame(pkey1.getRoot().getStatement(), pkey2.getRoot().getStatement());
200
        Assert.assertSame(cacher.getFromCache(pkey1.getRoot().getStatement()), cacher.getFromCache(pkey2.getRoot().getStatement()));
201
    }
202
    
203
    /**
204
     * when : retrieving objects using (first) recursive load directly and (second) lazy loading in the same session
205
     * then : the objects in the sub-graph having the same persistence id should be the same
206
     */
207
    @Test
208
    public void recursiveLoadAndLazyLoadTest() {
209
    	
210
    	// this call will load into the session cache the graph and update the objects in the sub-graph for a
211
    	// polytomous key  
212
    	// 	|- root : polytomous key node 
213
    	//		|- question : KeyStatement
214
    	//		|- statement : KeyStatement    	
215
        PolytomousKey pkey1 = CdmBase.deproxy(polytomousKeyService.load(polytomousKeyUuid, PKEY_DEPTH2_INIT_STRATEGY),PolytomousKey.class);
216
        pkey1 = cdmEntitySessionManager.load(sessionOwner, pkey1);
217
        CdmTransientEntityCacher cacher = getCacher(sessionOwner);
218
               
219
        // checking that the root is not null and 
220
        // that it exists in the cache and
221
        // that both the original object and the 
222
        // cached object are the same
223
        Assert.assertNotNull(pkey1.getRoot().getStatement());
224
        Assert.assertNotNull(cacher.getFromCache(pkey1.getRoot().getStatement()));
225
        
226
    	// this call will load into the session cache the graph and update the objects in the sub-graph for a
227
    	// polytomous key  
228
    	// 	|- root : polytomous key node  
229
        PolytomousKey pkey2 = CdmBase.deproxy(polytomousKeyService.find(polytomousKeyUuid),PolytomousKey.class);
230
        pkey2 = cdmEntitySessionManager.load(sessionOwner, pkey2);
231

  
232
        
233
        Assert.assertSame(pkey2.getRoot().getStatement(), cacher.getFromCache(pkey2.getRoot().getStatement()));
234
        Assert.assertSame(pkey1.getRoot().getStatement(), pkey2.getRoot().getStatement());
235
        Assert.assertSame(cacher.getFromCache(pkey1.getRoot().getStatement()), cacher.getFromCache(pkey2.getRoot().getStatement()));
236
    }
237
    
238
    /**
239
     * when : retrieving objects using (first) lazy loading  and (second) recursive load directly in the same session
240
     * then : the objects in the sub-graph having the same persistence id should be the same
241
     */
242
    @Test
243
    public void lazyLoadAndRecursiveLoadTest() {
244

  
245

  
246
    	// this call will load into the session cache the graph and update the objects in the sub-graph for a
247
    	// polytomous key  
248
    	// 	|- root : polytomous key node  
249
    	
250
    	PolytomousKey pkey1 = CdmBase.deproxy(polytomousKeyService.find(polytomousKeyUuid),PolytomousKey.class);
251
        pkey1 = cdmEntitySessionManager.load(sessionOwner, pkey1);
252
        
253
        // lazy initialising root.statement
254
        KeyStatement st = CdmBase.deproxy(pkey1.getRoot().getStatement(), KeyStatement.class); 
255
        st.getLabel();
256
        
257
        // checking that the root is not null and 
258
        // that it exists in the cache and
259
        // that both the original object and the 
260
        // cached object are the same
261
    	Assert.assertNotNull(pkey1.getRoot().getStatement());
262
    	Assert.assertSame(CdmBase.deproxy(pkey1.getRoot().getStatement(), KeyStatement.class),
263
    			cacher.getFromCache(pkey1.getRoot().getStatement(), KeyStatement.class));
264
    	
265
    	// this call will load into the session cache the graph and update the objects in the sub-graph for a
266
    	// polytomous key  
267
    	// 	|- root : polytomous key node 
268
    	//		|- question : KeyStatement
269
    	//		|- statement : KeyStatement    	
270
        
271
    	PolytomousKey pkey2 = CdmBase.deproxy(polytomousKeyService.load(polytomousKeyUuid, PKEY_DEPTH2_INIT_STRATEGY),PolytomousKey.class);
272
    	pkey2 = cdmEntitySessionManager.load(sessionOwner, pkey2);
273

  
274
    	Assert.assertSame(pkey2.getRoot().getStatement(), cacher.getFromCache(pkey2.getRoot().getStatement(), KeyStatement.class));
275
    	Assert.assertSame(st, pkey2.getRoot().getStatement());
276
    	Assert.assertSame(cacher.getFromCache(st), cacher.getFromCache(pkey2.getRoot().getStatement(), KeyStatement.class));
277
    }
278
    
279

  
280

  
281

  
282
    
283
    /**
284
     * when : loading an object (first) and then (second) loading a graph the object is contained in, in the same session
285
     * then : the object should be the same
286
     */
287
    @Test
288
    public void subGraphObjectLoadTest1() {
289

  
290
    	// this call will load into the session cache a polytomous key node object    	    	
291
    	PolytomousKeyNode rootPKNode = CdmBase.deproxy(polytomousKeyNodeService.find(polytomousKeyNodeUuid1),PolytomousKeyNode.class);
292
    	rootPKNode = cdmEntitySessionManager.load(sessionOwner, rootPKNode);
293

  
294
    	Assert.assertNotNull(rootPKNode);
295
    	Assert.assertSame(rootPKNode, cacher.getFromCache(rootPKNode));
296
    	
297
    	PolytomousKeyNode childOfRootPKNode = CdmBase.deproxy(polytomousKeyNodeService.find(polytomousKeyNodeUuid2),PolytomousKeyNode.class);
298
    	childOfRootPKNode = cdmEntitySessionManager.load(sessionOwner, childOfRootPKNode);
299
    	
300
    	Assert.assertNotNull(childOfRootPKNode);
301
    	Assert.assertSame(childOfRootPKNode, cacher.getFromCache(childOfRootPKNode));
302
    	
303
    	// this call will load into the session cache the graph and update the objects in the sub-graph for a
304
    	// polytomous key  
305
    	// 	|- root : polytomous key node 
306
    	//		|- question : KeyStatement
307
    	//		|- statement : KeyStatement    	
308
        
309
    	PolytomousKey pkey = CdmBase.deproxy(polytomousKeyService.load(polytomousKeyUuid, PKEY_DEPTH2_INIT_STRATEGY),PolytomousKey.class);
310
    	pkey = cdmEntitySessionManager.load(sessionOwner, pkey);
311
    	
312
    	Assert.assertSame(childOfRootPKNode, cacher.getFromCache(childOfRootPKNode));
313
    	Assert.assertSame(pkey.getRoot().getChildAt(1), childOfRootPKNode);
314
    }
315

  
316
    /**
317
     * when : loading a graph (first) and then (second) loading an object contained in in the graph, in the same session
318
     * then : the object should be the same
319
     */
320
    @Test
321
    public void subGraphObjectLoadTest2() {
322

  
323
    	// this call will load into the session cache the graph and update the objects in the sub-graph for a
324
    	// polytomous key  
325
    	// 	|- root : polytomous key node 
326
    	//		|- question : KeyStatement
327
    	//		|- statement : KeyStatement    	
328
        
329
    	PolytomousKey pkey = CdmBase.deproxy(polytomousKeyService.load(polytomousKeyUuid, PKEY_DEPTH2_INIT_STRATEGY),PolytomousKey.class);
330
    	pkey = cdmEntitySessionManager.load(sessionOwner, pkey);
331
    	
332
    	// this call will load into the session cache a polytomous key node object    	    	
333
    	PolytomousKeyNode rootPKNode = CdmBase.deproxy(polytomousKeyNodeService.find(polytomousKeyNodeUuid1),PolytomousKeyNode.class);
334
    	rootPKNode = cdmEntitySessionManager.load(sessionOwner, rootPKNode);
335

  
336
    	Assert.assertNotNull(rootPKNode);
337
    	Assert.assertSame(rootPKNode, cacher.getFromCache(rootPKNode));
338
    	
339
    	PolytomousKeyNode childOfRootPKNode = CdmBase.deproxy(polytomousKeyNodeService.find(polytomousKeyNodeUuid2),PolytomousKeyNode.class);
340
    	childOfRootPKNode = cdmEntitySessionManager.load(sessionOwner, childOfRootPKNode);
341
    	
342
    	Assert.assertNotNull(childOfRootPKNode);
343
    	Assert.assertSame(childOfRootPKNode, cacher.getFromCache(childOfRootPKNode));    	
344
    	
345
    	Assert.assertSame(childOfRootPKNode, cacher.getFromCache(childOfRootPKNode));
346
    	Assert.assertSame(pkey.getRoot().getChildAt(1), childOfRootPKNode);
347
    }
348

  
349
    
350
    /**
351
     * when : loading objects from a collection 
352
     * then : the object stored in the cache should be the same
353
     */
354
    @Test
355
    public void subGraphCollectionLoadTest() {
356
    	
357
    	// this call will load into the session cache the graph and update the objects in the sub-graph for a
358
    	// polytomous key  
359
    	// 	|- root : polytomous key node 
360
    	//		|- question : KeyStatement
361
    	//		|- statement : KeyStatement    	
362
        
363
    	PolytomousKey pkey = CdmBase.deproxy(polytomousKeyService.load(polytomousKeyUuid, PKEY_DEPTH2_INIT_STRATEGY),PolytomousKey.class);
364
    	pkey = cdmEntitySessionManager.load(sessionOwner, pkey);
365
    	
366
    	PolytomousKeyNode childOfRootPKNode = pkey.getRoot().getChildAt(1);
367
    	
368
    	Assert.assertSame(childOfRootPKNode, cacher.getFromCache(childOfRootPKNode));
369
    	Assert.assertSame(pkey.getRoot().getChildAt(1), childOfRootPKNode);
370
    	
371
    }
372
    
373
    /**
374
     * when : loading a non-lazy collection in a subgraph and loading the collection directly
375
     * then : the object stored in the cache should be the same as the object in the sub-graph collection and 
376
     *        the object in the directly loaded collection
377
     */
378
    @Test
379
    public void nonLazyCollectionLoadTest() {
380
    	// need to find an example of this
381
    }
382
    
383
    /**
384
     * when : loading objects from a map
385
     * then : the object stored in the cache should be the same
386
     */
387
    @Test
388
    public void subGraphMapLoadTest() {
389
    	
390
    	Language english = Language.getLanguageFromUuid(Language.uuidEnglish);
391
        Language hindi = Language.getLanguageFromUuid(UUID.fromString("0a1d9d1d-135d-4575-b172-669b51673c39"));
392
        
393
        
394
    	// this call will load into the session cache the graph and update the objects in the sub-graph for a
395
    	// polytomous key  
396
    	// 	|- root : polytomous key node 
397
    	//		|- question : KeyStatement
398
    	//		|- statement : KeyStatement    	
399
        
400
    	PolytomousKey pkey = CdmBase.deproxy(polytomousKeyService.load(polytomousKeyUuid, PKEY_DEPTH3_INIT_STRATEGY),PolytomousKey.class);
401
    	pkey = cdmEntitySessionManager.load(sessionOwner, pkey);
402
    	
403
    	Map<Language, LanguageString> labelMap = pkey.getRoot().getStatement().getLabel();
404
    	Set<Language> languages = labelMap.keySet();
405
    	Iterator<Language> languagesItr = languages.iterator();
406
    	while(languagesItr.hasNext()) {
407
    		Language lang = languagesItr.next();
408
    		if(lang.equals(english)) {
409
    			Assert.assertSame(lang, english);    			
410
    		}
411
    		if(lang.equals(hindi)) {
412
    			Assert.assertSame(lang, hindi);
413
    		}
414
    		Assert.assertSame(lang, cacher.getFromCache(lang));
415
    	}    	
416
    }
417
    
418
    /**
419
     * when : loading a non-lazy map in a subgraph and loading the map directly
420
     * then : the object stored in the cache should be the same as the object in the sub-graph map and 
421
     *        the object in the directly loaded map
422
     */
423
    @Test
424
    public void nonLazyMapLoadTest() {
425
    	// need to find an example of this
426
    }
427
    
428

  
429

  
430
}
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/cdm/api/cache/CdmModelGetMethodCacherTest.java
1
package eu.etaxonomy.cdm.api.cache;
2

  
3
import java.io.IOException;
4
import java.util.List;
5

  
6
import net.sf.ehcache.Cache;
7

  
8
import org.apache.log4j.Level;
9
import org.apache.log4j.Logger;
10
import org.junit.Assert;
11
import org.junit.Test;
12
import org.springframework.core.io.ClassPathResource;
13
import org.springframework.core.io.Resource;
14

  
15
import eu.etaxonomy.cdm.api.cache.CdmRemoteCacheManager.CdmCacheManagerType;
16

  
17

  
18
public class CdmModelGetMethodCacherTest {
19

  
20
	private static final Logger logger = Logger.getLogger(CdmModelGetMethodCacherTest.class);
21

  
22
    public static final Resource CDMLIB_DISK_STORE_RESOURCE =
23
            new ClassPathResource("/eu/etaxonomy/cache");
24
    
25
    
26

  
27
	@Test
28
	public void cacheGettersTest() {
29
		
30
		Logger.getRootLogger().setLevel(Level.INFO);
31
		try {
32
			System.setProperty("ehcache.disk.store.dir", CDMLIB_DISK_STORE_RESOURCE.getFile().getAbsolutePath());
33
		} catch (IOException e) {
34
			throw new CdmClientCacheException(e);
35
		}		
36
		CdmModelCacher cmdmc = new CdmModelCacher();
37
		
38
		//cmdmc.checkGetterMethods();
39
		
40
		cmdmc.cacheGetterFields();
41

  
42
						
43
		Cache cdmlibCache = CdmRemoteCacheManager.getInstance().getCdmModelGetMethodsCache();
44
		List<CdmModelFieldPropertyFromClass> cmgmfcList = cmdmc.getCdmModelGetMethodFromClassList();
45
		
46
		List<Object> keys = cdmlibCache.getKeys();
47
		Assert.assertEquals(cmgmfcList.size(), keys.size());
48
				
49
		for(CdmModelFieldPropertyFromClass cmgmfc: cmgmfcList) {
50
			String className = cmgmfc.getClassName();
51
			Assert.assertTrue(keys.contains(className));
52
			logger.info("Class Name : " + className + " has been cached");
53
		}
54
		cdmlibCache.removeAll();
55
		cdmlibCache.flush();
56
		CdmRemoteCacheManager.getInstance().shutdown(CdmCacheManagerType.CDMLIB_MODEL);
57
	}
58

  
59
	
60
	 
61

  
62
}
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/cdm/polytomouskey/PolytomousKeyTest.java
1
// $Id$
2
/**
3
* Copyright (C) 2014 EDIT
4
* European Distributed Institute of Taxonomy
5
* http://www.e-taxonomy.eu
6
*
7
* The contents of this file are subject to the Mozilla Public License Version 1.1
8
* See LICENSE.TXT at the top of this package for the full license terms.
9
*/
10
package eu.etaxonomy.cdm.polytomouskey;
11

  
12
import java.util.Iterator;
13
import java.util.List;
14
import java.util.Map;
15
import java.util.Set;
16
import java.util.UUID;
17

  
18
import org.apache.log4j.Level;
19
import org.apache.log4j.Logger;
20
import org.hibernate.collection.spi.PersistentCollection;
21
import org.junit.Assert;
22
import org.junit.Before;
23
import org.junit.BeforeClass;
24
import org.junit.Test;
25
import org.unitils.dbunit.annotation.DataSet;
26

  
27
import eu.etaxonomy.cdm.api.cache.CdmTransientEntityCacher;
28
import eu.etaxonomy.cdm.api.service.ICommonService;
29
import eu.etaxonomy.cdm.api.service.IPolytomousKeyService;
30
import eu.etaxonomy.cdm.api.service.ITaxonService;
31
import eu.etaxonomy.cdm.model.agent.AgentBase;
32
import eu.etaxonomy.cdm.model.common.CdmBase;
33
import eu.etaxonomy.cdm.model.common.Credit;
34
import eu.etaxonomy.cdm.model.common.Extension;
35
import eu.etaxonomy.cdm.model.common.IdentifiableSource;
36
import eu.etaxonomy.cdm.model.common.Language;
37
import eu.etaxonomy.cdm.model.common.LanguageString;
38
import eu.etaxonomy.cdm.model.description.KeyStatement;
39
import eu.etaxonomy.cdm.model.description.PolytomousKey;
40
import eu.etaxonomy.cdm.model.description.PolytomousKeyNode;
41
import eu.etaxonomy.cdm.model.media.Rights;
42
import eu.etaxonomy.cdm.model.taxon.Taxon;
43
import eu.etaxonomy.taxeditor.httpinvoker.BaseRemotingTest;
44
import eu.etaxonomy.taxeditor.httpinvoker.CDMServer;
45
import eu.etaxonomy.taxeditor.session.ISessionEventListener;
46
import eu.etaxonomy.taxeditor.session.MockSessionOwner;
47

  
48
/**
49
 * @author cmathew
50
 * @date 7 Oct 2014
51
 *
52
 */
53
@DataSet
54
public class PolytomousKeyTest extends BaseRemotingTest {
55

  
56
    private static final Logger logger = Logger.getLogger(PolytomousKeyTest.class);
57

  
58
    UUID polytomousKeyUuid = UUID.fromString("0d53ba20-7de4-4baa-bd8a-401048447d66");
59
    UUID taxon1Uuid = UUID.fromString("2b336df7-29e8-4f79-985f-66502739d22f");
60

  
61

  
62
    IPolytomousKeyService polytomousKeyService = getRemoteApplicationController().getPolytomousKeyService();
63
    ICommonService commonService = getRemoteApplicationController().getCommonService();
64
    ITaxonService taxonService = getRemoteApplicationController().getTaxonService();
65

  
66
    
67
	private CdmTransientEntityCacher cacher;
68
    private ISessionEventListener sessionOwner;
69
    
70
    Language english = Language.getLanguageFromUuid(Language.uuidEnglish);
71

  
72
    
73
    
74
    @BeforeClass
75
    public static void initializePolytomousKeyTest() {
76
        logger.setLevel(Level.INFO);
77
        CDMServer.getInstance().setKeepServerRunning(true);       
78
    }
79

  
80
    @Before
81
    public void initializeSession() {
82
    	sessionOwner = new MockSessionOwner();    
83
    	cdmEntitySessionManager.bind(sessionOwner);
84
    	cacher = getCacher(sessionOwner);
85
    }
86
    
87
    @Test
88
    public void readAllPolytomousKeys() {
89
        List<PolytomousKey> pKeys = polytomousKeyService.list(PolytomousKey.class, null, null, null, null);
90
        Iterator<PolytomousKey> pKeysItr = pKeys.iterator();
91
        Assert.assertEquals(pKeysItr.next().getUuid(),UUID.fromString("9d8bf4f6-a70a-4b80-8556-2ccfb436ff01"));
92
        Assert.assertEquals(pKeysItr.next().getUuid(),UUID.fromString("0d53ba20-7de4-4baa-bd8a-401048447d66"));        
93
    }
94

  
95

  
96
    @Test
97
    //@DataSet("PolytomousKeyTest.readPolytmousKeyData.xml")
98
    public void readPolytmousKeyData() {
99
        PolytomousKey pKey = CdmBase.deproxy(polytomousKeyService.find(polytomousKeyUuid),PolytomousKey.class);
100
        Set<Taxon> taxonomicScope = pKey.getTaxonomicScope();
101
        Iterator<Taxon> tsItr = taxonomicScope.iterator();
102
        Taxon taxon = tsItr.next();
103
        
104
        Assert.assertEquals("Achillea sec. Cyprus", taxon.getTitleCache());
105
        Assert.assertEquals(tsItr.hasNext(), false);
106

  
107
        List<Credit> credits = pKey.getCredits();
108
        AgentBase agent = credits.get(0).getAgent();
109
        Assert.assertEquals(agent.getId(),4809);
110
        Assert.assertEquals(agent.getTitleCache(),"R. A. Graham");
111
        Assert.assertEquals(credits.get(0).getText(),"Credits Text Test");
112

  
113
        Set<Extension> exts = pKey.getExtensions();
114
        Iterator<Extension> extItr = exts.iterator();
115
        Extension ext = extItr.next();
116
        Assert.assertEquals(ext.getValue(), "http://test.com");
117

  
118
        Set<Rights> rights = pKey.getRights();
119
        Iterator<Rights> rightsItr = rights.iterator();
120
        Rights right = rightsItr.next();
121
        Assert.assertEquals(right.getText(),"Rights Text Test");
122

  
123
        Set<IdentifiableSource> sources = pKey.getSources();
124
        Iterator<IdentifiableSource> sourcesItr = sources.iterator();
125
        IdentifiableSource source = sourcesItr.next();
126
        Assert.assertEquals(source.getId(), 23710);
127
        source = sourcesItr.next();
128
        Assert.assertEquals(source.getId(), 23711);
129

  
130
        // TO DO : Added tests for Annotations , Markers
131
    }
132

  
133
    @Test
134
    public void readPolytomousKeyDataFromNodes() {
135
        PolytomousKey pKey = CdmBase.deproxy(polytomousKeyService.find(polytomousKeyUuid),PolytomousKey.class);
136
        PolytomousKeyNode rootNode = pKey.getRoot();
137

  
138

  
139
        Assert.assertEquals(rootNode.getId(), 2750);
140

  
141
        Assert.assertEquals(rootNode.getChildAt(0).getId(), 2751);
142
        Assert.assertEquals(rootNode.getChildAt(0).getParent().getId(), rootNode.getId());
143
        Assert.assertEquals(rootNode.getKey().getId(), pKey.getId());
144
        Integer sortIndex = (Integer)getFieldValueViaReflection(rootNode.getChildAt(0), "sortIndex");
145
        Assert.assertEquals(sortIndex, new Integer(0));
146
        String statement = "Capitula without ligulate ray-florets; leaves entire or subentire";
147
        Assert.assertEquals(rootNode.getChildAt(0).getStatement().getLabelText(english), statement);
148

  
149
        Assert.assertEquals(rootNode.getChildAt(1).getId(), 2753);
150
        Assert.assertEquals(rootNode.getChildAt(1).getParent().getId(), rootNode.getId());
151
        Assert.assertEquals(rootNode.getChildAt(1).getKey().getId(), pKey.getId());
152
        sortIndex = (Integer)getFieldValueViaReflection(rootNode.getChildAt(1), "sortIndex");
153
        Assert.assertEquals(sortIndex, new Integer(1));
154
        statement = "Capitula with ligulate ray-florets; leaves pinnatisect";
155
        Assert.assertEquals(rootNode.getChildAt(1).getStatement().getLabelText(english), statement);
156

  
157
        Assert.assertEquals(rootNode.getChildAt(1).getChildAt(0).getId(), 2754);
158
        Assert.assertEquals(rootNode.getChildAt(1).getChildAt(0).getParent().getId(), rootNode.getChildAt(1).getId());
159
        Assert.assertEquals(rootNode.getChildAt(1).getChildAt(0).getKey().getId(), pKey.getId());
160
        sortIndex = (Integer)getFieldValueViaReflection(rootNode.getChildAt(1).getChildAt(0), "sortIndex");
161
        Assert.assertEquals(sortIndex, new Integer(0));
162
        statement = "Ray-florets yellow";
163
        Assert.assertEquals(rootNode.getChildAt(1).getChildAt(0).getStatement().getLabelText(english), statement);
164
        Assert.assertEquals(rootNode.getChildAt(1).getChildAt(0).getChildAt(0).getTaxon().getTitleCache(), "Achillea arabica Kotschy sec. Cyprus");
165
    }
166

  
167
    @Test
168
    public void savePolytomousKeyNodeData() {
169
        PolytomousKey pkey = CdmBase.deproxy(polytomousKeyService.find(polytomousKeyUuid),PolytomousKey.class);
170
        pkey = cdmEntitySessionManager.load(sessionOwner, pkey);
171
        PolytomousKeyNode pkeynode = pkey.getRoot();
172
        String newQuestion = "New Question";
173
        String newStatement = "New Statement";
174

  
175
        Assert.assertEquals("Question 1",pkeynode.getQuestion().getLabel().get(english).getText());
176
        for(PolytomousKeyNode node : pkeynode.getChildren()) {
177

  
178
            node.setQuestion(null);
179
            node.setStatement(null);
180
        }
181
        //FIXME:Remoting Add tests for feature after fixing problem
182

  
183
        //Feature feature = pkeynode.getFeature();
184
        //Assert.assertEquals(feature.getTitleCache(),"Systematics");
185
        //pkeynode.setFeature(null);
186

  
187
        Assert.assertEquals(pkeynode.getChildAt(0).getModifyingText().get(english).getText(),"Modifying Text 1a");
188
        String modifyingText = "Modifying Text 1a updated";
189

  
190
        //pkeynode.getChildAt(0).putModifyingText(english, modifyingText);
191

  
192
        Assert.assertEquals(pkeynode.getChildAt(0).getSubkey().getId(),1550);
193
        Assert.assertEquals("Achillea", pkeynode.getChildAt(0).getSubkey().getTitleCache());
194
        Assert.assertNull(pkeynode.getChildAt(1).getTaxon());
195
        Taxon taxon = CdmBase.deproxy(taxonService.find(taxon1Uuid),Taxon.class);
196
        pkeynode.getChildAt(1).setTaxon(taxon);
197

  
198
        polytomousKeyService.merge(pkey);
199

  
200
        pkey = CdmBase.deproxy(polytomousKeyService.find(polytomousKeyUuid),PolytomousKey.class);
201
        sessionOwner = new MockSessionOwner();
202
        pkey = cdmEntitySessionManager.load(sessionOwner, pkey);
203
        
204
        pkeynode = pkey.getRoot();
205
        for(PolytomousKeyNode node : pkeynode.getChildren()) {
206
            Assert.assertNull(node.getQuestion());
207
            node.setQuestion(KeyStatement.NewInstance(english,newQuestion));
208
            Assert.assertNull(node.getStatement());
209
            node.setStatement(KeyStatement.NewInstance(english,newStatement));
210
        }
211

  
212
        
213
        Assert.assertEquals(pkeynode.getChildAt(1).getTaxon(), taxon);
214

  
215
        polytomousKeyService.merge(pkey);
216

  
217
        pkey = CdmBase.deproxy(polytomousKeyService.find(polytomousKeyUuid),PolytomousKey.class);
218
        sessionOwner = new MockSessionOwner();
219
        pkey = cdmEntitySessionManager.load(sessionOwner, pkey);
220
        
221
        pkeynode = pkey.getRoot();
222
        for(PolytomousKeyNode node : pkeynode.getChildren()) {
223
            Assert.assertNotNull(node.getQuestion());
224
            Map<Language, LanguageString> label = node.getQuestion().getLabel();
225
            Assert.assertEquals(newQuestion, label.get(english).getText());
226
            Assert.assertNotNull(node.getStatement());
227
            Assert.assertEquals(newStatement, node.getStatement().getLabel(english).getText());
228
        }
229
        //Assert.assertEquals(pkeynode.getFeature().getId(), feature.getId());
230

  
231
    }
232

  
233
    @Test
234
    public void savePolytomousKeyNodeDataWithSameSubKey() {
235
        
236
    	ISessionEventListener sessionOwner = new MockSessionOwner();
237
    	cdmEntitySessionManager.bind(sessionOwner);
238
        PolytomousKey pkey = CdmBase.deproxy(polytomousKeyService.find(polytomousKeyUuid),PolytomousKey.class);
239
        pkey = cdmEntitySessionManager.load(sessionOwner, pkey);
240
        
241
        PolytomousKeyNode pkeynode = pkey.getRoot();
242

  
243
        PolytomousKey subkey1 = CdmBase.deproxy(pkeynode.getChildAt(0).getSubkey(), PolytomousKey.class);
244
        String subkey1title = subkey1.getTitleCache();
245
        subkey1.setTitleCache(subkey1title + "test", true);
246

  
247

  
248
        PolytomousKey subkey2 = CdmBase.deproxy(pkeynode.getChildAt(1).getChildAt(0).getSubkey(), PolytomousKey.class);
249
        String subkey2title = subkey2.getTitleCache();
250
        subkey2.setTitleCache(subkey2title + "test", true);
251

  
252
        Assert.assertSame(subkey1, subkey2);
253

  
254
        polytomousKeyService.merge(pkey);
255
    }
256

  
257
    @Test
258
    public void savePolytomousKeyNodeDataWithSameSubKeyUsingService() {
259
    	
260
        PolytomousKey pkey = CdmBase.deproxy(polytomousKeyService.find(polytomousKeyUuid),PolytomousKey.class);
261
        pkey = cdmEntitySessionManager.load(sessionOwner, pkey);
262
        
263
        PolytomousKeyNode pkeynode = pkey.getRoot();
264

  
265
        PersistentCollection children = (PersistentCollection) pkeynode.getChildren();
266
        PolytomousKeyNode childNode0 = (PolytomousKeyNode)commonService.get(children, 0);
267
        PolytomousKey subkey1 = CdmBase.deproxy(childNode0.getSubkey(),PolytomousKey.class);
268
        String subkey1title = subkey1.getTitleCache();
269
        subkey1.setTitleCache(subkey1title + "test", true);
270

  
271
        PolytomousKeyNode childNode1 = (PolytomousKeyNode)commonService.get(children, 1);
272
        PolytomousKey subkey2 = CdmBase.deproxy(childNode1.getSubkey(),PolytomousKey.class);
273
        String subkey2title = subkey2.getTitleCache();
274
        subkey2.setTitleCache(subkey2title + "test", true);
275

  
276
        Assert.assertNotSame(childNode0, childNode1);
277
        
278
        Assert.assertSame(subkey1, subkey2);
279

  
280
        polytomousKeyService.merge(pkey);
281
    }
282

  
283

  
284
    @Test
285
    public void savePolytomousKeyNodeDataWithSameLanguageInLabel() {
286
        PolytomousKey pkey = CdmBase.deproxy(polytomousKeyService.find(polytomousKeyUuid),PolytomousKey.class);
287
        PolytomousKeyNode pkeynode = pkey.getRoot();
288

  
289
        Map<Language, LanguageString> label1 = pkeynode.getQuestion().getLabel();
290
        label1.size();
291

  
292

  
293
        Map<Language, LanguageString> label2 = pkeynode.getChildAt(0).getStatement().getLabel();
294
        label2.size();
295

  
296

  
297
        polytomousKeyService.merge(pkey);
298
    }
299

  
300

  
301
}
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/exception/CDMServerException.java
1
// $Id$
2
/**
3
* Copyright (C) 2014 EDIT
4
* European Distributed Institute of Taxonomy
5
* http://www.e-taxonomy.eu
6
*
7
* The contents of this file are subject to the Mozilla Public License Version 1.1
8
* See LICENSE.TXT at the top of this package for the full license terms.
9
*/
10
package eu.etaxonomy.taxeditor.exception;
11

  
12
/**
13
 * @author cmathew
14
 * @date 23 Sep 2014
15
 *
16
 */
17
public class CDMServerException extends Exception {
18

  
19
    public CDMServerException(String message) {
20
        super(message);
21
    }
22

  
23
    public CDMServerException(Exception e) {
24
        super(e);
25
    }
26

  
27
    public CDMServerException(String message,Exception e) {
28
        super(message,e);
29
    }
30

  
31
}
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/httpinvoker/BaseRemotingTest.java
1
/**
2
 * Copyright (C) 2014 EDIT
3
 * European Distributed Institute of Taxonomy
4
 * http://www.e-taxonomy.eu
5
 *
6
 * The contents of this file are subject to the Mozilla Public License Version 1.1
7
 * See LICENSE.TXT at the top of this package for the full license terms.
8
 */
9
package eu.etaxonomy.taxeditor.httpinvoker;
10

  
11
import java.io.IOException;
12
import java.lang.reflect.Field;
13

  
14
import org.junit.AfterClass;
15
import org.junit.Assert;
16
import org.junit.BeforeClass;
17
import org.junit.Test;
18
import org.springframework.core.io.ClassPathResource;
19
import org.springframework.core.io.Resource;
20
import org.unitils.UnitilsJUnit4;
21
import org.unitils.database.DatabaseUnitils;
22
import org.unitils.database.annotations.Transactional;
23
import org.unitils.database.util.TransactionMode;
24
import org.unitils.spring.annotation.SpringApplicationContext;
25

  
26
import eu.etaxonomy.cdm.api.application.CdmApplicationRemoteController;
27
import eu.etaxonomy.cdm.api.cache.CdmClientCacheException;
28
import eu.etaxonomy.cdm.api.cache.CdmTransientEntityCacher;
29
import eu.etaxonomy.cdm.model.name.NomenclaturalCode;
30
import eu.etaxonomy.taxeditor.remoting.source.CdmPersistentRemoteSource;
31
import eu.etaxonomy.taxeditor.remoting.source.CdmRemoteSource;
32
import eu.etaxonomy.taxeditor.remoting.source.CdmRemoteSourceException;
33
import eu.etaxonomy.taxeditor.remoting.source.ICdmRemoteSource;
34
import eu.etaxonomy.taxeditor.session.ICdmEntitySessionManager;
35
import eu.etaxonomy.taxeditor.session.ISessionEventListener;
36

  
37

  
38
/**
39
 * Base class for remoting tests, responsible for
40
 * - starting / stop the cdm server
41
 * - running some basic connection tests
42
 * - setting up the remote configuration.
43
 *
44
 */
45
@Transactional(TransactionMode.DISABLED)
46
@SpringApplicationContext("file:./target/test-classes/eu/etaxonomy/cdm/testRemotingApplicationContext.xml")
47
public class BaseRemotingTest extends UnitilsJUnit4 {
48
    //private static final Logger logger = Logger.getLogger(BaseRemotingTest.class);
49

  
50
    private static final Resource TEST_REMOTE_APPLICATION_CONTEXT_RESOURCE =
51
            new ClassPathResource("/eu/etaxonomy/cdm/testRemotingApplicationContext.xml");
52

  
53
    private static CdmApplicationRemoteController remoteApplicationController;
54
    private static ICdmRemoteSource cdmRemoteSource;
55
    private static CdmPersistentRemoteSource remotePersistentSource;
56

  
57
    public static boolean useManagedServer = true;
58

  
59
    public static final Resource CDMLIB_DISK_STORE_RESOURCE =
60
            new ClassPathResource("/eu/etaxonomy/cache");
61
    
62
    protected static ICdmEntitySessionManager cdmEntitySessionManager;
63
    
64
    @BeforeClass
65
    public static void initializeBaseRemotingTest() {
66
        //NOTE: Run this the cdmTest H2 DB whenever it needs to be
67
    	//      recreated e.g. after a model change
68
    	//DatabaseUnitils.disableConstraints();
69

  
70
		try {
71
			System.setProperty("ehcache.disk.store.dir", CDMLIB_DISK_STORE_RESOURCE.getFile().getAbsolutePath());
72
		} catch (IOException e) {
73
			throw new CdmClientCacheException(e);
74
		}
75
        
76
        useManagedServer = (System.getProperty("use.managed.server") == null) ? useManagedServer : Boolean.valueOf(System.getProperty("use.managed.server"));
77
        if(useManagedServer) {
78
            try {
79
                CDMServer.getInstance().start();
80
            } catch (Exception e) {
81
                e.printStackTrace();
82
                Assert.fail("Server failed to start. Reason : " + e.getMessage());
83
            }
84

  
85
        initializeController(CDMServer.getInstance().getName(),
86
                CDMServer.getInstance().getHost(),
87
                CDMServer.getInstance().getPort(),
88
                CDMServer.getInstance().getContextPath(),
89
                NomenclaturalCode.ICNAFP);
90
        }
91
    }
92

  
93
    
94
    @Test
95
    public void disableConstraints() {
96
    	// To be run on the src/test/resources/h2/cdmTest h2 db after
97
    	// updating the unitils.properties 'database.url' property
98
    	DatabaseUnitils.disableConstraints();
99
    }
100
    public static void initializeController(String sourceName, String host, int port, String contextPath, NomenclaturalCode ncode) {
101

  
102
        cdmRemoteSource = CdmRemoteSource.NewInstance(sourceName, host, port, contextPath, ncode);
103
        remoteApplicationController =
104
                CdmApplicationRemoteController.NewInstance(cdmRemoteSource,
105
                        false,
106
                        null,
107
                        null);
108

  
109
        try {
110
            remotePersistentSource = CdmPersistentRemoteSource.NewInstance(sourceName);
111
        } catch (CdmRemoteSourceException e) {
112
            Assert.fail("Default Remote Persistent Source failed to load. Reason : " + e.getMessage());
113
        }
114
        cdmEntitySessionManager = getRemoteApplicationController().getCdmEntitySessionManager();
115
    }
116

  
117

  
118

  
119
    protected static CdmApplicationRemoteController getRemoteApplicationController() {
120
        return remoteApplicationController;
121
    }
122

  
123
    protected static ICdmRemoteSource getCdmRemoteSource() {
124
        return cdmRemoteSource;
125
    }
126

  
127
    protected static CdmPersistentRemoteSource getCdmPersistentRemoteSource() {
128
        return remotePersistentSource;
129
    }
130
    
131
    protected static ICdmEntitySessionManager getCdmEntitySessionManager() {
132
    	return cdmEntitySessionManager;
133
    }
134
    
135
    protected static CdmTransientEntityCacher getCacher(ISessionEventListener sessionOwner) {
136
    	return (CdmTransientEntityCacher) getFieldValueViaReflection(cdmEntitySessionManager.getSession(sessionOwner), "cdmTransientEntityCacher");
137
    }
138

  
139
    @AfterClass
140
    public static void cleanup() {
141
        try {
142
            CDMServer.getInstance().stop();
143
        } catch (Exception e) {
144
            Assert.fail("Server could not be stopped. Reason : " + e.getMessage());
145
        }
146
    }
147

  
148

  
149
    protected static Object getFieldValueViaReflection(Object object, String fieldName) {
150
        Class<?> clazz = object.getClass();
151
        try {
152
            Field field = clazz.getDeclaredField(fieldName);
153
            field.setAccessible(true);
154
            return field.get(object);
155
        } catch (NoSuchFieldException e) {
156
            e.printStackTrace();
157
        } catch (SecurityException e) {
158
            e.printStackTrace();
159
        } catch (IllegalArgumentException e) {
160
            e.printStackTrace();
161
        } catch (IllegalAccessException e) {
162
            e.printStackTrace();
163
        }
164
        return null;
165
    }
166

  
167

  
168

  
169

  
170
}
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/httpinvoker/CDMServer.java
1
// $Id$
2
/**
3
 * Copyright (C) 2014 EDIT
4
 * European Distributed Institute of Taxonomy
5
 * http://www.e-taxonomy.eu
6
 *
7
 * The contents of this file are subject to the Mozilla Public License Version 1.1
8
 * See LICENSE.TXT at the top of this package for the full license terms.
9
 */
10
package eu.etaxonomy.taxeditor.httpinvoker;
11

  
12
import java.io.BufferedReader;
13
import java.io.IOException;
14
import java.io.InputStreamReader;
15
import java.net.Socket;
16

  
17

  
18
import javax.sql.DataSource;
19

  
20
import org.apache.log4j.Level;
21
import org.apache.log4j.Logger;
22
import org.springframework.core.io.ClassPathResource;
23
import org.springframework.core.io.Resource;
24
import org.unitils.database.annotations.TestDataSource;
25
import org.unitils.spring.annotation.SpringApplicationContext;
26

  
27
import eu.etaxonomy.taxeditor.exception.CDMServerException;
28
import eu.etaxonomy.taxeditor.remoting.source.CdmRemoteSourceBase;
29

  
30
/**
31
 *
32
 * (Singleton) Server instance which manages a compatible cdmlib-webapp-war.
33
 * This is done by launching a jetty instance (using jetty-runner) as an
34
 * executed process. The choice of the external process over a more
35
 * preferable 'embedded jetty' instance is due to problems arising from the
36
 * class loading of classes (e.g. from hibernate core) which are needed
37
 * for both the webapp as well as the remoting client.
38
 *
39
 * @author cmathew
40
 * @date 23 Sep 2014
41
 *
42
 */
43

  
44
public class CDMServer {
45

  
46
    public static final Logger logger = Logger.getLogger(CDMServer.class);
47

  
48
    @TestDataSource
49
    protected DataSource dataSource;
50

  
51
    private final String name = "default";
52
    private final String host = "127.0.0.1";
53
    private final int port = 9090;
54
    private final int stopPort = 9191;
55
    private final String stopKey = "jetty-cdm-server";
56
    private final String contextPath = "";
57

  
58
    private boolean keepServerRunning = false;
59

  
60
    public static final Resource DEFAULT_CDM_WEBAPP_RESOURCE =
61
            new ClassPathResource("/etc/jetty/cdmlib-remote-webapp.war");
62

  
63
    public static final Resource DEFAULT_JETTY_CONFIG_RESOURCE =
64
            new ClassPathResource("/etc/jetty/jetty.xml");
65

  
66
    public static final Resource DEFAULT_JETTY_TEMP_RESOURCE =
67
            new ClassPathResource("/etc/jetty/temp");
68

  
69
    public static final Resource DEFAULT_JETTY_TEMP_WAR_LIB_RESOURCE =
70
            new ClassPathResource("/etc/jetty/temp/webapp/WEB-INF/lib");
71

  
72
    public static final Resource DEFAULT_DATASOURCE_FILE =
73
            new ClassPathResource("datasources.xml");
74

  
75
    public static final Resource DEFAULT_JETTY_RUNNER_RESOURCE =
76
            new ClassPathResource("/etc/jetty/jetty-runner-9.2.3.v20140905.jar");
77

  
78
    public static final Resource DEFAULT_JETTY_RESOURCE =
79
            new ClassPathResource("/etc/jetty/start-9.2.3.v20140905.jar");
80

  
81

  
82

  
83
    private static CDMServer cdmServer = null;
84
    private static CDMServerException cdmse = null;
85

  
86
    private void CDMServer() {
87
        logger.setLevel(Level.INFO);
88
    }
89

  
90
    public static CDMServer getInstance() {
91
        if(cdmServer == null) {
92
            cdmServer = new CDMServer();
93
        }
94
        return cdmServer;
95
    }
96

  
97
    public String getName() {
98
        return name;
99
    }
100

  
101
    public String getHost() {
102
        return host;
103
    }
104

  
105
    public int getPort() {
106
        return port;
107
    }
108

  
109
    public String getContextPath() {
110
        return contextPath;
111
    }
112

  
113
    public boolean getKeepServerRunning() {
114
        return keepServerRunning;
115
    }
116

  
117
    public void setKeepServerRunning(boolean keepServerRunning) {
118
        this.keepServerRunning = keepServerRunning;
119
    }
120

  
121
    public static boolean isRunningInEclipse() {
122
        return (System.getProperty("sun.java.command") != null &&
123
                System.getProperty("sun.java.command").startsWith("org.eclipse.jdt.internal.junit.runner.RemoteTestRunner"));
124
    }
125

  
126
    private String getVMArgs() throws IOException {
127
        StringBuilder sb = new StringBuilder();
128
        sb.append(" -Dspring.profiles.active=remoting");
129
        sb.append(" -Dcdm.beanDefinitionFile=" + DEFAULT_DATASOURCE_FILE.getFile().getAbsolutePath());
130
        sb.append(" -Dcdm.datasource=cdmTest");
131
        return sb.toString();
132
    }
133

  
134
    private String getStartServerArgs() {
135
        StringBuilder sb = new StringBuilder();
136
        sb.append(" --port ");
137
        sb.append(port);
138
        return sb.toString();
139
    }
140

  
141
    private String getStopServerSettings() {
142
        StringBuilder sb = new StringBuilder();
143
        sb.append(" --stop-port ");
144
        sb.append(stopPort);
145
        sb.append(" --stop-key ");
146
        sb.append(stopKey);
147
        return sb.toString();
148
    }
149

  
150
    private String getStopServerArgs() {
151
        StringBuilder sb = new StringBuilder();
152
        sb.append(" STOP.PORT=");
153
        sb.append(stopPort);
154
        sb.append(" STOP.KEY=");
155
        sb.append(stopKey);
156
        return sb.toString();
157
    }
158

  
159
    public void start() throws CDMServerException {
160

  
161
        /**
162
         * First check if the CDM server responds to a service request, which implies that
163
         * the server has started properly. If no response is received then check if the
164
         * server is listening on specific host / port, which implies that the server
165
         * has started but incorrectly, in which case we try to force stop it (if we can)
166
         * and start a new server.
167
         */
168
        if(isRunning(1)) {
169
            logger.info("[CDM-Server] Server already running @ " + host + ":" + port );
170
            return;
171
        } else if (isAvailable(1)){
172
            logger.info("[CDM-Server] Server available, but not started correctly @ " + host + ":" + port );
173
            logger.info("[CDM-Server] .... trying to force stop server @ " + host + ":" + port );
174
            try {
175
                stop(true);
176
            } catch (Exception e) {
177
                throw new CDMServerException("CDM Server could not be stopped : " + e.getMessage());
178
            }
179
        }
180

  
181
        Thread t = new Thread() {
182
            @Override
183
            public void run() {
184
                StringBuffer output = new StringBuffer();
185
                try{
186
                    Process p;
187
                    String command = "java "
188
                            + getVMArgs()
189
                            + " -jar "
190
                            + DEFAULT_JETTY_RUNNER_RESOURCE.getFile().getAbsolutePath()
191
                            + getStartServerArgs()
192
                            + getStopServerSettings()
193
                            + " "
194
                            + DEFAULT_CDM_WEBAPP_RESOURCE.getFile().getAbsolutePath();
195
                    logger.info("[CDM-Server] Starting server with Command : " + command);
196
                    p = Runtime.getRuntime().exec(command);
197

  
198
                    BufferedReader reader =
199
                            new BufferedReader(new InputStreamReader(p.getInputStream()));
200

  
201
                    String line = "";
202
                    while ((line = reader.readLine())!= null) {
203
                        logger.info("[CDM-Server] Start : " + line);
204
                    }
205

  
206
                } catch (Exception e) {
207
                    e.printStackTrace();
208
                    cdmse = new CDMServerException(e);
209
                }
210

  
211
            }
212
        };
213

  
214
        t.setDaemon(true);
215
        cdmse = null;
216
        t.start();
217

  
218
        if(isRunning(50)) {
219
            logger.info("[CDM-Server] Started Server @ " + host + ":" + port );
220
        } else {
221
            logger.info("[CDM-Server] Server not started within given interval");
222
            // making sure to kill server if it is not started correctly
223
            try {
224
                stop(true);
225
            } catch (Exception e) {
226
                throw new CDMServerException("CDM Server could not be stopped : " + e.getMessage());
227
            }
228
            throw new CDMServerException("CDM Server not started : ");
229
        }
230

  
231
    }
232

  
233
    public boolean isAvailable(int checkingIntervals) throws CDMServerException {
234
        int intervalsCount = 0;
235
        do {
236
            try {
237
                Socket s = new Socket(host, port);
238
                logger.info("[CDM-Server] Available @ " + host + ":" + port );
239
                return true;
240
            } catch (IOException ioe) {
241

  
242
            }
243
            try {
244
                Thread.sleep(1000);
245
            } catch (InterruptedException ie) {
246
                throw new CDMServerException("Error checking CDM Server status", ie);
247
            }
248
            intervalsCount++;
249
        } while (intervalsCount < checkingIntervals);
250

  
251
        return false;
252
    }
253

  
254
    public boolean isStopped(int checkingIntervals) throws CDMServerException {
255
        int intervalsCount = 0;
256
        do {
257
            try {
258
                Socket s = new Socket(host, port);
259
            } catch (IOException ioe) {               
260
                return true;
261
            }
262
            try {
263
                Thread.sleep(1000);
264
            } catch (InterruptedException ie) {
265
                throw new CDMServerException("Error checking CDM Server status", ie);
266
            }
267
            intervalsCount++;
268
        } while (intervalsCount < checkingIntervals);
269

  
270
        return false;
271
    }
272

  
273
    public boolean isRunning(int checkingIntervals) throws CDMServerException  {
274
        CdmRemoteSourceBase crsb = new CdmRemoteSourceBase("local-cdm-server",
275
                host,
276
                port,
277
                contextPath,
278
                null);
279
        int intervalsCount = 0;
280
        do {
281
            try {
282
                if(cdmse != null) {
283
                    return false;
284
                }
285
                if(crsb.checkConnection()) {
286
                    logger.info("[CDM-Server] Running @ " + host + ":" + port );
287
                    return true;
288
                }
289
            } catch (Exception e) {
290
            }
291
            try {
292
                Thread.sleep(1000);
293
            } catch (InterruptedException ie) {
294
                throw new CDMServerException("Error checking CDM Server status", ie);
295
            }
296
            intervalsCount++;
297
        } while (intervalsCount < checkingIntervals);
298
        return false;
299
    }
300

  
301
    public void stop() throws Exception {
302
        stop(false);
303
    }
304
    public void stop(boolean force) throws Exception {
305

  
306
        if(!force) {
307
            if(!getInstance().isAvailable(1)) {
308
                logger.info("[CDM-Server] Server already stopped @ " + host + ":" + port );
309
                return;
310
            }
311

  
312
            if(getInstance().getKeepServerRunning()) {
313
                logger.info("[CDM-Server] Server @ " + host + ":" + port + " is set to keep running");
314
                return;
315
            }
316
        }
317
        Thread t = new Thread() {
318
            @Override
319
            public void run() {
320
                StringBuffer output = new StringBuffer();
321
                try{
322
                    Process p;
323
                    String command = "java -jar " + DEFAULT_JETTY_RESOURCE.getFile().getAbsolutePath()
324
                            + getStopServerArgs() + " --stop ";
325
                    logger.info("[CDM-Server] Stop Command : " + command);
326
                    p = Runtime.getRuntime().exec(command);
327
                    p.waitFor();
328
                    BufferedReader reader =
329
                            new BufferedReader(new InputStreamReader(p.getInputStream()));
330
                    String line = "";
331
                    while ((line = reader.readLine())!= null) {
332
                        logger.info("CDM-Server Stop : " + line + "\n");
333
                    }
334
                } catch (Exception e) {
335
                    e.printStackTrace();
336
                }
337

  
338
            }
339
        };
340

  
341
        t.setDaemon(true);
342
        t.start();
343

  
344
        if(isStopped(5)) {
345
            logger.info("[CDM-Server] Stopped Server @ " + host + ":" + port );
346
        } else {
347
            logger.info("[CDM-Server] Could not stop @ " + host + ":" + port + ". Please kill it manually");
348
        }
349
    }
350
}
eu.etaxonomy.taxeditor.cdmlib/src/test/java/eu/etaxonomy/taxeditor/httpinvoker/CdmPersistentRemoteSourceTest.java
1
/**
2
 * Copyright (C) 2014 EDIT
3
 * European Distributed Institute of Taxonomy
4
 * http://www.e-taxonomy.eu
5
 *
6
 * The contents of this file are subject to the Mozilla Public License Version 1.1
7
 * See LICENSE.TXT at the top of this package for the full license terms.
8
 */
9
package eu.etaxonomy.taxeditor.httpinvoker;
10

  
11

  
12
import static org.hamcrest.CoreMatchers.containsString;
13

  
14
import java.util.Map;
15

  
16
import org.apache.log4j.Level;
17
import org.apache.log4j.Logger;
18
import org.junit.Assert;
19
import org.junit.BeforeClass;
20
import org.junit.Test;
21

  
22
import eu.etaxonomy.cdm.config.CdmPersistentSourceUtils;
23
import eu.etaxonomy.cdm.config.CdmPersistentXMLSource.CdmSourceProperties;
24
import eu.etaxonomy.cdm.config.CdmSourceException;
25
import eu.etaxonomy.cdm.model.metadata.CdmMetaData.MetaDataPropertyName;
26
import eu.etaxonomy.cdm.model.name.NomenclaturalCode;
27
import eu.etaxonomy.taxeditor.remoting.source.CdmPersistentRemoteSource;
28
import eu.etaxonomy.taxeditor.remoting.source.CdmRemoteSource;
29
import eu.etaxonomy.taxeditor.remoting.source.CdmRemoteSourceException;
30
import eu.etaxonomy.taxeditor.remoting.source.ICdmRemoteSource;
31

  
32
/**
33
 * Class to test the cdm persistent source functionality, including
34
 * initialising / saving / updating and deleting
35
 *
36
 * Corresponding test sources settings can be found at
37
 * /src/text/resources/eu.etaxonomy.cdm/cdm.datasources.xml
38
 *
39
 */
40
public class CdmPersistentRemoteSourceTest extends BaseRemotingTest {
41
    private static final Logger logger = Logger.getLogger(CdmPersistentRemoteSourceTest.class);
42

  
43
    private CdmPersistentRemoteSource remotePersistentSource;
44

  
45
    @BeforeClass
46
    public static void initialize() {
47
        Logger.getRootLogger().setLevel(Level.INFO);
48
    }
49

  
50
    @Test
51
    public void whenLoadingExistingCompleteRemoteSourceThenLoadIsSuccessful() {
52

  
53
        remotePersistentSource = getCdmPersistentRemoteSource();
54

  
55
        String expectedServer = "127.0.0.1";
56
        String expectedPort = "9090";
57
        String expectedContextPath = "";
58
        logger.info("Default remote source server : " + remotePersistentSource.getServer());
59
        Assert.assertTrue("Default server should be " + expectedServer,
60
                expectedServer.equals(remotePersistentSource.getServer()));
61

  
62
        logger.info("Default remote source port : " + remotePersistentSource.getPort());
63
        Assert.assertTrue("Default port should be 9090",
64
                expectedPort.equals(String.valueOf(remotePersistentSource.getPort())));
65

  
66
        logger.info("Default remote source context path : " + remotePersistentSource.getContextPath());
67
        Assert.assertTrue("Default remote source context path should be " + expectedContextPath,
68
                expectedContextPath.equals(remotePersistentSource.getContextPath()));
69

  
70
        logger.info("Default remote source nomenclatural code : " + remotePersistentSource.getNomenclaturalCode().toString());
71
        Assert.assertTrue("Default NomenclaturalCode should be ICNAFP",
72
                NomenclaturalCode.ICNAFP.equals(remotePersistentSource.getNomenclaturalCode()));
73
    }
74

  
75

  
76

  
77

  
78
    @Test
79
    public void whenConnectingToAnActiveServerThenConnectSuccessfully() {
80
        // check if active server throws the right exception
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff