Project

General

Profile

Download (8.57 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
* Copyright (C) 2009 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.database;
10

    
11
import java.util.HashMap;
12
import java.util.Map;
13
import java.util.UUID;
14

    
15
import javax.annotation.PostConstruct;
16
import javax.sql.DataSource;
17

    
18
import org.apache.log4j.Logger;
19
import org.dbunit.database.DatabaseConfig;
20
import org.dbunit.database.DatabaseConnection;
21
import org.dbunit.database.IDatabaseConnection;
22
import org.dbunit.dataset.IDataSet;
23
import org.dbunit.dataset.xml.FlatXmlDataSetBuilder;
24
import org.dbunit.ext.h2.H2DataTypeFactory;
25
import org.dbunit.operation.DatabaseOperation;
26
import org.hibernate.Hibernate;
27
import org.springframework.beans.factory.annotation.Autowired;
28
import org.springframework.core.io.Resource;
29
import org.springframework.transaction.PlatformTransactionManager;
30
import org.springframework.transaction.TransactionStatus;
31
import org.springframework.transaction.support.DefaultTransactionDefinition;
32

    
33
import eu.etaxonomy.cdm.model.term.DefaultTermInitializer;
34
import eu.etaxonomy.cdm.model.term.DefinedTermBase;
35
import eu.etaxonomy.cdm.model.term.Representation;
36
import eu.etaxonomy.cdm.model.term.TermVocabulary;
37
import eu.etaxonomy.cdm.model.term.VocabularyEnum;
38

    
39
public class TestingTermInitializer extends DefaultTermInitializer {
40

    
41
    private static final Logger logger = Logger.getLogger(TestingTermInitializer.class);
42

    
43
    protected PlatformTransactionManager transactionManager;
44
    protected DefaultTransactionDefinition txDefinition = new DefaultTransactionDefinition();
45

    
46
    protected TestingTermVocabularyDao vocabularyDao;
47

    
48
    private DataSource dataSource;
49

    
50
    private Resource termsDataSet;
51

    
52
    private Resource termsDtd;
53

    
54
    @Autowired
55
    public void setTransactionManager(PlatformTransactionManager transactionManager) {
56
        this.transactionManager = transactionManager;
57
    }
58

    
59
    @Autowired
60
    public void setVocabularyDao(TestingTermVocabularyDao vocabularyDao) {
61
        this.vocabularyDao = vocabularyDao;
62
    }
63

    
64
    @Autowired
65
    public void setDataSource(DataSource dataSource) {
66
        this.dataSource = dataSource;
67
    }
68

    
69
    public void setTermsDataSet(Resource termsDataSet) {
70
        this.termsDataSet = termsDataSet;
71
    }
72

    
73
    public void setTermsDtd(Resource termsDtd) {
74
        this.termsDtd = termsDtd;
75
    }
76

    
77
    @PostConstruct
78
    @Override
79
    public void initialize() {
80
        super.initialize();
81
    }
82

    
83
    @Override
84
    public void doInitialize(){
85
        logger.info("TestingTermInitializer initialize start ...");
86
        if (isOmit()){
87
            logger.info("TestingTermInitializer.omit == true, returning without initializing terms");
88
            return;
89
        } else {
90
            TransactionStatus txStatus = transactionManager.getTransaction(txDefinition);
91
            IDatabaseConnection connection = null;
92

    
93
            try {
94

    
95
                connection = getConnection();
96

    
97
//				MultiSchemaXmlDataSetFactory dataSetFactory = new MultiSchemaXmlDataSetFactory();
98
//		    	MultiSchemaDataSet multiSchemaDataset = dataSetFactory.createDataSet(termsDataSet.getFile());
99
//
100
//		    	if(multiSchemaDataset != null){
101
//			       	for (String name : multiSchemaDataset.getSchemaNames()) {
102
//			    		IDataSet clearDataSet = multiSchemaDataset.getDataSetForSchema(name);
103
//			    		DatabaseOperation.CLEAN_INSERT.execute(connection, clearDataSet);
104
//			    	}
105
//		    	}
106

    
107
//                logger.info("loading data base schema from " + termsDtd.getFile().getAbsolutePath());
108
//                logger.info("loading data set from " + termsDataSet.getFile().getAbsolutePath());
109

    
110

    
111
                //old: IDataSet dataSet = new FlatXmlDataSet(new InputStreamReader(termsDataSet.getInputStream()),new InputStreamReader(termsDtd.getInputStream()));
112

    
113
                IDataSet dataSet = new FlatXmlDataSetBuilder()
114
                	.setMetaDataSetFromDtd(termsDtd.getInputStream())
115
                	.build(termsDataSet.getInputStream());
116

    
117

    
118
                //ITable definedTermBase = dataSet.getTable("DEFINEDTERMBASE");
119
//				for(int rowId = 0; rowId < definedTermBase.getRowCount(); rowId++) {
120
//					System.err.println(rowId + " : " + definedTermBase.getValue(rowId, "CREATEDBY_ID"));
121
//				}
122
                DatabaseOperation.CLEAN_INSERT.execute(connection, dataSet);
123

    
124
            } catch (Exception e) {
125
                logger.error(e.getMessage(), e);
126
                throw new RuntimeException(e);
127
            } finally {
128
//                try {
129
//                    this.transactionManager.commit(txStatus);
130
//                    if (connection != null){
131
//                        connection.close();
132
//                    }
133
//                } catch (SQLException sqle) {
134
//                    logger.error(sqle);
135
//                }
136
            }
137

    
138
            transactionManager.commit(txStatus);
139

    
140
            txStatus = transactionManager.getTransaction(txDefinition);
141

    
142
            for(VocabularyEnum vocabularyType : VocabularyEnum.values()) {
143
            	initializeAndStore(vocabularyType, new HashMap<>(), null);
144
            }
145
            transactionManager.commit(txStatus);
146
            //txStatus = transactionManager.getTransaction(txDefinition);
147
        }
148
        logger.info("TestingTermInitializer initialize end ...");
149
    }
150

    
151
    /**
152
     * This methods should be an exact copy of the
153
     * cdmlib-persistence PersistentTermInitializer.initializeAndStore() method.
154
     * The problems is that both do not know about each other within their environment.
155
     *
156
     * FIXME Try to handle it such that we do not need to duplicate redundant code here.
157
     *
158
     *
159
     * Initializes the static fields of the <code>TermVocabulary</code> classes.
160
     *
161
     * @param clazz the <code>Class</code> of the vocabulary
162
     * @param vocabularyUuid the <code>UUID</code> of the vocabulary
163
     * @param terms a <code>Map</code> containing all already
164
     *                       loaded terms with their <code>UUID</code> as key
165
     * @param vocabularyMap
166
     */
167
    protected void initializeAndStore(VocabularyEnum vocType, Map<UUID,DefinedTermBase> terms, Map<UUID, TermVocabulary<?>> vocabularyMap) {
168
        Class<? extends DefinedTermBase<?>> clazz = vocType.getClazz();
169
        UUID vocabularyUuid = vocType.getUuid();
170

    
171
        if (logger.isDebugEnabled()){ logger.debug("Loading vocabulary for class " + clazz.getSimpleName() + " with uuid " + vocabularyUuid );}
172

    
173
        TermVocabulary<? extends DefinedTermBase> persistedVocabulary;
174
        if (vocabularyMap == null || vocabularyMap.get(vocabularyUuid) == null ){
175
            persistedVocabulary = vocabularyDao.findByUuid(vocabularyUuid);
176
        }else{
177
            persistedVocabulary = vocabularyMap.get(vocabularyUuid);
178
        }
179

    
180
        if (logger.isDebugEnabled()){ logger.debug("Initializing terms in vocabulary for class " + clazz.getSimpleName() + " with uuid " + vocabularyUuid );}
181
        //not really needed anymore as we do term initializing from the beginning now
182
        if (persistedVocabulary != null){
183
            for(DefinedTermBase<?> definedTermBase : persistedVocabulary.getTerms()) {
184

    
185
                Hibernate.initialize(definedTermBase.getRepresentations());
186
                for(Representation r : definedTermBase.getRepresentations()) {
187
                    Hibernate.initialize(r.getLanguage());
188
                }
189
                terms.put(definedTermBase.getUuid(), definedTermBase);
190
            }
191
        }else{
192
            logger.error("Persisted Vocabulary does not exist in database: " + vocabularyUuid);
193
            throw new IllegalStateException("Persisted Vocabulary does not exist in database: " + vocabularyUuid);
194
        }
195

    
196

    
197
        //fill term store
198
        if (logger.isDebugEnabled()){ logger.debug("Setting defined Terms for class " + clazz.getSimpleName() + ", " + persistedVocabulary.getTerms().size() + " in vocabulary");}
199
        super.setDefinedTerms(clazz, persistedVocabulary);
200
        if (logger.isDebugEnabled()){ logger.debug("Second pass - DONE");}
201

    
202
    }
203

    
204
    protected IDatabaseConnection getConnection() {
205
        IDatabaseConnection connection = null;
206
        try {
207
            connection = new DatabaseConnection(dataSource.getConnection());
208

    
209
            DatabaseConfig config = connection.getConfig();
210
            //FIXME must use unitils.properties: org.unitils.core.dbsupport.DbSupport.implClassName & database.dialect to find configured DataTypeFactory
211
            config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new H2DataTypeFactory());
212
        } catch (Exception e) {
213
            logger.error(e);
214
        }
215
        return connection;
216
    }
217
}
(3-3/4)