Project

General

Profile

Download (6.23 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
* Copyright (C) 2007 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.test.unitils;
10

    
11
import static org.unitils.thirdparty.org.apache.commons.io.IOUtils.closeQuietly;
12

    
13
import java.io.File;
14
import java.io.FileOutputStream;
15
import java.io.IOException;
16
import java.io.InputStream;
17
import java.io.OutputStream;
18
import java.net.URL;
19
import java.sql.SQLException;
20

    
21
import org.apache.commons.lang.StringUtils;
22
import org.apache.logging.log4j.LogManager;
23
import org.apache.logging.log4j.Logger;
24
import org.dbunit.DatabaseUnitException;
25
import org.dbunit.dataset.IDataSet;
26
import org.dbunit.dataset.xml.FlatXmlDataSet;
27
import org.dbunit.operation.DatabaseOperation;
28
import org.unitils.dbunit.datasetfactory.impl.MultiSchemaXmlDataSetFactory;
29
import org.unitils.dbunit.datasetloadstrategy.impl.CleanInsertLoadStrategy;
30
import org.unitils.dbunit.util.DbUnitDatabaseConnection;
31
import org.unitils.dbunit.util.MultiSchemaDataSet;
32
import org.unitils.thirdparty.org.apache.commons.io.IOUtils;
33
import org.unitils.util.FileUtils;
34

    
35
/**
36
 * Will clear all data in the DataSet except all term related tables
37
   before doing a CLEAN_INSERT:
38
 * @author Andreas Kohlbecker
39
 */
40
public class CleanSweepInsertLoadStrategy extends CleanInsertLoadStrategy {
41

    
42
    protected static final Logger logger = LogManager.getLogger();
43

    
44
    private static String clearDataResource = "eu/etaxonomy/cdm/database/ClearDBDataSet.xml";
45

    
46

    
47
    /**
48
     * Executes this DataSetLoadStrategy.
49
     * This means the given dataset is inserted in the database using the given dbUnit
50
     * database connection object.
51
     *
52
     * @param dbUnitDatabaseConnection DbUnit class providing access to the database
53
     * @param dataSet                  The dbunit dataset
54
     */
55
    @Override
56
    public void doExecute(DbUnitDatabaseConnection dbUnitDatabaseConnection, IDataSet dataSet) throws DatabaseUnitException, SQLException {
57

    
58
        // will clear all data in the DataSet except all term related tables
59
        // before doing a CLEAN_INSERT:
60
        MultiSchemaDataSet multiSchemaDataset = null;
61
        URL fileUrl = null;
62
        MultiSchemaXmlDataSetFactory dataSetFactory = new MultiSchemaXmlDataSetFactory();
63
        fileUrl = getClass().getClassLoader().getResource(clearDataResource);
64
        if (fileUrl == null) {
65
            throw new RuntimeException("the Resource " + clearDataResource + " could not be found");
66
        }
67
        try {
68
            File file;
69
            logger.debug("fileUrl:" + fileUrl.toString() + "; protocol: " +  fileUrl.getProtocol());
70
            if(fileUrl.toString().startsWith("jar:file:")){
71
                // extract file from jar into tmp folder
72
                String millisecTimeStamp = String.valueOf(System.currentTimeMillis());
73
                file = copyClassPathResource(fileUrl, System.getProperty("java.io.tmpdir") + File.separator + millisecTimeStamp);
74
            } else {
75
                file = new File(fileUrl.toURI());
76
            }
77
            multiSchemaDataset = dataSetFactory.createDataSet(file);
78
        } catch (Exception e) {
79
            logger.error("unable to load the clearing dataset as resource from " + fileUrl.toString(), e);
80
        }
81

    
82
        if(multiSchemaDataset != null){
83
            for (String name : multiSchemaDataset.getSchemaNames()) {
84
                IDataSet clearDataSet = multiSchemaDataset.getDataSetForSchema(name);
85
                logger.debug("doing CLEAN_INSERT with dataset '" + name + "'");
86
                DatabaseOperation.CLEAN_INSERT.execute(dbUnitDatabaseConnection, clearDataSet);
87
            }
88
        }
89

    
90
        super.doExecute(dbUnitDatabaseConnection, dataSet);
91

    
92
        // DEBUGGING the resulting database
93
//        try {
94
//            OutputStream out;
95
//            out = new FileOutputStream("CleanSweepInsertLoadStrategy-debug.xml");
96
////			printDataSet(dbUnitDatabaseConnection, out, (String[]) null);
97
//            printDataSet(dbUnitDatabaseConnection, out, new String[]{"TAXONNODE", "CLASSIFICATION", "CLASSIFICATION_TAXONNODE"});
98
//        } catch (FileNotFoundException e) {
99
//            e.printStackTrace();
100
//        }
101
    }
102

    
103

    
104
    /**
105
     * more or less 1:1 copy from {@link FileUtils#copyClassPathResource(String, String)}
106
     *
107
     * @param classPathResourceName
108
     * @param fileSystemDirectoryName
109
     * @return
110
     * @throws IOException
111
     */
112
    public File copyClassPathResource(URL resourceURL, String fileSystemDirectoryName) throws IOException {
113

    
114
        InputStream resourceInputStream = null;
115
        OutputStream fileOutputStream = null;
116
        File file = null;
117
        try {
118
            resourceInputStream = resourceURL.openStream();
119
            String fileName = StringUtils.substringAfterLast(resourceURL.getPath(), "/");
120
            File fileSystemDirectory = new File(fileSystemDirectoryName);
121
            fileSystemDirectory.mkdirs();
122
            String filePath = fileSystemDirectoryName + "/" + fileName;
123
            fileOutputStream = new FileOutputStream(filePath);
124
            IOUtils.copy(resourceInputStream, fileOutputStream);
125
            file = new File(filePath);
126
            if(!file.canRead()){
127
                throw new IOException("tmp file " + file.toString() + " not readable.");
128
            }
129
        } catch (IOException e) {
130
            throw e;
131
        } finally {
132
            closeQuietly(resourceInputStream);
133
            closeQuietly(fileOutputStream);
134
        }
135
        return file;
136
    }
137

    
138
    @SuppressWarnings("unused")
139
    private void printDataSet(DbUnitDatabaseConnection dbUnitDatabaseConnection, OutputStream out, String ... tableNames) {
140

    
141
        try {
142
            IDataSet actualDataSet;
143
            if(tableNames == null){
144
                actualDataSet = dbUnitDatabaseConnection.createDataSet();
145
            } else {
146
                actualDataSet = dbUnitDatabaseConnection.createDataSet(tableNames);
147
            }
148
            FlatXmlDataSet.write(actualDataSet, out);
149
        } catch (Exception e) {
150
            logger.error(e);
151
        } finally {
152
            try {
153
                dbUnitDatabaseConnection.close();
154
            } catch (SQLException sqle) {
155
                logger.error(sqle);
156
            }
157
        }
158
    }
159
}
(1-1/3)