Project

General

Profile

« Previous | Next » 

Revision 44b37b30

Added by Andreas Kohlbecker about 5 years ago

ref #8189 moving folder funstins from CdmUtils to ConfigFileUtil

View differences:

cdmlib-commons/pom.xml
16 16
  <description>EDIT CDM library - Commons</description>
17 17
  
18 18
  <dependencies>
19
    <dependency>
20
      <groupId>org.springframework</groupId>
21
      <artifactId>spring-context</artifactId>
22
    </dependency>
19 23
    <dependency>
20 24
      <groupId>org.springframework</groupId>
21 25
      <artifactId>spring-test</artifactId>
cdmlib-commons/src/main/java/eu/etaxonomy/cdm/common/AccountStore.java
24 24

  
25 25
    private static Logger logger = Logger.getLogger(AccountStore.class);
26 26

  
27
    public final static File accountsFile = new File(CdmUtils.perUserCdmFolder + File.separator + ".dbaccounts.properties");
27
    public final static File accountsFile = new File(ConfigFileUtil.perUserCdmFolder() + File.separator + ".dbaccounts.properties");
28 28

  
29 29
    public static String getAccountsFileName(){
30 30
        try {
cdmlib-commons/src/main/java/eu/etaxonomy/cdm/common/CdmUtils.java
10 10
package eu.etaxonomy.cdm.common;
11 11

  
12 12
import java.io.BufferedReader;
13
import java.io.File;
14 13
import java.io.IOException;
15 14
import java.io.InputStream;
16 15
import java.io.InputStreamReader;
......
31 30

  
32 31
import org.apache.commons.lang.StringUtils;
33 32
import org.apache.log4j.Logger;
34
import org.springframework.context.EnvironmentAware;
35
import org.springframework.core.env.Environment;
36 33

  
37 34
/**
38 35
 * Util class for consistent access to and creation of per instance application configuration files.
......
40 37
 * @author a.mueller
41 38
 * @author a.kohlbecker
42 39
 */
43
public class CdmUtils implements EnvironmentAware {
40
public class CdmUtils {
44 41

  
45 42
    private static final Logger logger = Logger.getLogger(CdmUtils.class);
46 43

  
47
    // ============= TODO externalize into CdmFileUtils class ? ========== //
48

  
49
    private static String userHome = null;
50

  
51
    /**
52
     * The per user cdm folder name: ".cdmLibrary"
53
     */
54
    private static final String CDM_FOLDER_NAME = ".cdmLibrary";
55

  
56
    /**
57
     * The per user cdm folder "~/.cdmLibrary"
58
     */
59
    public static File perUserCdmFolder = null;
60

  
61
    /**
62
     * suggested sub folder for web app related data and configurations.
63
     * Each webapp instance should use a dedicated subfolder or file
64
     * which is named by the data source bean id.
65
     */
66
    public static final String SUBFOLDER_WEBAPP = "remote-webapp";
67

  
68
    static final String MUST_EXIST_FILE = "MUST-EXIST.txt";
69

  
70
    //folder separator
71
    static String folderSeparator;
72

  
73
    protected Environment env;
74

  
75
    @Override
76
    public void setEnvironment(Environment environment) {
77
        this.env = environment;
78
        if(userHome == null){
79
            CdmUtils.userHome = env.getRequiredProperty("user.home");
80
            CdmUtils.perUserCdmFolder = new File(userHome + File.separator + CDM_FOLDER_NAME );
81
            logger.info("user.home is set to " + CdmUtils.userHome);
82
        }
83
    }
84

  
85
    public static File getCdmHomeDir() {
86
        return new File(perUserCdmFolder + File.separator);
87
    }
88

  
89
	/**
90
	 * Returns specified the sub folder of  {@link #CDM_FOLDER_NAME}.
91
	 * If the sub folder does not exist it will be created.
92
	 *
93
	 * @param subFolderName
94
	 * @return the sub folder or null in case the folder did not exist ant the attempt to create it has failed.
95
	 *
96
	 * @see {@link #SUBFOLDER_WEBAPP}
97
	 */
98
	public static File getCdmHomeSubDir(String subFolderName) {
99

  
100
		File parentFolder = getCdmHomeDir();
101
        return ensureSubfolderExists(parentFolder, subFolderName);
102
	}
103

  
104
	/**
105
     * Returns an instance specific folder folder in  {@link #CDM_FOLDER_NAME}/<code>subFolderName</code>
106
     * Non existing folders will be created.
107
     *
108
     * @param subFolderName
109
     *      The name of a subfolded. In most cases this will be {@link #SUBFOLDER_WEBAPP}
110
     * @param instanceName
111
     *      The name of the application instance. The name should be related to the data source id.
112
     * @return the sub folder or null in case the folder did not exist ant the attempt to create it has failed.
113
     *
114
     * @see {@link #SUBFOLDER_WEBAPP}
115
     */
116
    public static File getCdmInstanceSubDir(String subFolderName, String instanceName) {
117

  
118
        File subfolder = ensureSubfolderExists(getCdmHomeDir(), subFolderName);
119
        return ensureSubfolderExists(subfolder, instanceName);
120
    }
121

  
122
    /**
123
     * @param subFolderName
124
     * @param parentFolder
125
     * @return
126
     */
127
    private static File ensureSubfolderExists(File parentFolder, String subFolderName) {
128
        if (!parentFolder.exists()){
129
            if (!parentFolder.mkdir()) {
130
                throw new RuntimeException("Parent folder could not be created: " + parentFolder.getAbsolutePath());
131
            }
132
        }
133

  
134
        File subfolder = new File(parentFolder, subFolderName);
135
		// if the directory does not exist, create it
136
		if (!subfolder.exists()) {
137
			if (!subfolder.mkdir()) {
138
				throw new RuntimeException("Subfolder could not be created: " + subfolder.getAbsolutePath());
139
			}
140
		}
141
		return subfolder;
142
    }
143

  
144
	// ============= END of CdmFileUtils ========== //
145

  
146 44
    /**
147 45
     * Returns the an InputStream for a read-only source
148 46
     * @param resourceFileName the resources path within the classpath(!)
......
169 67
    }
170 68

  
171 69

  
172
    /**
173
     * @return
174
     */
175
    static public String getFolderSeperator(){
176
        if (folderSeparator == null){
177
            URL url = CdmUtils.class.getResource("/"+ MUST_EXIST_FILE);
178
            if ( url != null && ! urlIsJarOrBundle(url) ){
179
                folderSeparator =  File.separator;
180
            }else{
181
                folderSeparator = "/";
182
            }
183
        }
184
        return folderSeparator;
185
    }
186

  
187

  
188
    /**
189
     * @param url
190
     * @return
191
     */
192
    static private boolean urlIsJarOrBundle(URL url){
193
        return url.getProtocol().startsWith("jar") || url.getProtocol().startsWith("bundleresource");
194
    }
195 70

  
196 71
    /**
197 72
     * Returns the file name for the file in which 'clazz' is to be found (helps finding according libraries)
cdmlib-commons/src/main/java/eu/etaxonomy/cdm/common/ConfigFileUtil.java
13 13
import java.io.FileInputStream;
14 14
import java.io.FileNotFoundException;
15 15
import java.io.IOException;
16
import java.net.URL;
16 17
import java.nio.file.Files;
17 18
import java.util.Properties;
18 19

  
20
import org.apache.log4j.Logger;
21
import org.springframework.context.EnvironmentAware;
22
import org.springframework.core.env.Environment;
23

  
19 24
/**
20 25
 *
21 26
 * @author a.kohlbecker
22 27
 * @since May 8, 2017
23 28
 *
24 29
 */
25
public class ConfigFileUtil {
30
public class ConfigFileUtil implements EnvironmentAware {
31

  
32
    private static final Logger logger = Logger.getLogger(ConfigFileUtil.class);
33

  
34
    private static String userHome = null;
35

  
36
    /**
37
     * The per user cdm folder name: ".cdmLibrary"
38
     */
39
    private static final String CDM_FOLDER_NAME = ".cdmLibrary";
40

  
41
    /**
42
     * The per user cdm folder "~/.cdmLibrary"
43
     */
44
    private static File perUserCdmFolder = null;
45

  
46
    public static File perUserCdmFolder() {
47
        return perUserCdmFolder;
48
    }
49

  
50
    /**
51
     * suggested sub folder for web app related data and configurations.
52
     * Each webapp instance should use a dedicated subfolder or file
53
     * which is named by the data source bean id.
54
     */
55
    public static final String SUBFOLDER_WEBAPP = "remote-webapp";
56

  
57
    static final String MUST_EXIST_FILE = "MUST-EXIST.txt";
58

  
59
    //folder separator
60
    static String folderSeparator;
61

  
62
    protected Environment env;
63

  
64
    @Override
65
    public void setEnvironment(Environment environment) {
66
        this.env = environment;
67
        if(userHome == null){
68
            ConfigFileUtil.userHome = env.getRequiredProperty("user.home");
69
            ConfigFileUtil.perUserCdmFolder = new File(userHome + File.separator + CDM_FOLDER_NAME );
70
            logger.info("user.home is set to " + ConfigFileUtil.userHome);
71
        }
72
    }
73

  
74

  
75
    /**
76
     * @return
77
     */
78
    static public String getFolderSeperator(){
79
        if (folderSeparator == null){
80
            URL url = CdmUtils.class.getResource("/"+ MUST_EXIST_FILE);
81
            if ( url != null && ! urlIsJarOrBundle(url) ){
82
                folderSeparator =  File.separator;
83
            }else{
84
                folderSeparator = "/";
85
            }
86
        }
87
        return folderSeparator;
88
    }
89

  
26 90

  
27 91
    /**
92
     * @param url
93
     * @return
94
     */
95
    static private boolean urlIsJarOrBundle(URL url){
96
        return url.getProtocol().startsWith("jar") || url.getProtocol().startsWith("bundleresource");
97
    }
98

  
99

  
100
    public static File getCdmHomeDir() {
101
        return new File(perUserCdmFolder + File.separator);
102
    }
103

  
104
    /**
105
     * Returns specified the sub folder of  {@link #CDM_FOLDER_NAME}.
106
     * If the sub folder does not exist it will be created.
107
     *
108
     * @param subFolderName
109
     * @return the sub folder or null in case the folder did not exist ant the attempt to create it has failed.
110
     *
111
     * @see {@link #SUBFOLDER_WEBAPP}
112
     */
113
    public static File getCdmHomeSubDir(String subFolderName) {
114

  
115
        File parentFolder = getCdmHomeDir();
116
        return ensureSubfolderExists(parentFolder, subFolderName);
117
    }
118

  
119
    /**
120
     * Returns an instance specific folder folder in  {@link #CDM_FOLDER_NAME}/<code>subFolderName</code>
121
     * Non existing folders will be created.
122
     *
123
     * @param subFolderName
124
     *      The name of a subfolded. In most cases this will be {@link #SUBFOLDER_WEBAPP}
125
     * @param instanceName
126
     *      The name of the application instance. The name should be related to the data source id.
127
     * @return the sub folder or null in case the folder did not exist ant the attempt to create it has failed.
28 128
     *
129
     * @see {@link #SUBFOLDER_WEBAPP}
130
     */
131
    public static File getCdmInstanceSubDir(String subFolderName, String instanceName) {
132

  
133
        File subfolder = ensureSubfolderExists(getCdmHomeDir(), subFolderName);
134
        return ensureSubfolderExists(subfolder, instanceName);
135
    }
136

  
137
    /**
138
     * @param subFolderName
139
     * @param parentFolder
140
     * @return
29 141
     */
142
    private static File ensureSubfolderExists(File parentFolder, String subFolderName) {
143
        if (!parentFolder.exists()){
144
            if (!parentFolder.mkdir()) {
145
                throw new RuntimeException("Parent folder could not be created: " + parentFolder.getAbsolutePath());
146
            }
147
        }
148

  
149
        File subfolder = new File(parentFolder, subFolderName);
150
        // if the directory does not exist, create it
151
        if (!subfolder.exists()) {
152
            if (!subfolder.mkdir()) {
153
                throw new RuntimeException("Subfolder could not be created: " + subfolder.getAbsolutePath());
154
            }
155
        }
156
        return subfolder;
157
    }
30 158
    public static final String CDM_CONFIGFILE_OVERRIDE = "cdm.configfile.override.";
31 159

  
32 160
    private Properties props = null;
......
70 198
        if(override != null){
71 199
            return new File(override);
72 200
        } else {
73
            File configFolder = CdmUtils.getCdmInstanceSubDir(CdmUtils.SUBFOLDER_WEBAPP, instanceName);
201
            File configFolder = ConfigFileUtil.getCdmInstanceSubDir(ConfigFileUtil.SUBFOLDER_WEBAPP, instanceName);
74 202
            return new File(configFolder, propertiesSet + ".properties");
75 203
        }
76 204
    }
cdmlib-commons/src/test/java/eu/etaxonomy/cdm/common/CdmUtilsTest.java
9 9

  
10 10
package eu.etaxonomy.cdm.common;
11 11

  
12
import static org.junit.Assert.assertNotNull;
13

  
14
import java.io.File;
15
import java.io.IOException;
16
import java.io.InputStream;
17 12
import java.util.regex.Pattern;
18 13

  
19 14
import org.apache.log4j.Level;
......
42 37

  
43 38
/************************** TESTS ****************************************/
44 39

  
45
	@Test
46
	public void testGetReadableResourceStream() {
47
		String resourceFileName = CdmUtils.MUST_EXIST_FILE;
48
		try {
49
			InputStream inputStream = CdmUtils.getReadableResourceStream(resourceFileName);
50
			assertNotNull(inputStream);
51
		} catch (IOException e) {
52
			Assert.fail("IOException");
53
		}
54
	}
55

  
56
	@Test
57
	public void testGetFolderSeperator() {
58
		Assert.assertEquals(File.separator, CdmUtils.getFolderSeperator());
59
	}
60

  
61
	@Test
62
	public void testGetHomeDir() {
63
		//Assert.assertEquals("", CdmUtils.getHomeDir());
64
	}
65

  
66 40
	@Test
67 41
	public void testFindLibrary() {
68 42
		if (logger.isEnabledFor(Level.DEBUG)) {logger.debug(CdmUtils.findLibrary(CdmUtils.class));}
cdmlib-commons/src/test/java/eu/etaxonomy/cdm/common/ConfigFileUtilTest.java
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

  
10
package eu.etaxonomy.cdm.common;
11

  
12
import static org.junit.Assert.assertNotNull;
13

  
14
import java.io.File;
15
import java.io.IOException;
16
import java.io.InputStream;
17

  
18
import org.junit.Assert;
19
import org.junit.Ignore;
20
import org.junit.Test;
21

  
22

  
23
public class ConfigFileUtilTest {
24

  
25
	@Test
26
	public void testGetReadableResourceStream() {
27
		String resourceFileName = ConfigFileUtil.MUST_EXIST_FILE;
28
		try {
29
			InputStream inputStream = CdmUtils.getReadableResourceStream(resourceFileName);
30
			assertNotNull(inputStream);
31
		} catch (IOException e) {
32
			Assert.fail("IOException");
33
		}
34
	}
35

  
36
	@Test
37
	public void testGetFolderSeperator() {
38
		Assert.assertEquals(File.separator, ConfigFileUtil.getFolderSeperator());
39
	}
40

  
41
	@Test
42
	@Ignore
43
	public void testGetHomeDir() {
44
		Assert.assertEquals("", ConfigFileUtil.getCdmHomeDir());
45
	}
46

  
47

  
48
}
cdmlib-io/src/main/java/eu/etaxonomy/cdm/io/dwca/out/TermMapping.java
19 19

  
20 20
import au.com.bytecode.opencsv.CSVReader;
21 21
import eu.etaxonomy.cdm.common.CdmUtils;
22
import eu.etaxonomy.cdm.common.ConfigFileUtil;
22 23

  
23 24
/**
24 25
 * @author a.mueller
......
44 45

  
45 46

  
46 47
	private void readMapping(String filename) throws IOException {
47
		String strResourceFileName = "mapping" + CdmUtils.getFolderSeperator() + filename;
48
		String strResourceFileName = "mapping" + ConfigFileUtil.getFolderSeperator() + filename;
48 49
		InputStreamReader isr = CdmUtils.getUtf8ResourceReader(strResourceFileName);
49 50
		CSVReader reader = new CSVReader(isr, separator);
50 51

  
cdmlib-model/src/main/java/eu/etaxonomy/cdm/model/term/init/TermLoader.java
24 24

  
25 25
import au.com.bytecode.opencsv.CSVReader;
26 26
import eu.etaxonomy.cdm.common.CdmUtils;
27
import eu.etaxonomy.cdm.common.ConfigFileUtil;
27 28
import eu.etaxonomy.cdm.model.term.DefinedTermBase;
28 29
import eu.etaxonomy.cdm.model.term.OrderedTermBase;
29 30
import eu.etaxonomy.cdm.model.term.OrderedTermVocabulary;
......
196 197
	 */
197 198
	private CSVReader getCsvReader(VocabularyEnum vocType) throws IOException {
198 199
		String filename = vocType.name()+".csv";
199
		String strResourceFileName = "terms" + CdmUtils.getFolderSeperator() + filename;
200
		String strResourceFileName = "terms" + ConfigFileUtil.getFolderSeperator() + filename;
200 201
		if (logger.isDebugEnabled()){logger.debug("strResourceFileName is " + strResourceFileName);}
201 202
		CSVReader reader = new CSVReader(CdmUtils.getUtf8ResourceReader(strResourceFileName));
202 203
		return reader;
cdmlib-persistence/src/main/java/eu/etaxonomy/cdm/api/application/CdmApplicationUtils.java
18 18
import org.apache.log4j.Logger;
19 19

  
20 20
import eu.etaxonomy.cdm.common.CdmUtils;
21
import eu.etaxonomy.cdm.common.ConfigFileUtil;
21 22
import eu.etaxonomy.cdm.common.FileCopy;
22 23
import eu.etaxonomy.cdm.config.CdmPersistentXMLSource;
23 24

  
......
51 52
                if (file.exists()){
52 53
                    fileResourceDir = file.getParentFile();
53 54
                }else{
54
                    file = new File(CdmUtils.getCdmHomeDir(), "writableResources" );
55
                    file = new File(ConfigFileUtil.getCdmHomeDir(), "writableResources" );
55 56

  
56 57
                    file.mkdirs();
57 58
                    copyResources(file);
cdmlib-persistence/src/main/java/eu/etaxonomy/cdm/database/DataSourceBeanLoader.java
8 8
import org.springframework.core.io.FileSystemResource;
9 9
import org.springframework.stereotype.Component;
10 10

  
11
import eu.etaxonomy.cdm.common.CdmUtils;
11
import eu.etaxonomy.cdm.common.ConfigFileUtil;
12 12

  
13 13
@Component
14 14
public class DataSourceBeanLoader {
......
16 16
    private static final Logger logger = Logger.getLogger(DataSourceBeanLoader.class);
17 17

  
18 18
    private static final String DATASOURCE_BEANDEF_FILE = "datasources.xml";
19
    private static final String DATASOURCE_BEANDEF_PATH = CdmUtils.getCdmHomeDir().getPath();
19
    private static final String DATASOURCE_BEANDEF_PATH = ConfigFileUtil.getCdmHomeDir().getPath();
20 20

  
21 21
    private static String userdefinedBeanDefinitionFile = null;
22 22

  
......
41 41
            T datasource = beanFactory.getBean(beanName, requiredType);
42 42
            dataSources.put(beanName, datasource);
43 43
        }
44
        return (Map<String, T>) dataSources;
44
        return dataSources;
45 45
    }
46 46

  
47 47
}
cdmlib-persistence/src/main/java/eu/etaxonomy/cdm/database/update/v31_33/TermVocabularyRepresentationUpdater.java
17 17

  
18 18
import au.com.bytecode.opencsv.CSVReader;
19 19
import eu.etaxonomy.cdm.common.CdmUtils;
20
import eu.etaxonomy.cdm.common.ConfigFileUtil;
20 21
import eu.etaxonomy.cdm.common.monitor.IProgressMonitor;
21 22
import eu.etaxonomy.cdm.database.ICdmDataSource;
22 23
import eu.etaxonomy.cdm.database.update.CaseType;
......
66 67
			for(VocabularyEnum vocabularyEnum : VocabularyEnum.values()) {
67 68
				//read vocabulary from terms files
68 69
				String filename = vocabularyEnum.name()+".csv";
69
				CSVReader reader = new CSVReader(CdmUtils.getUtf8ResourceReader("terms" + CdmUtils.getFolderSeperator() + filename));
70
				CSVReader reader = new CSVReader(CdmUtils.getUtf8ResourceReader("terms" + ConfigFileUtil.getFolderSeperator() + filename));
70 71
				String [] nextLine = reader.readNext();
71 72
				TermVocabulary<?> voc = TermVocabulary.NewInstance(TermType.Unknown);
72 73
				voc.readCsvLine(arrayedLine(nextLine));
cdmlib-print/src/main/java/eu/etaxonomy/cdm/print/out/IPublishOutputModule.java
15 15

  
16 16
import org.jdom.Document;
17 17

  
18
import eu.etaxonomy.cdm.common.CdmUtils;
19 18
import eu.etaxonomy.cdm.common.monitor.IProgressMonitor;
20 19

  
21 20

  
......
49 48

  
50 49
    /**
51 50
     * Returns all available stylesheets for this output module.
52
     * Search path will include the users {@link CdmUtils.perUserCdmFolder} directory to allow for custom stylesheets
51
     * Search path will include the users {@link ConfigFileUtil.perUserCdmFolder()} directory to allow for custom stylesheets
53 52
     *
54 53
     * @return a set of xsl files
55 54
     * @throws IOException TODO
cdmlib-print/src/main/java/eu/etaxonomy/cdm/print/out/PublishOutputModuleBase.java
25 25
import org.apache.log4j.Logger;
26 26
import org.jdom.Document;
27 27

  
28
import eu.etaxonomy.cdm.common.CdmUtils;
28
import eu.etaxonomy.cdm.common.ConfigFileUtil;
29 29
import eu.etaxonomy.cdm.common.monitor.IProgressMonitor;
30 30

  
31 31
/**
32 32
 * This abstract implementation of the {@link IPublishOutputModule} contains
33 33
 * convenience methods for file path generation. Clients should consider
34 34
 * extending this class.
35
 * 
35
 *
36 36
 * @author n.hoffmann
37 37
 * @since Apr 20, 2010
38 38
 * @version 1.0
......
61 61
	/**
62 62
	 * Generates a string containing the current date followed by the given
63 63
	 * name.
64
	 * 
64
	 *
65 65
	 * @param name
66 66
	 *            a string.
67 67
	 * @return a string containing the current date followed by the given name.
......
95 95
		 */
96 96
		if (filePath == null) {
97 97
			filePath = getNewFilePath(outputFolder);
98
		} 
98
		}
99 99
			return filePath;
100 100
	}
101 101

  
102 102
	/**
103
	 * @return the complete path to the output file 
103
	 * @return the complete path to the output file
104 104
	 * @author s.buers
105 105
	 */
106 106
	public String getFilePath() {
107 107
		return filePath;
108 108
	}
109
	
109

  
110 110
	/**
111 111
	 * creates new name for the output file based on the given output
112
	 * folder and actual timestamp. 
112
	 * folder and actual timestamp.
113 113
	 * @author s.buers
114 114
	 * @param outputFolder
115 115
	 * @return
......
125 125

  
126 126
	/*
127 127
	 * (non-Javadoc)
128
	 * 
128
	 *
129 129
	 * @see
130 130
	 * eu.etaxonomy.printpublisher.out.IPublishOutputModule#output(org.jdom.
131 131
	 * Document, java.io.File)
132 132
	 */
133
	public void output(Document document, File exportFolder,
133
	@Override
134
    public void output(Document document, File exportFolder,
134 135
			IProgressMonitor progressMonitor) {
135 136
		if (progressMonitor == null) {
136 137
			throw new IllegalArgumentException(
......
173 174
		locationList.add(shippedStylesheetsDir);
174 175

  
175 176
		// TODO this should be configured in a central place, see #2387
176
		File userdir = new File(CdmUtils.perUserCdmFolder + l + "stylesheets"
177
		File userdir = new File(ConfigFileUtil.perUserCdmFolder() + l + "stylesheets"
177 178
				+ l + getOutputFileSuffix());
178 179
		locationList.add(userdir);
179 180

  
cdmlib-print/src/main/java/eu/etaxonomy/cdm/print/out/mediawiki/Cdm2MediawikiExporter.java
24 24
import org.jdom.output.XMLOutputter;
25 25
import org.jdom.xpath.XPath;
26 26

  
27
import eu.etaxonomy.cdm.common.CdmUtils;
27
import eu.etaxonomy.cdm.common.ConfigFileUtil;
28 28
import eu.etaxonomy.cdm.common.monitor.DefaultProgressMonitor;
29 29
import eu.etaxonomy.cdm.print.IXMLEntityFactory;
30 30
import eu.etaxonomy.cdm.print.PublishConfigurator;
......
34 34
/**
35 35
 * fill in all parameters and you get a complete export from a cdm database to a
36 36
 * mediawiki
37
 * 
37
 *
38 38
 * TODO would we move this class somewhere else and/or rename it?
39
 * 
39
 *
40 40
 * @author s.buers, l.morris
41
 * 
41
 *
42 42
 */
43 43
public class Cdm2MediawikiExporter {
44 44

  
......
62 62
			.getLogger(Cdm2MediawikiExporter.class);
63 63

  
64 64
	private PublishConfigurator configurator = PublishConfigurator.NewRemoteInstance();
65
			
65

  
66 66
	private IXMLEntityFactory factory;
67 67

  
68 68
	// where the mediawiki xml code is stored
......
80 80

  
81 81
	private List<String> localImages;
82 82

  
83
	
83

  
84 84
	public void export(String serviceUrl, UUID taxonNodeUuid, UUID treeNodeUuid,  String wikiUrl,
85 85
			String wikiLoginUid, String passwd, String wikiPageNamespace,
86 86
			boolean import2Mediawiki, boolean deleteOutputFiles,
......
92 92
	/**
93 93
	 * does the whole export process: runs cdm export to mediawiki xml-file and
94 94
	 * wiki import of this file
95
	 * 
95
	 *
96 96
	 * @param serviceUrl
97 97
	 * @param taxonName
98 98
	 * @param wikiUrl
......
105 105
	 *            - prefix that, will be added to all pages null or "" will make
106 106
	 *            no prefix
107 107
	 * @throws MalformedURLException
108
	 * 
108
	 *
109 109
	 *             TODO: make passwd "unplain" MAYDO: pass more parameters e.g.:
110 110
	 *             alternative stylesheet layout parameters (that may force the
111 111
	 *             use of different stylesheet) export folder - we use a
......
124 124
				// setup configurator
125 125
		setupConfigurator(serviceUrl);
126 126
		configurator.addSelectedTaxonNodeElements(factory.getTaxonNodesByName(taxonName, classificationName));
127
		
128
		
127

  
128

  
129 129
		export(portalUrl, serviceUrl, wikiUrl, wikiLoginUid, passwd,
130 130
				wikiPageNamespace, import2Mediawiki, deleteOutputFiles,
131 131
				importImages, true);
132 132
	}
133 133
	/**
134
	 * if you already have a cdm xml export in some file you put it in here 
134
	 * if you already have a cdm xml export in some file you put it in here
135 135
	 * the mediawiki xml is created and imported to an mediawiki
136 136
	 * does step 2 and 3 out of all 3 export steps
137
	 * 
137
	 *
138 138
	 * @param filename
139 139
	 * @param serviceUrl
140 140
	 * @param taxonName
......
156 156

  
157 157
		//put the document to a field:
158 158
		externalDocument = getDocument(filename);
159
		
159

  
160 160
//		setupConfigurator(serviceUrl);
161
		
161

  
162 162
		// and run export with usePublisher=false:
163 163
		export(portalUrl, serviceUrl, wikiUrl, wikiLoginUid, passwd,
164 164
				wikiPageNamespace, import2Mediawiki, deleteOutputFiles,
......
191 191
		// page
192 192
		// then it will be the same as the username that is used for the actual
193 193
		// mediawiki import.
194
		((MediawikiOutputModule) wikiOutputModule).setUsername(wikiLoginUid);
194
		wikiOutputModule.setUsername(wikiLoginUid);
195 195

  
196 196
		// if we actually export from the cdm and not from a file we run the
197 197
		// Publisher
......
215 215
		}
216 216

  
217 217
		// we get the whole filename that the wikiOutputModule created
218
		mediawikiFileWithPath = ((MediawikiOutputModule) wikiOutputModule)
218
		mediawikiFileWithPath = wikiOutputModule
219 219
				.getFilePath();
220 220

  
221 221
		logger.info("mediawiki xml file created and saved to"+mediawikiFileWithPath);
......
224 224
		if ((usePublisher && !deleteOutputFiles) || importImages) {
225 225
			// the cdm output where we want to fetch the urls of the
226 226
			// images:
227
			cdmOutputDocument = ((MediawikiOutputModule) wikiOutputModule)
227
			cdmOutputDocument = wikiOutputModule
228 228
					.getInputDocument();
229 229
		}
230 230

  
......
245 245
		else{
246 246
			logger.info("did not get images!");
247 247
		}
248
		
248

  
249 249
		if (import2Mediawiki && importImages && !(localImages.isEmpty())) {
250 250
			uploadImagesToMediawiki(wikiUrl, wikiLoginUid, passwd);
251 251
		}
252
		
252

  
253 253
		if (deleteOutputFiles) {
254 254
			deleteOutputFiles();
255 255
			logger.info("deleted temporary file(s)");
......
257 257
	}
258 258

  
259 259
	/**
260
	 * 
260
	 *
261 261
	 */
262 262
	private void createTemporaryExportFolder() {
263
		temporaryExportFolder = CdmUtils.getCdmHomeSubDir(MEDIAWIKI_CDM_SUB_DIR);
263
		temporaryExportFolder = ConfigFileUtil.getCdmHomeSubDir(MEDIAWIKI_CDM_SUB_DIR);
264 264
		if (temporaryExportFolder != null) {
265 265
			logger.info("using " + temporaryExportFolder.getAbsolutePath()
266 266
					+ " as temporary directory.");
......
277 277
	 */
278 278
	private void setupConfigurator(String serviceUrl)
279 279
			throws MalformedURLException {
280
		
280

  
281 281
		createTemporaryExportFolder();
282
		
282

  
283 283
		configurator.setWebserviceUrl(serviceUrl);
284 284
		factory = configurator.getFactory();
285 285

  
286 286
		// get feature tree from taxon name/taxon node and pass it to the
287 287
		// configurator:
288
		// TODO, get a feature tree name or uuid as method parameters 
288
		// TODO, get a feature tree name or uuid as method parameters
289 289
		String featureTree = getDefaultFeatureTree();
290 290
		configurator.setFeatureTree(UUID.fromString(featureTree));
291 291

  
......
324 324
		//JDOMParseException Invalid byte 2 of 3-byte UTF-8 sequence which occurs for e.g.
325 325
		//with German umlauts and French accents on characters
326 326
		format.setEncoding("ISO-8859-1");//"UTF-8");
327
		XMLOutputter xmlOutput = new XMLOutputter(format);	
328
		xmlOutput.setFormat(format);		
327
		XMLOutputter xmlOutput = new XMLOutputter(format);
328
		xmlOutput.setFormat(format);
329 329

  
330 330
		try {
331
			xmlOutput.output(cdmOutputDocument, new FileWriter(cdm_output_file));			
332
                    
331
			xmlOutput.output(cdmOutputDocument, new FileWriter(cdm_output_file));
332

  
333 333
		} catch (IOException e) {
334 334
			// TODO Auto-generated catch block
335 335
			e.printStackTrace();
......
353 353
	/**
354 354
	 * uploads a given mediawiki xml file to a mediawiki - does only third (last) step
355 355
	 * of the whole export process
356
	 * 
356
	 *
357 357
	 * @param inputFilePath
358 358
	 * @param wikiUrl
359 359
	 * @param wikiUser
......
372 372
	private void uploadToMediawiki(String wikiUrl, String wikiLoginUid, String passwd) {
373 373

  
374 374
		// login to mediawiki
375
		
375

  
376 376
		WikiBot myBot = getBotAndLogin(wikiUrl, wikiLoginUid, passwd);
377 377

  
378
		
378

  
379 379
		try {
380 380

  
381 381
			// parse wiki xml file and import pages one by one
......
437 437
	private void downloadImages() {
438 438
		org.jdom.Document document = wikiOutputModule.getInputDocument();
439 439
		localImages = new ArrayList<String>();
440
		
440

  
441 441
		try {
442 442
			List<Element> media_uris = XPath.selectNodes(document, "//Taxon/media/e/representations/e/parts/e/uri");
443
		
443

  
444 444
			if(media_uris.isEmpty()){
445 445
				logger.info("there are no images in the data.");
446 446
				return;
447 447
			}
448
			
448

  
449 449
			for (Element urlEl : media_uris) {
450 450
				String url=urlEl.getValue();
451 451
				URL imageUrl = new URL(url);
......
456 456
				String filePath = temporaryExportFolder.getAbsolutePath()
457 457
						+FILESEPARATOR + IMAGES_FOLDER +FILESEPARATOR+ filename;
458 458
				logger.info("downloading image " + url+" to "+filePath);
459
				
459

  
460 460
				FileUtils.copyURLToFile(imageUrl, new File(filePath));
461 461
				localImages.add(filePath);
462 462
			}
463
		
463

  
464 464
		} catch (JDOMException e) {
465 465
			// TODO Auto-generated catch block
466 466
			e.printStackTrace();
......
471 471
			// TODO Auto-generated catch block
472 472
			e.printStackTrace();
473 473
		}
474
		
474

  
475 475
	}
476 476

  
477 477
	private void uploadImagesToMediawiki(String wikiUrl, String wikiLoginUid, String passwd) {
478
		WikiBot myBot = getBotAndLogin(wikiUrl, wikiLoginUid, passwd); 
478
		WikiBot myBot = getBotAndLogin(wikiUrl, wikiLoginUid, passwd);
479 479
		// get published output file
480
		
481 480

  
482
			for(String localUri : localImages){						
483
				
481

  
482
			for(String localUri : localImages){
483

  
484 484
				try {
485 485
					uploadImage(myBot, localUri);
486 486
				} catch (MalformedURLException e) {
......
492 492
				}
493 493
			}
494 494

  
495
			// logout		
495
			// logout
496 496
		myBot.logout();
497 497
		logger.info("all images uploaded to mediawiki "+wikiUrl+" and logged out.");
498 498
	}
......
517 517
////		System.out.println(filePath);
518 518
//		File imageFile = new File(filePath);
519 519
//		logger.info("downloading image " + url);
520
		
520

  
521 521
//		FileUtils.copyURLToFile(imageUrl, new File(filePath));
522
		
523
		
522

  
523

  
524 524
		File imageFile = new File(filePath);
525 525
		String[] arr = filePath.split("/");
526 526
		String filename = arr[arr.length - 1];
......
536 536
	}
537 537

  
538 538
	private Document getDocument(String filePath) {
539
		SAXBuilder saxBuilder = new SAXBuilder();		
540
		
539
		SAXBuilder saxBuilder = new SAXBuilder();
540

  
541 541
		File file = new File(filePath);
542 542
		Document document = null;
543 543
		FileInputStream fileis;
......
546 546
		try {
547 547
			//document = saxBuilder.build(file);
548 548
			fileis = new FileInputStream(file);
549
			BufferedInputStream in = new BufferedInputStream(fileis); 
549
			BufferedInputStream in = new BufferedInputStream(fileis);
550 550
			document = saxBuilder.build(in);
551
			
551

  
552 552
		} catch (JDOMException e) {
553 553
			// TODO Auto-generated catch block
554 554
			logger.error(e.getCause().getMessage());
cdmlib-remote/src/main/java/eu/etaxonomy/cdm/opt/config/DataSourceConfigurer.java
40 40
import com.mchange.v2.c3p0.ComboPooledDataSource;
41 41

  
42 42
import eu.etaxonomy.cdm.api.config.CdmConfigurationKeys;
43
import eu.etaxonomy.cdm.common.CdmUtils;
43
import eu.etaxonomy.cdm.common.ConfigFileUtil;
44 44
import eu.etaxonomy.cdm.database.WrappedCdmDataSource;
45 45
import eu.etaxonomy.cdm.database.update.CdmUpdater;
46 46
import eu.etaxonomy.cdm.model.metadata.CdmMetaData;
......
125 125
     */
126 126
    public static final String ATTRIBUTE_FORCE_SCHEMA_UPDATE = "cdm.forceSchemaUpdate";
127 127

  
128
    protected static final String DATASOURCE_BEANDEF_DEFAULT = CdmUtils.getCdmHomeDir().getPath() + File.separator + "datasources.xml";
128
    protected static final String DATASOURCE_BEANDEF_DEFAULT = ConfigFileUtil.getCdmHomeDir().getPath() + File.separator + "datasources.xml";
129 129

  
130 130
    protected static String beanDefinitionFile = DATASOURCE_BEANDEF_DEFAULT;
131 131

  
......
345 345
    public Properties hibernateProperties(){
346 346
        Properties props = getHibernateProperties();
347 347
        props.setProperty(HIBERNATE_DIALECT, inferHibernateDialectName());
348
        String searchPath = CdmUtils.getCdmHomeSubDir(CdmUtils.SUBFOLDER_WEBAPP).getPath();
348
        String searchPath = ConfigFileUtil.getCdmHomeSubDir(ConfigFileUtil.SUBFOLDER_WEBAPP).getPath();
349 349
        props.setProperty(HIBERNATE_SEARCH_DEFAULT_INDEX_BASE,
350 350
                searchPath +
351 351
                "/index/".replace("/", File.separator) +
cdmlib-remote/src/main/java/eu/etaxonomy/cdm/opt/config/EhCacheDiskStoreConfiguration.java
15 15
import org.springframework.context.annotation.Bean;
16 16
import org.springframework.context.annotation.Configuration;
17 17

  
18
import eu.etaxonomy.cdm.common.CdmUtils;
18
import eu.etaxonomy.cdm.common.ConfigFileUtil;
19 19
import net.sf.ehcache.config.DiskStoreConfiguration;
20 20

  
21 21
/**
......
35 35
    public DiskStoreConfiguration diskStoreConfiguration(){
36 36

  
37 37
        DiskStoreConfiguration diskStoreConfiguration = new DiskStoreConfiguration();
38
        File ehcacheFolder = CdmUtils.getCdmHomeSubDir("ehcache");
38
        File ehcacheFolder = ConfigFileUtil.getCdmHomeSubDir("ehcache");
39 39
        String instanceName = dataSourceProperties.getCurrentDataSourceId();
40 40
        File instanceCacheFolder = new File(ehcacheFolder, instanceName);
41 41
        logger.debug("Setting ehcache diskstore location to " + instanceCacheFolder.getAbsolutePath());
cdmlib-remote/src/main/java/eu/etaxonomy/cdm/remote/config/AbstractWebApplicationConfigurer.java
21 21
import org.springframework.core.env.ConfigurableEnvironment;
22 22
import org.springframework.web.context.WebApplicationContext;
23 23

  
24
import eu.etaxonomy.cdm.common.CdmUtils;
24
import eu.etaxonomy.cdm.common.ConfigFileUtil;
25 25

  
26 26
/**
27 27
 * @author a.kohlbecker
......
51 51
            userDefinedProperties = new Properties();
52 52
            try {
53 53
                InputStream in = new FileInputStream(
54
                            CdmUtils.perUserCdmFolder
54
                            ConfigFileUtil.perUserCdmFolder()
55 55
                            + java.io.File.separator
56 56
                            + CDMLIB_REMOTE_PROPERTIES
57 57
                    );
cdmlib-remote/src/main/java/eu/etaxonomy/cdm/remote/config/MultiWebSecurityConfiguration.java
25 25
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
26 26
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
27 27

  
28
import eu.etaxonomy.cdm.common.CdmUtils;
28
import eu.etaxonomy.cdm.common.ConfigFileUtil;
29 29

  
30 30
/**
31 31
 *
......
135 135
        // Add an inMemoryUserManager to  enable access to the global ROLE_MANAGE_CLIENTs.
136 136
        // This is the casue for the need to do the configuration explicitly.
137 137
        InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder> inMemoryAuthConf = auth.inMemoryAuthentication();
138
        File managingUsersFile = new File(CdmUtils.getCdmHomeDir(), MANAGING_USERS_PROPERTIES);
138
        File managingUsersFile = new File(ConfigFileUtil.getCdmHomeDir(), MANAGING_USERS_PROPERTIES);
139 139
        if(!managingUsersFile.exists()){
140 140
            makeManagingUsersPropertiesFile(managingUsersFile);
141 141
        }

Also available in: Unified diff