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
        @SuppressWarnings("unchecked")
341
        T proxy = (T)enhancer.create();
342
        return proxy;
343
    }
344

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

    
373
            }
374
        });
375

    
376
        @SuppressWarnings("unchecked")
377
        T proxy = (T)enhancer.create();
378
        return proxy;
379
    }
380

    
381
    class UninitializedLazyInitializer implements LazyInitializer {
382

    
383
        @Override
384
        public  boolean isUninitialized() {
385
            return true;
386
        }
387

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

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

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

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

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

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

    
422
        }
423

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

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

    
434
        }
435

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

    
440
        }
441

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

    
446
        }
447

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

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

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

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

    
472
		}
473

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

    
480
		}
481

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

    
486
		}
487

    
488
    }
489

    
490

    
491

    
492

    
493
}
    (1-1/1)