Project

General

Profile

Download (20.4 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
* Copyright (C) 2010 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.cdm.remote.dto.assembler.lsid;
10

    
11
import static org.junit.Assert.assertEquals;
12
import static org.junit.Assert.assertNotNull;
13
import static org.junit.Assert.assertNull;
14
import static org.junit.Assert.assertTrue;
15

    
16
import java.io.Serializable;
17
import java.lang.reflect.Field;
18
import java.lang.reflect.Method;
19
import java.util.ArrayList;
20
import java.util.Arrays;
21
import java.util.Collection;
22
import java.util.HashSet;
23
import java.util.List;
24
import java.util.Set;
25
import java.util.UUID;
26

    
27
import org.apache.log4j.Logger;
28
import org.hibernate.Hibernate;
29
import org.hibernate.HibernateException;
30
import org.hibernate.LazyInitializationException;
31
import org.hibernate.collection.spi.PersistentCollection;
32
import org.hibernate.engine.spi.SessionImplementor;
33
import org.hibernate.proxy.HibernateProxy;
34
import org.hibernate.proxy.LazyInitializer;
35
import org.joda.time.DateTime;
36
import org.joda.time.DateTimeFieldType;
37
import org.joda.time.Partial;
38
import org.junit.Before;
39
import org.junit.BeforeClass;
40
import org.junit.Ignore;
41
import org.junit.Test;
42
import org.unitils.UnitilsJUnit4;
43
import org.unitils.spring.annotation.SpringApplicationContext;
44
import org.unitils.spring.annotation.SpringBeanByType;
45

    
46
import com.github.dozermapper.core.Mapper;
47

    
48
import eu.etaxonomy.cdm.common.URI;
49
import eu.etaxonomy.cdm.model.agent.Person;
50
import eu.etaxonomy.cdm.model.agent.TeamOrPersonBase;
51
import eu.etaxonomy.cdm.model.common.Credit;
52
import eu.etaxonomy.cdm.model.common.IdentifiableSource;
53
import eu.etaxonomy.cdm.model.common.LSID;
54
import eu.etaxonomy.cdm.model.common.Language;
55
import eu.etaxonomy.cdm.model.common.LanguageString;
56
import eu.etaxonomy.cdm.model.common.VerbatimTimePeriod;
57
import eu.etaxonomy.cdm.model.description.Distribution;
58
import eu.etaxonomy.cdm.model.description.PresenceAbsenceTerm;
59
import eu.etaxonomy.cdm.model.description.TaxonDescription;
60
import eu.etaxonomy.cdm.model.description.TextData;
61
import eu.etaxonomy.cdm.model.location.NamedArea;
62
import eu.etaxonomy.cdm.model.name.INonViralName;
63
import eu.etaxonomy.cdm.model.name.Rank;
64
import eu.etaxonomy.cdm.model.name.TaxonNameFactory;
65
import eu.etaxonomy.cdm.model.reference.IBook;
66
import eu.etaxonomy.cdm.model.reference.INomenclaturalReference;
67
import eu.etaxonomy.cdm.model.reference.Reference;
68
import eu.etaxonomy.cdm.model.reference.ReferenceFactory;
69
import eu.etaxonomy.cdm.model.taxon.Synonym;
70
import eu.etaxonomy.cdm.model.taxon.SynonymType;
71
import eu.etaxonomy.cdm.model.taxon.Taxon;
72
import eu.etaxonomy.cdm.model.taxon.TaxonBase;
73
import eu.etaxonomy.cdm.model.taxon.TaxonRelationship;
74
import eu.etaxonomy.cdm.model.term.DefaultTermInitializer;
75
import eu.etaxonomy.cdm.remote.dto.dwc.SimpleDarwinRecord;
76
import eu.etaxonomy.cdm.remote.dto.oaipmh.OaiDc;
77
import eu.etaxonomy.cdm.remote.dto.tdwg.voc.SpeciesProfileModel;
78
import eu.etaxonomy.cdm.remote.dto.tdwg.voc.TaxonConcept;
79
import eu.etaxonomy.cdm.remote.view.OaiPmhViewTest;
80
import net.sf.cglib.proxy.Enhancer;
81
import net.sf.cglib.proxy.MethodInterceptor;
82
import net.sf.cglib.proxy.MethodProxy;
83

    
84
@SpringApplicationContext("file:./target/test-classes/eu/etaxonomy/cdm/applicationContext-test.xml")
85
public class AssemblerTest extends UnitilsJUnit4 {
86

    
87
    public static final Logger logger = Logger.getLogger(AssemblerTest.class);
88

    
89
    @SpringBeanByType
90
    private Mapper mapper;
91

    
92
    private Taxon taxon;
93
    private IBook sec;
94
    private IBook book;
95
    private Reference bookSection;
96
    private TeamOrPersonBase<?> authorship;
97
    private INonViralName name;
98
    private LSID lsid;
99
    private TaxonDescription taxonDescription;
100

    
101
    @BeforeClass
102
    public static void onSetUp() {
103
        DefaultTermInitializer defaultTermInitializer = new DefaultTermInitializer();
104
        defaultTermInitializer.initialize();
105
    }
106

    
107
    @Before
108
    public void setUp() throws Exception {
109
        lsid = new LSID("urn:lsid:example.org:taxonconcepts:1");
110

    
111
        authorship = Person.NewInstance();
112
        authorship.setTitleCache("authorship.titleCache", true);
113
        authorship.setLsid(new LSID("urn:lsid:dagg.org:agents:2"));
114

    
115
        name = TaxonNameFactory.NewBotanicalInstance(null);
116
        name.setNameCache("nameCache");
117
        INomenclaturalReference nomenclaturalReference = ReferenceFactory.newArticle();
118
        nomenclaturalReference.setTitleCache("nomenclaturalReference", true);
119
        name.setNomenclaturalReference(nomenclaturalReference);
120
        name.setNomenclaturalMicroReference("1");
121
        name.setAuthorshipCache("authorshipCache");
122
        name.setRank(Rank.SPECIES());
123

    
124
        sec = ReferenceFactory.newBook();
125
        sec.setAuthorship(authorship);
126
        sec.setTitleCache("sec.titleCache", true);
127
        sec.setLsid(new LSID("urn:lsid:example.org:references:1"));
128

    
129
        taxon = Taxon.NewInstance(name, (Reference)sec);
130
        taxon.setCreated(new DateTime(2004, 12, 25, 12, 0, 0, 0));
131
        taxon.setUpdated(new DateTime(2005, 12, 25, 12, 0, 0, 0));
132
        taxon.setTitleCache("titleCache", true);
133
        taxon.setLsid(lsid);
134

    
135
        for(int i = 0; i < 10; i++) {
136
            Taxon child = Taxon.NewInstance(name, (Reference)sec);
137
            child.setLsid(new LSID("urn:lsid:example.org:taxonconcepts:" + (2 + i )));
138
//            taxon.addTaxonomicChild(child, null,null);
139
        }
140

    
141

    
142
        taxonDescription = TaxonDescription.NewInstance();
143
        taxon.addDescription(taxonDescription);
144

    
145
        TextData textData = TextData.NewInstance();
146
        Language english = Language.NewInstance();
147
        english.setIso639_1("en");
148
        Language french = Language.NewInstance();
149
        french.setIso639_1("fr");
150
        textData.getMultilanguageText().put(english, LanguageString.NewInstance("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce justo leo, tempus ultricies bibendum eu, interdum sit amet ipsum. Suspendisse eu odio in sem iaculis euismod. Suspendisse sed metus ante, in sodales risus. In sit amet magna sit amet risus elementum dapibus. Nullam in magna at mauris placerat sagittis. Proin urna nisl, porta at venenatis in, tristique tempus nisl. Proin vel arcu blandit velit vestibulum blandit. In at diam libero, vel malesuada mauris. Duis a enim diam. Donec urna dui, dictum at suscipit vel, consectetur quis est. In venenatis bibendum diam nec laoreet. ", english));
151
        textData.getMultilanguageText().put(french, LanguageString.NewInstance("Mauris elementum malesuada orci, non eleifend metus placerat ut. Aenean ornare felis sed lectus cursus id cursus nulla consectetur. Mauris magna justo, placerat id pretium posuere, ultrices et libero. Aliquam erat volutpat. Ut libero diam, interdum commodo fringilla sollicitudin, faucibus vel nisl. Fusce mattis justo interdum enim rhoncus eget sollicitudin dolor lobortis. Morbi mauris odio, tempus eget egestas eu, ornare vel ante. In quis placerat mi. Aliquam blandit tristique dictum. Donec pretium dui lacinia magna ornare eu venenatis ante dignissim. Integer ullamcorper tempus nisl et tincidunt. Curabitur vel nulla eu dolor faucibus porta. Mauris pulvinar est at est porta molestie. Nam varius nunc nec ipsum lacinia non egestas turpis congue. In at ipsum augue. Nulla mollis lobortis mauris ac sagittis. Nullam et facilisis lacus. Nam euismod sapien pellentesque lacus hendrerit dapibus. Aenean blandit rhoncus feugiat.", french));
152
        taxonDescription.addElement(textData);
153

    
154
        Distribution distribution = Distribution.NewInstance();
155
        NamedArea namedArea = NamedArea.NewInstance("Africa", "Africa", "Africa");
156
        namedArea.setTitleCache("Africa", true);
157
        distribution.setArea(namedArea);
158
        distribution.setStatus(PresenceAbsenceTerm.NATIVE());
159

    
160
        taxonDescription.addElement(distribution);
161

    
162
        // ------------------------------------------------------
163

    
164
        book = ReferenceFactory.newBook();
165
        book.setTitle("Book.title");
166
        book.setAuthorship(authorship);
167
        book.setCreated(new DateTime(2004, 12, 25, 12, 0, 0, 0));
168
        book.setDatePublished(VerbatimTimePeriod.NewVerbatimInstance(new Partial(DateTimeFieldType.year(), 1800)));
169
        book.setEdition("1st Edition");
170
        book.setEditor("Editor");
171
        book.setIsbn("isbn");
172
        book.setPlacePublished("placePublished");
173
        book.setPublisher("publisher");
174
        book.setReferenceAbstract("referenceAbstract");
175
        book.setUri(new URI("http://persitent.books.foo/myBook"));
176
        book.setUuid(UUID.randomUUID());
177
        book.setVolume("Volume 1");
178
        book.addSource(IdentifiableSource.NewDataImportInstance("http://persitent.IdentifiableSources.foo/1"));
179

    
180
        bookSection = ReferenceFactory.newBookSection();
181
        bookSection.setInReference((Reference)book);
182
        bookSection.setPages("999 ff.");
183
        bookSection.setTitle("BookSection.title");
184
        bookSection.setAuthorship(authorship);
185
        bookSection.setCreated(new DateTime(2004, 12, 25, 12, 0, 0, 0));
186
        bookSection.setDatePublished(VerbatimTimePeriod.NewVerbatimInstance(new Partial(DateTimeFieldType.year(), 1800)));
187
        bookSection.setReferenceAbstract("referenceAbstract");
188
        bookSection.setUri(new URI("http://persitent.books.foo/myBookSection"));
189
        bookSection.setUuid(UUID.randomUUID());
190
        bookSection.addCredit(Credit.NewInstance(authorship, "Credits to the authorship"));
191
        bookSection.addSource(IdentifiableSource.NewDataImportInstance("http://persitent.IdentifiableSources.foo/2"));
192
    }
193

    
194
    @Ignore
195
    @Test
196
    public void testDeepMapping() {
197

    
198
        if(!OaiPmhViewTest.dozerXsdIsAvailable()){
199
            return;
200
        }
201

    
202
        for(int i = 0; i < 3; i++) {
203
            Synonym synonym = Synonym.NewInstance(name,(Reference)sec);
204
            taxon.addSynonym(synonym, SynonymType.SYNONYM_OF());
205
        }
206

    
207
        TaxonConcept taxonConcept = mapper.map(taxon, TaxonConcept.class);
208

    
209
        assertNotNull("map() should return an object", taxonConcept);
210

    
211
        assertEquals("IdentifiableEntity.titleCache should be copied into BaseThing.title",taxon.getTitleCache(),taxonConcept.getTitle());
212
        assertEquals("IdentifiableEntity.lsid should be copied into BaseThing.identifier",taxon.getLsid().toString(),taxonConcept.getIdentifier().toString());
213
        assertEquals("BaseThing.sameAs should refer to the proxy version of the lsid","http://lsid.example.org/" + taxon.getLsid().toString(),taxonConcept.getSameAs());
214
        assertEquals("CdmBase.created should be copied into BaseThing.created",new DateTime(2004, 12, 25, 12, 0, 0, 0),taxonConcept.getCreated());
215
        assertNotNull("TaxonBase.sec should be mapped into BaseThing.publishedInCitation",taxonConcept.getPublishedInCitation());
216
        assertEquals("TaxonBase.sec.titleCache should be mapped into BaseThing.publishedInCitation.title",sec.getTitleCache(),taxonConcept.getPublishedInCitation().getTitle());
217
        assertNotNull("TaxonBase.sec.authorship should be mapped into TaxonConcept.accordingTo",taxonConcept.getAccordingTo());
218
        assertEquals("TaxonBase.sec.authorship.titleCache should be mapped into TaxonConcept.accordingTo.title",authorship.getTitleCache(),taxonConcept.getAccordingTo().getTitle());
219
        assertNotNull("TaxonBase.name should be mapped to TaxonConcept.hasName",taxonConcept.getHasName());
220
        assertEquals("NonViralName.nameCache should be mapped to TaxonName.nameComplete",name.getNameCache(),taxonConcept.getHasName().getNameComplete());
221
        assertNotNull("Taxon.relationsToThisTaxon should be copied into TaxonConcept.hasRelationship",taxonConcept.getHasRelationship());
222
        assertEquals("There should be 13 relations in TaxonConcept.hasRelationship",
223
                13, taxonConcept.getHasRelationship().size());
224
    }
225

    
226
    @Test
227
    public void testLazyInitializationExceptionWithProxy() throws Exception {
228

    
229
        if(!OaiPmhViewTest.dozerXsdIsAvailable()){
230
            return;
231
        }
232

    
233
        IBook proxy = getUninitializedDetachedProxy(Reference.class,(Reference)sec);
234
        assert !Hibernate.isInitialized(proxy);
235
        Field secField = TaxonBase.class.getDeclaredField("sec");
236
        secField.setAccessible(true);
237
        secField.set(taxon, proxy);
238

    
239
        TaxonConcept taxonConcept = mapper.map(taxon, TaxonConcept.class);
240
        assertNull("TaxonBase.sec was uninitialized, so TaxonConcept.publishedInCitation should be null",taxonConcept.getPublishedInCitation());
241
        assertNull("TaxonBase.sec was uninitialized, so TaxonConcept.accordingTo should be null",taxonConcept.getAccordingTo());
242
    }
243

    
244
    @Ignore
245
    @Test
246
    public void testLazyInitializationExceptionWithPersistentCollection() throws Exception {
247

    
248
        if(!OaiPmhViewTest.dozerXsdIsAvailable()){
249
            return;
250
        }
251

    
252
        @SuppressWarnings("unchecked")
253
        Set<TaxonRelationship> proxy = getUninitializedPersistentCollection(
254
                HashSet.class,(HashSet<TaxonRelationship>)taxon.getRelationsToThisTaxon());
255
        assert !Hibernate.isInitialized(proxy);
256
        Field relationsToThisTaxonField = Taxon.class.getDeclaredField("relationsToThisTaxon");
257
        relationsToThisTaxonField.setAccessible(true);
258
        relationsToThisTaxonField.set(taxon, proxy);
259

    
260
        TaxonConcept taxonConcept = mapper.map(taxon, TaxonConcept.class);
261
        assertTrue("TaxonBase.relationsToThisTaxon was uninitialized, so TaxonConcept.hasRelationship should be null",
262
                taxonConcept.getHasRelationship().isEmpty());
263
    }
264

    
265
    @Test
266
    public void testSpeciesProfileModelMapping() {
267

    
268
        if(!OaiPmhViewTest.dozerXsdIsAvailable()){
269
            return;
270
        }
271

    
272
        SpeciesProfileModel speciesProfileModel = mapper.map(taxonDescription, SpeciesProfileModel.class);
273
        assertEquals(speciesProfileModel.getHasInformation().size(),2);
274
    }
275

    
276
    @Test
277
    public void testSimpleDarwinCoreMapping() {
278

    
279
        if(!OaiPmhViewTest.dozerXsdIsAvailable()){
280
            return;
281
        }
282

    
283
        SimpleDarwinRecord simpleDarwinRecord = mapper.map(taxon, SimpleDarwinRecord.class);
284
        mapper.map(taxon.getName(), simpleDarwinRecord);
285

    
286
        assertNotNull(simpleDarwinRecord.getModified());
287
        assertEquals(taxon.getName().getTitleCache(), simpleDarwinRecord.getScientificName());
288
        assertEquals(taxon.getName().getAuthorshipCache(), simpleDarwinRecord.getScientificNameAuthorship());
289
        assertEquals(taxon.getName().getCitationString(), simpleDarwinRecord.getNamePublishedIn());
290
        assertEquals(Rank.SPECIES().getLabel(), simpleDarwinRecord.getTaxonRank());
291
    }
292

    
293
    @Test
294
    public void testOAIDublinCoreMapping() {
295

    
296
        if(!OaiPmhViewTest.dozerXsdIsAvailable()){
297
            return;
298
        }
299

    
300
        OaiDc oaiDcRecordBook = mapper.map(book, OaiDc.class);
301

    
302
        assertEquals(book.getTitle(), oaiDcRecordBook.getTitle());
303

    
304
        OaiDc oaiDcRecordBookSection = mapper.map(bookSection, OaiDc.class);
305
        assertNotNull(oaiDcRecordBookSection.getRelation());
306
    }
307

    
308
    private <T extends Collection> T getUninitializedPersistentCollection(final Class<T> clazz, final T wrappedCollection) {
309
        final Enhancer enhancer = new Enhancer();
310
        List<Class> interfaces = new ArrayList<>();
311
        interfaces.addAll(Arrays.asList(clazz.getInterfaces()));
312
        interfaces.add(PersistentCollection.class);
313
        enhancer.setSuperclass(clazz);
314
        enhancer.setInterfaces(interfaces.toArray(new Class[interfaces.size()]));
315
        enhancer.setCallback( new MethodInterceptor() {
316
            @Override
317
            public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
318
                if("wasInitialized".equals(method.getName())) {
319
                  return false;
320
                } else if(clazz.getDeclaredConstructor().equals(method)){
321
                     return proxy.invoke(obj, args);
322
                } else if("finalize".equals(method.getName())){
323
                     return proxy.invoke(obj, args);
324
                } else if("toString".equals(method.getName())) {
325
                    return wrappedCollection.toString();
326
                } else if("getClass".equals(method.getName())) {
327
                    return proxy.invoke(obj, args);
328
                } else if("hashCode".equals(method.getName())) {
329
                    return wrappedCollection.hashCode();
330
                }else if("initListener".equals(method.getName())) {
331
                    return null;
332
                } else {
333

    
334
                    throw new LazyInitializationException(null);
335
                }
336

    
337
            }
338
        });
339

    
340
        T proxy = (T)enhancer.create();
341
        return proxy;
342
    }
343

    
344
    private <T> T getUninitializedDetachedProxy(final Class<T> clazz,final T wrappedClass) {
345
        final Enhancer enhancer = new Enhancer();
346
        List<Class> interfaces = new ArrayList<Class>();
347
        interfaces.addAll(Arrays.asList(clazz.getInterfaces()));
348
        interfaces.add(HibernateProxy.class);
349
        enhancer.setSuperclass(clazz);
350
        enhancer.setInterfaces(interfaces.toArray(new Class[interfaces.size()]));
351
        enhancer.setCallback( new MethodInterceptor() {
352
            @Override
353
            public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
354
                if("getHibernateLazyInitializer".equals(method.getName())) {
355
                  return new UninitializedLazyInitializer();
356
                } else if(clazz.getDeclaredConstructor().equals(method)){
357
                     return proxy.invoke(obj, args);
358
                } else if("finalize".equals(method.getName())){
359
                     return proxy.invoke(obj, args);
360
                } else if("toString".equals(method.getName())) {
361
                    return wrappedClass.toString();
362
                } else if("getClass".equals(method.getName())) {
363
                    return proxy.invoke(obj, args);
364
                } else if("hashCode".equals(method.getName())) {
365
                    return wrappedClass.hashCode();
366
                } else if("initListener".equals(method.getName())) {
367
                    return null;
368
                } else {
369
                    throw new LazyInitializationException(null);
370
                }
371

    
372
            }
373
        });
374

    
375
        T proxy = (T)enhancer.create();
376
        return proxy;
377
    }
378

    
379
    class UninitializedLazyInitializer implements LazyInitializer {
380

    
381
        @Override
382
        public  boolean isUninitialized() {
383
            return true;
384
        }
385

    
386
        @Override
387
        public String getEntityName() {
388
            // TODO Auto-generated method stub
389
            return null;
390
        }
391

    
392
        @Override
393
        public Serializable getIdentifier() {
394
            // TODO Auto-generated method stub
395
            return null;
396
        }
397

    
398
        @Override
399
        public Object getImplementation() {
400
            // TODO Auto-generated method stub
401
            return null;
402
        }
403

    
404
        @Override
405
        public Class getPersistentClass() {
406
            // TODO Auto-generated method stub
407
            return null;
408
        }
409

    
410
        @Override
411
        public SessionImplementor getSession() {
412
            // TODO Auto-generated method stub
413
            return null;
414
        }
415

    
416
        @Override
417
        public void initialize() throws HibernateException {
418
            // TODO Auto-generated method stub
419

    
420
        }
421

    
422
        @Override
423
        public boolean isUnwrap() {
424
            // TODO Auto-generated method stub
425
            return false;
426
        }
427

    
428
        @Override
429
        public void setIdentifier(Serializable arg0) {
430
            // TODO Auto-generated method stub
431

    
432
        }
433

    
434
        @Override
435
        public void setImplementation(Object arg0) {
436
            // TODO Auto-generated method stub
437

    
438
        }
439

    
440
        @Override
441
        public void setUnwrap(boolean arg0) {
442
            // TODO Auto-generated method stub
443

    
444
        }
445

    
446
		@Override
447
		public Object getImplementation(
448
				org.hibernate.engine.spi.SessionImplementor session)
449
				throws HibernateException {
450
			// TODO Auto-generated method stub
451
			return null;
452
		}
453

    
454
		@Override
455
		public boolean isReadOnlySettingAvailable() {
456
			// TODO Auto-generated method stub
457
			return false;
458
		}
459

    
460
		@Override
461
		public boolean isReadOnly() {
462
			// TODO Auto-generated method stub
463
			return false;
464
		}
465

    
466
		@Override
467
		public void setReadOnly(boolean readOnly) {
468
			// TODO Auto-generated method stub
469

    
470
		}
471

    
472
		@Override
473
		public void setSession(
474
				org.hibernate.engine.spi.SessionImplementor session)
475
				throws HibernateException {
476
			// TODO Auto-generated method stub
477

    
478
		}
479

    
480
		@Override
481
		public void unsetSession() {
482
			// TODO Auto-generated method stub
483

    
484
		}
485

    
486
    }
487

    
488

    
489

    
490

    
491
}
    (1-1/1)