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

    
10
package eu.etaxonomy.cdm.database;
11

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

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

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

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

    
40
public class TestingTermInitializer extends DefaultTermInitializer {
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

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

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

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

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

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

    
78

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

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

    
95
            try {
96

    
97
                connection = getConnection();
98

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

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

    
112

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

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

    
119

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

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

    
140
            transactionManager.commit(txStatus);
141

    
142
            txStatus = transactionManager.getTransaction(txDefinition);
143

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

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

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

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

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

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

    
198

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

    
204
    }
205

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

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