Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that implements database 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: 2011-11-10 23:36:42 -0800 (Thu, 10 Nov 2011) $'
10
 * '$Revision: 6635 $'
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.log4j.Logger;
36
import org.dataone.client.CNode;
37
import org.dataone.client.D1Client;
38
import org.dataone.client.auth.CertificateManager;
39
import org.dataone.service.exceptions.IdentifierNotUnique;
40
import org.dataone.service.exceptions.InvalidRequest;
41
import org.dataone.service.exceptions.NotAuthorized;
42
import org.dataone.service.exceptions.NotFound;
43
import org.dataone.service.exceptions.NotImplemented;
44
import org.dataone.service.exceptions.ServiceFailure;
45
import org.dataone.service.types.v1.Node;
46
import org.dataone.service.types.v1.NodeList;
47
import org.dataone.service.types.v1.NodeReference;
48
import org.dataone.service.types.v1.Session;
49

    
50
import edu.ucsb.nceas.metacat.dataone.MNodeService;
51
import edu.ucsb.nceas.metacat.properties.PropertyService;
52
import edu.ucsb.nceas.metacat.shared.MetacatUtilException;
53
import edu.ucsb.nceas.metacat.util.RequestUtil;
54
import edu.ucsb.nceas.metacat.util.SystemUtil;
55
import edu.ucsb.nceas.utilities.FileUtil;
56
import edu.ucsb.nceas.utilities.GeneralPropertyException;
57
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
58

    
59
/**
60
 * Control the display of the database configuration page and the processing
61
 * of the configuration values.
62
 */
63
public class D1Admin extends MetacatAdmin {
64

    
65
	private static D1Admin instance = null;
66
	private Logger logMetacat = Logger.getLogger(D1Admin.class);
67

    
68
	/**
69
	 * private constructor since this is a singleton
70
	 */
71
	private D1Admin() throws AdminException {
72

    
73
	}
74

    
75
	/**
76
	 * Get the single instance of D1Admin.
77
	 * 
78
	 * @return the single instance of D1Admin
79
	 */
80
	public static D1Admin getInstance() throws AdminException {
81
		if (instance == null) {
82
			instance = new D1Admin();
83
		}
84
		return instance;
85
	}
86

    
87
	/**
88
	 * Handle configuration of the database the first time that Metacat starts
89
	 * or when it is explicitly called. Collect necessary update information
90
	 * from the administrator.
91
	 * 
92
	 * @param request
93
	 *            the http request information
94
	 * @param response
95
	 *            the http response to be sent back to the client
96
	 */
97
	public void configureDataONE(HttpServletRequest request,
98
			HttpServletResponse response) throws AdminException {
99

    
100
		String processForm = request.getParameter("processForm");
101
		String bypass = request.getParameter("bypass");
102
		String formErrors = (String) request.getAttribute("formErrors");
103

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

    
109
			try {
110
				
111
				// get the current configuration values
112
				String nodeName = PropertyService.getProperty("dataone.nodeName");
113
				String nodeDescription = PropertyService.getProperty("dataone.nodeDescription");
114
				String memberNodeId = PropertyService.getProperty("dataone.memberNodeId");
115
				String nodeSynchronize = PropertyService.getProperty("dataone.nodeSynchronize");
116
				String nodeReplicate = PropertyService.getProperty("dataone.nodeReplicate");
117
				String subject = PropertyService.getProperty("dataone.subject");
118
				String certpath = PropertyService.getProperty("D1Client.certificate.file");
119
				
120
				boolean synchronize = false;
121
				if (nodeSynchronize != null) {
122
					synchronize = Boolean.parseBoolean(nodeSynchronize);
123
				}
124
				boolean replicate = false;
125
				if (nodeReplicate != null) {
126
					replicate = Boolean.parseBoolean(nodeReplicate);
127
				}
128
				
129
				request.setAttribute("dataone.nodeName", nodeName);
130
				request.setAttribute("dataone.nodeDescription", nodeDescription);
131
				request.setAttribute("dataone.memberNodeId", memberNodeId);
132
				request.setAttribute("dataone.nodeSynchronize", synchronize);
133
				request.setAttribute("dataone.nodeReplicate", replicate);
134
				request.setAttribute("dataone.subject", subject);
135
				request.setAttribute("D1Client.certificate.file", certpath);
136

    
137
				// Forward the request to the JSP page
138
				RequestUtil.forwardRequest(request, response, "/admin/dataone-configuration.jsp", null);
139
			} catch (GeneralPropertyException gpe) {
140
				throw new AdminException("D1Admin.configureDataONE - Problem getting or " + 
141
						"setting property while initializing system properties page: " + gpe.getMessage());
142
			} catch (MetacatUtilException mue) {
143
				throw new AdminException("D1Admin.configureDataONE - utility problem while initializing "
144
						+ "system properties page:" + mue.getMessage());
145
			} 
146
		} else if (bypass != null && bypass.equals("true")) {
147
			Vector<String> processingErrors = new Vector<String>();
148
			Vector<String> processingSuccess = new Vector<String>();
149
			
150
			// Bypass the D1 configuration. 
151
			// This will keep Metacat running
152
			try {
153
				PropertyService.setProperty("configutil.dataoneConfigured", PropertyService.BYPASSED);
154
				
155
			} catch (GeneralPropertyException gpe) {
156
				String errorMessage = "D1Admin.configureDataONE - Problem getting or setting property while "
157
					+ "processing system properties page: " + gpe.getMessage();
158
				logMetacat.error(errorMessage);
159
				processingErrors.add(errorMessage);
160
			}
161
			try {
162
				if (processingErrors.size() > 0) {
163
					RequestUtil.clearRequestMessages(request);
164
					RequestUtil.setRequestErrors(request, processingErrors);
165
					RequestUtil.forwardRequest(request, response, "/admin", null);
166
				} else {			
167
					// Reload the main metacat configuration page
168
					processingSuccess.add("DataONE configuration successfully bypassed");
169
					RequestUtil.clearRequestMessages(request);
170
					RequestUtil.setRequestSuccess(request, processingSuccess);
171
					RequestUtil.forwardRequest(request, response, 
172
							"/admin?configureType=configure&processForm=false", null);
173
				}
174
			} catch (MetacatUtilException mue) {
175
				throw new AdminException("D1Admin.configureDataONE - utility problem while processing dataone page: "
176
						+ mue.getMessage());
177
			} 
178
		
179
		} else {
180
			// The configuration form is being submitted and needs to be
181
			// processed, setting the properties in the configuration file
182
			// then restart metacat
183

    
184
			// The configuration form is being submitted and needs to be
185
			// processed.
186
			Vector<String> validationErrors = new Vector<String>();
187
			Vector<String> processingErrors = new Vector<String>();
188
			Vector<String> processingSuccess = new Vector<String>();
189

    
190
			try {
191
				// Validate that the options provided are legitimate. Note that
192
				// we've allowed them to persist their entries. As of this point
193
				// there is no other easy way to go back to the configure form
194
				// and preserve their entries.
195
				validationErrors.addAll(validateOptions(request));
196
				
197
				String nodeName = (String)request.getParameter("dataone.nodeName");
198
				String nodeDescription = (String)request.getParameter("dataone.nodeDescription");
199
				String memberNodeId = (String)request.getParameter("dataone.memberNodeId");
200
				String nodeSynchronize = (String)request.getParameter("dataone.nodeSynchronize");
201
				String nodeReplicate = (String)request.getParameter("dataone.nodeReplicate");
202
				String subject = (String)request.getParameter("dataone.subject");
203
				String certpath = (String)request.getParameter("D1Client.certificate.file");
204
				
205
				boolean synchronize = false;
206
				if (nodeSynchronize != null) {
207
					synchronize = Boolean.parseBoolean(nodeSynchronize);
208
				}
209
				boolean replicate = false;
210
				if (nodeReplicate != null) {
211
					replicate = Boolean.parseBoolean(nodeReplicate);
212
				}
213
				
214
				// process the values, checking for nulls etc..
215
				if (nodeName == null ) {
216
					validationErrors.add("nodeName cannot be null");
217
				} else {
218
					
219
					PropertyService.setPropertyNoPersist("dataone.nodeName", nodeName);
220
					PropertyService.setPropertyNoPersist("dataone.nodeDescription", nodeDescription);
221
					PropertyService.setPropertyNoPersist("dataone.memberNodeId", memberNodeId);
222
					PropertyService.setPropertyNoPersist("dataone.nodeSynchronize", Boolean.toString(synchronize));
223
					PropertyService.setPropertyNoPersist("dataone.nodeReplicate", Boolean.toString(replicate));
224
					PropertyService.setPropertyNoPersist("dataone.subject", subject);
225
					PropertyService.setPropertyNoPersist("D1Client.certificate.file", certpath);
226
					
227
					PropertyService.persistProperties();
228

    
229
					// write the backup properties to a location outside the
230
					// application directories so they will be available after
231
					// the next upgrade
232
					PropertyService.persistMainBackupProperties();
233
					
234
			        // Register as a DataONE Member Node
235
					if (replicate) {
236
						registerDataONEMemberNode();
237
					}
238
				}
239
			} catch (GeneralPropertyException gpe) {
240
				String errorMessage = "D1Admin.configureDataONE - Problem getting or setting property while "
241
						+ "processing system properties page: " + gpe.getMessage();
242
				logMetacat.error(errorMessage);
243
				processingErrors.add(errorMessage);
244
			}
245

    
246
			try {
247
				if (validationErrors.size() > 0 || processingErrors.size() > 0) {
248
					RequestUtil.clearRequestMessages(request);
249
					RequestUtil.setRequestFormErrors(request, validationErrors);
250
					RequestUtil.setRequestErrors(request, processingErrors);
251
					RequestUtil.forwardRequest(request, response, "/admin", null);
252
				} else {
253
					// Now that the options have been set, change the
254
					// 'dataoneConfigured' option to 'true'
255
					PropertyService.setProperty("configutil.dataoneConfigured",
256
							PropertyService.CONFIGURED);
257
					
258
					// Reload the main metacat configuration page
259
					processingSuccess.add("DataONE successfully configured");
260
					RequestUtil.clearRequestMessages(request);
261
					RequestUtil.setRequestSuccess(request, processingSuccess);
262
					RequestUtil.forwardRequest(request, response, 
263
							"/admin?configureType=configure&processForm=false", null);
264
				}
265
			} catch (MetacatUtilException mue) {
266
				throw new AdminException("D1Admin.configureDataONE - utility problem while processing geoservices "
267
						+ "geoservices page: " + mue.getMessage());
268
			} catch (GeneralPropertyException gpe) {
269
				throw new AdminException("D1Admin.configureDataONE - problem with properties while "
270
						+ "processing geoservices configuration page: " + gpe.getMessage());
271
			}
272
		}
273
	}
274
	
275
	/**
276
	 * Register as a member node on the DataONE network.  The node description is
277
	 * retrieved from the getCapabilities() service, and so this should only be called
278
	 * after the properties have been properly set up in Metacat.
279
	 */
280
	private void registerDataONEMemberNode() {
281
        CNode cn;
282
        try {
283
            logMetacat.debug("Get the Node description.");
284
            Node node = MNodeService.getInstance(null).getCapabilities();
285
            logMetacat.debug("Setting client certificate location.");
286
            String mnCertificatePath = PropertyService.getProperty("D1Client.certificate.file");
287
            CertificateManager.getInstance().setCertificateLocation(mnCertificatePath);
288
            cn = D1Client.getCN();
289
            // check if this is new or an update
290
            boolean update = false;
291
            NodeList nodes = cn.listNodes();
292
            for (Node n: nodes.getNodeList()) {
293
            	if (n.getIdentifier().getValue().equals(node.getIdentifier().getValue())) {
294
            		update = true;
295
            		break;
296
            	}
297
            }
298
            // Session is null, because the libclient code automatically sets up an
299
            // SSL session for us using the client certificate provided
300
            Session session = null;
301
            if (update) {
302
            	logMetacat.debug("Updating node with DataONE. " + cn.getNodeBaseServiceUrl());
303
	            boolean result = cn.updateNodeCapabilities(session, node.getIdentifier(), node);
304
            } else {
305
	            logMetacat.debug("Registering node with DataONE. " + cn.getNodeBaseServiceUrl());
306
	            NodeReference mnode = cn.register(session, node);
307
            }
308
        } catch (ServiceFailure e) {
309
            logMetacat.warn("Could not register as node with DataONE (" + e.getCode() + "/" + e.getDetail_code() + "): " + e.getDescription());
310
        } catch (NotFound e) {
311
            logMetacat.warn("Could not register as node with DataONE (" + e.getCode() + "/" + e.getDetail_code() + "): " + e.getDescription());
312
        } catch (NotImplemented e) {
313
            logMetacat.warn("Could not register as node with DataONE (" + e.getCode() + "/" + e.getDetail_code() + "): " + e.getDescription());
314
        } catch (NotAuthorized e) {
315
            logMetacat.warn("Could not register as node with DataONE (" + e.getCode() + "/" + e.getDetail_code() + "): " + e.getDescription());
316
        } catch (InvalidRequest e) {
317
            logMetacat.warn("Could not register as node with DataONE (" + e.getCode() + "/" + e.getDetail_code() + "): " + e.getDescription());
318
        } catch (IdentifierNotUnique e) {
319
            logMetacat.warn("Could not register as node with DataONE (" + e.getCode() + "/" + e.getDetail_code() + "): " + e.getDescription());
320
        } catch (PropertyNotFoundException e) {
321
            logMetacat.warn("Could not find the location for client certificates: " + e.getMessage());
322
        }
323
	}
324

    
325
	/**
326
	 * Validate the most important configuration options submitted by the user.
327
	 * 
328
	 * @return a vector holding error message for any fields that fail
329
	 *         validation.
330
	 */
331
	protected Vector<String> validateOptions(HttpServletRequest request) {
332
		Vector<String> errorVector = new Vector<String>();
333

    
334
		// TODO MCD validate options.
335

    
336
		return errorVector;
337
	}
338
}
(4-4/11)