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: leinfelder $'
7
 *     '$Date: 2011-07-27 16:25:30 -0700 (Wed, 27 Jul 2011) $'
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;
24

    
25
import java.io.ByteArrayInputStream;
26
import java.io.File;
27
import java.io.FileInputStream;
28
import java.io.IOException;
29
import java.io.InputStream;
30
import java.io.OutputStream;
31
import java.io.UnsupportedEncodingException;
32
import java.text.DateFormat;
33
import java.text.ParseException;
34
import java.text.SimpleDateFormat;
35
import java.util.Date;
36
import java.util.Enumeration;
37
import java.util.Map;
38
import java.util.TimeZone;
39

    
40
import javax.servlet.ServletContext;
41
import javax.servlet.http.HttpServletRequest;
42
import javax.servlet.http.HttpServletResponse;
43

    
44
import org.apache.commons.fileupload.FileUploadException;
45
import org.apache.commons.io.IOUtils;
46
import org.apache.log4j.Logger;
47
import org.dataone.client.ObjectFormatCache;
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.AccessPolicy;
61
import org.dataone.service.types.v1.Checksum;
62
import org.dataone.service.types.v1.DescribeResponse;
63
import org.dataone.service.types.v1.Event;
64
import org.dataone.service.types.v1.Identifier;
65
import org.dataone.service.types.v1.Log;
66
import org.dataone.service.types.v1.MonitorList;
67
import org.dataone.service.types.v1.Node;
68
import org.dataone.service.types.v1.NodeList;
69
import org.dataone.service.types.v1.NodeReference;
70
import org.dataone.service.types.v1.ObjectFormat;
71
import org.dataone.service.types.v1.ObjectFormatIdentifier;
72
import org.dataone.service.types.v1.ObjectList;
73
import org.dataone.service.types.v1.Permission;
74
import org.dataone.service.types.v1.Subject;
75
import org.dataone.service.types.v1.SystemMetadata;
76
import org.jibx.runtime.JiBXException;
77

    
78
import edu.ucsb.nceas.metacat.dataone.MNodeService;
79

    
80
/**
81
 * MN REST service implementation handler
82
 * 
83
 * ******************
84
 * MNCore -- DONE
85
 * 		ping() - GET /d1/mn/monitor/ping
86
 * 		log() - GET /d1/mn/log
87
 * 		**getObjectStatistics() - GET /d1/mn/monitor/object
88
 * 		getOperationsStatistics - GET /d1/mn/monitor/event
89
 * 		**getStatus - GET /d1/mn/monitor/status
90
 * 		getCapabilities() - GET /d1/mn/ and /d1/mn/node
91
 * 	
92
 * 	MNRead -- DONE
93
 * 		get() - GET /d1/mn/object/PID
94
 * 		getSystemMetadata() - GET /d1/mn/meta/PID
95
 * 		describe() - HEAD /d1/mn/object/PID
96
 * 		getChecksum() - GET /d1/mn/checksum/PID
97
 * 		listObjects() - GET /d1/mn/object
98
 * 		synchronizationFailed() - POST /d1/mn/error
99
 * 	
100
 * 	MNAuthorization -- DONE
101
 * 		isAuthorized() - GET /d1/mn/isAuthorized/PID
102
 * 		setAccessPolicy() - PUT /d1/mn/accessRules/PID
103
 * 		
104
 * 	MNStorage - DONE
105
 * 		create() - POST /d1/mn/object/PID
106
 * 		update() - PUT /d1/mn/object/PID
107
 * 		delete() - DELETE /d1/mn/object/PID
108
 * 	
109
 * 	MNReplication
110
 * 		replicate() - POST /d1/mn/replicate
111
 * 
112
 * ******************
113
 * @author leinfelder
114
 *
115
 */
116
public class MNResourceHandler extends D1ResourceHandler{
117

    
118
    // MN-specific API Resources
119
    protected static final String RESOURCE_MONITOR = "monitor";
120
    protected static final String RESOURCE_REPLICATE = "replicate";
121
    protected static final String RESOURCE_NODE = "node";
122
    protected static final String RESOURCE_ERROR = "error";
123

    
124
    /**
125
     * Initializes new instance by setting servlet context,request and response
126
     * */
127
    public MNResourceHandler(ServletContext servletContext,
128
            HttpServletRequest request, HttpServletResponse response) {
129
    	super(servletContext, request, response);
130
        logMetacat = Logger.getLogger(MNResourceHandler.class);
131
    }
132

    
133
    /**
134
     * This function is called from REST API servlet and handles each request to the servlet 
135
     * 
136
     * @param httpVerb (GET, POST, PUT or DELETE)
137
     */
138
    @Override
139
    public void handle(byte httpVerb) {
140
    	// prepare the handler
141
    	super.handle(httpVerb);
142
    	
143
        try {
144
        	// get the resource
145
            String resource = request.getPathInfo();
146
            resource = resource.substring(resource.indexOf("/") + 1);
147
            
148
            // default to node info
149
            if (resource.equals("")) {
150
                resource = RESOURCE_NODE;
151
            }
152
            
153
            // get the rest of the path info
154
            String extra = null;
155
            if (resource.lastIndexOf("/") != -1) {
156
                extra = resource.substring(resource.lastIndexOf("/") + 1);
157
            }
158
                        
159
            logMetacat.debug("handling verb " + httpVerb + " request with resource '" + resource + "'");
160
            logMetacat.debug("resource: '" + resource + "'");
161
            boolean status = false;
162
            
163
            if (resource != null) {
164

    
165
                if (resource.startsWith(RESOURCE_NODE)) {
166
                    // node response
167
                    node();
168
                    status = true;
169
                } else if (resource.startsWith(RESOURCE_ACCESS_RULES)) {
170
                    if (httpVerb == POST) {
171
	                	// set the access rules
172
	                    setAccess();
173
	                    status = true;
174
	                    logMetacat.debug("done setting access");
175
                    }
176
                } else if (resource.startsWith(RESOURCE_IS_AUTHORIZED)) {
177
                    if (httpVerb == GET) {
178
	                	// check the access rules
179
	                    isAuthorized(extra);
180
	                    status = true;
181
	                    logMetacat.debug("done getting access");
182
                    }
183
                } else if (resource.startsWith(RESOURCE_META)) {
184
                    logMetacat.debug("Using resource 'meta'");
185
                    // get
186
                    if (httpVerb == GET) {
187
                        getSystemMetadataObject(extra);
188
                        status = true;
189
                    }
190
                    
191
                } else if (resource.startsWith(RESOURCE_OBJECTS)) {
192
                    logMetacat.debug("Using resource 'object'");
193
                    
194
                    logMetacat.debug("objectId: " + extra);
195
                    logMetacat.debug("verb:" + httpVerb);
196

    
197
                    if (httpVerb == GET) {
198
                        getObject(extra);
199
                        status = true;
200
                    } else if (httpVerb == POST) {
201
                        putObject(extra, FUNCTION_NAME_INSERT);
202
                        status = true;
203
                    } else if (httpVerb == PUT) {
204
                        putObject(extra, FUNCTION_NAME_UPDATE);
205
                        status = true;
206
                    } else if (httpVerb == DELETE) {
207
                        deleteObject(extra);
208
                        status = true;
209
                    } else if (httpVerb == HEAD) {
210
                        describeObject(extra);
211
                        status = true;
212
                    }
213
                  
214
                } else if (resource.startsWith(RESOURCE_LOG)) {
215
                    logMetacat.debug("Using resource 'log'");
216
                    // handle log events
217
                    if (httpVerb == GET) {
218
                        getLog();
219
                        status = true;
220
                    }
221
                } else if (resource.startsWith(RESOURCE_CHECKSUM)) {
222
                    logMetacat.debug("Using resource 'checksum'");
223
                    // handle checksum requests
224
                    if (httpVerb == GET) {
225
                        checksum(extra);
226
                        status = true;
227
                    }
228
                } else if (resource.startsWith(RESOURCE_MONITOR)) {
229
                    // there are various parts to monitoring
230
                    if (httpVerb == GET) {
231
                    	// health monitoring calls
232
                        status = monitor(extra);
233
                    }
234
                } else if (resource.startsWith(RESOURCE_REPLICATE)) {
235
                	if (httpVerb == POST) {
236
	                    logMetacat.debug("processing replicate request");
237
	                    replicate();
238
	                    status = true;
239
                	}
240
                } else if (resource.startsWith(RESOURCE_ERROR)) {
241
	                // sync error
242
	                if (httpVerb == POST) {
243
	                    syncError();
244
	                    status = true;
245
	                }
246
                }
247
                
248
                if (!status) {
249
                	throw new ServiceFailure("0000", "Unknown error, status = " + status);
250
                }
251
            } else {
252
            	throw new InvalidRequest("0000", "No resource matched for " + resource);
253
            }
254
        } catch (BaseException be) {
255
        	// report Exceptions as clearly as possible
256
        	OutputStream out = null;
257
			try {
258
				out = response.getOutputStream();
259
			} catch (IOException e) {
260
				logMetacat.error("Could not get output stream from response", e);
261
			}
262
            serializeException(be, out);
263
        } catch (Exception e) {
264
            // report Exceptions as clearly and generically as possible
265
            logMetacat.error(e.getClass() + ": " + e.getMessage(), e);
266
        	OutputStream out = null;
267
			try {
268
				out = response.getOutputStream();
269
			} catch (IOException ioe) {
270
				logMetacat.error("Could not get output stream from response", ioe);
271
			}
272
			ServiceFailure se = new ServiceFailure("0000", e.getMessage());
273
            serializeException(se, out);
274
        }
275
    }
276
    
277
    /**
278
     * Checks the access policy
279
     * @param id
280
     * @return
281
     * @throws ServiceFailure
282
     * @throws InvalidToken
283
     * @throws NotFound
284
     * @throws NotAuthorized
285
     * @throws NotImplemented
286
     * @throws InvalidRequest
287
     */
288
    private boolean isAuthorized(String id) throws ServiceFailure, InvalidToken, NotFound, NotAuthorized, NotImplemented, InvalidRequest {
289
		Identifier pid = new Identifier();
290
		pid.setValue(id);
291
		Permission permission = null;
292
		try {
293
			String perm = params.get("permission")[0];
294
			permission = Permission.valueOf(perm);
295
		} catch (Exception e) {
296
			logMetacat.warn("No permission specified");
297
		}
298
		boolean result = MNodeService.getInstance().isAuthorized(session, pid, permission);
299
		response.setStatus(200);
300
		response.setContentType("text/xml");
301
		return result;
302
    }
303
    
304
    /**
305
     * Processes failed synchronization message
306
     * @throws NotImplemented
307
     * @throws ServiceFailure
308
     * @throws NotAuthorized
309
     * @throws InvalidRequest
310
     * @throws UnsupportedEncodingException
311
     * @throws JiBXException
312
     */
313
    private void syncError() throws NotImplemented, ServiceFailure, NotAuthorized, InvalidRequest, UnsupportedEncodingException, JiBXException {
314
    	SynchronizationFailed syncFailed = null;
315
    	if (params.containsKey("message")) {
316
            String message = params.get("message")[0];
317
            syncFailed = (SynchronizationFailed) deserializeServiceType(SynchronizationFailed.class, new ByteArrayInputStream(message.getBytes("UTF-8")));
318
        }
319
		MNodeService.getInstance().synchronizationFailed(session, syncFailed);
320
    }
321
    
322
    /**
323
     * Handles the monitoring resources
324
     * @return
325
     * @throws NotFound
326
     * @throws ParseException
327
     * @throws NotImplemented
328
     * @throws ServiceFailure
329
     * @throws NotAuthorized
330
     * @throws InvalidRequest
331
     * @throws InsufficientResources
332
     * @throws UnsupportedType
333
     * @throws IOException
334
     * @throws JiBXException
335
     */
336
    private boolean monitor(String pathInfo) 
337
      throws NotFound, ParseException, NotImplemented, ServiceFailure, 
338
      NotAuthorized, InvalidRequest, InsufficientResources, UnsupportedType, 
339
      IOException, JiBXException {
340
    	logMetacat.debug("processing monitor request");
341
        
342
        logMetacat.debug("verb is GET");
343
        logMetacat.debug("pathInfo is " + pathInfo);
344
        
345
        if (pathInfo.toLowerCase().equals("ping")) {
346
            logMetacat.debug("processing ping request");
347
            boolean result = MNodeService.getInstance().ping();
348
            return result;
349
            
350
        } else if (pathInfo.toLowerCase().equals("status")) {
351
            logMetacat.debug("processing status request");
352
            // TODO: implement in MNCore
353
            //MNodeService.getInstance().getStatus();
354
            return false;
355
            
356
        } else if (pathInfo.toLowerCase().equals("object")) {
357
            logMetacat.debug("processing object request");
358
            Identifier pid = null;
359
            ObjectFormat format = null;
360
            if (params.containsKey("format")) {
361
                String f = params.get("format")[0];
362
                format = ObjectFormatCache.getInstance().getFormat(f);
363
            }
364
            if (params.containsKey("pid")) {
365
                String id = params.get("pid")[0];
366
                pid = new Identifier();
367
                pid.setValue(id);
368
            }
369
            
370
            // TODO: implement in MNCore
371
            //ObjectStatistics objectStats = MNodeService.getInstance().getObjectStatistics(format, pid);
372
            return false;
373
            
374
        } else if (pathInfo.toLowerCase().equals("event")) {
375
            logMetacat.debug("processing event request");
376
            ObjectFormatIdentifier fmtid = null;
377
            String fromDateStr = null;
378
            Date fromDate = null;
379
            String toDateStr = null;
380
            Date toDate = null;
381
            String requestor = null;
382
            Subject subject = null;
383
            String eventName = null;
384
            Event event = null;
385

    
386
            if (params.containsKey("formatId")) {
387
                String f = params.get("formatId")[0];
388
                fmtid = ObjectFormatCache.getInstance().getFormat(f).getFmtid();
389
            }
390
            
391
            if (params.containsKey("fromDate")) {
392
                fromDateStr = params.get("fromDate")[0];
393
                fromDate = getDateAsUTC(fromDateStr);
394
            }
395
            
396
            if (params.containsKey("toDate")) {
397
              toDateStr = params.get("toDate")[0];
398
              toDate = getDateAsUTC(toDateStr);
399
            }
400
            
401
            if (params.containsKey("requestor")) {
402
            	requestor = params.get("requestor")[0];
403
            	subject = new Subject();
404
            	subject.setValue(requestor);
405
            }
406
            
407
            if (params.containsKey("event")) {
408
            	eventName = params.get("event")[0];
409
                event = Event.valueOf(eventName);
410
            }
411
            
412
            MonitorList monitorList = MNodeService.getInstance().getOperationStatistics(session, fromDate, toDate, subject, event, fmtid);
413
            
414
            OutputStream out = response.getOutputStream();
415
            response.setStatus(200);
416
            response.setContentType("text/xml");
417
            
418
            serializeServiceType(MonitorList.class, monitorList, out);
419
            
420
            return true;
421
            
422
        }
423
        
424
        return false;
425
    }
426
    
427
    /*
428
     * Parse an ISO8601 date string, returning a Date in UTC time if the string
429
     * ends in 'Z'.
430
     * 
431
     * @param fromDateStr -  the date string to be parsed
432
     * @return date -  the date object represented by the string
433
     */
434
    private Date getDateAsUTC(String fromDateStr)
435
      throws ParseException {
436

    
437
    	Date date = null;
438
    	
439
    	try {
440
    		// try the expected date format
441
        // a date format for date string arguments
442
        DateFormat dateFormat = 
443
        	new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
444

    
445
	      date = dateFormat.parse(fromDateStr);
446
      
447
    	} catch (ParseException e) {
448
    		// try the date with the UTC indicator
449
        DateFormat utcDateFormat = 
450
        	new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
451
        utcDateFormat.setTimeZone(TimeZone.getTimeZone("GMT-0"));
452
        date = utcDateFormat.parse(fromDateStr);
453
        
454
      }
455
    	
456
    	return date;
457
    }
458

    
459
		/**
460
     * Calculate the checksum 
461
     * @throws NotImplemented
462
     * @throws JiBXException
463
     * @throws IOException
464
     * @throws InvalidToken
465
     * @throws ServiceFailure
466
     * @throws NotAuthorized
467
     * @throws NotFound
468
     * @throws InvalidRequest
469
     */
470
    private void checksum(String pid) throws NotImplemented, JiBXException, IOException, InvalidToken, ServiceFailure, NotAuthorized, NotFound, InvalidRequest {
471
    	String checksumAlgorithm = "MD5";
472
        
473
        Identifier pidid = new Identifier();
474
        pidid.setValue(pid);
475
        try {
476
            checksumAlgorithm = params.get("checksumAlgorithm")[0];
477
        } catch(Exception e) {
478
            //do nothing.  default to MD5
479
        	logMetacat.warn("No algorithm specified, using default: " + checksumAlgorithm);
480
        }
481
        logMetacat.debug("getting checksum for object " + pid + " with algorithm " + checksumAlgorithm);
482
        
483
        Checksum c = MNodeService.getInstance().getChecksum(session, pidid, checksumAlgorithm);
484
        logMetacat.debug("got checksum " + c.getValue());
485
        response.setStatus(200);
486
        logMetacat.debug("serializing response");
487
        serializeServiceType(Checksum.class, c, response.getOutputStream());
488
        logMetacat.debug("done serializing response.");
489
        
490
    }
491
    
492
	/**
493
     * handle the replicate action for MN
494
	 * @throws JiBXException 
495
	 * @throws FileUploadException 
496
	 * @throws IOException 
497
	 * @throws InvalidRequest 
498
	 * @throws ServiceFailure 
499
	 * @throws UnsupportedType 
500
	 * @throws InsufficientResources 
501
	 * @throws NotAuthorized 
502
	 * @throws NotImplemented 
503
     */
504
    private void replicate() throws ServiceFailure, InvalidRequest, IOException, FileUploadException, JiBXException, NotImplemented, NotAuthorized, InsufficientResources, UnsupportedType {
505

    
506
        logMetacat.debug("in POST replicate()");
507
        
508
        //parse the systemMetadata
509
        SystemMetadata sysmeta = collectSystemMetadata();
510
        
511
        String sn = multipartparams.get("sourceNode").get(0);
512
        logMetacat.debug("sourceNode: " + sn);
513
        NodeReference sourceNode = (NodeReference) deserializeServiceType(NodeReference.class, new ByteArrayInputStream(sn.getBytes("UTF-8")));
514
        
515
        MNodeService.getInstance().replicate(session, sysmeta, sourceNode);
516

    
517
        response.setStatus(200);
518

    
519
    }
520
    
521
    /**
522
     * Get the Node information
523
     * 
524
     * @throws JiBXException
525
     * @throws IOException
526
     * @throws InvalidRequest 
527
     * @throws ServiceFailure 
528
     * @throws NotAuthorized 
529
     * @throws NotImplemented 
530
     */
531
    private void node() 
532
        throws JiBXException, IOException, NotImplemented, NotAuthorized, ServiceFailure, InvalidRequest {
533
        
534
        Node n = MNodeService.getInstance().getCapabilities();
535
        
536
        NodeList nl = new NodeList();
537
        nl.addNode(n);
538
        
539
        response.setContentType("text/xml");
540
        response.setStatus(200);
541
        serializeServiceType(NodeList.class, nl, response.getOutputStream());
542
        
543
    }
544
    
545
    /**
546
     * MN_crud.describe()
547
     * http://mule1.dataone.org/ArchitectureDocs/mn_api_crud.html#MN_crud.describe
548
     * @param pid
549
     * @throws InvalidRequest 
550
     * @throws NotImplemented 
551
     * @throws NotFound 
552
     * @throws NotAuthorized 
553
     * @throws ServiceFailure 
554
     * @throws InvalidToken 
555
     */
556
    private void describeObject(String pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented, InvalidRequest
557
    {
558
        response.setStatus(200);
559
        response.setContentType("text/xml");
560
        
561
        Identifier id = new Identifier();
562
        id.setValue(pid);
563

    
564
        DescribeResponse dr = MNodeService.getInstance().describe(session, id);
565
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SZ");
566
        response.addHeader("pid", pid);
567
        response.addHeader("checksum", dr.getDataONE_Checksum().getValue());
568
        response.addHeader("checksum_algorithm", dr.getDataONE_Checksum().getAlgorithm().name());
569
        response.addHeader("content_length", dr.getContent_Length() + "");
570
        response.addHeader("last_modified", dateFormat.format(dr.getLast_Modified()));
571
        response.addHeader("format", dr.getDataONE_ObjectFormat().toString());
572
       
573
    }
574
    
575
    /**
576
     * get the logs based on passed params.  Available 
577
     * See http://mule1.dataone.org/ArchitectureDocs/mn_api_crud.html#MN_crud.getLogRecords
578
     * for more info
579
     * @throws NotImplemented 
580
     * @throws InvalidRequest 
581
     * @throws NotAuthorized 
582
     * @throws ServiceFailure 
583
     * @throws InvalidToken 
584
     * @throws IOException 
585
     * @throws JiBXException 
586
     */
587
    private void getLog() throws InvalidToken, ServiceFailure, NotAuthorized, InvalidRequest, NotImplemented, IOException, JiBXException
588
    {
589
            
590
        Date fromDate = null;
591
        Date toDate = null;
592
        Event event = null;
593
        Integer start = null;
594
        Integer count = null;
595
        
596
        try {
597
        	String fromDateS = params.get("fromDate")[0];
598
            logMetacat.debug("param fromDateS: " + fromDateS);
599
            fromDate = parseDateAndConvertToGMT(fromDateS);
600
        } catch (Exception e) {
601
        	logMetacat.warn("Could not parse fromDate: " + e.getMessage());
602
        }
603
        try {
604
        	String toDateS = params.get("toDate")[0];
605
            logMetacat.debug("param toDateS: " + toDateS);
606
            toDate = parseDateAndConvertToGMT(toDateS);
607
        } catch (Exception e) {
608
        	logMetacat.warn("Could not parse toDate: " + e.getMessage());
609
		}
610
        try {
611
        	String eventS = params.get("event")[0];
612
            event = Event.convert(eventS);
613
        } catch (Exception e) {
614
        	logMetacat.warn("Could not parse event: " + e.getMessage());
615
		}
616
        logMetacat.debug("fromDate: " + fromDate + " toDate: " + toDate);
617
        
618
        try {
619
        	start =  Integer.parseInt(params.get("start")[0]);
620
        } catch (Exception e) {
621
			logMetacat.warn("Could not parse start: " + e.getMessage());
622
		}
623
        try {
624
        	count =  Integer.parseInt(params.get("count")[0]);
625
        } catch (Exception e) {
626
			logMetacat.warn("Could not parse count: " + e.getMessage());
627
		}
628
        
629
        logMetacat.debug("calling getLogRecords");
630
        Log log = MNodeService.getInstance().getLogRecords(session, fromDate, toDate, event, start, count);
631
        
632
        OutputStream out = response.getOutputStream();
633
        response.setStatus(200);
634
        response.setContentType("text/xml");
635
        
636
        serializeServiceType(Log.class, log, out);
637
        
638
    }
639
    
640
    /**
641
     * Implements REST version of DataONE CRUD API --> get
642
     * @param pid ID of data object to be read
643
     * @throws NotImplemented 
644
     * @throws InvalidRequest 
645
     * @throws NotFound 
646
     * @throws NotAuthorized 
647
     * @throws ServiceFailure 
648
     * @throws InvalidToken 
649
     * @throws IOException 
650
     * @throws JiBXException 
651
     */
652
    protected void getObject(String pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, InvalidRequest, NotImplemented, IOException, JiBXException {
653
        OutputStream out = null;
654
        
655
        if (pid != null) { //get a specific document                
656
            Identifier id = new Identifier();
657
            id.setValue(pid);
658
                
659
            SystemMetadata sm = MNodeService.getInstance().getSystemMetadata(session, id);
660
            
661
            //set the content type
662
            if (sm.getObjectFormat().getFmtid().getValue().trim().equals(
663
            		ObjectFormatCache.getInstance().getFormat("text/csv").getFmtid().getValue()))
664
            {
665
                response.setContentType("text/csv");
666
                response.setHeader("Content-Disposition", "inline; filename=" + id.getValue() + ".csv");
667
            }
668
            else if (sm.getObjectFormat().getFmtid().getValue().trim().equals(
669
            		ObjectFormatCache.getInstance().getFormat("text/plain").getFmtid().getValue()))
670
            {
671
                response.setContentType("text/plain");
672
                response.setHeader("Content-Disposition", "inline; filename=" + id.getValue() + ".txt");
673
            } 
674
            else if (sm.getObjectFormat().getFmtid().getValue().trim().equals(
675
            		ObjectFormatCache.getInstance().getFormat("application/octet-stream").getFmtid().getValue()))
676
            {
677
                response.setContentType("application/octet-stream");
678
            }
679
            else
680
            {
681
                response.setContentType("text/xml");
682
                response.setHeader("Content-Disposition", "inline; filename=" + id.getValue() + ".xml");
683
            }
684
            
685
            InputStream data = MNodeService.getInstance().get(session, id);
686

    
687
            out = response.getOutputStream();  
688
            IOUtils.copyLarge(data, out);
689
            
690
        }
691
        else
692
        { //call listObjects with specified params
693
            Date startTime = null;
694
            Date endTime = null;
695
            ObjectFormat objectFormat = null;
696
            boolean replicaStatus = false;
697
            int start = 0;
698
            //TODO: make the max count into a const
699
            int count = 1000;
700
            Enumeration paramlist = request.getParameterNames();
701
            while (paramlist.hasMoreElements()) 
702
            { //parse the params and make the crud call
703
                String name = (String) paramlist.nextElement();
704
                String[] value = (String[])request.getParameterValues(name);
705

    
706
                if (name.equals("startTime") && value != null)
707
                {
708
                    try
709
                    {
710
                      //startTime = dateFormat.parse(value[0]);
711
                        startTime = parseDateAndConvertToGMT(value[0]);
712
                    }
713
                    catch(Exception e)
714
                    {  //if we can't parse it, just don't use the startTime param
715
                        logMetacat.warn("Could not parse startTime: " + value[0]);
716
                        startTime = null;
717
                    }
718
                }
719
                else if(name.equals("endTime") && value != null)
720
                {
721
                    try
722
                    {
723
                      //endTime = dateFormat.parse(value[0]);
724
                        endTime = parseDateAndConvertToGMT(value[0]);
725
                    }
726
                    catch(Exception e)
727
                    {  //if we can't parse it, just don't use the endTime param
728
                        logMetacat.warn("Could not parse endTime: " + value[0]);
729
                        endTime = null;
730
                    }
731
                }
732
                else if(name.equals("objectFormat") && value != null) 
733
                {
734
                    objectFormat = ObjectFormatCache.getInstance().getFormat(value[0]);
735
                }
736
                else if(name.equals("replicaStatus") && value != null)
737
                {
738
                    if(value != null && 
739
                       value.length > 0 && 
740
                       (value[0].equals("true") || value[0].equals("TRUE") || value[0].equals("YES")))
741
                    {
742
                        replicaStatus = true;
743
                    }
744
                }
745
                else if(name.equals("start") && value != null)
746
                {
747
                    start = new Integer(value[0]).intValue();
748
                }
749
                else if(name.equals("count") && value != null)
750
                {
751
                    count = new Integer(value[0]).intValue();
752
                }
753
            }
754
            //make the crud call
755
            logMetacat.debug("session: " + session + " startTime: " + startTime +
756
                    " endtime: " + endTime + " objectFormat: " + 
757
                    objectFormat + " replicaStatus: " + replicaStatus + 
758
                    " start: " + start + " count: " + count);
759
           
760
            ObjectFormatIdentifier fmtid = new ObjectFormatIdentifier();
761
           
762
            if ( objectFormat != null ) {
763
          	 fmtid = objectFormat.getFmtid();
764
          	 
765
            }
766
            ObjectList ol = 
767
           	 MNodeService.getInstance().listObjects(session, startTime, endTime, 
768
               fmtid, replicaStatus, start, count);
769
           
770
            out = response.getOutputStream();  
771
            response.setStatus(200);
772
            response.setContentType("text/xml");
773
            // Serialize and write it to the output stream
774
            serializeServiceType(ObjectList.class, ol, out);
775
            
776
        }
777
        
778
    }
779
    
780

    
781
    /**
782
     * Retrieve System Metadata
783
     * @param pid
784
     * @throws InvalidToken
785
     * @throws ServiceFailure
786
     * @throws NotAuthorized
787
     * @throws NotFound
788
     * @throws InvalidRequest
789
     * @throws NotImplemented
790
     * @throws IOException
791
     * @throws JiBXException
792
     */
793
    protected void getSystemMetadataObject(String pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, InvalidRequest, NotImplemented, IOException, JiBXException {
794

    
795
        Identifier id = new Identifier();
796
        id.setValue(pid);
797
        SystemMetadata sysmeta = MNodeService.getInstance().getSystemMetadata(session, id);
798
        
799
        response.setContentType("text/xml");
800
        response.setStatus(200);
801
        OutputStream out = response.getOutputStream();
802
        
803
        // Serialize and write it to the output stream
804
       serializeServiceType(SystemMetadata.class, sysmeta, out);
805
   }
806
    
807
    
808
    /**
809
     * Inserts or updates the object
810
     * 
811
     * @param pid - ID of data object to be inserted or updated.  If action is update, the pid
812
     *               is the existing pid.  If insert, the pid is the new one
813
     * @throws InvalidRequest 
814
     * @throws ServiceFailure 
815
     * @throws JiBXException 
816
     * @throws NotImplemented 
817
     * @throws InvalidSystemMetadata 
818
     * @throws InsufficientResources 
819
     * @throws UnsupportedType 
820
     * @throws IdentifierNotUnique 
821
     * @throws NotAuthorized 
822
     * @throws InvalidToken 
823
     * @throws NotFound 
824
     * @throws IOException 
825
     */
826
    protected void putObject(String pid, String action) throws ServiceFailure, InvalidRequest, JiBXException, InvalidToken, NotAuthorized, IdentifierNotUnique, UnsupportedType, InsufficientResources, InvalidSystemMetadata, NotImplemented, NotFound, IOException {
827
        logMetacat.debug("putObject with pid " + pid);
828
        logMetacat.debug("Entering putObject: " + pid + "/" + action);
829
        
830
        response.setStatus(200);
831
        response.setContentType("text/xml");
832
        OutputStream out = response.getOutputStream();
833
        
834
        // Read the incoming data from its Mime Multipart encoding
835
    	Map<String, File> files = collectMultipartFiles();
836
        InputStream object = null;
837
        InputStream sysmeta = null;
838

    
839
        File smFile = files.get("sysmeta");
840
        sysmeta = new FileInputStream(smFile);
841
        File objFile = files.get("object");
842
        object = new FileInputStream(objFile);
843
        
844
        if (action.equals(FUNCTION_NAME_INSERT)) { 
845
            // handle inserts
846
            logMetacat.debug("Commence creation...");
847
            SystemMetadata smd = (SystemMetadata) deserializeServiceType(SystemMetadata.class, sysmeta);
848

    
849
            Identifier id = new Identifier();
850
            id.setValue(pid);
851
            logMetacat.debug("creating object with pid " + pid);
852
            Identifier rId = MNodeService.getInstance().create(session, id, object, smd);
853
            serializeServiceType(Identifier.class, rId, out);
854
            
855
        } else if (action.equals(FUNCTION_NAME_UPDATE)) {
856
        	// handle updates
857
        	
858
            // construct pids
859
            Identifier newPid = new Identifier();
860
            try {
861
            	String newPidString = multipartparams.get("newPid").get(0);
862
                newPid.setValue(newPidString);
863
            } catch (Exception e) {
864
				logMetacat.warn("newPid not given");
865
			}
866
            
867
            Identifier obsoletedPid = new Identifier();
868
            obsoletedPid.setValue(pid);
869
           
870
            logMetacat.debug("Commence update...");
871
            
872
            // get the systemmetadata object
873
            SystemMetadata smd = (SystemMetadata) deserializeServiceType(SystemMetadata.class, sysmeta);
874

    
875
            Identifier rId = MNodeService.getInstance().update(session, newPid, object, obsoletedPid, smd);
876
            serializeServiceType(Identifier.class, rId, out);
877
        } else {
878
            throw new InvalidRequest("1000", "Operation must be create or update.");
879
        }
880
            
881
            
882
    }
883

    
884
    /**
885
     * Handle delete 
886
     * @param pid ID of data object to be deleted
887
     * @throws IOException
888
     * @throws InvalidRequest 
889
     * @throws NotImplemented 
890
     * @throws NotFound 
891
     * @throws NotAuthorized 
892
     * @throws ServiceFailure 
893
     * @throws InvalidToken 
894
     * @throws JiBXException 
895
     */
896
    private void deleteObject(String pid) throws IOException, InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented, InvalidRequest, JiBXException 
897
    {
898

    
899
        OutputStream out = response.getOutputStream();
900
        response.setStatus(200);
901
        response.setContentType("text/xml");
902

    
903
        Identifier id = new Identifier();
904
        id.setValue(pid);
905

    
906
        logMetacat.debug("Calling delete");
907
        MNodeService.getInstance().delete(session, id);
908
        serializeServiceType(Identifier.class, id, out);
909
        
910
    }    
911
    
912
    /**
913
     * set the access perms on a document
914
     * @throws JiBXException 
915
     * @throws UnsupportedEncodingException 
916
     * @throws InvalidRequest 
917
     * @throws NotImplemented 
918
     * @throws NotAuthorized 
919
     * @throws NotFound 
920
     * @throws ServiceFailure 
921
     * @throws InvalidToken 
922
     */
923
    protected void setAccess() throws UnsupportedEncodingException, JiBXException, InvalidToken, ServiceFailure, NotFound, NotAuthorized, NotImplemented, InvalidRequest
924
    {
925
    
926
        String pid = params.get("pid")[0];
927
        Identifier id = new Identifier();
928
        id.setValue(pid);
929
        String accesspolicy = params.get("accesspolicy")[0];
930
        AccessPolicy accessPolicy = (AccessPolicy) deserializeServiceType(AccessPolicy.class, new ByteArrayInputStream(accesspolicy.getBytes("UTF-8")));
931
        MNodeService.getInstance().setAccessPolicy(session, id, accessPolicy);
932
        
933
        
934
    }
935

    
936
}
(8-8/11)