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-08-14 17:38:05 -0700 (Fri, 14 Aug 2009) $'
10
 * '$Revision: 5028 $'
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.properties;
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.commons.configuration.ConfigurationException;
39
import org.apache.log4j.Logger;
40
import org.dataone.configuration.Settings;
41

    
42
import edu.ucsb.nceas.metacat.service.ServiceService;
43
import edu.ucsb.nceas.metacat.shared.BaseService;
44
import edu.ucsb.nceas.metacat.shared.MetacatUtilException;
45
import edu.ucsb.nceas.metacat.shared.ServiceException;
46
import edu.ucsb.nceas.metacat.util.SystemUtil;
47
import edu.ucsb.nceas.utilities.FileUtil;
48
import edu.ucsb.nceas.utilities.GeneralPropertyException;
49
import edu.ucsb.nceas.utilities.MetaDataProperty;
50
import edu.ucsb.nceas.utilities.PropertiesMetaData;
51
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
52
import edu.ucsb.nceas.utilities.SortedProperties;
53

    
54
/**
55
 * A suite of utility classes for the metadata configuration utility
56
 */
57
public class ConfigurableProperties extends BaseService implements PropertiesInterface {
58
	
59
	private static final String MAIN_CONFIG_FILE_NAME = "metacat.properties";
60
	private static String mainConfigFilePath  = null;
61
	private static SortedProperties mainProperties = null;
62
	
63
	private static final String MAIN_METADATA_FILE_NAME = "metacat.properties.metadata.xml";
64
	private static String mainMetadataFilePath = null;
65
	private static PropertiesMetaData mainMetaData = null;
66
	
67
	private static final String MAIN_BACKUP_FILE_NAME = "metacat.properties.backup";
68
	private static String mainBackupFilePath  = null;
69
	private static SortedProperties mainBackupProperties = null;
70
	
71
	private static final String AUTH_METADATA_FILE_NAME = "auth.properties.metadata.xml";
72
	private static String authMetadataFilePath = null;
73
	private static PropertiesMetaData authMetaData = null;
74
	
75
	private static final String AUTH_BACKUP_FILE_NAME = "auth.properties.backup";
76
	private static String authBackupFilePath = null;
77
	private static SortedProperties authBackupProperties = null;
78
	
79
	private static boolean bypassAlreadyChecked = false;
80
	
81
	private static Logger logMetacat = Logger.getLogger(ConfigurableProperties.class);
82

    
83
	/**
84
	 * private constructor since this is a singleton
85
	 * 
86
	 * @param servletContext the context we will use to get relative paths
87
	 */
88
	protected ConfigurableProperties() throws ServiceException {		
89
		_serviceName = "ConfigurableProperties";
90
		
91
		initialize();		
92
	}
93
	
94
	public boolean refreshable() {
95
		return true;
96
	}
97
	
98
	public void doRefresh() throws ServiceException {
99
		initialize();
100
	}
101
	
102
	public void stop() throws ServiceException {
103
		return;
104
	}
105
	
106
	/**
107
	 * Initialize the singleton.
108
	 * 
109
	 * @param servletContext the context we will use to get relative paths
110
	 */
111
	private void initialize() throws ServiceException {
112
		
113
		logMetacat.debug("Initializing ConfigurableProperties");
114
		
115
		try {
116
			mainConfigFilePath = 
117
				PropertyService.CONFIG_FILE_DIR + FileUtil.getFS() + MAIN_CONFIG_FILE_NAME;
118
			mainMetadataFilePath = 
119
				PropertyService.CONFIG_FILE_DIR + FileUtil.getFS() + MAIN_METADATA_FILE_NAME;
120
//			mainBackupFilePath = 
121
//				PropertyService.CONFIG_FILE_DIR + FileUtil.getFS() + MAIN_BACKUP_FILE_NAME;
122
			authMetadataFilePath = 
123
				PropertyService.CONFIG_FILE_DIR + FileUtil.getFS() + AUTH_METADATA_FILE_NAME;
124
//			authBackupFilePath = 
125
//				PropertyService.CONFIG_FILE_DIR + FileUtil.getFS() + AUTH_BACKUP_FILE_NAME;
126
			
127
			
128
			// mainProperties will hold the primary configuration values for
129
			// metacat.
130
			mainProperties = new SortedProperties(mainConfigFilePath);
131
			mainProperties.load();
132
			
133
			// include main metacat properties in d1 properties as overrides
134
			try {
135
				Settings.augmentConfiguration(mainConfigFilePath);
136
			} catch (ConfigurationException e) {
137
				logMetacat.error("Could not augment DataONE properties. " + e.getMessage(), e);
138
			}
139

    
140
			// mainMetaData holds configuration information about main
141
			// properties. This is primarily used to display input fields on 
142
			// the configuration page. The information is retrieved from an 
143
			// xml metadata file
144
			mainMetaData = new PropertiesMetaData(mainMetadataFilePath);
145

    
146
			// authMetaData holds configuration information about organization
147
			// level
148
			// properties. This is primarily used to display input fields on
149
			// the auth configuration page. The information is retrieved
150
			// from an xml metadata file dedicated just to auth properties.
151
			authMetaData = new PropertiesMetaData(authMetadataFilePath);
152

    
153
			String recommendedExternalDir = SystemUtil.discoverExternalDir();
154
			PropertyService.setRecommendedExternalDir(recommendedExternalDir);
155
			
156
			String backupPath = getProperty("application.backupDir");
157
			if (backupPath == null || backupPath.equals("")) {
158
				backupPath = SystemUtil.getStoredBackupDir();
159
			}
160
			if (backupPath == null || backupPath.equals("") && recommendedExternalDir != null) {
161
				backupPath = 
162
					recommendedExternalDir + FileUtil.getFS() + "." + ServiceService.getRealApplicationContext();
163
			}
164

    
165
			// if backupPath is still null, no reason to initialize the
166
			// backup properties. The system will need to prompt the user for 
167
			// the backup properties and reinitialize ConfigurableProperties.
168
			if (backupPath != null && !backupPath.equals("")) {		
169
				setProperty("application.backupDir", backupPath);
170
				SystemUtil.writeStoredBackupFile(backupPath);
171

    
172
				// The mainBackupProperties hold properties that were backed up
173
				// the last time the application was configured. On disk, the 
174
				// file will look like a smaller version of metacat.properties. 
175
				// It is stored in the data storage directory outside the 
176
				// application directories.
177
				mainBackupFilePath = backupPath + FileUtil.getFS() + MAIN_BACKUP_FILE_NAME;
178
				mainBackupProperties = new SortedProperties(mainBackupFilePath);
179
				mainBackupProperties.load();
180

    
181
				// The authBackupProperties hold properties that were backed up
182
				// the last time the auth was configured. On disk, the file 
183
				// will look like a smaller version of metacat.properties. It 
184
				// is stored in the data storage directory outside the 
185
				// application directories.
186
				authBackupFilePath = backupPath + FileUtil.getFS() + AUTH_BACKUP_FILE_NAME;
187
				authBackupProperties = new SortedProperties(authBackupFilePath);
188
				authBackupProperties.load();
189
			}
190
		} catch (TransformerException te) {
191
			throw new ServiceException("Transform problem while loading properties: "
192
					+ te.getMessage());
193
		} catch (IOException ioe) {
194
			throw new ServiceException("I/O problem while loading properties: "
195
					+ ioe.getMessage());
196
		} catch (GeneralPropertyException gpe) {
197
			throw new ServiceException("General properties problem while loading properties: "
198
					+ gpe.getMessage());
199
		} catch (MetacatUtilException ue) {
200
			throw new ServiceException("Utilities problem while loading properties: "
201
					+ ue.getMessage());
202
		} 
203
	}
204

    
205
	/**
206
	 * Utility method to get a property value from the properties file
207
	 * 
208
	 * @param propertyName
209
	 *            the name of the property requested
210
	 * @return the String value for the property
211
	 */
212
	public String getProperty(String propertyName) throws PropertyNotFoundException {
213
		return mainProperties.getProperty(propertyName);
214
	}
215
	
216
	/**
217
     * Get a set of all property names.
218
     * 
219
     * @return Set of property names  
220
     */
221
    public Vector<String> getPropertyNames() {   	
222
    	return mainProperties.getPropertyNames();
223
    }
224
    
225

    
226
	/**
227
	 * Get a Set of all property names that start with the groupName prefix.
228
	 * 
229
	 * @param groupName
230
	 *            the prefix of the keys to search for.
231
	 * @return enumeration of property names
232
	 */
233
    public Vector<String> getPropertyNamesByGroup(String groupName) {   	
234
    	return mainProperties.getPropertyNamesByGroup(groupName);
235
    }
236
    
237
	/**
238
	 * Get a Map of all properties that start with the groupName prefix.
239
	 * 
240
	 * @param groupName
241
	 *            the prefix of the keys to search for.
242
	 * @return Map of property names
243
	 */
244
    public Map<String, String> getPropertiesByGroup(String groupName) throws PropertyNotFoundException {   	
245
    	return mainProperties.getPropertiesByGroup(groupName);
246
    }
247
    
248
	/**
249
	 * Utility method to add a property value both in memory and to the
250
	 * properties file
251
	 * 
252
	 * @param propertyName
253
	 *            the name of the property to add
254
	 * @param newValue
255
	 *            the value for the property
256
	 */
257
	public void addProperty(String propertyName, String value) throws GeneralPropertyException {
258
			mainProperties.addProperty(propertyName, value);
259
			mainProperties.store();
260
	}
261

    
262
	/**
263
	 * Utility method to set a property value both in memory and to the
264
	 * properties file
265
	 * 
266
	 * @param propertyName
267
	 *            the name of the property requested
268
	 * @param newValue
269
	 *            the new value for the property
270
	 */
271
	public void setProperty(String propertyName, String newValue) throws GeneralPropertyException {
272
			mainProperties.setProperty(propertyName, newValue);
273
			mainProperties.store();
274
	}
275

    
276
	/**
277
	 * Utility method to set a property value in memory. This will NOT cause the
278
	 * property to be written to disk. Use this method to set multiple
279
	 * properties in a row without causing excessive I/O. You must call
280
	 * persistProperties() once you're done setting properties to have them
281
	 * written to disk.
282
	 * 
283
	 * @param propertyName
284
	 *            the name of the property requested
285
	 * @param newValue
286
	 *            the new value for the property
287
	 */
288
	public void setPropertyNoPersist(String propertyName, String newValue) throws GeneralPropertyException {
289
		mainProperties.setPropertyNoPersist(propertyName, newValue);
290
	}
291

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

    
351
		// Use the metadata to extract configurable properties from the 
352
		// overall properties list, and store those properties.
353
		try {
354
			SortedProperties backupProperties = new SortedProperties(mainBackupFilePath);
355
			
356
			// Populate the backup properties for main metacat properties using
357
			// the associated metadata file
358
			PropertiesMetaData mainMetadata = new PropertiesMetaData(mainMetadataFilePath);
359

    
360
			Map<String, MetaDataProperty> mainKeyMap = mainMetadata.getProperties();
361
			Set<String> mainKeySet = mainKeyMap.keySet();
362
			for (String propertyKey : mainKeySet) {
363
				// don't backup passwords
364
				MetaDataProperty metaData = mainKeyMap.get(propertyKey);
365
				if (!metaData.getFieldType().equals(MetaDataProperty.PASSWORD_TYPE)) {
366
					backupProperties.addProperty(propertyKey, getProperty(propertyKey));
367
				}
368
			}
369
			
370
			// store the properties to file
371
			backupProperties.store();
372
			mainBackupProperties = 
373
				new SortedProperties(mainBackupFilePath);
374
			mainBackupProperties.load();
375

    
376
		} catch (TransformerException te) {
377
			throw new GeneralPropertyException("Could not transform backup properties xml: "
378
					+ te.getMessage());
379
		} catch (IOException ioe) {
380
			throw new GeneralPropertyException("Could not backup configurable properties: "
381
					+ ioe.getMessage());
382
		}
383
	}
384
	
385
	/**
386
	 * Writes out backup configurable properties to a file.
387
	 */
388
	public void persistAuthBackupProperties(ServletContext servletContext)
389
			throws GeneralPropertyException {
390

    
391
		// Use the metadata to extract configurable properties from the 
392
		// overall properties list, and store those properties.
393
		try {
394
			SortedProperties backupProperties = 
395
				new SortedProperties(authBackupFilePath);
396
			
397
			// Populate the backup properties for auth properties using
398
			// the associated metadata file
399
			PropertiesMetaData authMetadata = new PropertiesMetaData(authMetadataFilePath);
400
			
401
			Map<String, MetaDataProperty> authKeyMap = authMetadata.getProperties();
402
			Set<String> authKeySet = authKeyMap.keySet();
403
			for (String propertyKey : authKeySet) {
404
				// don't backup passwords
405
				MetaDataProperty metaData = authKeyMap.get(propertyKey);
406
				if (!metaData.getFieldType().equals(MetaDataProperty.PASSWORD_TYPE)) {
407
					backupProperties.addProperty(propertyKey, getProperty(propertyKey));
408
				}
409
			}
410
			
411
			// store the properties to file
412
			backupProperties.store();
413
			authBackupProperties = 
414
				new SortedProperties(authBackupFilePath);
415
			authBackupProperties.load();
416

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

    
487
			if (!doBypass) {
488
				throw new GeneralPropertyException(
489
						"Attempting to do bypass when system is not configured for it.");
490
			}			
491

    
492
			// The system is bypassing the configuration utility. We need to
493
			// get the backup properties and replace existing properties with
494
			// backup values.  We do this for main and org properties.		
495
			logMetacat.debug("bypassConfiguration: setting main backup properties.");
496
			SortedProperties mainBackupProperties = getMainBackupProperties();
497
			Vector<String> backupPropertyNames = 
498
				mainBackupProperties.getPropertyNames();
499
			for (String backupPropertyName : backupPropertyNames) {
500
				String value = mainBackupProperties.getProperty(backupPropertyName);
501
				setPropertyNoPersist(backupPropertyName, value);
502
			}
503

    
504
			logMetacat.debug("bypassConfiguration: setting auth backup properties.");
505
			SortedProperties authBackupProperties = getAuthBackupProperties();
506
			Vector<String> authBackupPropertyNames = 
507
				authBackupProperties.getPropertyNames();
508
			for (String authBackupPropertyName : authBackupPropertyNames) {
509
				String value = authBackupProperties.getProperty(authBackupPropertyName);
510
				setPropertyNoPersist(authBackupPropertyName, value);
511
			}
512

    
513
			logMetacat.debug("bypassConfiguration: setting configutil sections to true.");
514
			setPropertyNoPersist("configutil.propertiesConfigured", "true");
515
			setPropertyNoPersist("configutil.authConfigured", "true");
516
			setPropertyNoPersist("configutil.skinsConfigured", "true");
517
			setPropertyNoPersist("configutil.databaseConfigured", "true");
518
			setPropertyNoPersist("configutil.geoserverConfigured", "bypassed");
519
				
520
			persistProperties();
521

    
522
		} catch (PropertyNotFoundException pnfe) {
523
			logMetacat.error("bypassConfiguration: Could not find property: " + pnfe.getMessage());
524
		} catch (GeneralPropertyException gpe) {
525
			logMetacat.error("bypassConfiguration: General property error: " + gpe.getMessage());
526
		}
527

    
528
		bypassAlreadyChecked = true;
529
	}
530
	
531
	/**
532
	 * Take input from the user in an HTTP request about an property to be changed
533
	 * and update the metacat property file with that new value if it has
534
	 * changed from the value that was originally set.
535
	 * 
536
	 * @param request
537
	 *            that was generated by the user
538
	 * @param response
539
	 *            to send output back to the user
540
	 * @param propertyName
541
	 *            the name of the property to be checked and set
542
	 */
543
	public boolean checkAndSetProperty(HttpServletRequest request, String propertyName) 
544
			throws GeneralPropertyException {
545
		boolean changed = false;
546
		String value = getProperty(propertyName);
547
		String newValue = request.getParameter(propertyName);
548
		if (newValue != null && !newValue.trim().equals(value)) {
549
			setPropertyNoPersist(propertyName, newValue.trim());
550
			changed = true;
551
		}
552
		return changed;
553
	}
554

    
555
}
(1-1/5)