Project

General

Profile

« Previous | Next » 

Revision 6273

throw exceptions up the call stack and handle exception reporting/serialization centrally in the handle() method

View differences:

src/edu/ucsb/nceas/metacat/restservice/MNResourceHandler.java
25 25
import java.io.ByteArrayInputStream;
26 26
import java.io.File;
27 27
import java.io.FileInputStream;
28
import java.io.FileNotFoundException;
29 28
import java.io.IOException;
30 29
import java.io.InputStream;
31 30
import java.io.OutputStream;
32
import java.io.StringReader;
33 31
import java.io.UnsupportedEncodingException;
34 32
import java.text.DateFormat;
35 33
import java.text.ParseException;
36 34
import java.text.SimpleDateFormat;
37 35
import java.util.Date;
38 36
import java.util.Enumeration;
39
import java.util.Iterator;
40
import java.util.List;
41 37
import java.util.Map;
42 38

  
43 39
import javax.servlet.ServletContext;
44 40
import javax.servlet.http.HttpServletRequest;
45 41
import javax.servlet.http.HttpServletResponse;
46 42

  
43
import org.apache.commons.fileupload.FileUploadException;
47 44
import org.apache.commons.io.IOUtils;
48 45
import org.apache.log4j.Logger;
49 46
import org.dataone.client.ObjectFormatCache;
50
import org.dataone.mimemultipart.MultipartRequest;
51
import org.dataone.mimemultipart.MultipartRequestResolver;
52 47
import org.dataone.service.exceptions.BaseException;
53 48
import org.dataone.service.exceptions.IdentifierNotUnique;
54 49
import org.dataone.service.exceptions.InsufficientResources;
......
171 166
                } else if (resource.equals(RESOURCE_ACCESS_RULES)) {
172 167
                    if (httpVerb == POST) {
173 168
	                	// set the access rules
174
	                    setaccess();
169
	                    setAccess();
175 170
	                    status = true;
176 171
	                    logMetacat.debug("done setting access");
177 172
                    }
......
265 260
                }
266 261
                
267 262
                if (!status) {
268
                    response.setStatus(400);
269
                    printError("Incorrect parameters!", response);
263
                	throw new ServiceFailure("0000", "Unknown error, status = " + status);
270 264
                }
271 265
            } else {
272
                response.setStatus(400);
273
                printError("Incorrect resource!", response);
266
            	throw new InvalidRequest("0000", "No resource matched for " + resource);
274 267
            }
275 268
        } catch (BaseException be) {
276 269
        	// report Exceptions as clearly as possible
......
282 275
			}
283 276
            serializeException(be, out);
284 277
        } catch (Exception e) {
285
            logMetacat.error(e.getClass() + ": " + e.getMessage());
286
            logMetacat.debug("Error handle(): " + e.getClass() + ": " + e.getMessage());
287
            e.printStackTrace();
278
            // report Exceptions as clearly and generically as possible
279
            logMetacat.error(e.getClass() + ": " + e.getMessage(), e);
280
        	OutputStream out = null;
281
			try {
282
				out = response.getOutputStream();
283
			} catch (IOException ioe) {
284
				logMetacat.error("Could not get output stream from response", ioe);
285
			}
286
			ServiceFailure se = new ServiceFailure("0000", e.getMessage());
287
            serializeException(se, out);
288 288
        }
289 289
    }
290 290
    
291
    /**
292
     * Checks the access policy
293
     * @param id
294
     * @return
295
     * @throws ServiceFailure
296
     * @throws InvalidToken
297
     * @throws NotFound
298
     * @throws NotAuthorized
299
     * @throws NotImplemented
300
     * @throws InvalidRequest
301
     */
291 302
    private boolean isAuthorized(String id) throws ServiceFailure, InvalidToken, NotFound, NotAuthorized, NotImplemented, InvalidRequest {
292 303
		Identifier pid = new Identifier();
293 304
		pid.setValue(id);
......
304 315
		return result;
305 316
    }
306 317
    
318
    /**
319
     * Processes failed synchronization message
320
     * @throws NotImplemented
321
     * @throws ServiceFailure
322
     * @throws NotAuthorized
323
     * @throws InvalidRequest
324
     * @throws UnsupportedEncodingException
325
     * @throws JiBXException
326
     */
307 327
    private void syncError() throws NotImplemented, ServiceFailure, NotAuthorized, InvalidRequest, UnsupportedEncodingException, JiBXException {
308 328
    	SynchronizationFailed syncFailed = null;
309 329
    	if (params.containsKey("message")) {
......
313 333
		MNodeService.getInstance().synchronizationFailed(session, syncFailed);
314 334
    }
315 335
    
336
    /**
337
     * Handles the monitoring resources
338
     * @return
339
     * @throws NotFound
340
     * @throws ParseException
341
     * @throws NotImplemented
342
     * @throws ServiceFailure
343
     * @throws NotAuthorized
344
     * @throws InvalidRequest
345
     * @throws InsufficientResources
346
     * @throws UnsupportedType
347
     * @throws IOException
348
     * @throws JiBXException
349
     */
316 350
    private boolean monitor() throws NotFound, ParseException, NotImplemented, ServiceFailure, NotAuthorized, InvalidRequest, InsufficientResources, UnsupportedType, IOException, JiBXException {
317 351
    	logMetacat.debug("processing monitor request");
318 352
        String pathInfo = request.getPathInfo();
......
389 423
        return true;
390 424
    }
391 425
    
392
    private void checksum() throws NotImplemented, JiBXException, IOException {
426
    /**
427
     * Calculate the checksum 
428
     * @throws NotImplemented
429
     * @throws JiBXException
430
     * @throws IOException
431
     * @throws InvalidToken
432
     * @throws ServiceFailure
433
     * @throws NotAuthorized
434
     * @throws NotFound
435
     * @throws InvalidRequest
436
     */
437
    private void checksum() throws NotImplemented, JiBXException, IOException, InvalidToken, ServiceFailure, NotAuthorized, NotFound, InvalidRequest {
393 438
    	String checksumAlgorithm = "MD5";
394 439
        String guid = request.getPathInfo();
395 440
        if (guid != null && guid.length() > 1) {
......
404 449
        	logMetacat.warn("No algorithm specified, using default: " + checksumAlgorithm);
405 450
        }
406 451
        logMetacat.debug("getting checksum for object " + guid + " with algorithm " + checksumAlgorithm);
407
        try {
408
            Checksum c = MNodeService.getInstance().getChecksum(session, guidid, checksumAlgorithm);
409
            logMetacat.debug("got checksum " + c.getValue());
410
            response.setStatus(200);
411
            logMetacat.debug("serializing response");
412
            serializeServiceType(Checksum.class, c, response.getOutputStream());
413
            logMetacat.debug("done serializing response.");
414
        }
415
        catch(NotAuthorized na)
416
        {
417
            na.setDetail_code("1400");
418
            serializeException(na, response.getOutputStream());
419
        }
420
        catch(NotFound nf)
421
        {
422
            nf.setDetail_code("1420");
423
            serializeException(nf, response.getOutputStream());
424
        }
425
        catch(InvalidRequest ir)
426
        {
427
            ir.setDetail_code("1402");
428
            serializeException(ir, response.getOutputStream());
429
        }
430
        catch(ServiceFailure sf)
431
        {
432
            sf.setDetail_code("1410");
433
            serializeException(sf, response.getOutputStream());
434
        }
435
        catch(InvalidToken it)
436
        {
437
            it.setDetail_code("1430");
438
            serializeException(it, response.getOutputStream());
439
        }
452
        
453
        Checksum c = MNodeService.getInstance().getChecksum(session, guidid, checksumAlgorithm);
454
        logMetacat.debug("got checksum " + c.getValue());
455
        response.setStatus(200);
456
        logMetacat.debug("serializing response");
457
        serializeServiceType(Checksum.class, c, response.getOutputStream());
458
        logMetacat.debug("done serializing response.");
459
        
440 460
    }
441 461
    
442 462
	/**
443 463
     * handle the replicate action for MN
444
	 * @throws Exception 
464
	 * @throws JiBXException 
465
	 * @throws FileUploadException 
466
	 * @throws IOException 
467
	 * @throws InvalidRequest 
468
	 * @throws ServiceFailure 
469
	 * @throws UnsupportedType 
470
	 * @throws InsufficientResources 
471
	 * @throws NotAuthorized 
472
	 * @throws NotImplemented 
445 473
     */
446
    private void replicate() throws Exception {
474
    private void replicate() throws ServiceFailure, InvalidRequest, IOException, FileUploadException, JiBXException, NotImplemented, NotAuthorized, InsufficientResources, UnsupportedType {
447 475

  
448 476
        logMetacat.debug("in POST replicate()");
449

  
450
        File tmpDir = getTempDirectory();
451
        logMetacat.debug("temp dir: " + tmpDir.getAbsolutePath());
452
        MultipartRequestResolver mrr = new MultipartRequestResolver(
453
                tmpDir.getAbsolutePath(), 1000000000, 0);
454
        MultipartRequest mr = mrr.resolveMultipart(request);
455
        Map<String, File> files = mr.getMultipartFiles();
456
        Iterator keys = files.keySet().iterator();
457
        while(keys.hasNext()) {
458
            String key = (String)keys.next();
459
            logMetacat.debug("files key: " + key);
460
            logMetacat.debug("files value: " + files.get(key));
461
        }
462 477
        
463
        Map<String, List<String>> params = mr.getMultipartParameters();
464
        keys = params.keySet().iterator();
465
        while(keys.hasNext()) {
466
            String key = (String)keys.next();
467
            logMetacat.debug("params key: " + key);
468
            logMetacat.debug("params value: " + params.get(key));
469
        }
478
        //parse the systemMetadata
479
        SystemMetadata sysmeta = collectSystemMetadata();
470 480
        
471
        // File f = files.get("sysmeta");
472
        // the files are not being keyed by the part name, but rather the filename
473
        File f = files.get(files.keySet().iterator().next());
474
        
475
        logMetacat.debug("file: " + f.getAbsolutePath());
476
        FileInputStream fis = new FileInputStream(f);
477

  
478
        String sn = params.get("sourceNode").get(0);
481
        String sn = multipartparams.get("sourceNode").get(0);
479 482
        logMetacat.debug("sourceNode: " + sn);
480 483
        NodeReference sourceNode = (NodeReference) deserializeServiceType(NodeReference.class, new ByteArrayInputStream(sn.getBytes("UTF-8")));
481 484
        
482
        //parse the systemMetadata
483
        SystemMetadata sysmeta = (SystemMetadata) deserializeServiceType(SystemMetadata.class, fis);
484

  
485 485
        MNodeService.getInstance().replicate(session, sysmeta, sourceNode);
486 486

  
487 487
        response.setStatus(200);
......
516 516
     * MN_crud.describe()
517 517
     * http://mule1.dataone.org/ArchitectureDocs/mn_api_crud.html#MN_crud.describe
518 518
     * @param guid
519
     * @throws InvalidRequest 
520
     * @throws NotImplemented 
521
     * @throws NotFound 
522
     * @throws NotAuthorized 
523
     * @throws ServiceFailure 
524
     * @throws InvalidToken 
519 525
     */
520
    private void describeObject(String guid)
526
    private void describeObject(String guid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented, InvalidRequest
521 527
    {
522
        Logger logMetacat = Logger.getLogger(MNResourceHandler.class);
523
        OutputStream out = null;
524
        try
525
        {
526
            out = response.getOutputStream();
527
        }
528
        catch(Exception e)
529
        {
530
            logMetacat.error("Error getting output stream in describeObject: " + e.getClass() + ": " + e.getMessage());
531
            return;
532
        }
533 528
        response.setStatus(200);
534 529
        response.setContentType("text/xml");
530
        
535 531
        Identifier id = new Identifier();
536 532
        id.setValue(guid);
537
        try
538
        {
539
            DescribeResponse dr = MNodeService.getInstance().describe(session, id);
540
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SZ");
541
            response.addHeader("guid", guid);
542
            response.addHeader("checksum", dr.getDataONE_Checksum().getValue());
543
            response.addHeader("checksum_algorithm", dr.getDataONE_Checksum().getAlgorithm().name());
544
            response.addHeader("content_length", dr.getContent_Length() + "");
545
            response.addHeader("last_modified", dateFormat.format(dr.getLast_Modified()));
546
            response.addHeader("format", dr.getDataONE_ObjectFormat().toString());
547
        }
548
        catch(InvalidRequest ir)
549
        {
550
            serializeException(ir, out);
551
        }
552
        catch(NotImplemented ni)
553
        {
554
            serializeException(ni, out);
555
        }
556
        catch(NotAuthorized na)
557
        {
558
            serializeException(na, out);
559
        }
560
        catch(ServiceFailure sf)
561
        {
562
            serializeException(sf, out);
563
        }
564
        catch(NotFound nf)
565
        {
566
            serializeException(nf, out);
567
        }
568
        catch(InvalidToken it)
569
        {
570
            serializeException(it, out);
571
        }
533

  
534
        DescribeResponse dr = MNodeService.getInstance().describe(session, id);
535
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SZ");
536
        response.addHeader("guid", guid);
537
        response.addHeader("checksum", dr.getDataONE_Checksum().getValue());
538
        response.addHeader("checksum_algorithm", dr.getDataONE_Checksum().getAlgorithm().name());
539
        response.addHeader("content_length", dr.getContent_Length() + "");
540
        response.addHeader("last_modified", dateFormat.format(dr.getLast_Modified()));
541
        response.addHeader("format", dr.getDataONE_ObjectFormat().toString());
542
       
572 543
    }
573 544
    
574 545
    /**
575 546
     * get the logs based on passed params.  Available 
576 547
     * See http://mule1.dataone.org/ArchitectureDocs/mn_api_crud.html#MN_crud.getLogRecords
577 548
     * for more info
549
     * @throws NotImplemented 
550
     * @throws InvalidRequest 
551
     * @throws NotAuthorized 
552
     * @throws ServiceFailure 
553
     * @throws InvalidToken 
554
     * @throws IOException 
555
     * @throws JiBXException 
578 556
     */
579
    private void getLog()
557
    private void getLog() throws InvalidToken, ServiceFailure, NotAuthorized, InvalidRequest, NotImplemented, IOException, JiBXException
580 558
    {
581
        OutputStream out = null;
559
            
560
        Date fromDate = null;
561
        Date toDate = null;
562
        Event event = null;
563
        Integer start = null;
564
        Integer count = null;
565
        
582 566
        try {
583
            
584
            Date fromDate = null;
585
            Date toDate = null;
586
            Event event = null;
587
            Integer start = null;
588
            Integer count = null;
589
            
590
            try {
591
            	String fromDateS = params.get("fromDate")[0];
592
                logMetacat.debug("param fromDateS: " + fromDateS);
593
                fromDate = parseDateAndConvertToGMT(fromDateS);
594
            } catch (Exception e) {
595
            	logMetacat.warn("Could not parse fromDate: " + e.getMessage());
596
            }
597
            try {
598
            	String toDateS = params.get("toDate")[0];
599
                logMetacat.debug("param toDateS: " + toDateS);
600
                toDate = parseDateAndConvertToGMT(toDateS);
601
            } catch (Exception e) {
602
            	logMetacat.warn("Could not parse toDate: " + e.getMessage());
603
			}
604
            try {
605
            	String eventS = params.get("event")[0];
606
                event = Event.convert(eventS);
607
            } catch (Exception e) {
608
            	logMetacat.warn("Could not parse event: " + e.getMessage());
609
			}
610
            logMetacat.debug("fromDate: " + fromDate + " toDate: " + toDate);
611
            
612
            try {
613
            	start =  Integer.parseInt(params.get("start")[0]);
614
            } catch (Exception e) {
615
				logMetacat.warn("Could not parse start: " + e.getMessage());
616
			}
617
            try {
618
            	count =  Integer.parseInt(params.get("count")[0]);
619
            } catch (Exception e) {
620
				logMetacat.warn("Could not parse count: " + e.getMessage());
621
			}
622
            
623
            logMetacat.debug("calling getLogRecords");
624
            Log log = MNodeService.getInstance().getLogRecords(session, fromDate, toDate, event, start, count);
625
            
626
            out = response.getOutputStream();
627
            response.setStatus(200);
628
            response.setContentType("text/xml");
629
            
630
            serializeServiceType(Log.class, log, out);
567
        	String fromDateS = params.get("fromDate")[0];
568
            logMetacat.debug("param fromDateS: " + fromDateS);
569
            fromDate = parseDateAndConvertToGMT(fromDateS);
570
        } catch (Exception e) {
571
        	logMetacat.warn("Could not parse fromDate: " + e.getMessage());
631 572
        }
632
        catch(Exception e) {
633
            String msg = "Could not get logs: " + e.getClass() + ": " + e.getMessage();
634
            response.setStatus(500);
635
            ServiceFailure sf = new ServiceFailure("1490", msg);
636
            logMetacat.error(msg);
637
            e.printStackTrace();
638
            serializeException(sf, out);
639
        }
573
        try {
574
        	String toDateS = params.get("toDate")[0];
575
            logMetacat.debug("param toDateS: " + toDateS);
576
            toDate = parseDateAndConvertToGMT(toDateS);
577
        } catch (Exception e) {
578
        	logMetacat.warn("Could not parse toDate: " + e.getMessage());
579
		}
580
        try {
581
        	String eventS = params.get("event")[0];
582
            event = Event.convert(eventS);
583
        } catch (Exception e) {
584
        	logMetacat.warn("Could not parse event: " + e.getMessage());
585
		}
586
        logMetacat.debug("fromDate: " + fromDate + " toDate: " + toDate);
587
        
588
        try {
589
        	start =  Integer.parseInt(params.get("start")[0]);
590
        } catch (Exception e) {
591
			logMetacat.warn("Could not parse start: " + e.getMessage());
592
		}
593
        try {
594
        	count =  Integer.parseInt(params.get("count")[0]);
595
        } catch (Exception e) {
596
			logMetacat.warn("Could not parse count: " + e.getMessage());
597
		}
598
        
599
        logMetacat.debug("calling getLogRecords");
600
        Log log = MNodeService.getInstance().getLogRecords(session, fromDate, toDate, event, start, count);
601
        
602
        OutputStream out = response.getOutputStream();
603
        response.setStatus(200);
604
        response.setContentType("text/xml");
605
        
606
        serializeServiceType(Log.class, log, out);
607
        
640 608
    }
641 609
    
642 610
    /**
643 611
     * Implements REST version of DataONE CRUD API --> get
644 612
     * @param guid ID of data object to be read
613
     * @throws NotImplemented 
614
     * @throws InvalidRequest 
615
     * @throws NotFound 
616
     * @throws NotAuthorized 
617
     * @throws ServiceFailure 
618
     * @throws InvalidToken 
619
     * @throws IOException 
620
     * @throws JiBXException 
645 621
     */
646
    protected void getObject(String guid) {
622
    protected void getObject(String guid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, InvalidRequest, NotImplemented, IOException, JiBXException {
647 623
        OutputStream out = null;
648
        try {
649
            out = response.getOutputStream();
650
            response.setStatus(200);
624
        
625
        if (guid != null) { //get a specific document                
626
            Identifier id = new Identifier();
627
            id.setValue(guid);
628
                
629
            SystemMetadata sm = MNodeService.getInstance().getSystemMetadata(session, id);
651 630
            
652
            if(guid != null)
653
            { //get a specific document                
654
                Identifier id = new Identifier();
655
                id.setValue(guid);
656
                try
631
            //set the content type
632
            if (sm.getObjectFormat().getFmtid().getValue().trim().equals(
633
            		ObjectFormatCache.getInstance().getFormat("text/csv").getFmtid().getValue()))
634
            {
635
                response.setContentType("text/csv");
636
                response.setHeader("Content-Disposition", "inline; filename=" + id.getValue() + ".csv");
637
            }
638
            else if (sm.getObjectFormat().getFmtid().getValue().trim().equals(
639
            		ObjectFormatCache.getInstance().getFormat("text/plain").getFmtid().getValue()))
640
            {
641
                response.setContentType("text/plain");
642
                response.setHeader("Content-Disposition", "inline; filename=" + id.getValue() + ".txt");
643
            } 
644
            else if (sm.getObjectFormat().getFmtid().getValue().trim().equals(
645
            		ObjectFormatCache.getInstance().getFormat("application/octet-stream").getFmtid().getValue()))
646
            {
647
                response.setContentType("application/octet-stream");
648
            }
649
            else
650
            {
651
                response.setContentType("text/xml");
652
                response.setHeader("Content-Disposition", "inline; filename=" + id.getValue() + ".xml");
653
            }
654
            
655
            InputStream data = MNodeService.getInstance().get(session, id);
656

  
657
            out = response.getOutputStream();  
658
            IOUtils.copyLarge(data, out);
659
            
660
        }
661
        else
662
        { //call listObjects with specified params
663
            Date startTime = null;
664
            Date endTime = null;
665
            ObjectFormat objectFormat = null;
666
            boolean replicaStatus = false;
667
            int start = 0;
668
            //TODO: make the max count into a const
669
            int count = 1000;
670
            Enumeration paramlist = request.getParameterNames();
671
            while (paramlist.hasMoreElements()) 
672
            { //parse the params and make the crud call
673
                String name = (String) paramlist.nextElement();
674
                String[] value = (String[])request.getParameterValues(name);
675

  
676
                if (name.equals("startTime") && value != null)
657 677
                {
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()))
678
                    try
664 679
                    {
665
                        response.setContentType("text/csv");
666
                        response.setHeader("Content-Disposition", "inline; filename=" + id.getValue() + ".csv");
680
                      //startTime = dateFormat.parse(value[0]);
681
                        startTime = parseDateAndConvertToGMT(value[0]);
667 682
                    }
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");
683
                    catch(Exception e)
684
                    {  //if we can't parse it, just don't use the startTime param
685
                        logMetacat.warn("Could not parse startTime: " + value[0]);
686
                        startTime = null;
678 687
                    }
679
                    else
688
                }
689
                else if(name.equals("endTime") && value != null)
690
                {
691
                    try
680 692
                    {
681
                        response.setContentType("text/xml");
682
                        response.setHeader("Content-Disposition", "inline; filename=" + id.getValue() + ".xml");
693
                      //endTime = dateFormat.parse(value[0]);
694
                        endTime = parseDateAndConvertToGMT(value[0]);
683 695
                    }
684
                    
685
                    InputStream data = MNodeService.getInstance().get(session, id);
686
                    IOUtils.copyLarge(data, response.getOutputStream());
696
                    catch(Exception e)
697
                    {  //if we can't parse it, just don't use the endTime param
698
                        logMetacat.warn("Could not parse endTime: " + value[0]);
699
                        endTime = null;
700
                    }
687 701
                }
688
                catch(InvalidToken it)
702
                else if(name.equals("objectFormat") && value != null) 
689 703
                {
690
                    response.setStatus(500);
691
                    serializeException(it, out); 
704
                    objectFormat = ObjectFormatCache.getInstance().getFormat(value[0]);
692 705
                }
693
                catch(ServiceFailure sf)
706
                else if(name.equals("replicaStatus") && value != null)
694 707
                {
695
                    response.setStatus(500);
696
                    serializeException(sf, out); 
708
                    if(value != null && 
709
                       value.length > 0 && 
710
                       (value[0].equals("true") || value[0].equals("TRUE") || value[0].equals("YES")))
711
                    {
712
                        replicaStatus = true;
713
                    }
697 714
                }
698
                catch(NotAuthorized na)
715
                else if(name.equals("start") && value != null)
699 716
                {
700
                    response.setStatus(500);
701
                    serializeException(na, out); 
717
                    start = new Integer(value[0]).intValue();
702 718
                }
703
                catch(NotFound nf)
719
                else if(name.equals("count") && value != null)
704 720
                {
705
                    response.setStatus(500);
706
                    serializeException(nf, out); 
721
                    count = new Integer(value[0]).intValue();
707 722
                }
708
                catch(NotImplemented ni)
709
                {
710
                    response.setStatus(500);
711
                    serializeException(ni, out); 
712
                }
713
                catch(Exception e)
714
                {
715
                    response.setStatus(500);
716
                    logMetacat.error("Error with Crud.get().  " +
717
                            "If this is an 'Exception producing data' error, " +
718
                            "go to CrudService.get() for better debugging.  " +
719
                            "Here's the error: " + e.getClass() + ": " + e.getMessage());
720
                    e.printStackTrace();
721
                    ServiceFailure sf = new ServiceFailure("1030", 
722
                            "IO Error in getObject: " + e.getClass() + ": " + e.getMessage());
723
                    serializeException(sf, out); 
724
                }
725 723
            }
726
            else
727
            { //call listObjects with specified params
728
                Date startTime = null;
729
                Date endTime = null;
730
                ObjectFormat objectFormat = null;
731
                boolean replicaStatus = false;
732
                int start = 0;
733
                //TODO: make the max count into a const
734
                int count = 1000;
735
                Enumeration paramlist = request.getParameterNames();
736
                while (paramlist.hasMoreElements()) 
737
                { //parse the params and make the crud call
738
                    String name = (String) paramlist.nextElement();
739
                    String[] value = (String[])request.getParameterValues(name);
740
                    /*for(int i=0; i<value.length; i++)
741
                    {
742
                        logMetacat.debug("name: " + name + " value: " + value[i]);
743
                    }*/
744
                    if(name.equals("startTime") && value != null)
745
                    {
746
                        try
747
                        {
748
                          //startTime = dateFormat.parse(value[0]);
749
                            startTime = parseDateAndConvertToGMT(value[0]);
750
                        }
751
                        catch(Exception e)
752
                        {  //if we can't parse it, just don't use the startTime param
753
                            logMetacat.warn("Could not parse startTime: " + value[0]);
754
                            startTime = null;
755
                        }
756
                    }
757
                    else if(name.equals("endTime") && value != null)
758
                    {
759
                        try
760
                        {
761
                          //endTime = dateFormat.parse(value[0]);
762
                            endTime = parseDateAndConvertToGMT(value[0]);
763
                        }
764
                        catch(Exception e)
765
                        {  //if we can't parse it, just don't use the endTime param
766
                            logMetacat.warn("Could not parse endTime: " + value[0]);
767
                            endTime = null;
768
                        }
769
                    }
770
                    else if(name.equals("objectFormat") && value != null) 
771
                    {
772
                        objectFormat = ObjectFormatCache.getInstance().getFormat(value[0]);
773
                    }
774
                    else if(name.equals("replicaStatus") && value != null)
775
                    {
776
                        if(value != null && 
777
                           value.length > 0 && 
778
                           (value[0].equals("true") || value[0].equals("TRUE") || value[0].equals("YES")))
779
                        {
780
                            replicaStatus = true;
781
                        }
782
                    }
783
                    else if(name.equals("start") && value != null)
784
                    {
785
                        start = new Integer(value[0]).intValue();
786
                    }
787
                    else if(name.equals("count") && value != null)
788
                    {
789
                        count = new Integer(value[0]).intValue();
790
                    }
791
                }
792
                //make the crud call
793
                logMetacat.debug("session: " + session + " startTime: " + startTime +
794
                        " endtime: " + endTime + " objectFormat: " + 
795
                        objectFormat + " replicaStatus: " + replicaStatus + 
796
                        " start: " + start + " count: " + count);
797
               
798
                ObjectList ol = MNodeService.getInstance().listObjects(session, startTime, endTime, 
799
                        objectFormat, replicaStatus, start, count);
800
                
801
                StringReader sr = new StringReader(ol.toString());                
802
                out = response.getOutputStream();  
803
                response.setStatus(200);
804
                response.setContentType("text/xml");
805
                // Serialize and write it to the output stream
806
                
807
                try {
808
                    serializeServiceType(ObjectList.class, ol, out);
809
                } catch (JiBXException e) {
810
                    throw new ServiceFailure("1190", "Failed to serialize ObjectList: " + e.getMessage());
811
                }
812
            }
813
        } catch (BaseException e) {
814
                response.setStatus(500);
815
                serializeException(e, out);
816
        } catch (IOException e) {
817
            e.printStackTrace();
818
            response.setStatus(500);
819
            ServiceFailure sf = new ServiceFailure("1030", 
820
                    "IO Error in getObject: " + e.getMessage());
821
            serializeException(sf, out); 
822
        } catch(NumberFormatException ne) {
823
            response.setStatus(500);
824
            InvalidRequest ir = new InvalidRequest("1030", "Invalid format for parameter: " + ne.getMessage());
825
            serializeException(ir, out);
826
        } catch (Exception e) {
827
            e.printStackTrace();
828
            response.setStatus(500);
829
            ServiceFailure sf = new ServiceFailure("1030", 
830
                    "Exception " + e.getClass().getName() + " raised while handling listObjects request: " + 
831
                    e.getMessage());
832
            serializeException(sf, out);
724
            //make the crud call
725
            logMetacat.debug("session: " + session + " startTime: " + startTime +
726
                    " endtime: " + endTime + " objectFormat: " + 
727
                    objectFormat + " replicaStatus: " + replicaStatus + 
728
                    " start: " + start + " count: " + count);
729
           
730
            ObjectList ol = 
731
            	MNodeService.getInstance().listObjects(session, startTime, endTime, 
732
                    objectFormat, replicaStatus, start, count);
733
            
734
            out = response.getOutputStream();  
735
            response.setStatus(200);
736
            response.setContentType("text/xml");
737
            // Serialize and write it to the output stream
738
            serializeServiceType(ObjectList.class, ol, out);
739
            
833 740
        }
741
        
834 742
    }
835 743
    
744

  
836 745
    /**
837
     * Implements REST version of DataONE CRUD API --> getSystemMetadata
838
     * @param guid ID of data object to be read
746
     * Retrieve System Metadata
747
     * @param guid
748
     * @throws InvalidToken
749
     * @throws ServiceFailure
750
     * @throws NotAuthorized
751
     * @throws NotFound
752
     * @throws InvalidRequest
753
     * @throws NotImplemented
754
     * @throws IOException
755
     * @throws JiBXException
839 756
     */
840
    protected void getSystemMetadataObject(String guid) {
841
        OutputStream out = null;
842
        try {
843
            response.setContentType("text/xml");
844
            response.setStatus(200);
845
            out = response.getOutputStream();
846
            Identifier id = new Identifier();
847
            id.setValue(guid);
848
            SystemMetadata sysmeta = MNodeService.getInstance().getSystemMetadata(session, id);
849
            
850
            // Serialize and write it to the output stream
851
            try {
852
                serializeServiceType(SystemMetadata.class, sysmeta, out);
853
            } catch (JiBXException e) {
854
                throw new ServiceFailure("1190", "Failed to serialize SystemMetadata: " + e.getMessage());
855
            }
856
        } catch (BaseException e) {
857
            response.setStatus(500);
858
                serializeException(e, out);
859
        } catch (IOException e) {
860
            response.setStatus(500);
861
            ServiceFailure sf = new ServiceFailure("1030", 
862
                    "IO Error in getSystemMetadataObject: " + e.getMessage());
863
            serializeException(sf, out);
864
        } finally {
865
            IOUtils.closeQuietly(out);
866
        }
867
    }
757
    protected void getSystemMetadataObject(String guid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, InvalidRequest, NotImplemented, IOException, JiBXException {
758

  
759
        Identifier id = new Identifier();
760
        id.setValue(guid);
761
        SystemMetadata sysmeta = MNodeService.getInstance().getSystemMetadata(session, id);
762
        
763
        response.setContentType("text/xml");
764
        response.setStatus(200);
765
        OutputStream out = response.getOutputStream();
766
        
767
        // Serialize and write it to the output stream
768
       serializeServiceType(SystemMetadata.class, sysmeta, out);
769
   }
868 770
    
869 771
    
870 772
    /**
......
874 776
     *               is the existing pid.  If insert, the pid is the new one
875 777
     * @throws InvalidRequest 
876 778
     * @throws ServiceFailure 
877
     * @throws FileNotFoundException 
878 779
     * @throws JiBXException 
879 780
     * @throws NotImplemented 
880 781
     * @throws InvalidSystemMetadata 
......
884 785
     * @throws NotAuthorized 
885 786
     * @throws InvalidToken 
886 787
     * @throws NotFound 
788
     * @throws IOException 
887 789
     */
888
    protected void putObject(String pid, String action) throws ServiceFailure, InvalidRequest, FileNotFoundException, JiBXException, InvalidToken, NotAuthorized, IdentifierNotUnique, UnsupportedType, InsufficientResources, InvalidSystemMetadata, NotImplemented, NotFound {
790
    protected void putObject(String pid, String action) throws ServiceFailure, InvalidRequest, JiBXException, InvalidToken, NotAuthorized, IdentifierNotUnique, UnsupportedType, InsufficientResources, InvalidSystemMetadata, NotImplemented, NotFound, IOException {
889 791
        logMetacat.debug("putObject with pid " + pid);
890 792
        logMetacat.debug("Entering putObject: " + pid + "/" + action);
891
        OutputStream out = null;
892
        try {
893
            out = response.getOutputStream();
894
            response.setStatus(200);
895
            response.setContentType("text/xml");
896
        } catch (IOException e1) {
897
            logMetacat.error("Could not get the output stream for writing in putObject");
898
        }
899 793
        
794
        response.setStatus(200);
795
        response.setContentType("text/xml");
796
        OutputStream out = response.getOutputStream();
797
        
900 798
        // Read the incoming data from its Mime Multipart encoding
901 799
    	Map<String, File> files = collectMultipartFiles();
902 800
        InputStream object = null;
......
951 849
     * Handle delete 
952 850
     * @param guid ID of data object to be deleted
953 851
     * @throws IOException
852
     * @throws InvalidRequest 
853
     * @throws NotImplemented 
854
     * @throws NotFound 
855
     * @throws NotAuthorized 
856
     * @throws ServiceFailure 
857
     * @throws InvalidToken 
858
     * @throws JiBXException 
954 859
     */
955
    private void deleteObject(String guid) throws IOException 
860
    private void deleteObject(String guid) throws IOException, InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented, InvalidRequest, JiBXException 
956 861
    {
957 862

  
958 863
        OutputStream out = response.getOutputStream();
......
961 866

  
962 867
        Identifier id = new Identifier();
963 868
        id.setValue(guid);
964
        try {
965
            logMetacat.debug("Calling delete");
966
            MNodeService.getInstance().delete(session, id);
967
            serializeServiceType(Identifier.class, id, out);
968
        } 
969
        catch (NotAuthorized e) {
970
            response.setStatus(500);
971
            serializeException(e, out);
972
        } catch (InvalidToken e) {
973
            response.setStatus(500);
974
            serializeException(e, out);
975
        } catch (ServiceFailure e) {
976
            response.setStatus(500);
977
            serializeException(e, out);
978
        } catch (NotImplemented e) {
979
            response.setStatus(500);
980
            serializeException(e, out);
981
        } catch (InvalidRequest e) {
982
            response.setStatus(500);
983
            serializeException(e, out);
984
        } catch(NotFound e) {
985
            response.setStatus(500);
986
            serializeException(e, out);
987
        } catch(JiBXException e) {
988
            response.setStatus(500);
989
            serializeException(new ServiceFailure("1350", "JiBXException: " + e.getMessage()), out);
990
        }
991
        out.close();
992
    }
869

  
870
        logMetacat.debug("Calling delete");
871
        MNodeService.getInstance().delete(session, id);
872
        serializeServiceType(Identifier.class, id, out);
873
        
874
    }    
993 875
    
994
    
995
    
996
    
997 876
    /**
998 877
     * set the access perms on a document
999
     * @throws Exception
878
     * @throws JiBXException 
879
     * @throws UnsupportedEncodingException 
880
     * @throws InvalidRequest 
881
     * @throws NotImplemented 
882
     * @throws NotAuthorized 
883
     * @throws NotFound 
884
     * @throws ServiceFailure 
885
     * @throws InvalidToken 
1000 886
     */
1001
    protected void setaccess() throws Exception
887
    protected void setAccess() throws UnsupportedEncodingException, JiBXException, InvalidToken, ServiceFailure, NotFound, NotAuthorized, NotImplemented, InvalidRequest
1002 888
    {
1003
        try
1004
        {
1005
            String guid = params.get("guid")[0];
1006
            Identifier id = new Identifier();
1007
            id.setValue(guid);
1008
            String accesspolicy = params.get("accesspolicy")[0];
1009
            AccessPolicy accessPolicy = (AccessPolicy) deserializeServiceType(AccessPolicy.class, new ByteArrayInputStream(accesspolicy.getBytes("UTF-8")));
1010
            MNodeService.getInstance().setAccessPolicy(session, id, accessPolicy);
1011
        }
1012
        catch(Exception e)
1013
        {
1014
            response.setStatus(500);
1015
            printError("Error setting access: " + e.getClass() + ": " + e.getMessage(), response);
1016
            throw e;
1017
        }
889
    
890
        String guid = params.get("guid")[0];
891
        Identifier id = new Identifier();
892
        id.setValue(guid);
893
        String accesspolicy = params.get("accesspolicy")[0];
894
        AccessPolicy accessPolicy = (AccessPolicy) deserializeServiceType(AccessPolicy.class, new ByteArrayInputStream(accesspolicy.getBytes("UTF-8")));
895
        MNodeService.getInstance().setAccessPolicy(session, id, accessPolicy);
896
        
897
        
1018 898
    }
1019 899

  
1020 900
}

Also available in: Unified diff