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: jones $'
9
 *     '$Date: 2011-09-22 00:05:37 -0700 (Thu, 22 Sep 2011) $'
10
 * '$Revision: 6493 $'
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.util.Vector;
30

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

    
34
import org.apache.log4j.Logger;
35
import org.dataone.client.CNode;
36
import org.dataone.client.D1Client;
37
import org.dataone.client.auth.CertificateManager;
38
import org.dataone.service.exceptions.IdentifierNotUnique;
39
import org.dataone.service.exceptions.InvalidRequest;
40
import org.dataone.service.exceptions.NotAuthorized;
41
import org.dataone.service.exceptions.NotImplemented;
42
import org.dataone.service.exceptions.ServiceFailure;
43
import org.dataone.service.types.v1.Node;
44
import org.dataone.service.types.v1.NodeReference;
45
import org.dataone.service.types.v1.Session;
46

    
47
import edu.ucsb.nceas.metacat.MetacatVersion;
48
import edu.ucsb.nceas.metacat.database.DBVersion;
49
import edu.ucsb.nceas.metacat.dataone.MNodeService;
50
import edu.ucsb.nceas.metacat.properties.PropertyService;
51
import edu.ucsb.nceas.metacat.service.ServiceService;
52
import edu.ucsb.nceas.metacat.shared.MetacatUtilException;
53
import edu.ucsb.nceas.metacat.shared.ServiceException;
54
import edu.ucsb.nceas.metacat.util.RequestUtil;
55
import edu.ucsb.nceas.metacat.util.SystemUtil;
56
import edu.ucsb.nceas.utilities.FileUtil;
57
import edu.ucsb.nceas.utilities.GeneralPropertyException;
58
import edu.ucsb.nceas.utilities.PropertiesMetaData;
59
import edu.ucsb.nceas.utilities.SortedProperties;
60
import edu.ucsb.nceas.utilities.UtilException;
61

    
62
/**
63
 * Control the display of the main properties configuration page and the 
64
 * processing of the configuration values.
65
 */
66
public class PropertiesAdmin extends MetacatAdmin {
67

    
68
	private static PropertiesAdmin propertiesAdmin = null;
69
	private static Logger logMetacat = Logger.getLogger(PropertiesAdmin.class);
70

    
71
	/**
72
	 * private constructor since this is a singleton
73
	 */
74
	private PropertiesAdmin() {}
75

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

    
99
		String processForm = request.getParameter("processForm");
100
		String formErrors = (String)request.getAttribute("formErrors");
101

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

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

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

    
143
				PropertyService.persistProperties();
144

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

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

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

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

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

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

    
204
				// Validate that the options provided are legitimate. Note that
205
				// we've allowed them to persist their entries. As of this point
206
				// there is no other easy way to go back to the configure form
207
				// and preserve their entries.
208
				validationErrors.addAll(validateOptions(request));
209
				
210
				// Try to create data directories if necessary.
211
				String dataDir = PropertyService.getProperty("application.datafilepath");
212
				try {
213
					FileUtil.createDirectory(dataDir);
214
				} catch (UtilException ue) {
215
					String errorString = "PropertiesAdmin.configureProperties - Could not create directory: " + dataDir +
216
					" : " + ue.getMessage();
217
					logMetacat.error(errorString);
218
					validationErrors.add(errorString);
219
				}
220
				
221
				// Try to create inline-data directories if necessary.
222
				String inlineDataDir = PropertyService.getProperty("application.inlinedatafilepath");
223
				try {
224
					FileUtil.createDirectory(inlineDataDir);
225
				} catch (UtilException ue) {
226
					String errorString = "PropertiesAdmin.configureProperties - Could not create directory: " + inlineDataDir +
227
						" : " + ue.getMessage();
228
					logMetacat.error(errorString);
229
					validationErrors.add(errorString);
230
				}
231
				
232
				// Try to create document directories if necessary.
233
				String documentfilepath = PropertyService.getProperty("application.documentfilepath");
234
				try {
235
					FileUtil.createDirectory(documentfilepath);
236
				} catch (UtilException ue) {	
237
					String errorString = "PropertiesAdmin.configureProperties - Could not create directory: " + documentfilepath +
238
						" : " + ue.getMessage();
239
					logMetacat.error(errorString);
240
					validationErrors.add(errorString);
241
				}
242
				
243
				// Try to create temporary directories if necessary.
244
				String tempDir = PropertyService.getProperty("application.tempDir");
245
				try {
246
					FileUtil.createDirectory(tempDir);
247
				} catch (UtilException ue) {		
248
					String errorString = "PropertiesAdmin.configureProperties - Could not create directory: " + tempDir +
249
						" : " + ue.getMessage();
250
					logMetacat.error(errorString);
251
					validationErrors.add(errorString);
252
				}
253
				
254
				// Try to create temporary directories if necessary.
255
				String replLogDir = PropertyService.getProperty("replication.logdir");
256
				try {
257
					FileUtil.createDirectory(replLogDir);
258
				} catch (UtilException ue) {		
259
					String errorString = "PropertiesAdmin.configureProperties - Could not create directory: " + replLogDir +
260
						" : " + ue.getMessage();
261
					logMetacat.error(errorString);
262
					validationErrors.add(errorString);
263
				}
264

    
265
		        // Register as a DataONE Member Node
266
				registerDataONEMemberNode();
267
				
268
				// write the backup properties to a location outside the 
269
				// application directories so they will be available after
270
				// the next upgrade
271
				PropertyService.persistMainBackupProperties();
272

    
273
			} catch (GeneralPropertyException gpe) {
274
				String errorMessage = "PropertiesAdmin.configureProperties - Problem getting or setting property while "
275
						+ "processing system properties page: " + gpe.getMessage();
276
				logMetacat.error(errorMessage);
277
				processingErrors.add(errorMessage);
278
			} 
279
			
280
			try {
281
				if (validationErrors.size() > 0 || processingErrors.size() > 0) {
282
					RequestUtil.clearRequestMessages(request);
283
					RequestUtil.setRequestFormErrors(request, validationErrors);
284
					RequestUtil.setRequestErrors(request, processingErrors);
285
					RequestUtil.forwardRequest(request, response, "/admin", null);
286
				} else {
287
					// Now that the options have been set, change the
288
					// 'propertiesConfigured' option to 'true'
289
					PropertyService.setProperty("configutil.propertiesConfigured",
290
							PropertyService.CONFIGURED);
291
					
292
					// if the db version is already the same as the metacat version,
293
					// update metacat.properties. Have to do this after
294
					// propertiesConfigured is set to CONFIGURED
295
					DBVersion dbVersion = DBAdmin.getInstance().getDBVersion();
296
					if (dbVersion != null && metacatVersion != null && 
297
							dbVersion.compareTo(metacatVersion) == 0) {
298
						PropertyService.setProperty("configutil.databaseConfigured", 
299
								PropertyService.CONFIGURED);
300
					}
301
					
302
					// Reload the main metacat configuration page
303
					processingSuccess.add("Properties successfully configured");
304
					RequestUtil.clearRequestMessages(request);
305
					RequestUtil.setRequestSuccess(request, processingSuccess);
306
					RequestUtil.forwardRequest(request, response, 
307
							"/admin?configureType=configure&processForm=false", null);
308
				}
309
			} catch (MetacatUtilException mue) {
310
				throw new AdminException("PropertiesAdmin.configureProperties - utility problem while processing system "
311
						+ "properties page: " + mue.getMessage());
312
			} catch (GeneralPropertyException gpe) {
313
				throw new AdminException("PropertiesAdmin.configureProperties - problem with properties while "
314
						+ "processing system properties page: " + gpe.getMessage());
315
			}
316
		}
317
	}
318

    
319
	/**
320
	 * Validate the most important configuration options submitted by the user.
321
	 * 
322
	 * @param request
323
	 *            the http request object
324
	 * 
325
	 * @return a vector holding error message for any fields that fail
326
	 *         validation.
327
	 */
328
	protected Vector<String> validateOptions(HttpServletRequest request) {
329
		Vector<String> errorVector = new Vector<String>();
330

    
331
		// Test database connectivity
332
		try {
333
			String dbError = DBAdmin.getInstance().validateDBConnectivity(
334
					request.getParameter("database.driver"),
335
					request.getParameter("database.connectionURI"),
336
					request.getParameter("database.user"),
337
					request.getParameter("database.password"));
338
			if (dbError != null) {
339
				errorVector.add(dbError);
340
			}
341
		} catch (AdminException ae) {
342
			errorVector.add("Could not instantiate database admin: "
343
					+ ae.getMessage());
344
		}
345

    
346
		return errorVector;
347
	}
348
	
349
	/**
350
	 * Register as a member node on the DataONE network.  The node description is
351
	 * retrieved from the getCapabilities() service, and so this should only be called
352
	 * after the properties have been properly set up in Metacat.
353
	 */
354
	private void registerDataONEMemberNode() {
355
        CNode cn;
356
        try {
357
            logMetacat.debug("Setting client certificate location.");
358
            String mnCertificatePath = "/etc/dataone/client/certs/DEMO01.pem";
359
            CertificateManager.getInstance().setCertificateLocation(mnCertificatePath);
360
            cn = D1Client.getCN();
361
            logMetacat.debug("Get the Node description.");
362
            Node node = MNodeService.getInstance().getCapabilities();
363
            logMetacat.debug("Registering node with DataONE.");
364
            // Session is null, because the libclient code automatically sets up an
365
            // SSL session for us using the client certificate provided
366
            Session session = null;
367
            NodeReference mnode = cn.register(session, node);
368
        } catch (ServiceFailure e) {
369
            logMetacat.warn("Could not register as node with DataONE (" + e.getCode() + "/" + e.getDetail_code() + "): " + e.getDescription());
370
        } catch (NotImplemented e) {
371
            logMetacat.warn("Could not register as node with DataONE (" + e.getCode() + "/" + e.getDetail_code() + "): " + e.getDescription());
372
        } catch (NotAuthorized e) {
373
            logMetacat.warn("Could not register as node with DataONE (" + e.getCode() + "/" + e.getDetail_code() + "): " + e.getDescription());
374
        } catch (InvalidRequest e) {
375
            logMetacat.warn("Could not register as node with DataONE (" + e.getCode() + "/" + e.getDetail_code() + "): " + e.getDescription());
376
        } catch (IdentifierNotUnique e) {
377
            logMetacat.warn("Could not register as node with DataONE (" + e.getCode() + "/" + e.getDetail_code() + "): " + e.getDescription());
378
        }
379
	}
380
}
(9-9/10)