Project

General

Profile

1 5033 daigle
/**
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.log4j.Logger;
39
40
import edu.ucsb.nceas.metacat.service.ServiceService;
41
import edu.ucsb.nceas.metacat.shared.BaseService;
42
import edu.ucsb.nceas.metacat.shared.MetacatUtilException;
43
import edu.ucsb.nceas.metacat.shared.ServiceException;
44
import edu.ucsb.nceas.metacat.util.SystemUtil;
45
import edu.ucsb.nceas.utilities.FileUtil;
46
import edu.ucsb.nceas.utilities.GeneralPropertyException;
47
import edu.ucsb.nceas.utilities.MetaDataProperty;
48
import edu.ucsb.nceas.utilities.PropertiesMetaData;
49
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
50
import edu.ucsb.nceas.utilities.SortedProperties;
51
52
/**
53
 * A suite of utility classes for the metadata configuration utility
54
 */
55
public class ConfigurableProperties extends BaseService implements PropertiesInterface {
56
57
	private static final String MAIN_CONFIG_FILE_NAME = "metacat.properties";
58
	private static String mainConfigFilePath  = null;
59
	private static SortedProperties mainProperties = null;
60
61
	private static final String MAIN_METADATA_FILE_NAME = "metacat.properties.metadata.xml";
62
	private static String mainMetadataFilePath = null;
63
	private static PropertiesMetaData mainMetaData = null;
64
65
	private static final String MAIN_BACKUP_FILE_NAME = "metacat.properties.backup";
66
	private static String mainBackupFilePath  = null;
67
	private static SortedProperties mainBackupProperties = null;
68
69
	private static final String AUTH_METADATA_FILE_NAME = "auth.properties.metadata.xml";
70
	private static String authMetadataFilePath = null;
71
	private static PropertiesMetaData authMetaData = null;
72
73
	private static final String AUTH_BACKUP_FILE_NAME = "auth.properties.backup";
74
	private static String authBackupFilePath = null;
75
	private static SortedProperties authBackupProperties = null;
76
77
	private static boolean bypassAlreadyChecked = false;
78
79
	private static Logger logMetacat = Logger.getLogger(ConfigurableProperties.class);
80
81
	/**
82
	 * private constructor since this is a singleton
83
	 *
84
	 * @param servletContext the context we will use to get relative paths
85
	 */
86
	protected ConfigurableProperties() throws ServiceException {
87
		_serviceName = "ConfigurableProperties";
88
89
		initialize();
90
	}
91
92
	public boolean refreshable() {
93
		return true;
94
	}
95
96
	public void doRefresh() throws ServiceException {
97
		initialize();
98
	}
99
100
	public void stop() throws ServiceException {
101
		return;
102
	}
103
104
	/**
105
	 * Initialize the singleton.
106
	 *
107
	 * @param servletContext the context we will use to get relative paths
108
	 */
109
	private void initialize() throws ServiceException {
110
111
		logMetacat.debug("Initializing ConfigurableProperties");
112
113
		try {
114
			mainConfigFilePath =
115
				PropertyService.CONFIG_FILE_DIR + FileUtil.getFS() + MAIN_CONFIG_FILE_NAME;
116
			mainMetadataFilePath =
117
				PropertyService.CONFIG_FILE_DIR + FileUtil.getFS() + MAIN_METADATA_FILE_NAME;
118
//			mainBackupFilePath =
119
//				PropertyService.CONFIG_FILE_DIR + FileUtil.getFS() + MAIN_BACKUP_FILE_NAME;
120
			authMetadataFilePath =
121
				PropertyService.CONFIG_FILE_DIR + FileUtil.getFS() + AUTH_METADATA_FILE_NAME;
122
//			authBackupFilePath =
123
//				PropertyService.CONFIG_FILE_DIR + FileUtil.getFS() + AUTH_BACKUP_FILE_NAME;
124
125
126
			// mainProperties will hold the primary configuration values for
127
			// metacat.
128
			mainProperties = new SortedProperties(mainConfigFilePath);
129
			mainProperties.load();
130
131
			// mainMetaData holds configuration information about main
132
			// properties. This is primarily used to display input fields on
133
			// the configuration page. The information is retrieved from an
134
			// xml metadata file
135
			mainMetaData = new PropertiesMetaData(mainMetadataFilePath);
136
137
			// authMetaData holds configuration information about organization
138
			// level
139
			// properties. This is primarily used to display input fields on
140
			// the auth configuration page. The information is retrieved
141
			// from an xml metadata file dedicated just to auth properties.
142
			authMetaData = new PropertiesMetaData(authMetadataFilePath);
143
144
			String recommendedExternalDir = SystemUtil.discoverExternalDir();
145
			PropertyService.setRecommendedExternalDir(recommendedExternalDir);
146
147
			String backupPath = getProperty("application.backupDir");
148
			if (backupPath == null || backupPath.equals("")) {
149
				backupPath = SystemUtil.getStoredBackupDir();
150
			}
151
			if (backupPath == null || backupPath.equals("") && recommendedExternalDir != null) {
152
				backupPath =
153
					recommendedExternalDir + FileUtil.getFS() + "." + ServiceService.getRealApplicationContext();
154
			}
155
156
			// if backupPath is still null, no reason to initialize the
157
			// backup properties. The system will need to prompt the user for
158
			// the backup properties and reinitialize ConfigurableProperties.
159
			if (backupPath != null && !backupPath.equals("")) {
160
				setProperty("application.backupDir", backupPath);
161
				SystemUtil.writeStoredBackupFile(backupPath);
162
163
				// The mainBackupProperties hold properties that were backed up
164
				// the last time the application was configured. On disk, the
165
				// file will look like a smaller version of metacat.properties.
166
				// It is stored in the data storage directory outside the
167
				// application directories.
168
				mainBackupFilePath = backupPath + FileUtil.getFS() + MAIN_BACKUP_FILE_NAME;
169
				mainBackupProperties = new SortedProperties(mainBackupFilePath);
170
				mainBackupProperties.load();
171
172
				// The authBackupProperties hold properties that were backed up
173
				// the last time the auth was configured. On disk, the file
174
				// will look like a smaller version of metacat.properties. It
175
				// is stored in the data storage directory outside the
176
				// application directories.
177
				authBackupFilePath = backupPath + FileUtil.getFS() + AUTH_BACKUP_FILE_NAME;
178
				authBackupProperties = new SortedProperties(authBackupFilePath);
179
				authBackupProperties.load();
180
			}
181
		} catch (TransformerException te) {
182
			throw new ServiceException("Transform problem while loading properties: "
183
					+ te.getMessage());
184
		} catch (IOException ioe) {
185
			throw new ServiceException("I/O problem while loading properties: "
186
					+ ioe.getMessage());
187
		} catch (GeneralPropertyException gpe) {
188
			throw new ServiceException("General properties problem while loading properties: "
189
					+ gpe.getMessage());
190
		} catch (MetacatUtilException ue) {
191
			throw new ServiceException("Utilities problem while loading properties: "
192
					+ ue.getMessage());
193
		}
194
	}
195
196
	/**
197
	 * Utility method to get a property value from the properties file
198
	 *
199
	 * @param propertyName
200
	 *            the name of the property requested
201
	 * @return the String value for the property
202
	 */
203
	public String getProperty(String propertyName) throws PropertyNotFoundException {
204
		return mainProperties.getProperty(propertyName);
205
	}
206
207
	/**
208
     * Get a set of all property names.
209
     *
210
     * @return Set of property names
211
     */
212
    public Vector<String> getPropertyNames() {
213
    	return mainProperties.getPropertyNames();
214
    }
215
216
217
	/**
218
	 * Get a Set of all property names that start with the groupName prefix.
219
	 *
220
	 * @param groupName
221
	 *            the prefix of the keys to search for.
222
	 * @return enumeration of property names
223
	 */
224
    public Vector<String> getPropertyNamesByGroup(String groupName) {
225
    	return mainProperties.getPropertyNamesByGroup(groupName);
226
    }
227
228
	/**
229
	 * Get a Map of all properties that start with the groupName prefix.
230
	 *
231
	 * @param groupName
232
	 *            the prefix of the keys to search for.
233
	 * @return Map of property names
234
	 */
235
    public Map<String, String> getPropertiesByGroup(String groupName) throws PropertyNotFoundException {
236
    	return mainProperties.getPropertiesByGroup(groupName);
237
    }
238
239
	/**
240
	 * Utility method to set a property value both in memory and to the
241
	 * properties file
242
	 *
243
	 * @param propertyName
244
	 *            the name of the property requested
245
	 * @param newValue
246
	 *            the new value for the property
247
	 */
248
	public void setProperty(String propertyName, String newValue) throws GeneralPropertyException {
249
			mainProperties.setProperty(propertyName, newValue);
250
			mainProperties.store();
251
	}
252
253
	/**
254
	 * Utility method to set a property value in memory. This will NOT cause the
255
	 * property to be written to disk. Use this method to set multiple
256
	 * properties in a row without causing excessive I/O. You must call
257
	 * persistProperties() once you're done setting properties to have them
258
	 * written to disk.
259
	 *
260
	 * @param propertyName
261
	 *            the name of the property requested
262
	 * @param newValue
263
	 *            the new value for the property
264
	 */
265
	public void setPropertyNoPersist(String propertyName, String newValue) throws GeneralPropertyException {
266
		mainProperties.setPropertyNoPersist(propertyName, newValue);
267
	}
268
269
	/**
270
	 * Save the properties to a properties file. Note, the
271
	 * order and comments will be preserved.
272
	 */
273
	public void persistProperties() throws GeneralPropertyException {
274
		mainProperties.store();
275
	}
276
277
	/**
278
	 * Get the main backup properties file. These are configurable properties that
279
	 * are stored outside the metacat install directories so the user does not
280
	 * need to re-enter all the configuration information every time they do an
281
	 * upgrade.
282
	 *
283
	 * @return a SortedProperties object with the backup properties
284
	 */
285
	public SortedProperties getMainBackupProperties() {
286
		return mainBackupProperties;
287
	}
288
289
	/**
290
	 * Get the auth backup properties file. These are configurable
291
	 * properties that are stored outside the metacat install directories so
292
	 * the user does not need to re-enter all the configuration information
293
	 * every time they do an upgrade.
294
	 *
295
	 * @return a SortedProperties object with the backup properties
296
	 */
297
	public SortedProperties getAuthBackupProperties() {
298
		return authBackupProperties;
299
	}
300
301
	/**
302
	 * Get the main properties metadata. This is retrieved from an xml file that
303
	 * describes the attributes of configurable properties.
304
	 *
305
	 * @return a PropertiesMetaData object with the main properties metadata
306
	 */
307
	public PropertiesMetaData getMainMetaData() {
308
		return mainMetaData;
309
	}
310
311
	/**
312
	 * Get the auth properties metadata. This is retrieved from an xml
313
	 * file that describes the attributes of configurable properties.
314
	 *
315
	 * @return a PropertiesMetaData object with the organization properties
316
	 *         metadata
317
	 */
318
	public PropertiesMetaData getAuthMetaData() {
319
		return authMetaData;
320
	}
321
322
	/**
323
	 * Writes out backup configurable properties to a file.
324
	 */
325
	public void persistMainBackupProperties()
326
			throws GeneralPropertyException {
327
328
		// Use the metadata to extract configurable properties from the
329
		// overall properties list, and store those properties.
330
		try {
331
			SortedProperties backupProperties = new SortedProperties(mainBackupFilePath);
332
333
			// Populate the backup properties for main metacat properties using
334
			// the associated metadata file
335
			PropertiesMetaData mainMetadata = new PropertiesMetaData(mainMetadataFilePath);
336
337
			Map<String, MetaDataProperty> mainKeyMap = mainMetadata.getProperties();
338
			Set<String> mainKeySet = mainKeyMap.keySet();
339
			for (String propertyKey : mainKeySet) {
340
				// don't backup passwords
341
				MetaDataProperty metaData = mainKeyMap.get(propertyKey);
342
				if (!metaData.getFieldType().equals(MetaDataProperty.PASSWORD_TYPE)) {
343
					backupProperties.addProperty(propertyKey, getProperty(propertyKey));
344
				}
345
			}
346
347
			// store the properties to file
348
			backupProperties.store();
349
			mainBackupProperties =
350
				new SortedProperties(mainBackupFilePath);
351
			mainBackupProperties.load();
352
353
		} catch (TransformerException te) {
354
			throw new GeneralPropertyException("Could not transform backup properties xml: "
355
					+ te.getMessage());
356
		} catch (IOException ioe) {
357
			throw new GeneralPropertyException("Could not backup configurable properties: "
358
					+ ioe.getMessage());
359
		}
360
	}
361
362
	/**
363
	 * Writes out backup configurable properties to a file.
364
	 */
365
	public void persistAuthBackupProperties(ServletContext servletContext)
366
			throws GeneralPropertyException {
367
368
		// Use the metadata to extract configurable properties from the
369
		// overall properties list, and store those properties.
370
		try {
371
			SortedProperties backupProperties =
372
				new SortedProperties(authBackupFilePath);
373
374
			// Populate the backup properties for auth properties using
375
			// the associated metadata file
376
			PropertiesMetaData authMetadata = new PropertiesMetaData(authMetadataFilePath);
377
378
			Map<String, MetaDataProperty> authKeyMap = authMetadata.getProperties();
379
			Set<String> authKeySet = authKeyMap.keySet();
380
			for (String propertyKey : authKeySet) {
381
				// don't backup passwords
382
				MetaDataProperty metaData = authKeyMap.get(propertyKey);
383
				if (!metaData.getFieldType().equals(MetaDataProperty.PASSWORD_TYPE)) {
384
					backupProperties.addProperty(propertyKey, getProperty(propertyKey));
385
				}
386
			}
387
388
			// store the properties to file
389
			backupProperties.store();
390
			authBackupProperties =
391
				new SortedProperties(authBackupFilePath);
392
			authBackupProperties.load();
393
394
		} catch (TransformerException te) {
395
			throw new GeneralPropertyException("Could not transform backup properties xml: "
396
					+ te.getMessage());
397
		} catch (IOException ioe) {
398
			throw new GeneralPropertyException("Could not backup configurable properties: "
399
					+ ioe.getMessage());
400
		}
401
	}
402
403
	/**
404
	 * Reports whether properties are fully configured.
405
	 *
406
	 * @return a boolean that is true if properties are not unconfigured and
407
	 *         false otherwise
408
	 */
409
	public boolean arePropertiesConfigured() throws GeneralPropertyException {
410
		String propertiesConfigured = getProperty("configutil.propertiesConfigured");
411
		if (propertiesConfigured != null && !propertiesConfigured.equals(UNCONFIGURED)) {
412
			return true;
413
		}
414
		return false;
415
	}
416
417
	/**
418
	 * Determine if the system is configured to bypass configuration. If so, the
419
	 * system will look for backup configuration files at startup time and use
420
	 * those to configure metacat. The bypass options should only be set by
421
	 * developers. Production code should never bypass confguration.
422
	 *
423
	 * @return true if dev.runConfiguration is set to true in metacat.properties
424
	 *         and we have not already checked for bypass, false otherwise.
425
	 */
426
	public boolean doBypass() throws PropertyNotFoundException {
427
		// We only want to go through the check once to see if we want to
428
		// bypass the configuration.  We don't want to run through all of
429
		// this every time  we hit metacat.
430
		if (bypassAlreadyChecked) {
431
			logMetacat.debug("bypassConfiguration not performing full bypass check.  Bypass set to false");
432
			return false;
433
		}
434
435
		// check how dev.runConfiguration is set in metacat.properties
436
		String strRunConfiguration = getProperty("dev.runConfiguration");
437
		boolean runConfiguration = Boolean.parseBoolean(strRunConfiguration);
438
		logMetacat.debug("bypassConfiguration: dev.runConfiguration property set to: " + strRunConfiguration);
439
440
		// if the dev.runConfiguration is true, return false here.
441
		if (runConfiguration) {
442
			bypassAlreadyChecked = true;
443
			return false;
444
		}
445
446
		return true;
447
	}
448
449
	/**
450
	 * Reports whether the metacat configuration utility should be run.
451
	 * Returns false if
452
	 *   -- dev.runConfiguration=false and
453
	 *   -- backup properties file exists
454
	 * Note that dev.runConfiguration should only be set to false when
455
	 * reinstalling the same version of the application in developement.
456
	 *
457
	 * @return a boolean that is false if dev.runConfiguration is false and
458
	 * the backup properties file exists.
459
	 */
460
	public void bypassConfiguration() throws GeneralPropertyException {
461
		try {
462
			boolean doBypass = doBypass();
463
464
			if (!doBypass) {
465
				throw new GeneralPropertyException(
466
						"Attempting to do bypass when system is not configured for it.");
467
			}
468
469
			// The system is bypassing the configuration utility. We need to
470
			// get the backup properties and replace existing properties with
471
			// backup values.  We do this for main and org properties.
472
			logMetacat.debug("bypassConfiguration: setting main backup properties.");
473
			SortedProperties mainBackupProperties = getMainBackupProperties();
474
			Vector<String> backupPropertyNames =
475
				mainBackupProperties.getPropertyNames();
476
			for (String backupPropertyName : backupPropertyNames) {
477
				String value = mainBackupProperties.getProperty(backupPropertyName);
478
				setPropertyNoPersist(backupPropertyName, value);
479
			}
480
481
			logMetacat.debug("bypassConfiguration: setting auth backup properties.");
482
			SortedProperties authBackupProperties = getAuthBackupProperties();
483
			Vector<String> authBackupPropertyNames =
484
				authBackupProperties.getPropertyNames();
485
			for (String authBackupPropertyName : authBackupPropertyNames) {
486
				String value = authBackupProperties.getProperty(authBackupPropertyName);
487
				setPropertyNoPersist(authBackupPropertyName, value);
488
			}
489
490
			logMetacat.debug("bypassConfiguration: setting configutil sections to true.");
491
			setPropertyNoPersist("configutil.propertiesConfigured", "true");
492
			setPropertyNoPersist("configutil.authConfigured", "true");
493
			setPropertyNoPersist("configutil.skinsConfigured", "true");
494
			setPropertyNoPersist("configutil.databaseConfigured", "true");
495
			setPropertyNoPersist("configutil.geoserverConfigured", "bypassed");
496
497
			persistProperties();
498
499
		} catch (PropertyNotFoundException pnfe) {
500
			logMetacat.error("bypassConfiguration: Could not find property: " + pnfe.getMessage());
501
		} catch (GeneralPropertyException gpe) {
502
			logMetacat.error("bypassConfiguration: General property error: " + gpe.getMessage());
503
		}
504
505
		bypassAlreadyChecked = true;
506
	}
507
508
	/**
509
	 * Take input from the user in an HTTP request about an property to be changed
510
	 * and update the metacat property file with that new value if it has
511
	 * changed from the value that was originally set.
512
	 *
513
	 * @param request
514
	 *            that was generated by the user
515
	 * @param response
516
	 *            to send output back to the user
517
	 * @param propertyName
518
	 *            the name of the property to be checked and set
519
	 */
520
	public void checkAndSetProperty(HttpServletRequest request, String propertyName)
521
			throws GeneralPropertyException {
522
		String value = getProperty(propertyName);
523
		String newValue = request.getParameter(propertyName);
524
		if (newValue != null && !newValue.trim().equals(value)) {
525
			setPropertyNoPersist(propertyName, newValue.trim());
526
		}
527
	}
528
529
}