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-09-23 15:54:55 -0700 (Mon, 23 Sep 2013) $'
10
 * '$Revision: 8265 $'
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.io.StringReader;
31
import java.util.Vector;
32

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

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

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

    
57
/**
58
 * Control the display of the main properties configuration page and the 
59
 * processing of the configuration values.
60
 */
61
public class PropertiesAdmin extends MetacatAdmin {
62
    private static String BACKSLASH = "/";
63
    private static String DEFAULTMETACATCONTEXT = "knb";
64
    private static String METACATPROPERTYAPPENDIX = "/WEB-INF/metacat.properties";
65
	private static PropertiesAdmin propertiesAdmin = null;
66
	private static Logger logMetacat = Logger.getLogger(PropertiesAdmin.class);
67

    
68
	/**
69
	 * private constructor since this is a singleton
70
	 */
71
	private PropertiesAdmin() {}
72

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

    
96
		String processForm = request.getParameter("processForm");
97
		String formErrors = (String)request.getAttribute("formErrors");
98

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

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

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

    
142
				PropertyService.persistProperties();
143

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

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

    
167
				// Forward the request to the JSP page
168
				RequestUtil.forwardRequest(request, response,
169
						"/admin/properties-configuration.jsp", null);
170

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

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

    
199
				// we need to write the options from memory to the properties
200
				// file
201
				PropertyService.persistProperties();
202

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

    
307
			} catch (GeneralPropertyException gpe) {
308
				String errorMessage = "PropertiesAdmin.configureProperties - Problem getting or setting property while "
309
						+ "processing system properties page: " + gpe.getMessage();
310
				logMetacat.error(errorMessage);
311
				processingErrors.add(errorMessage);
312
			} 
313
			
314
			try {
315
				if (validationErrors.size() > 0 || processingErrors.size() > 0) {
316
					RequestUtil.clearRequestMessages(request);
317
					RequestUtil.setRequestFormErrors(request, validationErrors);
318
					RequestUtil.setRequestErrors(request, processingErrors);
319
					RequestUtil.forwardRequest(request, response, "/admin", null);
320
				} else {
321
					// Now that the options have been set, change the
322
					// 'propertiesConfigured' option to 'true'
323
					PropertyService.setProperty("configutil.propertiesConfigured",
324
							PropertyService.CONFIGURED);
325
					
326
					// if the db version is already the same as the metacat version,
327
					// update metacat.properties. Have to do this after
328
					// propertiesConfigured is set to CONFIGURED
329
					DBVersion dbVersion = DBAdmin.getInstance().getDBVersion();
330
					if (dbVersion != null && metacatVersion != null && 
331
							dbVersion.compareTo(metacatVersion) == 0) {
332
						PropertyService.setProperty("configutil.databaseConfigured", 
333
								PropertyService.CONFIGURED);
334
					}
335
					
336
					// Reload the main metacat configuration page
337
					processingSuccess.add("Properties successfully configured");
338
					RequestUtil.clearRequestMessages(request);
339
					RequestUtil.setRequestSuccess(request, processingSuccess);
340
					RequestUtil.forwardRequest(request, response, 
341
							"/admin?configureType=configure&processForm=false", null);
342
				}
343
			} catch (MetacatUtilException mue) {
344
				throw new AdminException("PropertiesAdmin.configureProperties - utility problem while processing system "
345
						+ "properties page: " + mue.getMessage());
346
			} catch (GeneralPropertyException gpe) {
347
				throw new AdminException("PropertiesAdmin.configureProperties - problem with properties while "
348
						+ "processing system properties page: " + gpe.getMessage());
349
			}
350
		}
351
	}
352
	
353
	/**
354
	 * In the web.xml of the Metacat-index context, there is a parameter:
355
	 * <context-param>
356
     * <param-name>metacat.properties.path</param-name>
357
     * <param-value>/metacat/WEB-INF/metacat.properties</param-value>
358
     * <description>The metacat.properties file for sibling metacat deployment. Note that the context can change</description>
359
     *  </context-param>
360
     *  It points to the default metacat context - knb. If we rename the context, we need to change the value of there.
361
	 */
362
	private void modifyIndexContextParams(String indexContext) {
363
	    if(indexContext != null) {
364
	        try {
365
	            String metacatContext = PropertyService.getProperty("application.context");
366
	            //System.out.println("the metacat context is ========================="+metacatContext);
367
	            if(metacatContext != null && !metacatContext.equals(DEFAULTMETACATCONTEXT)) {
368
	                String indexConfigFile = 
369
	                                PropertyService.getProperty("application.deployDir")
370
	                                + FileUtil.getFS()
371
	                                + indexContext
372
	                                + FileUtil.getFS() 
373
	                                + "WEB-INF"
374
	                                + FileUtil.getFS()
375
	                                + "web.xml";
376
	                //System.out.println("============================== the web.xml file is "+indexConfigFile);
377
	                String configContents = FileUtil.readFileToString(indexConfigFile, "UTF-8");
378
	                //System.out.println("============================== the content of web.xml file is "+configContents);
379
	                configContents = configContents.replace(BACKSLASH+DEFAULTMETACATCONTEXT+METACATPROPERTYAPPENDIX, BACKSLASH+metacatContext+METACATPROPERTYAPPENDIX);
380
	                FileUtil.writeFile(indexConfigFile, new StringReader(configContents), "UTF-8");
381
	            }
382
                
383
            } catch (Exception e) {
384
                String errorMessage = "PropertiesAdmin.configureProperties - Problem getting/setting the \"metacat.properties.path\" in the web.xml of the index context : " + e.getMessage();
385
                logMetacat.error(errorMessage);
386
            }
387
	    }
388
	}
389
	
390
	/**
391
	 * Changes the Hazelcast group name to match the current context
392
	 * This ensures we do not share the same group if multiple Metacat 
393
	 * instances are running in the same Tomcat container.
394
	 */
395
	private void modifyHazelcastConfig() {
396
        try {
397
            String metacatContext = PropertyService.getProperty("application.context");
398
            //System.out.println("the metacat context is ========================="+metacatContext);
399
            if (metacatContext != null) {
400
                String hzConfigFile = 
401
                                PropertyService.getProperty("application.deployDir")
402
                                + FileUtil.getFS()
403
                                + metacatContext
404
                                + FileUtil.getFS() 
405
                                + "WEB-INF"
406
                                + FileUtil.getFS()
407
                                + "hazelcast.xml";
408
                //System.out.println("============================== the web.xml file is "+indexConfigFile);
409
                String configContents = FileUtil.readFileToString(hzConfigFile, "UTF-8");
410
                //System.out.println("============================== the content of web.xml file is "+configContents);
411
                configContents = configContents.replace("<name>DataONE</name>", "<name>" + metacatContext + "</name>");
412
                FileUtil.writeFile(hzConfigFile, new StringReader(configContents), "UTF-8");
413
            }
414
            
415
        } catch (Exception e) {
416
            String errorMessage = "PropertiesAdmin.configureProperties - Problem setting groupName in hazelcast.xml: " + e.getMessage();
417
            logMetacat.error(errorMessage);
418
        }
419
	}
420

    
421
	/**
422
	 * Validate the most important configuration options submitted by the user.
423
	 * 
424
	 * @param request
425
	 *            the http request object
426
	 * 
427
	 * @return a vector holding error message for any fields that fail
428
	 *         validation.
429
	 */
430
	protected Vector<String> validateOptions(HttpServletRequest request) {
431
		Vector<String> errorVector = new Vector<String>();
432

    
433
		// Test database connectivity
434
		try {
435
			String dbError = DBAdmin.getInstance().validateDBConnectivity(
436
					request.getParameter("database.driver"),
437
					request.getParameter("database.connectionURI"),
438
					request.getParameter("database.user"),
439
					request.getParameter("database.password"));
440
			if (dbError != null) {
441
				errorVector.add(dbError);
442
			}
443
		} catch (AdminException ae) {
444
			errorVector.add("Could not instantiate database admin: "
445
					+ ae.getMessage());
446
		}
447

    
448
		return errorVector;
449
	}
450
	
451

    
452
}
(10-10/12)