Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose:  A Class that implements main property configuration methods
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: leinfelder $'
9
 *     '$Date: 2013-06-18 14:59:12 -0700 (Tue, 18 Jun 2013) $'
10
 * '$Revision: 7809 $'
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.admin;
28

    
29
import java.io.File;
30
import java.util.Vector;
31

    
32
import javax.servlet.http.HttpServletRequest;
33
import javax.servlet.http.HttpServletResponse;
34

    
35
import org.apache.commons.io.FileUtils;
36
import org.apache.commons.io.filefilter.DirectoryFileFilter;
37
import org.apache.commons.io.filefilter.OrFileFilter;
38
import org.apache.commons.io.filefilter.WildcardFileFilter;
39
import org.apache.log4j.Logger;
40

    
41
import edu.ucsb.nceas.metacat.MetacatVersion;
42
import edu.ucsb.nceas.metacat.database.DBVersion;
43
import edu.ucsb.nceas.metacat.properties.PropertyService;
44
import edu.ucsb.nceas.metacat.service.ServiceService;
45
import edu.ucsb.nceas.metacat.shared.MetacatUtilException;
46
import edu.ucsb.nceas.metacat.shared.ServiceException;
47
import edu.ucsb.nceas.metacat.util.RequestUtil;
48
import edu.ucsb.nceas.metacat.util.SystemUtil;
49
import edu.ucsb.nceas.utilities.FileUtil;
50
import edu.ucsb.nceas.utilities.GeneralPropertyException;
51
import edu.ucsb.nceas.utilities.PropertiesMetaData;
52
import edu.ucsb.nceas.utilities.SortedProperties;
53
import edu.ucsb.nceas.utilities.UtilException;
54

    
55
/**
56
 * Control the display of the main properties configuration page and the 
57
 * processing of the configuration values.
58
 */
59
public class PropertiesAdmin extends MetacatAdmin {
60

    
61
	private static PropertiesAdmin propertiesAdmin = null;
62
	private static Logger logMetacat = Logger.getLogger(PropertiesAdmin.class);
63

    
64
	/**
65
	 * private constructor since this is a singleton
66
	 */
67
	private PropertiesAdmin() {}
68

    
69
	/**
70
	 * Get the single instance of the MetaCatConfig.
71
	 * 
72
	 * @return the single instance of MetaCatConfig
73
	 */
74
	public static PropertiesAdmin getInstance() {
75
		if (propertiesAdmin == null) {
76
			propertiesAdmin = new PropertiesAdmin();
77
		}
78
		return propertiesAdmin;
79
	}
80
	
81
	/**
82
	 * Handle configuration of the main application properties
83
	 * 
84
	 * @param request
85
	 *            the http request object
86
	 * @param response
87
	 *            the http response to be sent back to the client
88
	 */
89
	public void configureProperties(HttpServletRequest request,
90
			HttpServletResponse response) throws AdminException {
91

    
92
		String processForm = request.getParameter("processForm");
93
		String formErrors = (String)request.getAttribute("formErrors");
94

    
95
		if (processForm == null || !processForm.equals("true") || formErrors != null) {
96
			// The servlet configuration parameters have not been set, or there
97
			// were form errors on the last attempt to configure, so redirect to
98
			// the web form for configuring metacat
99

    
100
			try {
101
				// Load the properties metadata file so that the JSP page can
102
				// use the metadata to construct the editing form
103
				PropertiesMetaData metadata = PropertyService.getMainMetaData();
104
				request.setAttribute("metadata", metadata);
105

    
106
				String externalDir = PropertyService.getRecommendedExternalDir();
107
				
108
				if (externalDir == null) {
109
					throw new AdminException("Could not initialize property configuration "
110
									+ "page recommended application backup directory was null");
111
				}
112
				
113
				// Attempt to discover the following properties.  These will show
114
				// up in the configuration fields if nothing else is provided.
115
				PropertyService.setPropertyNoPersist("application.context",
116
						ServiceService.getRealApplicationContext());
117
				PropertyService.setPropertyNoPersist("server.name", SystemUtil
118
						.discoverServerName(request));
119
				PropertyService.setPropertyNoPersist("server.httpPort", SystemUtil
120
						.discoverServerPort(request));
121
				PropertyService.setPropertyNoPersist("server.httpSSLPort",
122
						SystemUtil.discoverServerSSLPort(request));
123
				PropertyService.setPropertyNoPersist("application.deployDir",
124
						SystemUtil.discoverDeployDir(request));
125
				PropertyService.setPropertyNoPersist("application.datafilepath",
126
						externalDir + FileUtil.getFS() + "data");
127
				PropertyService.setPropertyNoPersist("application.inlinedatafilepath",
128
						externalDir + FileUtil.getFS() + "inline-data");
129
				PropertyService.setPropertyNoPersist("application.documentfilepath",
130
						externalDir + FileUtil.getFS() + "documents");
131
				PropertyService.setPropertyNoPersist("application.tempDir",
132
						externalDir + FileUtil.getFS() + "temporary");
133
				PropertyService.setPropertyNoPersist("replication.logdir",
134
						externalDir + FileUtil.getFS() + "logs");
135
				PropertyService.setPropertyNoPersist("solr.homeDir",
136
						externalDir + FileUtil.getFS() + "solr-home");
137

    
138
				PropertyService.persistProperties();
139

    
140
				// Add the list of properties from metacat.properties to the request
141
				Vector<String> propertyNames = PropertyService.getPropertyNames();
142
				for (String propertyName : propertyNames) {
143
					request.setAttribute(propertyName, PropertyService.getProperty(propertyName));
144
				}
145

    
146
				// Check for any backup properties and apply them to the
147
				// request. These are properties from previous configurations. 
148
				// They keep the user from having to re-enter all values when 
149
				// upgrading. If this is a first time install, getBackupProperties 
150
				// will return null.
151
				SortedProperties backupProperties = null;
152
				if ((backupProperties = 
153
						PropertyService.getMainBackupProperties()) != null) {
154
					Vector<String> backupKeys = backupProperties.getPropertyNames();
155
					for (String key : backupKeys) {
156
						String value = backupProperties.getProperty(key);
157
						if (value != null) {
158
							request.setAttribute(key, value);
159
						}
160
					}
161
				}
162

    
163
				// Forward the request to the JSP page
164
				RequestUtil.forwardRequest(request, response,
165
						"/admin/properties-configuration.jsp", null);
166

    
167
			} catch (GeneralPropertyException gpe) {
168
				throw new AdminException("PropertiesAdmin.configureProperties - Problem getting or " + 
169
						"setting property while initializing system properties page: " + gpe.getMessage());
170
			} catch (MetacatUtilException mue) {
171
				throw new AdminException("PropertiesAdmin.configureProperties - utility problem while initializing "
172
						+ "system properties page:" + mue.getMessage());
173
			} catch (ServiceException se) {
174
				throw new AdminException("PropertiesAdmin.configureProperties - Service problem while initializing "
175
						+ "system properties page:" + se.getMessage());
176
			} 
177
		} else {
178
			// The configuration form is being submitted and needs to be
179
			// processed.
180
			Vector<String> validationErrors = new Vector<String>();
181
			Vector<String> processingErrors = new Vector<String>();
182
			Vector<String> processingSuccess = new Vector<String>();
183

    
184
			MetacatVersion metacatVersion = null;
185
			
186
			try {
187
				metacatVersion = SystemUtil.getMetacatVersion();
188
				
189
				// For each property, check if it is changed and save it
190
				Vector<String> propertyNames = PropertyService.getPropertyNames();
191
				for (String name : propertyNames) {
192
					PropertyService.checkAndSetProperty(request, name);
193
				}
194

    
195
				// we need to write the options from memory to the properties
196
				// file
197
				PropertyService.persistProperties();
198

    
199
				// Validate that the options provided are legitimate. Note that
200
				// we've allowed them to persist their entries. As of this point
201
				// there is no other easy way to go back to the configure form
202
				// and preserve their entries.
203
				validationErrors.addAll(validateOptions(request));
204
				
205
				// Try to create data directories if necessary.
206
				String dataDir = PropertyService.getProperty("application.datafilepath");
207
				try {
208
					FileUtil.createDirectory(dataDir);
209
				} catch (UtilException ue) {
210
					String errorString = "PropertiesAdmin.configureProperties - Could not create directory: " + dataDir +
211
					" : " + ue.getMessage();
212
					logMetacat.error(errorString);
213
					validationErrors.add(errorString);
214
				}
215
				
216
				// Try to create inline-data directories if necessary.
217
				String inlineDataDir = PropertyService.getProperty("application.inlinedatafilepath");
218
				try {
219
					FileUtil.createDirectory(inlineDataDir);
220
				} catch (UtilException ue) {
221
					String errorString = "PropertiesAdmin.configureProperties - Could not create directory: " + inlineDataDir +
222
						" : " + ue.getMessage();
223
					logMetacat.error(errorString);
224
					validationErrors.add(errorString);
225
				}
226
				
227
				// Try to create document directories if necessary.
228
				String documentfilepath = PropertyService.getProperty("application.documentfilepath");
229
				try {
230
					FileUtil.createDirectory(documentfilepath);
231
				} catch (UtilException ue) {	
232
					String errorString = "PropertiesAdmin.configureProperties - Could not create directory: " + documentfilepath +
233
						" : " + ue.getMessage();
234
					logMetacat.error(errorString);
235
					validationErrors.add(errorString);
236
				}
237
				
238
				// Try to create temporary directories if necessary.
239
				String tempDir = PropertyService.getProperty("application.tempDir");
240
				try {
241
					FileUtil.createDirectory(tempDir);
242
				} catch (UtilException ue) {		
243
					String errorString = "PropertiesAdmin.configureProperties - Could not create directory: " + tempDir +
244
						" : " + ue.getMessage();
245
					logMetacat.error(errorString);
246
					validationErrors.add(errorString);
247
				}
248
				
249
				// Try to create temporary directories if necessary.
250
				String replLogDir = PropertyService.getProperty("replication.logdir");
251
				try {
252
					FileUtil.createDirectory(replLogDir);
253
				} catch (UtilException ue) {		
254
					String errorString = "PropertiesAdmin.configureProperties - Could not create directory: " + replLogDir +
255
						" : " + ue.getMessage();
256
					logMetacat.error(errorString);
257
					validationErrors.add(errorString);
258
				}
259
				
260
				// Try to create and initialize the solr-home directory if necessary.
261
				String solrHomePath = PropertyService.getProperty("solr.homeDir");
262
				String indexContext = PropertyService.getProperty("index.context");
263
				boolean solrHomeExists = new File(solrHomePath).exists();
264
				if (!solrHomeExists) {
265
					try {
266
						String metacatWebInf = ServiceService.getRealConfigDir();
267
						String metacatIndexSolrHome = metacatWebInf + "/../../" + indexContext + "/WEB-INF/classes/solr-home";
268
						// only attempt to copy if we have the source directory to copy from
269
						File sourceDir = new File(metacatIndexSolrHome);
270
						if (sourceDir.exists()) {
271
							FileUtil.createDirectory(solrHomePath);
272
							OrFileFilter fileFilter = new OrFileFilter();
273
							fileFilter.addFileFilter(DirectoryFileFilter.DIRECTORY);
274
							fileFilter.addFileFilter(new WildcardFileFilter("*"));
275
							FileUtils.copyDirectory(new File(metacatIndexSolrHome), new File(solrHomePath), fileFilter );
276
						}
277
					} catch (Exception ue) {	
278
						String errorString = "PropertiesAdmin.configureProperties - Could not initialize directory: " + solrHomePath +
279
								" : " + ue.getMessage();
280
						logMetacat.error(errorString);
281
						validationErrors.add(errorString);
282
					}
283
				} else {
284
					// check it
285
					if (!FileUtil.isDirectory(solrHomePath)) {
286
						String errorString = "PropertiesAdmin.configureProperties - SOLR home is not a directory: " + solrHomePath;
287
						logMetacat.error(errorString);
288
						validationErrors.add(errorString);
289
					}
290
				}
291
				
292
				// write the backup properties to a location outside the 
293
				// application directories so they will be available after
294
				// the next upgrade
295
				PropertyService.persistMainBackupProperties();
296

    
297
			} catch (GeneralPropertyException gpe) {
298
				String errorMessage = "PropertiesAdmin.configureProperties - Problem getting or setting property while "
299
						+ "processing system properties page: " + gpe.getMessage();
300
				logMetacat.error(errorMessage);
301
				processingErrors.add(errorMessage);
302
			} 
303
			
304
			try {
305
				if (validationErrors.size() > 0 || processingErrors.size() > 0) {
306
					RequestUtil.clearRequestMessages(request);
307
					RequestUtil.setRequestFormErrors(request, validationErrors);
308
					RequestUtil.setRequestErrors(request, processingErrors);
309
					RequestUtil.forwardRequest(request, response, "/admin", null);
310
				} else {
311
					// Now that the options have been set, change the
312
					// 'propertiesConfigured' option to 'true'
313
					PropertyService.setProperty("configutil.propertiesConfigured",
314
							PropertyService.CONFIGURED);
315
					
316
					// if the db version is already the same as the metacat version,
317
					// update metacat.properties. Have to do this after
318
					// propertiesConfigured is set to CONFIGURED
319
					DBVersion dbVersion = DBAdmin.getInstance().getDBVersion();
320
					if (dbVersion != null && metacatVersion != null && 
321
							dbVersion.compareTo(metacatVersion) == 0) {
322
						PropertyService.setProperty("configutil.databaseConfigured", 
323
								PropertyService.CONFIGURED);
324
					}
325
					
326
					// Reload the main metacat configuration page
327
					processingSuccess.add("Properties successfully configured");
328
					RequestUtil.clearRequestMessages(request);
329
					RequestUtil.setRequestSuccess(request, processingSuccess);
330
					RequestUtil.forwardRequest(request, response, 
331
							"/admin?configureType=configure&processForm=false", null);
332
				}
333
			} catch (MetacatUtilException mue) {
334
				throw new AdminException("PropertiesAdmin.configureProperties - utility problem while processing system "
335
						+ "properties page: " + mue.getMessage());
336
			} catch (GeneralPropertyException gpe) {
337
				throw new AdminException("PropertiesAdmin.configureProperties - problem with properties while "
338
						+ "processing system properties page: " + gpe.getMessage());
339
			}
340
		}
341
	}
342

    
343
	/**
344
	 * Validate the most important configuration options submitted by the user.
345
	 * 
346
	 * @param request
347
	 *            the http request object
348
	 * 
349
	 * @return a vector holding error message for any fields that fail
350
	 *         validation.
351
	 */
352
	protected Vector<String> validateOptions(HttpServletRequest request) {
353
		Vector<String> errorVector = new Vector<String>();
354

    
355
		// Test database connectivity
356
		try {
357
			String dbError = DBAdmin.getInstance().validateDBConnectivity(
358
					request.getParameter("database.driver"),
359
					request.getParameter("database.connectionURI"),
360
					request.getParameter("database.user"),
361
					request.getParameter("database.password"));
362
			if (dbError != null) {
363
				errorVector.add(dbError);
364
			}
365
		} catch (AdminException ae) {
366
			errorVector.add("Could not instantiate database admin: "
367
					+ ae.getMessage());
368
		}
369

    
370
		return errorVector;
371
	}
372
	
373

    
374
}
(10-10/12)