Project

General

Profile

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

    
11
import java.io.BufferedWriter;
12
import java.io.File;
13
import java.io.FileInputStream;
14
import java.io.FileNotFoundException;
15
import java.io.IOException;
16
import java.net.URL;
17
import java.nio.file.Files;
18
import java.util.Properties;
19

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

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

    
26
/**
27
 *
28
 * @author a.kohlbecker
29
 * @since May 8, 2017
30
 *
31
 */
32
public class ConfigFileUtil implements EnvironmentAware {
33

    
34
    private static final Logger logger = Logger.getLogger(ConfigFileUtil.class);
35

    
36
    private static String userHome = null;
37

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

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

    
48
    public static File perUserCdmFolder() {
49
        return perUserCdmFolder;
50
    }
51

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

    
59
    static final String MUST_EXIST_FILE = "MUST-EXIST.txt";
60

    
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
    //folder separator
75
    static String folderSeparator;
76

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

    
92

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

    
101

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

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

    
117
        File parentFolder = getCdmHomeDir();
118
        return ensureSubfolderExists(parentFolder, subFolderName);
119
    }
120

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

    
135
        File subfolder = ensureSubfolderExists(getCdmHomeDir(), subFolderName);
136
        return ensureSubfolderExists(subfolder, instanceName);
137
    }
138

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

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

    
162
    private Properties props = null;
163

    
164
    private String defaultContent = "";
165

    
166
    public ConfigFileUtil(){
167

    
168
    }
169

    
170
    public ConfigFileUtil setDefaultContent(String content) {
171
        if(content != null){
172
            defaultContent = content;
173
        }
174
        return this;
175
    }
176

    
177
    /**
178
     * Per default the <code>propertiesSet</code> is loaded from a file located in
179
     * <code>~/.cdmLibrary/remote-webapp/{instanceName}/{propertiesSet}.properties</code>.
180
     * <p>
181
     * This behavior can be overwritten by setting the java System property
182
     * <code>cdm.configfile.override.{propertiesSet}</code> to an alternative file location.
183
     * This mechanism should only be used for unit and integration tests.
184
     *
185
     * @param instanceName the name of the cdm instance. This value can be retrieved from the
186
     *      Spring environment with the key DataSourceConfigurer.CDM_DATA_SOURCE_ID ("")
187
     * @param propertiesSet
188
     *      The base name of the properties file to be loaded. This name is extended with
189
     *      ".properties" to form the actual filename
190
     *
191
     * @return
192
     *      The file containing the properties
193
     */
194
    public File getPropertiesFile(String instanceName, String propertiesSet) {
195

    
196
        if(propertiesSet == null){
197
            throw new NullPointerException();
198
        }
199
        String override = System.getProperty(CDM_CONFIGFILE_OVERRIDE + propertiesSet);
200
        if(override != null){
201
            return new File(override);
202
        } else {
203
            File configFolder = ConfigFileUtil.getCdmInstanceSubDir(ConfigFileUtil.SUBFOLDER_WEBAPP, instanceName);
204
            return new File(configFolder, propertiesSet + ".properties");
205
        }
206
    }
207

    
208
    /**
209
     * Per default the <code>propertiesSet</code> is loaded from a file located in
210
     * <code>~/.cdmLibrary/remote-webapp/{instanceName}/{propertiesSet}.properties</code>.
211
     * <p>
212
     * This behavior can be overwritten by setting the java System property
213
     * <code>cdm.configfile.override.{propertiesSet}</code> to an alternative file location.
214
     * This mechanism should only be used for unit and integration tests.
215
     *
216
     * @param instanceName the name of the cdm instance. This value can be retrieved from the
217
     *      Spring environment with the key DataSourceConfigurer.CDM_DATA_SOURCE_ID ("")
218
     * @param propertiesSet
219
     *      The base name of the properties file to be loaded. This name is extended with
220
     *      ".properties" to form the actual filename
221
     *
222
     * @return
223
     *      The properties loaded from the file
224
     */
225
    public Properties getProperties(String instanceName, String propertiesName) throws IOException {
226

    
227
        if(instanceName == null){
228
            throw new NullPointerException();
229
        }
230
        if(props == null){
231
            props = new Properties();
232
            File uiPropertiesFile = getPropertiesFile(instanceName, propertiesName);
233
            if(!uiPropertiesFile.exists()){
234
                BufferedWriter writer = Files.newBufferedWriter(uiPropertiesFile.toPath());
235
                writer.write(defaultContent);
236
                writer.close();
237
            }
238
            try {
239
                props.load(new FileInputStream(uiPropertiesFile));
240
            } catch (FileNotFoundException e) {
241
                // must not happen since we checked before
242
            }
243

    
244
        }
245
        return props;
246
    }
247
}
(8-8/11)