Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that implements properties methods for metacat
4
 *  Copyright: 2008 Regents of the University of California and the
5
 *             National Center for Ecological Analysis and Synthesis
6
 *    Authors: Michael Daigle
7
 *
8
 *   '$Author: daigle $'
9
 *     '$Date: 2009-01-20 10:09:29 -0800 (Tue, 20 Jan 2009) $'
10
 * '$Revision: 4766 $'
11
 *
12
 * This program is free software; you can redistribute it and/or modify
13
 * it under the terms of the GNU General Public License as published by
14
 * the Free Software Foundation; either version 2 of the License, or
15
 * (at your option) any later version.
16
 *
17
 * This program is distributed in the hope that it will be useful,
18
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
 * GNU General Public License for more details.
21
 *
22
 * You should have received a copy of the GNU General Public License
23
 * along with this program; if not, write to the Free Software
24
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
25
 */
26

    
27
package edu.ucsb.nceas.metacat.service;
28

    
29
import java.io.IOException;
30
import java.util.Map;
31
import java.util.Set;
32
import java.util.Vector;
33

    
34
import javax.servlet.ServletContext;
35
import javax.servlet.http.HttpServletRequest;
36
import javax.xml.transform.TransformerException;
37

    
38
import org.apache.log4j.Logger;
39

    
40
import edu.ucsb.nceas.metacat.util.SystemUtil;
41
import edu.ucsb.nceas.metacat.util.UtilException;
42
import edu.ucsb.nceas.utilities.FileUtil;
43
import edu.ucsb.nceas.utilities.GeneralPropertyException;
44
import edu.ucsb.nceas.utilities.MetaDataProperty;
45
import edu.ucsb.nceas.utilities.PropertiesMetaData;
46
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
47
import edu.ucsb.nceas.utilities.SortedProperties;
48

    
49
/**
50
 * A suite of utility classes for the metadata configuration utility
51
 */
52
public class PropertyService extends BaseService {
53
	
54
	private static PropertyService propertyService = null;
55
	
56
	// system is configured
57
	public static final String CONFIGURED = "true"; 
58
	// system has never been configured
59
	public static final String UNCONFIGURED = "false"; 
60
	public static final String BYPASSED = "bypassed";
61
	
62
	private static final String MAIN_CONFIG_NAME = "metacat.properties";
63
	private static final String AUTH_CONFIG_NAME = "auth.properties";
64
	
65
	private static boolean bypassAlreadyChecked = false;
66
	
67
	private static String mainPropertiesFilePath = null;
68
	private static SortedProperties mainProperties = null;
69
	
70
	private static String mainBackupPropertiesFilePath = null;
71
	private static SortedProperties mainBackupProperties = null;
72
	
73
	private static String propertiesMetaDataFilePath = null;
74
	private static PropertiesMetaData mainMetaData = null;
75
	
76
	private static String authBackupPropertiesFilePath = null;
77
	private static SortedProperties authBackupProperties = null;
78
	
79
	private static String authMetaDataFilePath = null;
80
	private static PropertiesMetaData authMetaData = null;
81
	
82
	private static boolean testInstance = false;
83
	private static String testConfigDir = null;
84
	
85
	private static Logger logMetacat = Logger.getLogger(PropertyService.class);
86

    
87
	/**
88
	 * private constructor since this is a singleton
89
	 * 
90
	 * @param servletContext the context we will use to get relative paths
91
	 */
92
	private PropertyService() throws ServiceException {
93
		try {
94
			initialize();
95
		} catch (GeneralPropertyException gpe) {
96
			throw new ServiceException("Properties problem while initializing " + 
97
					"PropertyService: " + gpe.getMessage());
98
		} catch (IOException ioe) {
99
			throw new ServiceException("I/O Problem while initializing " + 
100
					"PropertyService: " + ioe.getMessage());
101
		}
102
	}
103
	
104
	/**
105
	 * Get the single instance of PropertyService.
106
	 * 
107
	 * @return the single instance of PropertyService
108
	 */
109
	public static PropertyService getInstance() throws ServiceException {
110
		if (propertyService == null) {
111
			
112
			propertyService = new PropertyService();
113
		}
114
		return propertyService;
115
	}
116
	
117
	/**
118
	 * Get the single instance of PropertyService for test purposes.  In this
119
	 * case, we allow the configuration directory to be passed in.
120
	 * 
121
	 * @param configDir the configuration directory we need to look in
122
	 * @return the single instance of PropertyService
123
	 */
124
	public static PropertyService getTestInstance(String configDir) throws ServiceException {
125
		if (propertyService == null) {
126
			
127
			testInstance = true;
128
			testConfigDir = configDir;
129
			
130
			propertyService = new PropertyService();
131
		}
132
		return propertyService;
133
	}
134
	
135
	public boolean refreshable() {
136
		return true;
137
	}
138
	
139
	protected void doRefresh() throws ServiceException {
140
		try {
141
			initialize();
142
		} catch (IOException ioe) {
143
			throw new ServiceException("Could not refresh SkinPropertyService due to"
144
					+ " I/O error: " + ioe.getMessage());
145
		} catch (GeneralPropertyException gpe) {
146
			throw new ServiceException("Could not refresh SkinPropertyService due to"
147
					+ " property error: " + gpe.getMessage());
148
		}
149
	}
150
	
151
	/**
152
	 * Initialize the singleton.
153
	 * 
154
	 * @param servletContext the context we will use to get relative paths
155
	 */
156
	private void initialize()
157
			throws IOException, GeneralPropertyException, ServiceException {
158
		
159
		logMetacat.debug("Initializing PropertyService");
160
		
161
		String configDir;
162
		if (testInstance) {
163
			configDir = testConfigDir;
164
		} else {
165
			configDir = ServiceService.getRealConfigDir();
166
		}
167

    
168
		// mainProperties will hold the primary configuration values for metacat.
169
		mainPropertiesFilePath = configDir + FileUtil.getFS() + MAIN_CONFIG_NAME;
170
		mainProperties = new SortedProperties(mainPropertiesFilePath);
171
		mainProperties.load();
172

    
173
		try {
174
			// mainMetaData holds configuration information about main properties.
175
			// This is primarily used to display input fields on the configuration
176
			// page. The information is retrieved from an xml metadata file
177
			propertiesMetaDataFilePath = configDir + FileUtil.getFS() + MAIN_CONFIG_NAME + ".metadata.xml";
178
			mainMetaData = new PropertiesMetaData(propertiesMetaDataFilePath);
179

    
180
			// authMetaData holds configuration information about organization level 
181
			// properties.  This is primarily used to display input fields on 
182
			// the auth configuration page. The information is retrieved 
183
			// from an xml metadata file dedicated just to auth properties.
184
			authMetaDataFilePath = configDir + FileUtil.getFS() + AUTH_CONFIG_NAME + ".metadata.xml";
185
			authMetaData = new PropertiesMetaData(authMetaDataFilePath);
186
		} catch (TransformerException te) {
187
			throw new GeneralPropertyException(te.getMessage());
188
		}
189
		
190
		String backupBasePath = getProperty("application.backupDir");
191
		
192
		// If the backupBasePath does not exist in metacat.properties, see if we can discover it.
193
		if (backupBasePath == null || backupBasePath.equals("")) {
194
			backupBasePath = SystemUtil.discoverExternalBaseDir();
195
		}
196

    
197
		// if backupBasePath is still null, no reason to initialize the backup properties. The
198
		// system will need to prompt the user for the backup properties and reinitialize 
199
		// PropertyService.
200
		if (backupBasePath != null && !backupBasePath.equals("")) {
201
			setProperty("application.backupDir", backupBasePath);
202
			
203
			String backupDirPath = backupBasePath + FileUtil.getFS() + ".metacat";
204

    
205
			// The mainBackupProperties hold properties that were backed up the
206
			// last time the application was configured. On disk, the file will
207
			// look like a smaller version of metacat.properties. It is stored
208
			// in the data storage directory outside the application
209
			// directories.
210
			mainBackupPropertiesFilePath = 
211
				backupDirPath + FileUtil.getFS() + MAIN_CONFIG_NAME + ".backup";
212
			mainBackupProperties = new SortedProperties(mainBackupPropertiesFilePath);
213
			mainBackupProperties.load();
214

    
215
			// The authBackupProperties hold properties that were backed up the
216
			// last time the auth was configured. On disk, the file will
217
			// look like a smaller version of metacat.properties. It is stored
218
			// in the data storage directory outside the application
219
			// directories.
220
			authBackupPropertiesFilePath = 
221
				backupDirPath + FileUtil.getFS() + AUTH_CONFIG_NAME + ".backup";
222
			authBackupProperties = new SortedProperties(authBackupPropertiesFilePath);
223
			authBackupProperties.load();
224
		}
225
	}
226

    
227
	/**
228
	 * Utility method to get a property value from the properties file
229
	 * 
230
	 * @param propertyName
231
	 *            the name of the property requested
232
	 * @return the String value for the property
233
	 */
234
	public static String getProperty(String propertyName)
235
			throws PropertyNotFoundException {
236
		return mainProperties.getProperty(propertyName);
237
	}
238
	
239
	/**
240
     * Get a set of all property names.
241
     * 
242
     * @return Set of property names  
243
     */
244
    public static Vector<String> getPropertyNames() {   	
245
    	return mainProperties.getPropertyNames();
246
    }
247
    
248

    
249
	/**
250
	 * Get a Set of all property names that start with the groupName prefix.
251
	 * 
252
	 * @param groupName
253
	 *            the prefix of the keys to search for.
254
	 * @return enumeration of property names
255
	 */
256
    public static Vector<String> getPropertyNamesByGroup(String groupName) {   	
257
    	return mainProperties.getPropertyNamesByGroup(groupName);
258
    }
259
    
260
	/**
261
	 * Get a Map of all properties that start with the groupName prefix.
262
	 * 
263
	 * @param groupName
264
	 *            the prefix of the keys to search for.
265
	 * @return Map of property names
266
	 */
267
    public static Map<String, String> getPropertiesByGroup(String groupName) throws PropertyNotFoundException {   	
268
    	return mainProperties.getPropertiesByGroup(groupName);
269
    }
270

    
271
	/**
272
	 * Utility method to set a property value both in memory and to the
273
	 * properties file
274
	 * 
275
	 * @param propertyName
276
	 *            the name of the property requested
277
	 * @param newValue
278
	 *            the new value for the property
279
	 */
280
	public static void setProperty(String propertyName, String newValue) throws GeneralPropertyException {
281
			mainProperties.setProperty(propertyName, newValue);
282
			mainProperties.store();
283
	}
284

    
285
	/**
286
	 * Utility method to set a property value in memory. This will NOT cause the
287
	 * property to be written to disk. Use this method to set multiple
288
	 * properties in a row without causing excessive I/O. You must call
289
	 * persistProperties() once you're done setting properties to have them
290
	 * written to disk.
291
	 * 
292
	 * @param propertyName
293
	 *            the name of the property requested
294
	 * @param newValue
295
	 *            the new value for the property
296
	 */
297
	public static void setPropertyNoPersist(String propertyName, String newValue) throws GeneralPropertyException {
298
		mainProperties.setPropertyNoPersist(propertyName, newValue);
299
	}
300

    
301
	/**
302
	 * Save the properties to a properties file. Note, the 
303
	 * order and comments will be preserved.
304
	 */
305
	public static void persistProperties() throws GeneralPropertyException {
306
		mainProperties.store();
307
	}
308
	
309
	/**
310
	 * Get the main backup properties file. These are configurable properties that
311
	 * are stored outside the metacat install directories so the user does not
312
	 * need to re-enter all the configuration information every time they do an
313
	 * upgrade.
314
	 * 
315
	 * @return a SortedProperties object with the backup properties
316
	 */
317
	public static SortedProperties getMainBackupProperties() {
318
		return mainBackupProperties;
319
	}
320
	
321
	/**
322
	 * Get the auth backup properties file. These are configurable 
323
	 * properties that are stored outside the metacat install directories so 
324
	 * the user does not need to re-enter all the configuration information 
325
	 * every time they do an upgrade.
326
	 * 
327
	 * @return a SortedProperties object with the backup properties
328
	 */
329
	public static SortedProperties getAuthBackupProperties() {
330
		return authBackupProperties;
331
	}
332
	
333
	/**
334
	 * Get the main properties metadata. This is retrieved from an xml file that
335
	 * describes the attributes of configurable properties.
336
	 * 
337
	 * @return a PropertiesMetaData object with the main properties metadata
338
	 */
339
	public static PropertiesMetaData getMainMetaData() {
340
		return mainMetaData;
341
	}
342
	
343
	/**
344
	 * Get the auth properties metadata. This is retrieved from an xml
345
	 * file that describes the attributes of configurable properties.
346
	 * 
347
	 * @return a PropertiesMetaData object with the organization properties
348
	 *         metadata
349
	 */
350
	public static PropertiesMetaData getAuthMetaData() {
351
		return authMetaData;
352
	}
353
	
354
	/**
355
	 * Writes out backup configurable properties to a file.
356
	 */
357
	public static void persistMainBackupProperties(ServletContext servletContext)
358
			throws GeneralPropertyException {
359

    
360
		// Use the metadata to extract configurable properties from the 
361
		// overall properties list, and store those properties.
362
		try {
363
			SortedProperties backupProperties = new SortedProperties(mainBackupPropertiesFilePath);
364
			
365
			// Populate the backup properties for main metacat properties using
366
			// the associated metadata file
367
			PropertiesMetaData mainMetadata = new PropertiesMetaData(propertiesMetaDataFilePath);
368

    
369
			Map<String, MetaDataProperty> mainKeyMap = mainMetadata.getProperties();
370
			Set<String> mainKeySet = mainKeyMap.keySet();
371
			for (String propertyKey : mainKeySet) {
372
				// don't backup passwords
373
				MetaDataProperty metaData = mainKeyMap.get(propertyKey);
374
				if (!metaData.getFieldType().equals(MetaDataProperty.PASSWORD_TYPE)) {
375
					backupProperties.addProperty(propertyKey, getProperty(propertyKey));
376
				}
377
			}
378
			
379
			// store the properties to file
380
			backupProperties.store();
381
			mainBackupProperties = 
382
				new SortedProperties(mainBackupPropertiesFilePath);
383
			mainBackupProperties.load();
384

    
385
		} catch (TransformerException te) {
386
			throw new GeneralPropertyException("Could not transform backup properties xml: "
387
					+ te.getMessage());
388
		} catch (IOException ioe) {
389
			throw new GeneralPropertyException("Could not backup configurable properties: "
390
					+ ioe.getMessage());
391
		}
392
	}
393
	
394
	/**
395
	 * Writes out backup configurable properties to a file.
396
	 */
397
	public static void persistAuthBackupProperties(ServletContext servletContext)
398
			throws GeneralPropertyException {
399

    
400
		// Use the metadata to extract configurable properties from the 
401
		// overall properties list, and store those properties.
402
		try {
403
			SortedProperties backupProperties = 
404
				new SortedProperties(authBackupPropertiesFilePath);
405
			
406
			// Populate the backup properties for auth properties using
407
			// the associated metadata file
408
			PropertiesMetaData authMetadata = new PropertiesMetaData(authMetaDataFilePath);
409
			
410
			Map<String, MetaDataProperty> authKeyMap = authMetadata.getProperties();
411
			Set<String> authKeySet = authKeyMap.keySet();
412
			for (String propertyKey : authKeySet) {
413
				// don't backup passwords
414
				MetaDataProperty metaData = authKeyMap.get(propertyKey);
415
				if (!metaData.getFieldType().equals(MetaDataProperty.PASSWORD_TYPE)) {
416
					backupProperties.addProperty(propertyKey, getProperty(propertyKey));
417
				}
418
			}
419
			
420
			// store the properties to file
421
			backupProperties.store();
422
			authBackupProperties = 
423
				new SortedProperties(authBackupPropertiesFilePath);
424
			authBackupProperties.load();
425

    
426
		} catch (TransformerException te) {
427
			throw new GeneralPropertyException("Could not transform backup properties xml: "
428
					+ te.getMessage());
429
		} catch (IOException ioe) {
430
			throw new GeneralPropertyException("Could not backup configurable properties: "
431
					+ ioe.getMessage());
432
		} 
433
	}
434
	
435
	/**
436
	 * Reports whether properties are fully configured.
437
	 * 
438
	 * @return a boolean that is true if properties are not unconfigured and
439
	 *         false otherwise
440
	 */
441
	public static boolean arePropertiesConfigured() throws UtilException {		
442
		try {
443
			String propertiesConfigured = PropertyService.getProperty("configutil.propertiesConfigured");
444
			if (propertiesConfigured != null && !propertiesConfigured.equals(UNCONFIGURED)) {
445
				return true;
446
			}			
447
			return false;
448
		} catch (PropertyNotFoundException pnfe) {
449
			throw new UtilException("Could not determine if properties are configured: "
450
					+ pnfe.getMessage());
451
		}
452
	}
453
	
454
	/**
455
	 * Determine if the system is configured to bypass configuration. If so, the
456
	 * system will look for backup configuration files at startup time and use
457
	 * those to configure metacat. The bypass options should only be set by
458
	 * developers. Production code should never bypass confguration.
459
	 * 
460
	 * @return true if dev.runConfiguration is set to true in metacat.properties
461
	 *         and we have not already checked for bypass, false otherwise.
462
	 */
463
	public static boolean doBypass() throws PropertyNotFoundException {
464
		// We only want to go through the check once to see if we want to
465
		// bypass the configuration.  We don't want to run through all of
466
		// this every time  we hit metacat. 
467
		if (bypassAlreadyChecked) {
468
			logMetacat.debug("bypassConfiguration not performing full bypass check.  Bypass set to false");
469
			return false;
470
		}
471
		
472
		// check how dev.runConfiguration is set in metacat.properties
473
		String strRunConfiguration = PropertyService.getProperty("dev.runConfiguration");
474
		boolean runConfiguration = Boolean.parseBoolean(strRunConfiguration);
475
		logMetacat.debug("bypassConfiguration: dev.runConfiguration property set to: " + strRunConfiguration);
476
		
477
		// if the dev.runConfiguration is true, return false here.
478
		if (runConfiguration) {
479
			bypassAlreadyChecked = true;
480
			return false;
481
		} 
482
		
483
		return true;
484
	}
485
	
486
	/**
487
	 * Reports whether the metacat configuration utility should be run.  
488
	 * Returns false if  
489
	 *   -- dev.runConfiguration=false and
490
	 *   -- backup properties file exists
491
	 * Note that dev.runConfiguration should only be set to false when
492
	 * reinstalling the same version of the application in developement.
493
	 * 
494
	 * @return a boolean that is false if dev.runConfiguration is false and 
495
	 * the backup properties file exists.  
496
	 */
497
	public static void bypassConfiguration() throws ServiceException {
498
		try {
499
			boolean doBypass = doBypass();
500

    
501
			if (!doBypass) {
502
				throw new ServiceException(
503
						"Attempting to do bypass when system is not configured for it.");
504
			}			
505

    
506
			// The system is bypassing the configuration utility. We need to
507
			// get the backup properties and replace existing properties with
508
			// backup values.  We do this for main and org properties.		
509
			logMetacat.debug("bypassConfiguration: setting main backup properties.");
510
			SortedProperties mainBackupProperties = getMainBackupProperties();
511
			Vector<String> backupPropertyNames = 
512
				mainBackupProperties.getPropertyNames();
513
			for (String backupPropertyName : backupPropertyNames) {
514
				String value = mainBackupProperties.getProperty(backupPropertyName);
515
				setPropertyNoPersist(backupPropertyName, value);
516
			}
517

    
518
			logMetacat.debug("bypassConfiguration: setting auth backup properties.");
519
			SortedProperties authBackupProperties = getAuthBackupProperties();
520
			Vector<String> authBackupPropertyNames = 
521
				authBackupProperties.getPropertyNames();
522
			for (String authBackupPropertyName : authBackupPropertyNames) {
523
				String value = authBackupProperties.getProperty(authBackupPropertyName);
524
				setPropertyNoPersist(authBackupPropertyName, value);
525
			}
526

    
527
			logMetacat.debug("bypassConfiguration: setting configutil sections to true.");
528
			setPropertyNoPersist("configutil.propertiesConfigured", "true");
529
			setPropertyNoPersist("configutil.authConfigured", "true");
530
			setPropertyNoPersist("configutil.skinsConfigured", "true");
531
			setPropertyNoPersist("configutil.databaseConfigured", "true");
532
			setPropertyNoPersist("configutil.geoserverConfigured", "bypassed");
533
				
534
			persistProperties();
535

    
536
		} catch (PropertyNotFoundException pnfe) {
537
			logMetacat.error("bypassConfiguration: Could not find property: " + pnfe.getMessage());
538
		} catch (GeneralPropertyException gpe) {
539
			logMetacat.error("bypassConfiguration: General property error: " + gpe.getMessage());
540
		}
541

    
542
		bypassAlreadyChecked = true;
543
	}
544
	
545
	/**
546
	 * Take input from the user in an HTTP request about an property to be changed
547
	 * and update the metacat property file with that new value if it has
548
	 * changed from the value that was originally set.
549
	 * 
550
	 * @param request
551
	 *            that was generated by the user
552
	 * @param response
553
	 *            to send output back to the user
554
	 * @param propertyName
555
	 *            the name of the property to be checked and set
556
	 */
557
	public static void checkAndSetProperty(HttpServletRequest request, String propertyName) 
558
			throws GeneralPropertyException {
559
		String value = PropertyService.getProperty(propertyName);
560
		String newValue = request.getParameter(propertyName);
561
		if (newValue != null && !newValue.trim().equals(value)) {
562
			PropertyService.setPropertyNoPersist(propertyName, newValue.trim());
563
		}
564
	}
565

    
566
}
(3-3/9)