Project

General

Profile

Download (20.9 KB) Statistics
| Branch: | Tag: | Revision:
1
package eu.etaxonomy.cdm.remote.dto.assembler.lsid;
2

    
3
import static org.junit.Assert.assertEquals;
4
import static org.junit.Assert.assertNotNull;
5
import static org.junit.Assert.assertNull;
6
import static org.junit.Assert.assertTrue;
7

    
8
import java.io.Serializable;
9
import java.lang.reflect.Field;
10
import java.lang.reflect.Method;
11
import java.net.URI;
12
import java.time.Year;
13
import java.time.ZoneId;
14
import java.time.ZonedDateTime;
15
import java.util.ArrayList;
16
import java.util.Arrays;
17
import java.util.Collection;
18
import java.util.HashSet;
19
import java.util.List;
20
import java.util.Set;
21
import java.util.UUID;
22

    
23
import org.apache.log4j.Logger;
24
import org.dozer.Mapper;
25
import org.hibernate.Hibernate;
26
import org.hibernate.HibernateException;
27
import org.hibernate.LazyInitializationException;
28
import org.hibernate.collection.spi.PersistentCollection;
29
import org.hibernate.engine.spi.SessionImplementor;
30
import org.hibernate.proxy.HibernateProxy;
31
import org.hibernate.proxy.LazyInitializer;
32
import org.junit.Before;
33
import org.junit.BeforeClass;
34
import org.junit.Ignore;
35
import org.junit.Test;
36
import org.unitils.UnitilsJUnit4;
37
import org.unitils.spring.annotation.SpringApplicationContext;
38
import org.unitils.spring.annotation.SpringBeanByType;
39

    
40
import eu.etaxonomy.cdm.common.UriUtils;
41
import eu.etaxonomy.cdm.model.agent.Person;
42
import eu.etaxonomy.cdm.model.agent.TeamOrPersonBase;
43
import eu.etaxonomy.cdm.model.common.Credit;
44
import eu.etaxonomy.cdm.model.common.DefaultTermInitializer;
45
import eu.etaxonomy.cdm.model.common.IdentifiableSource;
46
import eu.etaxonomy.cdm.model.common.LSID;
47
import eu.etaxonomy.cdm.model.common.Language;
48
import eu.etaxonomy.cdm.model.common.LanguageString;
49
import eu.etaxonomy.cdm.model.common.TimePeriod;
50
import eu.etaxonomy.cdm.model.description.Distribution;
51
import eu.etaxonomy.cdm.model.description.PresenceAbsenceTerm;
52
import eu.etaxonomy.cdm.model.description.TaxonDescription;
53
import eu.etaxonomy.cdm.model.description.TextData;
54
import eu.etaxonomy.cdm.model.location.NamedArea;
55
import eu.etaxonomy.cdm.model.name.INonViralName;
56
import eu.etaxonomy.cdm.model.name.Rank;
57
import eu.etaxonomy.cdm.model.name.TaxonNameFactory;
58
import eu.etaxonomy.cdm.model.reference.IBook;
59
import eu.etaxonomy.cdm.model.reference.INomenclaturalReference;
60
import eu.etaxonomy.cdm.model.reference.Reference;
61
import eu.etaxonomy.cdm.model.reference.ReferenceFactory;
62
import eu.etaxonomy.cdm.model.taxon.Synonym;
63
import eu.etaxonomy.cdm.model.taxon.SynonymType;
64
import eu.etaxonomy.cdm.model.taxon.Taxon;
65
import eu.etaxonomy.cdm.model.taxon.TaxonBase;
66
import eu.etaxonomy.cdm.model.taxon.TaxonRelationship;
67
import eu.etaxonomy.cdm.remote.dto.dwc.SimpleDarwinRecord;
68
import eu.etaxonomy.cdm.remote.dto.oaipmh.OaiDc;
69
import eu.etaxonomy.cdm.remote.dto.tdwg.voc.SpeciesProfileModel;
70
import eu.etaxonomy.cdm.remote.dto.tdwg.voc.TaxonConcept;
71
import net.sf.cglib.proxy.Enhancer;
72
import net.sf.cglib.proxy.MethodInterceptor;
73
import net.sf.cglib.proxy.MethodProxy;
74

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

    
78
    public static final Logger logger = Logger.getLogger(AssemblerTest.class);
79

    
80
    @SpringBeanByType
81
    private Mapper mapper;
82

    
83
    private Taxon taxon;
84
    private IBook sec;
85
    private IBook book;
86
    private Reference bookSection;
87
    private TeamOrPersonBase<?> authorship;
88
    private INonViralName name;
89
    private LSID lsid;
90
    private TaxonDescription taxonDescription;
91

    
92
    @BeforeClass
93
    public static void onSetUp() {
94
        DefaultTermInitializer defaultTermInitializer = new DefaultTermInitializer();
95
        defaultTermInitializer.initialize();
96
    }
97

    
98
    @Before
99
    public void setUp() throws Exception {
100
        lsid = new LSID("urn:lsid:example.org:taxonconcepts:1");
101

    
102
        authorship = Person.NewInstance();
103
        authorship.setTitleCache("authorship.titleCache", true);
104
        authorship.setLsid(new LSID("urn:lsid:dagg.org:agents:2"));
105

    
106
        name = TaxonNameFactory.NewBotanicalInstance(null);
107
        name.setNameCache("nameCache");
108
        INomenclaturalReference nomenclaturalReference = ReferenceFactory.newArticle();
109
        nomenclaturalReference.setTitleCache("nomenclaturalReference", true);
110
        name.setNomenclaturalReference(nomenclaturalReference);
111
        name.setNomenclaturalMicroReference("1");
112
        name.setAuthorshipCache("authorshipCache");
113
        name.setRank(Rank.SPECIES());
114

    
115
        sec = ReferenceFactory.newBook();
116
        sec.setAuthorship(authorship);
117
        sec.setTitleCache("sec.titleCache", true);
118
        sec.setLsid(new LSID("urn:lsid:example.org:references:1"));
119

    
120
        taxon = Taxon.NewInstance(name, (Reference)sec);
121
        taxon.setCreated(ZonedDateTime.of(20014, 12, 25, 12, 0, 0, 0, ZoneId.systemDefault()));
122
        taxon.setUpdated(ZonedDateTime.of(20014, 12, 25, 12, 0, 0, 0, ZoneId.systemDefault()));
123
        taxon.setTitleCache("titleCache", true);
124
        taxon.setLsid(lsid);
125

    
126
        for(int i = 0; i < 10; i++) {
127
            Taxon child = Taxon.NewInstance(name, (Reference)sec);
128
            child.setLsid(new LSID("urn:lsid:example.org:taxonconcepts:" + (2 + i )));
129
//            taxon.addTaxonomicChild(child, null,null);
130
        }
131

    
132

    
133
        taxonDescription = TaxonDescription.NewInstance();
134
        taxon.addDescription(taxonDescription);
135

    
136
        TextData textData = TextData.NewInstance();
137
        Language english = Language.NewInstance();
138
        english.setIso639_1("en");
139
        Language french = Language.NewInstance();
140
        french.setIso639_1("fr");
141
        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));
142
        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));
143
        taxonDescription.addElement(textData);
144

    
145
        Distribution distribution = Distribution.NewInstance();
146
        NamedArea namedArea = NamedArea.NewInstance("Africa", "Africa", "Africa");
147
        namedArea.setTitleCache("Africa", true);
148
        distribution.setArea(namedArea);
149
        distribution.setStatus(PresenceAbsenceTerm.NATIVE());
150

    
151
        taxonDescription.addElement(distribution);
152

    
153
        // ------------------------------------------------------
154

    
155
        book = ReferenceFactory.newBook();
156
        book.setTitle("Book.title");
157
        book.setAuthorship(authorship);
158
        book.setCreated(ZonedDateTime.of(20014, 12, 25, 12, 0, 0, 0, ZoneId.systemDefault()));
159
        book.setDatePublished(new TimePeriod(Year.of(1800)));
160
        book.setEdition("1st Edition");
161
        book.setEditor("Editor");
162
        book.setIsbn("isbn");
163
        book.setPlacePublished("placePublished");
164
        book.setPublisher("publisher");
165
        book.setReferenceAbstract("referenceAbstract");
166
        book.setUri(new URI("http://persitent.books.foo/myBook"));
167
        book.setUuid(UUID.randomUUID());
168
        book.setVolume("Volume 1");
169
        book.addSource(IdentifiableSource.NewDataImportInstance("http://persitent.IdentifiableSources.foo/1"));
170

    
171
        bookSection = ReferenceFactory.newBookSection();
172
        bookSection.setInReference((Reference)book);
173
        bookSection.setPages("999 ff.");
174
        bookSection.setTitle("BookSection.title");
175
        bookSection.setAuthorship(authorship);
176
        bookSection.setCreated(ZonedDateTime.of(20014, 12, 25, 12, 0, 0, 0, ZoneId.systemDefault()));
177
        bookSection.setDatePublished(new TimePeriod(Year.of(1800)));
178
        bookSection.setReferenceAbstract("referenceAbstract");
179
        bookSection.setUri(new URI("http://persitent.books.foo/myBookSection"));
180
        bookSection.setUuid(UUID.randomUUID());
181
        bookSection.addCredit(Credit.NewInstance(authorship, "Credits to the authorship"));
182
        bookSection.addSource(IdentifiableSource.NewDataImportInstance("http://persitent.IdentifiableSources.foo/2"));
183
    }
184

    
185
    @Ignore
186
    @Test
187
    public void testDeepMapping() {
188
        for(int i = 0; i < 3; i++) {
189
            Synonym synonym = Synonym.NewInstance(name,(Reference)sec);
190
            taxon.addSynonym(synonym, SynonymType.SYNONYM_OF());
191
        }
192

    
193
        if(!UriUtils.isInternetAvailable(null)){
194
            // dozer requires access to dozer.sourceforge.net
195
            logger.info("Internet is not available: Skipping test");
196
            return;
197
        }
198

    
199
        TaxonConcept taxonConcept = mapper.map(taxon, TaxonConcept.class);
200

    
201
        assertNotNull("map() should return an object", taxonConcept);
202
        assertTrue("map() should return a TaxonConcept",taxonConcept instanceof TaxonConcept);
203

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

    
218
    @Ignore
219
    @Test
220
    public void testLazyInitializationExceptionWithProxy() throws Exception {
221

    
222
        if(!UriUtils.isInternetAvailable(null)){
223
            // dozer requires access to dozer.sourceforge.net
224
            logger.info("Internet is not available: Skipping test");
225
            return;
226
        }
227

    
228
        IBook proxy = getUninitializedDetachedProxy(Reference.class,(Reference)sec);
229
        assert !Hibernate.isInitialized(proxy);
230
        Field secField = TaxonBase.class.getDeclaredField("sec");
231
        secField.setAccessible(true);
232
        secField.set(taxon, proxy);
233

    
234
        TaxonConcept taxonConcept = mapper.map(taxon, TaxonConcept.class);
235
        assertNull("TaxonBase.sec was uninitialized, so TaxonConcept.publishedInCitation should be null",taxonConcept.getPublishedInCitation());
236
        assertNull("TaxonBase.sec was uninitialized, so TaxonConcept.accordingTo should be null",taxonConcept.getAccordingTo());
237
    }
238

    
239
    @Ignore
240
    @Test
241
    public void testLazyInitializationExceptionWithPersistentCollection() throws Exception {
242

    
243
        if(!UriUtils.isInternetAvailable(null)){
244
            // dozer requires access to dozer.sourceforge.net
245
            logger.info("Internet is not available: Skipping test");
246
            return;
247
        }
248

    
249
        Set<TaxonRelationship> proxy = getUninitializedPersistentCollection(HashSet.class,(HashSet<TaxonRelationship>)taxon.getRelationsToThisTaxon());
250
        assert !Hibernate.isInitialized(proxy);
251
        Field relationsToThisTaxonField = Taxon.class.getDeclaredField("relationsToThisTaxon");
252
        relationsToThisTaxonField.setAccessible(true);
253
        relationsToThisTaxonField.set(taxon, proxy);
254

    
255
        TaxonConcept taxonConcept = mapper.map(taxon, TaxonConcept.class);
256
        assertTrue("TaxonBase.relationsToThisTaxon was uninitialized, so TaxonConcept.hasRelationship should be null",taxonConcept.getHasRelationship().isEmpty());
257
    }
258

    
259
    @Ignore
260
    @Test
261
    public void testSpeciesProfileModelMapping() {
262

    
263
        if(!UriUtils.isInternetAvailable(null)){
264
            // dozer requires access to dozer.sourceforge.net
265
            logger.info("Internet is not available: Skipping test");
266
            return;
267
        }
268

    
269
        SpeciesProfileModel speciesProfileModel = mapper.map(taxonDescription, SpeciesProfileModel.class);
270
        assertEquals(speciesProfileModel.getHasInformation().size(),2);
271
    }
272

    
273
    @Ignore
274
    @Test
275
    public void testSimpleDarwinCoreMapping() {
276

    
277
        if(!UriUtils.isInternetAvailable(null)){
278
            // dozer requires access to dozer.sourceforge.net
279
            logger.info("Internet is not available: Skipping test");
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
    @Ignore
294
    @Test
295
    public void testOAIDublinCoreMapping() {
296

    
297
        if(!UriUtils.isInternetAvailable(null)){
298
            // dozer requires access to dozer.sourceforge.net
299
            logger.info("Internet is not available: Skipping test");
300
            return;
301
        }
302

    
303
        OaiDc oaiDcRecordBook = mapper.map(book, OaiDc.class);
304

    
305
        assertEquals(book.getTitle(), book.getTitle());
306

    
307
        OaiDc oaiDcRecordBookSection = mapper.map(bookSection, OaiDc.class);
308
        assertNotNull(oaiDcRecordBookSection.getRelation());
309
    }
310

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

    
337
                    throw new LazyInitializationException(null);
338
                }
339

    
340
            }
341
        });
342

    
343
        T proxy = (T)enhancer.create();
344
        return proxy;
345
    }
346

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

    
375
            }
376
        });
377

    
378
        T proxy = (T)enhancer.create();
379
        return proxy;
380
    }
381

    
382
    class UninitializedLazyInitializer implements LazyInitializer {
383

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

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

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

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

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

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

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

    
423
        }
424

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

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

    
435
        }
436

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

    
441
        }
442

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

    
447
        }
448

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

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

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

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

    
473
		}
474

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

    
481
		}
482

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

    
487
		}
488

    
489
    }
490

    
491

    
492

    
493

    
494
}
    (1-1/1)