Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *  Copyright: 2011 Regents of the University of California and the
4
 *              National Center for Ecological Analysis and Synthesis
5
 *
6
 *   '$Author: tao $'
7
 *     '$Date: 2015-08-19 11:41:59 -0700 (Wed, 19 Aug 2015) $'
8
 *
9
 * This program is free software; you can redistribute it and/or modify
10
 * it under the terms of the GNU General Public License as published by
11
 * the Free Software Foundation; either version 2 of the License, or
12
 * (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program; if not, write to the Free Software
21
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22
 */
23
package edu.ucsb.nceas.metacat.restservice.v1;
24

    
25
import java.io.File;
26
import java.io.FileInputStream;
27
import java.io.IOException;
28
import java.io.InputStream;
29
import java.io.OutputStream;
30
import java.util.Date;
31
import java.util.Enumeration;
32
import java.util.Map;
33
import java.util.concurrent.ExecutorService;
34
import java.util.concurrent.Executors;
35

    
36
import javax.servlet.ServletContext;
37
import javax.servlet.http.HttpServletRequest;
38
import javax.servlet.http.HttpServletResponse;
39
import javax.xml.parsers.ParserConfigurationException;
40

    
41
import org.apache.commons.fileupload.FileUploadException;
42
import org.apache.commons.io.IOUtils;
43
import org.apache.log4j.Logger;
44
import org.dataone.client.v2.formats.ObjectFormatInfo;
45
import org.dataone.mimemultipart.MultipartRequest;
46
import org.dataone.mimemultipart.MultipartRequestResolver;
47
import org.dataone.portal.TokenGenerator;
48
import org.dataone.service.exceptions.BaseException;
49
import org.dataone.service.exceptions.IdentifierNotUnique;
50
import org.dataone.service.exceptions.InsufficientResources;
51
import org.dataone.service.exceptions.InvalidRequest;
52
import org.dataone.service.exceptions.InvalidSystemMetadata;
53
import org.dataone.service.exceptions.InvalidToken;
54
import org.dataone.service.exceptions.NotAuthorized;
55
import org.dataone.service.exceptions.NotFound;
56
import org.dataone.service.exceptions.NotImplemented;
57
import org.dataone.service.exceptions.ServiceFailure;
58
import org.dataone.service.exceptions.SynchronizationFailed;
59
import org.dataone.service.exceptions.UnsupportedType;
60
import org.dataone.service.types.v1.Checksum;
61
import org.dataone.service.types.v1.DescribeResponse;
62
import org.dataone.service.types.v1.Event;
63
import org.dataone.service.types.v1.Identifier;
64
import org.dataone.service.types.v1.Log;
65
import org.dataone.service.types.v1.Node;
66
import org.dataone.service.types.v1.NodeReference;
67
import org.dataone.service.types.v1.ObjectFormatIdentifier;
68
import org.dataone.service.types.v1.ObjectList;
69
import org.dataone.service.types.v1.Permission;
70
import org.dataone.service.types.v1.Person;
71
import org.dataone.service.types.v1.SystemMetadata;
72
import org.dataone.service.types.v1_1.QueryEngineDescription;
73
import org.dataone.service.types.v1_1.QueryEngineList;
74
import org.dataone.service.util.Constants;
75
import org.dataone.service.util.DateTimeMarshaller;
76
import org.dataone.service.util.ExceptionHandler;
77
import org.dataone.service.util.TypeMarshaller;
78
import org.jibx.runtime.JiBXException;
79
import org.xml.sax.SAXException;
80

    
81
import edu.ucsb.nceas.metacat.common.query.stream.ContentTypeInputStream;
82
import edu.ucsb.nceas.metacat.dataone.v1.MNodeService;
83
import edu.ucsb.nceas.metacat.properties.PropertyService;
84
import edu.ucsb.nceas.metacat.restservice.D1ResourceHandler;
85
import edu.ucsb.nceas.metacat.util.DeleteOnCloseFileInputStream;
86
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
87
import edu.ucsb.nceas.metacat.MetaCatServlet;
88

    
89

    
90
/**
91
 * MN REST service implementation handler
92
 * 
93
 * ******************
94
 * MNCore -- DONE
95
 * 		ping() - GET /d1/mn/monitor/ping
96
 * 		log() - GET /d1/mn/log
97
 * 		**getObjectStatistics() - GET /d1/mn/monitor/object
98
 * 		getOperationsStatistics - GET /d1/mn/monitor/event
99
 * 		**getStatus - GET /d1/mn/monitor/status
100
 * 		getCapabilities() - GET /d1/mn/ and /d1/mn/node
101
 * 	
102
 * 	MNRead -- DONE
103
 * 		get() - GET /d1/mn/object/PID
104
 * 		getSystemMetadata() - GET /d1/mn/meta/PID
105
 * 		describe() - HEAD /d1/mn/object/PID
106
 * 		getChecksum() - GET /d1/mn/checksum/PID
107
 * 		listObjects() - GET /d1/mn/object
108
 * 		synchronizationFailed() - POST /d1/mn/error
109
 * 	
110
 * 	MNAuthorization -- DONE
111
 * 		isAuthorized() - GET /d1/mn/isAuthorized/PID
112
 * 		setAccessPolicy() - PUT /d1/mn/accessRules/PID
113
 * 		
114
 * 	MNStorage - DONE
115
 * 		create() - POST /d1/mn/object/PID
116
 * 		update() - PUT /d1/mn/object/PID
117
 * 		delete() - DELETE /d1/mn/object/PID
118
 * 		archive() - PUT /d1/mn/archive/PID
119

    
120
 *    systemMetadataChanged() - POST /dirtySystemMetadata/PID
121
 * 	
122
 * 	MNReplication
123
 * 		replicate() - POST /d1/mn/replicate
124
 *    getReplica() - GET /d1/mn/replica
125
 * 
126
 * ******************
127
 * @author leinfelder
128
 *
129
 */
130
public class MNResourceHandler extends D1ResourceHandler {
131

    
132
    // MN-specific API Resources
133
    protected static final String RESOURCE_MONITOR = "monitor";
134
    protected static final String RESOURCE_REPLICATE = "replicate";
135
    protected static final String RESOURCE_REPLICAS = "replica";
136
    protected static final String RESOURCE_NODE = "node";
137
    protected static final String RESOURCE_ERROR = "error";
138
    protected static final String RESOURCE_META_CHANGED = "dirtySystemMetadata";
139
    protected static final String RESOURCE_GENERATE_ID = "generate";
140
    protected static final String RESOURCE_PUBLISH = "publish";
141
    protected static final String RESOURCE_PACKAGE = "packages";
142
    protected static final String RESOURCE_VIEWS = "views";
143
    protected static final String RESOURCE_TOKEN = "token";
144

    
145

    
146
    
147
    // shared executor
148
	private static ExecutorService executor = null;
149

    
150
	static {
151
		// use a shared executor service with nThreads == one less than available processors
152
    	int availableProcessors = Runtime.getRuntime().availableProcessors();
153
        int nThreads = availableProcessors * 1;
154
        nThreads--;
155
        nThreads = Math.max(1, nThreads);
156
    	executor = Executors.newFixedThreadPool(nThreads);	
157
	}
158
	
159
    /**
160
     * Initializes new instance by setting servlet context,request and response
161
     * */
162
    public MNResourceHandler(ServletContext servletContext,
163
            HttpServletRequest request, HttpServletResponse response) {
164
    	super(servletContext, request, response);
165
        logMetacat = Logger.getLogger(MNResourceHandler.class);
166
    }
167
    
168
    @Override
169
    protected boolean isD1Enabled() {
170
    	
171
    	boolean enabled = false;
172
    	try {
173
			enabled = Boolean.parseBoolean(PropertyService.getProperty("dataone.mn.services.enabled"));
174
		} catch (PropertyNotFoundException e) {
175
			logMetacat.error("Could not check if DataONE is enabled: " + e.getMessage());
176
		}
177
    	
178
    	return enabled;	
179
    }
180

    
181
    /**
182
     * This function is called from REST API servlet and handles each request to the servlet 
183
     * 
184
     * @param httpVerb (GET, POST, PUT or DELETE)
185
     */
186
    @Override
187
    public void handle(byte httpVerb) {
188
    	// prepare the handler
189
    	super.handle(httpVerb);
190
    	
191
        try {
192
        	
193
        	// only service requests if we have D1 configured
194
        	if (!isD1Enabled()) {
195
        		ServiceFailure se = new ServiceFailure("0000", "DataONE services are not enabled on this node");
196
                serializeException(se, response.getOutputStream());
197
                return;
198
        	}
199
        	
200
        	// get the resource
201
            String resource = request.getPathInfo();
202
            resource = resource.substring(resource.indexOf("/") + 1);
203
            
204
            // default to node info
205
            if (resource.equals("")) {
206
                resource = RESOURCE_NODE;
207
            }
208
            
209
            // get the rest of the path info
210
            String extra = null;
211
                        
212
            logMetacat.debug("handling verb " + httpVerb + " request with resource '" + resource + "'");
213
            logMetacat.debug("resource: '" + resource + "'");
214
            boolean status = false;
215
            
216
            if (resource != null) {
217

    
218
                if (resource.startsWith(RESOURCE_NODE)) {
219
                    // node response
220
                    node();
221
                    status = true;
222
                } else if (resource.startsWith(RESOURCE_TOKEN)) {
223
                    logMetacat.debug("Using resource 'token'");
224
                    // get
225
                    if (httpVerb == GET) {
226
                    	// after the command
227
                        getToken();
228
                        status = true;
229
                    }
230
                    
231
                } else if (resource.startsWith(RESOURCE_IS_AUTHORIZED)) {
232
                    if (httpVerb == GET) {
233
                    	// after the command
234
                        extra = parseTrailing(resource, RESOURCE_IS_AUTHORIZED);
235
                        extra = decode(extra);
236
	                	// check the access rules
237
	                    isAuthorized(extra);
238
	                    status = true;
239
	                    logMetacat.debug("done getting access");
240
                    }
241
                } else if (resource.startsWith(RESOURCE_META)) {
242
                    logMetacat.debug("Using resource 'meta'");
243
                    // get
244
                    if (httpVerb == GET) {
245
                    	// after the command
246
                        extra = parseTrailing(resource, RESOURCE_META);
247
                        extra = decode(extra);
248
                        getSystemMetadataObject(extra);
249
                        status = true;
250
                    }
251
                    
252
                } else if (resource.startsWith(RESOURCE_OBJECTS)) {
253
                    logMetacat.debug("Using resource 'object'");
254
                    // after the command
255
                    extra = parseTrailing(resource, RESOURCE_OBJECTS);
256
                    logMetacat.debug("objectId(before decoded: " + extra);
257
                    extra = decode(extra);
258
                    logMetacat.debug("objectId: " + extra);
259
                    logMetacat.debug("verb:" + httpVerb);
260

    
261
                    if (httpVerb == GET) {
262
                        getObject(extra);
263
                        status = true;
264
                    } else if (httpVerb == POST) {
265
                    	// part of the params, not the URL
266
                        putObject(null, FUNCTION_NAME_INSERT);
267
                        status = true;
268
                    } else if (httpVerb == PUT) {
269
                        putObject(extra, FUNCTION_NAME_UPDATE);
270
                        status = true;
271
                    } else if (httpVerb == DELETE) {
272
                        deleteObject(extra);
273
                        status = true;
274
                    } else if (httpVerb == HEAD) {
275
                        describeObject(extra);
276
                        status = true;
277
                    }
278
                  
279
                } else if (resource.startsWith(RESOURCE_LOG)) {
280
                    logMetacat.debug("Using resource 'log'");
281
                    // handle log events
282
                    if (httpVerb == GET) {
283
                        getLog();
284
                        status = true;
285
                    }
286
                } else if (resource.startsWith(Constants.RESOURCE_ARCHIVE)) {
287
                    logMetacat.debug("Using resource " + Constants.RESOURCE_ARCHIVE);
288
                    // handle archive events
289
                    if (httpVerb == PUT) {
290
                        extra = parseTrailing(resource, Constants.RESOURCE_ARCHIVE);
291
                        extra = decode(extra);
292
                        archive(extra);
293
                        status = true;
294
                    }
295
                } else if (resource.startsWith(Constants.RESOURCE_CHECKSUM)) {
296
                    logMetacat.debug("Using resource 'checksum'");
297
                    // handle checksum requests
298
                    if (httpVerb == GET) {
299
                    	// after the command
300
                        extra = parseTrailing(resource, Constants.RESOURCE_CHECKSUM);
301
                        extra = decode(extra);
302
                        checksum(extra);
303
                        status = true;
304
                    }
305
                } else if (resource.startsWith(RESOURCE_MONITOR)) {
306
                    // there are various parts to monitoring
307
                    if (httpVerb == GET) {
308
                    	// after the command
309
                        extra = parseTrailing(resource, RESOURCE_MONITOR);
310
                        extra = decode(extra);
311
                        // ping
312
                        if (extra.toLowerCase().equals("ping")) {
313
                            logMetacat.debug("processing ping request");
314
                            Date result = MNodeService.getInstance(request).ping();
315
                            // TODO: send to output	
316
                            status = true;
317
                            
318
                        }
319
                        
320
                    }
321
                } else if (resource.startsWith(RESOURCE_REPLICATE)) {
322
                	if (httpVerb == POST) {
323
	                    logMetacat.debug("processing replicate request");
324
	                    replicate();
325
	                    status = true;
326
                	}
327
                } else if (resource.startsWith(RESOURCE_ERROR)) {
328
	                // sync error
329
	                if (httpVerb == POST) {
330
	                    syncError();
331
	                    status = true;
332
	                }
333
                } else if (resource.startsWith(RESOURCE_META_CHANGED)) {
334
                    // system metadata changed
335
                    if (httpVerb == POST) {
336
                        systemMetadataChanged();
337
                        status = true;
338
                    }
339
                } else if (resource.startsWith(RESOURCE_REPLICAS)) {
340
                    // get replica
341
                    if (httpVerb == GET) {
342
                        extra = parseTrailing(resource, RESOURCE_REPLICAS);
343
                        extra = decode(extra);
344
                        getReplica(extra);
345
                        status = true;
346
                    }
347
                } else if (resource.startsWith(RESOURCE_QUERY)) {
348
	                logMetacat.debug("Using resource " + RESOURCE_QUERY);
349
	                // after the command
350
	                extra = parseTrailing(resource, RESOURCE_QUERY);
351
	                logMetacat.debug("query extra: " + extra);
352

    
353
	                String engine = null;
354
	                String query = null;
355

    
356
	                if (extra != null) {
357
		                // get the engine
358
		                int engineIndex = extra.length();
359
		                if (extra.indexOf("/") > -1) {
360
		                	engineIndex = extra.indexOf("/");
361
		                }
362
		                engine = extra.substring(0, engineIndex);
363
		                engine = decode(engine);
364
		                logMetacat.debug("query engine: " + engine);
365
		                
366
		                // get the query if it is there
367
		                query = extra.substring(engineIndex, extra.length());
368
		                query = decode(query);
369
		                if (query != null && query.length() == 0) {
370
		                	query = null;
371
		                } else {
372
		                	if (query.startsWith("/")) {
373
		                		query = query.substring(1);
374
		                    }
375
		                	// remove the query delimiter if it exists
376
		                	if (query.startsWith("?")) {
377
		                		query = query.substring(1);
378
		                    }
379
		                }
380
		                logMetacat.debug("query: " + query);
381

    
382
	                }
383
	                logMetacat.debug("verb:" + httpVerb);
384
	                if (httpVerb == GET) {
385
	                    doQuery(engine, query);
386
	                    status = true;
387
	                }
388
                } else if (resource.startsWith(RESOURCE_GENERATE_ID)) {
389
                	// generate an id
390
                    if (httpVerb == POST) {
391
                        generateIdentifier();
392
                        status = true;
393
                    }
394
                } else if (resource.startsWith(RESOURCE_PUBLISH)) {
395
                    logMetacat.debug("Using resource: " + RESOURCE_PUBLISH);
396
                    // PUT
397
                    if (httpVerb == PUT) {
398
                    	// after the command
399
                        extra = parseTrailing(resource, RESOURCE_PUBLISH);
400
                        extra = decode(extra);
401
                        publish(extra);
402
                        status = true;
403
                    }  
404
                } else if (resource.startsWith(RESOURCE_PACKAGE)) {
405
                    logMetacat.debug("Using resource: " + RESOURCE_PACKAGE);
406
                    // get
407
                    if (httpVerb == GET) {
408
                    	// after the command
409
                        extra = parseTrailing(resource, RESOURCE_PACKAGE);
410
                        extra = decode(extra);
411
                        getPackage(extra);
412
                        status = true;
413
                    }  
414
                } else if (resource.startsWith(RESOURCE_VIEWS)) {
415
	                logMetacat.debug("Using resource " + RESOURCE_VIEWS);
416
	                // after the command
417
	                extra = parseTrailing(resource, RESOURCE_VIEWS);
418
	                logMetacat.debug("view extra: " + extra);
419

    
420
	                String format = null;
421
	                String pid = null;
422

    
423
	                if (extra != null) {
424
		                // get the format
425
		                int formatIndex = extra.length();
426
		                if (extra.indexOf("/") > -1) {
427
		                	formatIndex = extra.indexOf("/");
428
		                }
429
		                format = extra.substring(0, formatIndex);
430
		                format = decode(format);
431
		                logMetacat.debug("view format: " + format);
432
		                
433
		                // get the pid if it is there
434
		                pid = extra.substring(formatIndex, extra.length());
435
		                if (pid != null && pid.length() == 0) {
436
		                	pid = null;
437
		                } else {
438
		                	if (pid.startsWith("/")) {
439
		                		pid = pid.substring(1);
440
		                    }
441
		                }
442
		                pid = decode(pid);
443
		                logMetacat.debug("pid: " + pid);
444

    
445
	                }
446
	                logMetacat.debug("verb:" + httpVerb);
447
	                if (httpVerb == GET) {
448
	                    doViews(format, pid);
449
	                    status = true;
450
	                }
451
                } else {
452
                    throw new InvalidRequest("0000", "No resource matched for " + resource);
453
                } 
454
                
455
                if (!status) {
456
                	throw new ServiceFailure("0000", "Unknown error, status = " + status);
457
                }
458
            } else {
459
            	throw new InvalidRequest("0000", "No resource matched for " + resource);
460
            }
461
        } catch (BaseException be) {
462
        	// report Exceptions as clearly as possible
463
        	OutputStream out = null;
464
			try {
465
				out = response.getOutputStream();
466
			} catch (IOException e) {
467
				logMetacat.error("Could not get output stream from response", e);
468
			}
469
            serializeException(be, out);
470
        } catch (Exception e) {
471
            // report Exceptions as clearly and generically as possible
472
            logMetacat.error(e.getClass() + ": " + e.getMessage(), e);
473
        	OutputStream out = null;
474
			try {
475
				out = response.getOutputStream();
476
			} catch (IOException ioe) {
477
				logMetacat.error("Could not get output stream from response", ioe);
478
			}
479
			ServiceFailure se = new ServiceFailure("0000", e.getMessage());
480
            serializeException(se, out);
481
        }
482
    }
483
    
484
    private void getToken() throws Exception {
485
		
486
		if (this.session != null) {
487
			String userId = this.session.getSubject().getValue();
488
			String fullName = null;
489
			try {
490
				Person person = this.session.getSubjectInfo().getPerson(0);
491
				fullName = person.getGivenName(0) + " " + person.getFamilyName();
492
			} catch (Exception e) {
493
				logMetacat.warn(e.getMessage(), e);
494
			}
495
			String token = null;
496
			token = TokenGenerator.getInstance().getJWT(userId, fullName);
497
			
498
			response.setStatus(200);
499
			response.setContentType("text/plain");
500
	        OutputStream out = response.getOutputStream();
501
	        out.write(token.getBytes(MetaCatServlet.DEFAULT_ENCODING));
502
	        out.close();
503
		} else {
504
			response.setStatus(401);
505
			response.setContentType("text/plain");
506
			OutputStream out = response.getOutputStream();
507
	        out.write("No session information found".getBytes(MetaCatServlet.DEFAULT_ENCODING));
508
	        out.close();
509
		}
510
		
511
    }
512

    
513
    private void doQuery(String engine, String query) {
514
    	
515
		OutputStream out = null;
516

    
517
    	try {
518
    		// NOTE: we set the session explicitly for the MNode instance since these methods do not provide a parameter			
519
	    	if (engine == null) {
520
	    		// just looking for list of engines
521
	    		MNodeService mnode = MNodeService.getInstance(request);
522
    			mnode.setSession(session);
523
	    		QueryEngineList qel = mnode.listQueryEngines();
524
	    		response.setContentType("text/xml");
525
	            response.setStatus(200);
526
	            out = response.getOutputStream();
527
	            TypeMarshaller.marshalTypeToOutputStream(qel, out);
528
	            return;
529
	    	} else {
530
	    		if (query != null) {
531
	    			MNodeService mnode = MNodeService.getInstance(request);
532
	    			mnode.setSession(session);
533
	    			InputStream stream = mnode.query(engine, query);
534

    
535
	    			// set the content-type if we have it from the implementation
536
	    			if (stream instanceof ContentTypeInputStream) {
537
		    			//response.setContentType("application/octet-stream");
538
		    			//response.setContentType("text/xml");
539
	    				response.setContentType(((ContentTypeInputStream) stream).getContentType());
540
	    			}
541
	                response.setStatus(200);
542
	                out = response.getOutputStream();
543
	                // write the results to the output stream
544
	                IOUtils.copyLarge(stream, out);
545
	                return;
546
	    		} else {
547
	    			MNodeService mnode = MNodeService.getInstance(request);
548
	    			mnode.setSession(session);
549
	    			QueryEngineDescription qed = mnode.getQueryEngineDescription(engine);
550
	    			response.setContentType("text/xml");
551
		            response.setStatus(200);
552
		            out = response.getOutputStream();
553
		            TypeMarshaller.marshalTypeToOutputStream(qed, out);
554
		            return;
555
	    		}
556
	    	}
557
	        
558
	        
559
    	} catch (BaseException be) {
560
        	// report Exceptions as clearly as possible
561
			try {
562
				out = response.getOutputStream();
563
			} catch (IOException e) {
564
				logMetacat.error("Could not get output stream from response", e);
565
			}
566
            serializeException(be, out);
567
        } catch (Exception e) {
568
            // report Exceptions as clearly and generically as possible
569
            logMetacat.error(e.getClass() + ": " + e.getMessage(), e);
570
			try {
571
				out = response.getOutputStream();
572
			} catch (IOException ioe) {
573
				logMetacat.error("Could not get output stream from response", ioe);
574
			}
575
			ServiceFailure se = new ServiceFailure("0000", e.getMessage());
576
            serializeException(se, out);
577
        }
578
    }
579
    
580
    private void doViews(String format, String pid) {
581
    	
582
		OutputStream out = null;
583
		MNodeService mnode = MNodeService.getInstance(request);
584

    
585
    	try {
586
    		// get a list of views
587
    		if (pid != null) {
588
    			Identifier identifier = new Identifier();
589
    			identifier.setValue(pid);
590
				InputStream stream = mnode.view(session, format, identifier);
591

    
592
    			// set the content-type if we have it from the implementation
593
    			if (stream instanceof ContentTypeInputStream) {
594
    				response.setContentType(((ContentTypeInputStream) stream).getContentType());
595
    			}
596
                response.setStatus(200);
597
                out = response.getOutputStream();
598
                // write the results to the output stream
599
                IOUtils.copyLarge(stream, out);
600
                return;
601
    		} else {
602
    			// TODO: list the registered views
603
                BaseException ni = new NotImplemented("9999", "MN.listViews() is not implemented at this node");
604
				throw ni;
605
    		}
606
	    	
607
	        
608
    	} catch (BaseException be) {
609
        	// report Exceptions as clearly as possible
610
			try {
611
				out = response.getOutputStream();
612
			} catch (IOException e) {
613
				logMetacat.error("Could not get output stream from response", e);
614
			}
615
            serializeException(be, out);
616
        } catch (Exception e) {
617
            // report Exceptions as clearly and generically as possible
618
            logMetacat.error(e.getClass() + ": " + e.getMessage(), e);
619
			try {
620
				out = response.getOutputStream();
621
			} catch (IOException ioe) {
622
				logMetacat.error("Could not get output stream from response", ioe);
623
			}
624
			ServiceFailure se = new ServiceFailure("0000", e.getMessage());
625
            serializeException(se, out);
626
        }
627
    }
628
    
629
    /**
630
     * Handles notification of system metadata changes for the given identifier
631
     * 
632
     * @param id  the identifier for the object
633
     * @throws InvalidToken 
634
     * @throws InvalidRequest 
635
     * @throws NotAuthorized 
636
     * @throws ServiceFailure 
637
     * @throws NotImplemented 
638
     */
639
    private void systemMetadataChanged() 
640
        throws NotImplemented, ServiceFailure, NotAuthorized, InvalidRequest, 
641
        InvalidToken {
642

    
643
        long serialVersion = 0L;
644
        String serialVersionStr = null;
645
        Date dateSysMetaLastModified = null;
646
        String dateSysMetaLastModifiedStr = null;
647
        Identifier pid = null;
648
        
649
        // mkae sure we have the multipart params
650
        try {
651
			initMultipartParams();
652
		} catch (Exception e1) {
653
			throw new ServiceFailure("1333", "Could not collect the multipart params for the request");
654
		}
655
        
656
        // get the pid
657
        try {
658
        	String id = multipartparams.get("pid").get(0);
659
        	pid = new Identifier();
660
            pid.setValue(id);            
661
        } catch (NullPointerException e) {
662
            String msg = "The 'pid' must be provided as a parameter and was not.";
663
            logMetacat.error(msg);
664
            throw new InvalidRequest("1334", msg);
665
        }      
666
        
667
        // get the serialVersion
668
        try {
669
            serialVersionStr = multipartparams.get("serialVersion").get(0);
670
            serialVersion = new Long(serialVersionStr).longValue();
671
            
672
        } catch (NullPointerException e) {
673
            String msg = "The 'serialVersion' must be provided as a parameter and was not.";
674
            logMetacat.error(msg);
675
            throw new InvalidRequest("1334", msg);
676
            
677
        }       
678
        
679
        // get the dateSysMetaLastModified
680
        try {
681
            dateSysMetaLastModifiedStr = multipartparams.get("dateSysMetaLastModified").get(0);
682
            dateSysMetaLastModified = DateTimeMarshaller.deserializeDateToUTC(dateSysMetaLastModifiedStr);
683
            
684
        } catch (NullPointerException e) {
685
            String msg = 
686
                "The 'dateSysMetaLastModified' must be provided as a " + 
687
                "parameter and was not, or was an invalid representation of the timestamp.";
688
            logMetacat.error(msg);
689
            throw new InvalidRequest("1334", msg);
690
            
691
        }       
692
        
693
        // call the service
694
        MNodeService.getInstance(request).systemMetadataChanged(session, pid, serialVersion, dateSysMetaLastModified);
695
        response.setStatus(200);
696
    }
697
    
698
    /**
699
     * Handles identifier generation calls
700
     * 
701
     * @throws InvalidRequest 
702
     * @throws NotImplemented 
703
     * @throws NotAuthorized 
704
     * @throws ServiceFailure 
705
     * @throws InvalidToken 
706
     * @throws IOException 
707
     * @throws JiBXException 
708
     */
709
    private void generateIdentifier() throws InvalidToken, ServiceFailure, NotAuthorized, NotImplemented, InvalidRequest, IOException, JiBXException {
710
        
711
        // make sure we have the multipart params
712
        try {
713
			initMultipartParams();
714
		} catch (Exception e1) {
715
			throw new ServiceFailure("1333", "Could not collect the multipart params for the request");
716
		}
717
        
718
        // get the scheme
719
		String scheme = null;
720
        try {
721
        	scheme = multipartparams.get("scheme").get(0);	           
722
        } catch (NullPointerException e) {
723
            String msg = "The 'scheme' parameter was not provided, using default";
724
            logMetacat.warn(msg);
725
        }
726
        
727
        // get the fragment
728
		String fragment = null;
729
        try {
730
        	fragment = multipartparams.get("fragment").get(0);	           
731
        } catch (NullPointerException e) {
732
            String msg = "The 'fragment' parameter was not provided, using default";
733
            logMetacat.warn(msg);
734
        }
735

    
736
        // call the service
737
        Identifier identifier = MNodeService.getInstance(request).generateIdentifier(session, scheme, fragment);
738
        response.setStatus(200);
739
        response.setContentType("text/xml");
740
        OutputStream out = response.getOutputStream();
741
        TypeMarshaller.marshalTypeToOutputStream(identifier, out);
742
    }
743

    
744
    /**
745
     * Checks the access policy
746
     * @param id
747
     * @return
748
     * @throws ServiceFailure
749
     * @throws InvalidToken
750
     * @throws NotFound
751
     * @throws NotAuthorized
752
     * @throws NotImplemented
753
     * @throws InvalidRequest
754
     */
755
    private boolean isAuthorized(String id) throws ServiceFailure, InvalidToken, NotFound, NotAuthorized, NotImplemented, InvalidRequest {
756
		Identifier pid = new Identifier();
757
		pid.setValue(id);
758
		Permission permission = null;
759
		try {
760
			String perm = params.get("action")[0];
761
			permission = Permission.convert(perm);
762
		} catch (Exception e) {
763
			logMetacat.warn("No permission specified");
764
		}
765
		boolean result = MNodeService.getInstance(request).isAuthorized(session, pid, permission);
766
		response.setStatus(200);
767
		response.setContentType("text/xml");
768
		return result;
769
    }
770
    
771
    /**
772
     * Processes failed synchronization message
773
     * @throws NotImplemented
774
     * @throws ServiceFailure
775
     * @throws NotAuthorized
776
     * @throws InvalidRequest
777
     * @throws JiBXException
778
     * @throws IllegalAccessException 
779
     * @throws InstantiationException 
780
     * @throws IOException 
781
     * @throws InvalidToken 
782
     */
783
    private void syncError() throws NotImplemented, ServiceFailure, NotAuthorized, InvalidRequest, JiBXException, IOException, InstantiationException, IllegalAccessException, InvalidToken {
784
    	SynchronizationFailed syncFailed = null;
785
		try {
786
			syncFailed = collectSynchronizationFailed();
787
		} catch (ParserConfigurationException e) {
788
			throw new ServiceFailure("2161", e.getMessage());
789
		} catch (SAXException e) {
790
			throw new ServiceFailure("2161", e.getMessage());
791
		}
792
		
793
		MNodeService.getInstance(request).synchronizationFailed(session, syncFailed);
794
    }
795

    
796
	/**
797
     * Calculate the checksum 
798
     * @throws NotImplemented
799
     * @throws JiBXException
800
     * @throws IOException
801
     * @throws InvalidToken
802
     * @throws ServiceFailure
803
     * @throws NotAuthorized
804
     * @throws NotFound
805
     * @throws InvalidRequest
806
     */
807
    private void checksum(String pid) throws NotImplemented, JiBXException, IOException, InvalidToken, ServiceFailure, NotAuthorized, NotFound, InvalidRequest {
808
    	String checksumAlgorithm = "MD5";
809
    	try {
810
    		checksumAlgorithm = PropertyService.getProperty("dataone.checksumAlgorithm.default");
811
        } catch(Exception e) {
812
        	logMetacat.warn("Could not lookup configured default checksum algorithm, using: " + checksumAlgorithm);
813
        }    
814
        
815
        Identifier pidid = new Identifier();
816
        pidid.setValue(pid);
817
        try {
818
            checksumAlgorithm = params.get("checksumAlgorithm")[0];
819
        } catch(Exception e) {
820
            //do nothing.  use the default
821
        	logMetacat.warn("No algorithm specified, using default: " + checksumAlgorithm);
822
        }
823
        logMetacat.debug("getting checksum for object " + pid + " with algorithm " + checksumAlgorithm);
824
        
825
        Checksum c = MNodeService.getInstance(request).getChecksum(session, pidid, checksumAlgorithm);
826
        logMetacat.debug("got checksum " + c.getValue());
827
        response.setStatus(200);
828
        logMetacat.debug("serializing response");
829
        TypeMarshaller.marshalTypeToOutputStream(c, response.getOutputStream());
830
        logMetacat.debug("done serializing response.");
831
        
832
    }
833
    
834
	/**
835
     * handle the replicate action for MN
836
	 * @throws JiBXException 
837
	 * @throws FileUploadException 
838
	 * @throws IOException 
839
	 * @throws InvalidRequest 
840
	 * @throws ServiceFailure 
841
	 * @throws UnsupportedType 
842
	 * @throws InsufficientResources 
843
	 * @throws NotAuthorized 
844
	 * @throws NotImplemented 
845
	 * @throws IllegalAccessException 
846
	 * @throws InstantiationException 
847
	 * @throws InvalidToken 
848
     */
849
    private void replicate() 
850
        throws ServiceFailure, InvalidRequest, IOException, FileUploadException, 
851
        JiBXException, NotImplemented, NotAuthorized, InsufficientResources, 
852
        UnsupportedType, InstantiationException, IllegalAccessException, InvalidToken {
853

    
854
        logMetacat.debug("in POST replicate()");
855
        
856
        // somewhat unorthodox, but the call is asynchronous and we'd like to return this info sooner
857
        boolean allowed = false;
858
        if (session == null) {
859
        	String msg = "No session was provided.";
860
            NotAuthorized failure = new NotAuthorized("2152", msg);
861
        	throw failure;
862
        } else {
863
        	allowed = MNodeService.getInstance(request).isAdminAuthorized(session);
864
        	if (!allowed) {
865
        		String msg = "User is not an admin user";
866
                NotAuthorized failure = new NotAuthorized("2152", msg);
867
            	throw failure;
868
        	}
869
        }
870
        
871
        // parse the systemMetadata
872
        Map<String, File> files = collectMultipartFiles();        
873
        final SystemMetadata sysmeta = TypeMarshaller.unmarshalTypeFromFile(SystemMetadata.class, files.get("sysmeta"));
874
        
875
        String sn = multipartparams.get("sourceNode").get(0);
876
        logMetacat.debug("sourceNode: " + sn);
877
        final NodeReference sourceNode = new NodeReference();
878
        sourceNode.setValue(sn);
879
        
880
        // run it in a thread to avoid connection timeout
881
        Runnable runner = new Runnable() {
882
			@Override
883
			public void run() {
884
				try {
885
			        MNodeService.getInstance(request).replicate(session, sysmeta, sourceNode);
886
				} catch (Exception e) {
887
					logMetacat.error("Error running replication: " + e.getMessage(), e);
888
					throw new RuntimeException(e.getMessage(), e);
889
				}
890
			}
891
    	};
892
    	// submit the task, and that's it
893
    	executor.submit(runner);
894
        
895
    	// thread was started, so we return success
896
        response.setStatus(200);
897
        
898
    }
899

    
900
    /**
901
     * Handle the getReplica action for the MN
902
     * @param id  the identifier for the object
903
     * @throws NotFound 
904
     * @throws ServiceFailure 
905
     * @throws NotImplemented 
906
     * @throws NotAuthorized 
907
     * @throws InvalidToken 
908
     * @throws InvalidRequest 
909
     * @throws InsufficientResources 
910
     */
911
    private void getReplica(String id) 
912
        throws InvalidRequest, InvalidToken, NotAuthorized, NotImplemented, 
913
        ServiceFailure, NotFound, InsufficientResources {
914
        
915
        Identifier pid = new Identifier();
916
        pid.setValue(id);
917
        OutputStream out = null;
918
        InputStream dataBytes = null;
919
                
920
        try {
921
            // call the service
922
            dataBytes = MNodeService.getInstance(request).getReplica(session, pid);
923

    
924
            response.setContentType("application/octet-stream");
925
            response.setStatus(200);
926
            out = response.getOutputStream();
927
            // write the object to the output stream
928
            IOUtils.copyLarge(dataBytes, out);
929
            
930
        } catch (IOException e) {
931
            String msg = "There was an error writing the output: " + e.getMessage();
932
            logMetacat.error(msg);
933
            throw new ServiceFailure("2181", msg);
934
        
935
        }
936

    
937
    }
938

    
939
    /**
940
     * Get the Node information
941
     * 
942
     * @throws JiBXException
943
     * @throws IOException
944
     * @throws InvalidRequest 
945
     * @throws ServiceFailure 
946
     * @throws NotAuthorized 
947
     * @throws NotImplemented 
948
     */
949
    private void node() 
950
        throws JiBXException, IOException, NotImplemented, NotAuthorized, ServiceFailure, InvalidRequest {
951
        
952
        Node n = MNodeService.getInstance(request).getCapabilities();
953
        
954
        response.setContentType("text/xml");
955
        response.setStatus(200);
956
        TypeMarshaller.marshalTypeToOutputStream(n, response.getOutputStream());
957
        
958
    }
959
    
960
    /**
961
     * MN_crud.describe()
962
     * http://mule1.dataone.org/ArchitectureDocs/mn_api_crud.html#MN_crud.describe
963
     * @param pid
964
     * @throws InvalidRequest 
965
     * @throws NotImplemented 
966
     * @throws NotFound 
967
     * @throws NotAuthorized 
968
     * @throws ServiceFailure 
969
     * @throws InvalidToken 
970
     */
971
    private void describeObject(String pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented, InvalidRequest
972
    {
973
        
974
        response.setContentType("text/xml");
975

    
976
        Identifier id = new Identifier();
977
        id.setValue(pid);
978

    
979
        DescribeResponse dr = null;
980
        try {
981
        	dr = MNodeService.getInstance(request).describe(session, id);
982
        } catch (BaseException e) {
983
        	response.setStatus(e.getCode());
984
        	response.addHeader("DataONE-Exception-Name", e.getClass().getName());
985
            response.addHeader("DataONE-Exception-DetailCode", e.getDetail_code());
986
            response.addHeader("DataONE-Exception-Description", e.getDescription());
987
            response.addHeader("DataONE-Exception-PID", id.getValue());
988
            return;
989
		}
990
        
991
        response.setStatus(200);
992
        
993
        //response.addHeader("pid", pid);
994
        response.addHeader("DataONE-Checksum", dr.getDataONE_Checksum().getAlgorithm() + "," + dr.getDataONE_Checksum().getValue());
995
        response.addHeader("Content-Length", dr.getContent_Length() + "");
996
        response.addHeader("Last-Modified", DateTimeMarshaller.serializeDateToUTC(dr.getLast_Modified()));
997
        response.addHeader("DataONE-ObjectFormat", dr.getDataONE_ObjectFormatIdentifier().getValue());
998
        response.addHeader("DataONE-SerialVersion", dr.getSerialVersion().toString());
999

    
1000
        
1001
    }
1002
    
1003
    /**
1004
     * get the logs based on passed params.  Available 
1005
     * See http://mule1.dataone.org/ArchitectureDocs/mn_api_crud.html#MN_crud.getLogRecords
1006
     * for more info
1007
     * @throws NotImplemented 
1008
     * @throws InvalidRequest 
1009
     * @throws NotAuthorized 
1010
     * @throws ServiceFailure 
1011
     * @throws InvalidToken 
1012
     * @throws IOException 
1013
     * @throws JiBXException 
1014
     */
1015
    private void getLog() throws InvalidToken, ServiceFailure, NotAuthorized, InvalidRequest, NotImplemented, IOException, JiBXException
1016
    {
1017
            
1018
        Date fromDate = null;
1019
        Date toDate = null;
1020
        Event event = null;
1021
        Integer start = null;
1022
        Integer count = null;
1023
        String pidFilter = null;
1024
        
1025
        try {
1026
        	String fromDateS = params.get("fromDate")[0];
1027
            logMetacat.debug("param fromDateS: " + fromDateS);
1028
            fromDate = DateTimeMarshaller.deserializeDateToUTC(fromDateS);
1029
        } catch (Exception e) {
1030
        	logMetacat.warn("Could not parse fromDate: " + e.getMessage());
1031
        }
1032
        try {
1033
        	String toDateS = params.get("toDate")[0];
1034
            logMetacat.debug("param toDateS: " + toDateS);
1035
            toDate = DateTimeMarshaller.deserializeDateToUTC(toDateS);
1036
        } catch (Exception e) {
1037
        	logMetacat.warn("Could not parse toDate: " + e.getMessage());
1038
		}
1039
        try {
1040
        	String eventS = params.get("event")[0];
1041
            event = Event.convert(eventS);
1042
        } catch (Exception e) {
1043
        	logMetacat.warn("Could not parse event: " + e.getMessage());
1044
		}
1045
        logMetacat.debug("fromDate: " + fromDate + " toDate: " + toDate);
1046
        
1047
        try {
1048
        	start =  Integer.parseInt(params.get("start")[0]);
1049
        } catch (Exception e) {
1050
			logMetacat.warn("Could not parse start: " + e.getMessage());
1051
		}
1052
        try {
1053
        	count =  Integer.parseInt(params.get("count")[0]);
1054
        } catch (Exception e) {
1055
			logMetacat.warn("Could not parse count: " + e.getMessage());
1056
		}
1057
        
1058
        try {
1059
            pidFilter = params.get("pidFilter")[0];
1060
        } catch (Exception e) {
1061
            logMetacat.warn("Could not parse pidFilter: " + e.getMessage());
1062
        }
1063
        
1064
        logMetacat.debug("calling getLogRecords");
1065
        Log log = MNodeService.getInstance(request).getLogRecords(session, fromDate, toDate, event, pidFilter, start, count);
1066
        
1067
        OutputStream out = response.getOutputStream();
1068
        response.setStatus(200);
1069
        response.setContentType("text/xml");
1070
        
1071
        TypeMarshaller.marshalTypeToOutputStream(log, out);
1072
        
1073
    }
1074
    
1075
    
1076
    
1077
    /**
1078
     * Implements REST version of DataONE CRUD API --> get
1079
     * @param pid ID of data object to be read
1080
     * @throws NotImplemented 
1081
     * @throws InvalidRequest 
1082
     * @throws NotFound 
1083
     * @throws NotAuthorized 
1084
     * @throws ServiceFailure 
1085
     * @throws InvalidToken 
1086
     * @throws IOException 
1087
     * @throws JiBXException 
1088
     * @throws InsufficientResources 
1089
     */
1090
    protected void getObject(String pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, InvalidRequest, NotImplemented, IOException, JiBXException, InsufficientResources {
1091
        OutputStream out = null;
1092
        
1093
        if (pid != null) { //get a specific document                
1094
            Identifier id = new Identifier();
1095
            id.setValue(pid);
1096
            InputStream data = MNodeService.getInstance(request).get(session, id);
1097
            SystemMetadata sm = MNodeService.getInstance(request).getSystemMetadata(session, id);
1098
            
1099
            // set the headers for the content
1100
            String mimeType = ObjectFormatInfo.instance().getMimeType(sm.getFormatId().getValue());
1101
            if (mimeType == null) {
1102
            	mimeType = "application/octet-stream";
1103
            }
1104
            String extension = ObjectFormatInfo.instance().getExtension(sm.getFormatId().getValue());
1105
            String filename = id.getValue();
1106
            if (extension != null) {
1107
            	filename = id.getValue() + extension;
1108
            }
1109
            response.setContentType(mimeType);
1110
            response.setHeader("Content-Disposition", "inline; filename=" + filename);
1111
            out = response.getOutputStream();  
1112
            IOUtils.copyLarge(data, out);
1113
            
1114
        }
1115
        else
1116
        { //call listObjects with specified params
1117
            Date startTime = null;
1118
            Date endTime = null;
1119
            ObjectFormatIdentifier formatId = null;
1120
            boolean replicaStatus = true;
1121
            int start = 0;
1122
            //TODO: make the max count into a const
1123
            int count = 1000;
1124
            Enumeration paramlist = request.getParameterNames();
1125
            while (paramlist.hasMoreElements()) 
1126
            { //parse the params and make the crud call
1127
                String name = (String) paramlist.nextElement();
1128
                String[] value = (String[])request.getParameterValues(name);
1129

    
1130
                if (name.equals("fromDate") && value != null)
1131
                {
1132
                    try
1133
                    {
1134
                      //startTime = dateFormat.parse(value[0]);
1135
                    	startTime = DateTimeMarshaller.deserializeDateToUTC(value[0]);
1136
                        //startTime = parseDateAndConvertToGMT(value[0]);
1137
                    }
1138
                    catch(Exception e)
1139
                    {  //if we can't parse it, just don't use the fromDate param
1140
                        logMetacat.warn("Could not parse fromDate: " + value[0]);
1141
                        startTime = null;
1142
                    }
1143
                }
1144
                else if(name.equals("toDate") && value != null)
1145
                {
1146
                    try
1147
                    {
1148
                    	endTime = DateTimeMarshaller.deserializeDateToUTC(value[0]);
1149
                    }
1150
                    catch(Exception e)
1151
                    {  //if we can't parse it, just don't use the toDate param
1152
                        logMetacat.warn("Could not parse toDate: " + value[0]);
1153
                        endTime = null;
1154
                    }
1155
                }
1156
                else if(name.equals("formatId") && value != null) 
1157
                {
1158
                	formatId = new ObjectFormatIdentifier();
1159
                	formatId.setValue(value[0]);
1160
                }
1161
                else if(name.equals("replicaStatus") && value != null)
1162
                {
1163
                    if(value != null && 
1164
                       value.length > 0 && 
1165
                       (value[0].equalsIgnoreCase("false") || value[0].equalsIgnoreCase("no")))
1166
                    {
1167
                        replicaStatus = false;
1168
                    }
1169
                }
1170
                else if(name.equals("start") && value != null)
1171
                {
1172
                    start = new Integer(value[0]).intValue();
1173
                }
1174
                else if(name.equals("count") && value != null)
1175
                {
1176
                    count = new Integer(value[0]).intValue();
1177
                }
1178
            }
1179
            //make the crud call
1180
            logMetacat.debug("session: " + session + " startTime: " + startTime +
1181
                    " endTime: " + endTime + " formatId: " + 
1182
                    formatId + " replicaStatus: " + replicaStatus + 
1183
                    " start: " + start + " count: " + count);
1184
           
1185
            ObjectList ol = 
1186
           	 MNodeService.getInstance(request).listObjects(session, startTime, endTime, 
1187
           			formatId, replicaStatus, start, count);
1188
           
1189
            out = response.getOutputStream();  
1190
            response.setStatus(200);
1191
            response.setContentType("text/xml");
1192
            // Serialize and write it to the output stream
1193
            TypeMarshaller.marshalTypeToOutputStream(ol, out);
1194
            
1195
        }
1196
        
1197
    }
1198
    
1199

    
1200
    /**
1201
     * Retrieve data package as Bagit zip
1202
     * @param pid
1203
     * @throws NotImplemented 
1204
     * @throws NotFound 
1205
     * @throws NotAuthorized 
1206
     * @throws ServiceFailure 
1207
     * @throws InvalidToken 
1208
     * @throws IOException 
1209
     * @throws InvalidRequest 
1210
     */
1211
    protected void getPackage(String pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented, IOException, InvalidRequest {
1212

    
1213
        Identifier id = new Identifier();
1214
        id.setValue(pid);
1215
        InputStream is = MNodeService.getInstance(request).getPackage(session, null, id);
1216
        
1217
        // use the provided filename
1218
        String filename = null;
1219
        if (is instanceof DeleteOnCloseFileInputStream) {
1220
            filename = ((DeleteOnCloseFileInputStream)is).getFile().getName();
1221
        } else {
1222
        	filename = "dataPackage-" + System.currentTimeMillis() + ".zip";
1223
        }
1224
        response.setHeader("Content-Disposition", "inline; filename=" + filename);
1225
        response.setContentType("application/zip");
1226
        response.setStatus(200);
1227
        OutputStream out = response.getOutputStream();
1228
        
1229
        // write it to the output stream
1230
        IOUtils.copyLarge(is, out);
1231
   }
1232
    
1233
	protected void publish(String pid) throws InvalidToken, ServiceFailure,
1234
			NotAuthorized, NotFound, NotImplemented, IOException,
1235
			JiBXException, InvalidRequest, IdentifierNotUnique,
1236
			UnsupportedType, InsufficientResources, InvalidSystemMetadata {
1237

    
1238
		// publish the object
1239
		Identifier originalIdentifier = new Identifier();
1240
		originalIdentifier.setValue(pid);
1241
		Identifier newIdentifier = MNodeService.getInstance(request).publish(session, originalIdentifier);
1242

    
1243
		response.setStatus(200);
1244
		response.setContentType("text/xml");
1245
		OutputStream out = response.getOutputStream();
1246

    
1247
		// write new identifier to the output stream
1248
		TypeMarshaller.marshalTypeToOutputStream(newIdentifier, out);
1249
	}
1250
    
1251
    /**
1252
     * Retrieve System Metadata
1253
     * @param pid
1254
     * @throws InvalidToken
1255
     * @throws ServiceFailure
1256
     * @throws NotAuthorized
1257
     * @throws NotFound
1258
     * @throws InvalidRequest
1259
     * @throws NotImplemented
1260
     * @throws IOException
1261
     * @throws JiBXException
1262
     */
1263
    protected void getSystemMetadataObject(String pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, InvalidRequest, NotImplemented, IOException, JiBXException {
1264

    
1265
        Identifier id = new Identifier();
1266
        id.setValue(pid);
1267
        SystemMetadata sysmeta = MNodeService.getInstance(request).getSystemMetadata(session, id);
1268
        
1269
        response.setContentType("text/xml");
1270
        response.setStatus(200);
1271
        OutputStream out = response.getOutputStream();
1272
        
1273
        // Serialize and write it to the output stream
1274
        TypeMarshaller.marshalTypeToOutputStream(sysmeta, out);
1275
   }
1276
    
1277
    
1278
    /**
1279
     * Inserts or updates the object
1280
     * 
1281
     * @param pid - ID of data object to be inserted or updated.  If action is update, the pid
1282
     *               is the existing pid.  If insert, the pid is the new one
1283
     * @throws InvalidRequest 
1284
     * @throws ServiceFailure 
1285
     * @throws JiBXException 
1286
     * @throws NotImplemented 
1287
     * @throws InvalidSystemMetadata 
1288
     * @throws InsufficientResources 
1289
     * @throws UnsupportedType 
1290
     * @throws IdentifierNotUnique 
1291
     * @throws NotAuthorized 
1292
     * @throws InvalidToken 
1293
     * @throws NotFound 
1294
     * @throws IOException 
1295
     * @throws IllegalAccessException 
1296
     * @throws InstantiationException 
1297
     */
1298
    protected void putObject(String trailingPid, String action) throws ServiceFailure, InvalidRequest, JiBXException, InvalidToken, NotAuthorized, IdentifierNotUnique, UnsupportedType, InsufficientResources, InvalidSystemMetadata, NotImplemented, NotFound, IOException, InstantiationException, IllegalAccessException {
1299
       
1300
    	// Read the incoming data from its Mime Multipart encoding
1301
    	Map<String, File> files = collectMultipartFiles();
1302
               
1303
    	Identifier pid = new Identifier();
1304
        if (trailingPid == null) {
1305
	        // get the pid string from the body and set the value
1306
	        String pidString = multipartparams.get("pid").get(0);
1307
	        if (pidString != null) {
1308
            pid.setValue(pidString);
1309
            
1310
          } else {
1311
              throw new InvalidRequest("1102", "The pid param must be included and contain the identifier.");
1312
              
1313
          }
1314
        } else {
1315
        	// use the pid included in the URL
1316
        	pid.setValue(trailingPid);
1317
        }
1318
        logMetacat.debug("putObject with pid " + pid.getValue());
1319
        logMetacat.debug("Entering putObject: " + pid.getValue() + "/" + action);
1320

    
1321
        InputStream object = null;
1322
        InputStream sysmeta = null;
1323
        File smFile = files.get("sysmeta");
1324
        sysmeta = new FileInputStream(smFile);
1325
        File objFile = files.get("object");
1326
        object = new FileInputStream(objFile);
1327
        
1328
        // ensure we have the object bytes
1329
        if  ( objFile == null ) {
1330
            throw new InvalidRequest("1102", "The object param must contain the object bytes.");
1331
            
1332
        }
1333
        
1334
        // ensure we have the system metadata
1335
        if  ( smFile == null ) {
1336
            throw new InvalidRequest("1102", "The sysmeta param must contain the system metadata document.");
1337
            
1338
        }
1339
        
1340
        response.setStatus(200);
1341
        response.setContentType("text/xml");
1342
        OutputStream out = response.getOutputStream();
1343
        
1344
        if (action.equals(FUNCTION_NAME_INSERT)) { 
1345
            // handle inserts
1346
            logMetacat.debug("Commence creation...");
1347
            SystemMetadata smd = TypeMarshaller.unmarshalTypeFromStream(SystemMetadata.class, sysmeta);
1348

    
1349
            logMetacat.debug("creating object with pid " + pid.getValue());
1350
            Identifier rId = MNodeService.getInstance(request).create(session, pid, object, smd);
1351
            TypeMarshaller.marshalTypeToOutputStream(rId, out);
1352
            
1353
        } else if (action.equals(FUNCTION_NAME_UPDATE)) {
1354
        	// handle updates
1355
        	
1356
            // construct pids
1357
            Identifier newPid = null;
1358
            try {
1359
            	String newPidString = multipartparams.get("newPid").get(0);
1360
            	newPid = new Identifier();
1361
            	newPid.setValue(newPidString);
1362
            } catch (Exception e) {
1363
				logMetacat.error("Could not get newPid from request");
1364
			}
1365
            logMetacat.debug("Commence update...");
1366
            
1367
            // get the systemmetadata object
1368
            SystemMetadata smd = TypeMarshaller.unmarshalTypeFromStream(SystemMetadata.class, sysmeta);
1369

    
1370
            Identifier rId = MNodeService.getInstance(request).update(session, pid, object, newPid, smd);
1371
            TypeMarshaller.marshalTypeToOutputStream(rId, out);
1372
        } else {
1373
            throw new InvalidRequest("1000", "Operation must be create or update.");
1374
        }
1375
   
1376
    }
1377

    
1378
    /**
1379
     * Handle delete 
1380
     * @param pid ID of data object to be deleted
1381
     * @throws IOException
1382
     * @throws InvalidRequest 
1383
     * @throws NotImplemented 
1384
     * @throws NotFound 
1385
     * @throws NotAuthorized 
1386
     * @throws ServiceFailure 
1387
     * @throws InvalidToken 
1388
     * @throws JiBXException 
1389
     */
1390
    private void deleteObject(String pid) throws IOException, InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented, InvalidRequest, JiBXException 
1391
    {
1392

    
1393
        OutputStream out = response.getOutputStream();
1394
        response.setStatus(200);
1395
        response.setContentType("text/xml");
1396

    
1397
        Identifier id = new Identifier();
1398
        id.setValue(pid);
1399

    
1400
        logMetacat.debug("Calling delete");
1401
        MNodeService.getInstance(request).delete(session, id);
1402
        TypeMarshaller.marshalTypeToOutputStream(id, out);
1403
        
1404
    }
1405
    
1406
    /**
1407
     * Archives the given pid
1408
     * @param pid
1409
     * @throws InvalidToken
1410
     * @throws ServiceFailure
1411
     * @throws NotAuthorized
1412
     * @throws NotFound
1413
     * @throws NotImplemented
1414
     * @throws IOException
1415
     * @throws JiBXException
1416
     */
1417
    private void archive(String pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented, IOException, JiBXException {
1418

    
1419
        OutputStream out = response.getOutputStream();
1420
        response.setStatus(200);
1421
        response.setContentType("text/xml");
1422

    
1423
        Identifier id = new Identifier();
1424
        id.setValue(pid);
1425

    
1426
        logMetacat.debug("Calling archive");
1427
        MNodeService.getInstance(request).archive(session, id);
1428
        
1429
        TypeMarshaller.marshalTypeToOutputStream(id, out);
1430
        
1431
    }
1432

    
1433
	protected SynchronizationFailed collectSynchronizationFailed() throws IOException, ServiceFailure, InvalidRequest, JiBXException, InstantiationException, IllegalAccessException, ParserConfigurationException, SAXException  {
1434
		
1435
		// Read the incoming data from its Mime Multipart encoding
1436
		logMetacat.debug("Disassembling MIME multipart form");
1437
		InputStream sf = null;
1438
	
1439
		// handle MMP inputs
1440
		File tmpDir = getTempDirectory();
1441
		logMetacat.debug("temp dir: " + tmpDir.getAbsolutePath());
1442
		MultipartRequestResolver mrr = 
1443
			new MultipartRequestResolver(tmpDir.getAbsolutePath(), MAX_UPLOAD_SIZE, 0);
1444
		MultipartRequest mr = null;
1445
		try {
1446
			mr = mrr.resolveMultipart(request);
1447
		} catch (Exception e) {
1448
			throw new ServiceFailure("2161", 
1449
					"Could not resolve multipart: " + e.getMessage());
1450
		}
1451
		logMetacat.debug("resolved multipart request");
1452
		Map<String, File> files = mr.getMultipartFiles();
1453
		if (files == null || files.keySet() == null) {
1454
			throw new InvalidRequest("2163",
1455
					"must have multipart file with name 'message'");
1456
		}
1457
		logMetacat.debug("got multipart files");
1458
	
1459
		multipartparams = mr.getMultipartParameters();
1460
	
1461
		File sfFile = files.get("message");
1462
		if (sfFile == null) {
1463
			throw new InvalidRequest("2163",
1464
					"Missing the required file-part 'message' from the multipart request.");
1465
		}
1466
		logMetacat.debug("sfFile: " + sfFile.getAbsolutePath());
1467
		sf = new FileInputStream(sfFile);
1468
	
1469
		SynchronizationFailed syncFailed = (SynchronizationFailed) ExceptionHandler.deserializeXml(sf, "Error deserializing exception");
1470
		return syncFailed;
1471
	}
1472

    
1473
}
(3-3/4)