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: cjones $'
7
 *     '$Date: 2011-08-31 14:36:32 -0700 (Wed, 31 Aug 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.util.Date;
32
import java.util.Map;
33

    
34
import javax.servlet.ServletContext;
35
import javax.servlet.http.HttpServletRequest;
36
import javax.servlet.http.HttpServletResponse;
37

    
38
import org.apache.commons.fileupload.FileUploadException;
39
import org.apache.commons.io.IOUtils;
40
import org.apache.log4j.Logger;
41
import org.dataone.client.ObjectFormatCache;
42
import org.dataone.service.exceptions.BaseException;
43
import org.dataone.service.exceptions.IdentifierNotUnique;
44
import org.dataone.service.exceptions.InsufficientResources;
45
import org.dataone.service.exceptions.InvalidRequest;
46
import org.dataone.service.exceptions.InvalidSystemMetadata;
47
import org.dataone.service.exceptions.InvalidToken;
48
import org.dataone.service.exceptions.NotAuthorized;
49
import org.dataone.service.exceptions.NotFound;
50
import org.dataone.service.exceptions.NotImplemented;
51
import org.dataone.service.exceptions.ServiceFailure;
52
import org.dataone.service.exceptions.UnsupportedType;
53
import org.dataone.service.types.v1.AccessPolicy;
54
import org.dataone.service.types.v1.Checksum;
55
import org.dataone.service.types.v1.Event;
56
import org.dataone.service.types.v1.Identifier;
57
import org.dataone.service.types.v1.Log;
58
import org.dataone.service.types.v1.ObjectFormat;
59
import org.dataone.service.types.v1.ObjectFormatIdentifier;
60
import org.dataone.service.types.v1.ObjectFormatList;
61
import org.dataone.service.types.v1.ObjectLocationList;
62
import org.dataone.service.types.v1.Permission;
63
import org.dataone.service.types.v1.QueryType;
64
import org.dataone.service.types.v1.Subject;
65
import org.dataone.service.types.v1.SystemMetadata;
66
import org.dataone.service.util.TypeMarshaller;
67
import org.jibx.runtime.JiBXException;
68

    
69
import edu.ucsb.nceas.metacat.dataone.CNodeService;
70

    
71
/**
72
 * CN REST service implementation handler
73
 * 
74
 * ******************
75
 	CNCore -- DONE
76
		create() - POST /d1/cn/object/PID
77
		listFormats() - GET /d1/cn/formats
78
		getFormat() - GET /d1/cn/formats/FMTID
79
		getLogRecords - GET /d1/cn/log
80
		reserveIdentifier() - POST /d1/cn/reserve
81
		listNodes() - Not implemented
82
		registerSystemMetadata() - POST /d1/meta/PID
83
	
84
	CNRead -- DONE
85
		get() - GET /d1/cn/object/PID
86
		getSystemMetadata() - GET /d1/cn/meta/PID
87
		resolve() - GET /d1/cn/resolve/PID
88
		assertRelation() - GET /d1/cn/assertRelation/PID
89
		getChecksum() - GET /d1/cn/checksum
90
		search() - Not implemented in Metacat
91
	
92
	CNAuthorization
93
		setOwner() - PUT /d1/cn/owner/PID
94
		isAuthorized() - GET /d1/cn/isAuthorized/PID
95
		setAccessPolicy() - POST /d1/cn/accessRules
96
		
97
	CNIdentity - not implemented at all on Metacat
98
	
99
	CNReplication
100
		setReplicationStatus() - Not exposed
101
		updateReplicationMetadata() - New method?
102
		setReplicationPolicy() - Not exposed
103
	
104
	CNRegister -- not implemented at all in Metacat
105
 * ******************
106
 * @author leinfelder
107
 *
108
 */
109
public class CNResourceHandler extends D1ResourceHandler {
110

    
111
	/** CN-specific operations **/
112
    protected static final String RESOURCE_RESERVE = "reserve";
113
    protected static final String RESOURCE_FORMATS = "formats";
114
    protected static final String RESOURCE_RESOLVE = "resolve";
115
    protected static final String RESOURCE_ASSERT_RELATION = "assertRelation";
116
    protected static final String RESOURCE_OWNER = "owner";
117
    protected static final String RESOURCE_NOTIFY = "notify";
118
    protected static final String RESOURCE_META_REPLICATION = "meta/replication";
119
    protected static final String RESOURCE_META_POLICY = "meta/policy";
120
	
121
    public CNResourceHandler(ServletContext servletContext,
122
			HttpServletRequest request, HttpServletResponse response) {
123
		super(servletContext, request, response);
124
        logMetacat = Logger.getLogger(CNResourceHandler.class);
125
	}
126

    
127
	/**
128
     * This function is called from REST API servlet and handles each request to the servlet 
129
     * 
130
     * @param httpVerb (GET, POST, PUT or DELETE)
131
     */
132
    @Override
133
    public void handle(byte httpVerb) {
134
    	// prepare the handler
135
    	super.handle(httpVerb);
136
    	
137
        try {
138

    
139
        	// get the resource
140
            String resource = request.getPathInfo();
141
            resource = resource.substring(resource.indexOf("/") + 1);
142
                        
143
            // get the rest
144
            String extra = null;
145
            if (resource.lastIndexOf("/") != -1) {
146
                extra = resource.substring(resource.lastIndexOf("/") + 1);
147
            }
148
            
149
            logMetacat.debug("handling verb " + httpVerb + " request with resource '" + resource + "'");
150
            boolean status = false;
151

    
152
            if (resource != null) {
153

    
154
                if (resource.startsWith(RESOURCE_ACCESS_RULES) && httpVerb == PUT) {
155
                    logMetacat.debug("Setting access policy");
156
                    setAccess();
157
                    status = true;
158
                    logMetacat.debug("done setting access");
159
                    
160
                } else if (resource.startsWith(RESOURCE_META)) {
161
                    logMetacat.debug("Using resource: " + RESOURCE_META);
162
                    
163
                    // get
164
                    if (httpVerb == GET) {
165
                        getSystemMetadataObject(extra);
166
                        status = true;
167
                    }
168
                    // post to register system metadata
169
                    if (httpVerb == POST) {
170
                    	registerSystemMetadata(extra);
171
                    	status = true;
172
                    }
173

    
174
                } else if (resource.startsWith(RESOURCE_RESERVE)) {
175
                    // reserve the ID (in params)
176
                    if (httpVerb == POST) {
177
                    	reserve();
178
                    	status = true;
179
                    }
180
                } else if (resource.startsWith(RESOURCE_ASSERT_RELATION)) {
181
                	
182
                    // reserve the ID (in params)
183
                    if (httpVerb == GET) {
184
                    	assertRelation(extra);
185
                    	status = true;
186
                    }    
187
                } else if (resource.startsWith(RESOURCE_RESOLVE)) {
188
                	
189
                    // resolve the object location
190
                    if (httpVerb == GET) {
191
                    	resolve(extra);
192
                    	status = true;
193
                    }
194
                } else if (resource.startsWith(RESOURCE_OWNER)) {
195
                	
196
                    // set the owner
197
                    if (httpVerb == PUT) {
198
                    	owner(extra);
199
                    	status = true;
200
                    }    
201
                } else if (resource.startsWith(RESOURCE_OWNER)) {
202
                	
203
                    // set the owner
204
                    if (httpVerb == PUT) {
205
                    	owner(extra);
206
                    	status = true;
207
                    }
208
                } else if (resource.startsWith(RESOURCE_IS_AUTHORIZED)) {
209
                	
210
                    // authorized?
211
                    if (httpVerb == GET) {
212
                    	isAuthorized(extra);
213
                    	status = true;
214
                    }    
215
                } else if (resource.startsWith(RESOURCE_OBJECTS)) {
216
                    logMetacat.debug("Using resource 'object'");
217
                    logMetacat.debug("D1 Rest: Starting resource processing...");
218
                    
219
                    logMetacat.debug("objectId: " + extra);
220
                    logMetacat.debug("verb:" + httpVerb);
221

    
222
                    if (httpVerb == GET) {
223
                    	if (extra != null) {
224
                    		getObject(extra);
225
                    	} else {
226
                    		query();
227
                    	}
228
                        status = true;
229
                    } else if (httpVerb == POST) {
230
                        putObject(extra, FUNCTION_NAME_INSERT);
231
                        status = true;
232
                    }
233
                    
234
                } else if (resource.startsWith(RESOURCE_FORMATS)) {
235
                  logMetacat.debug("Using resource: " + RESOURCE_FORMATS);
236
                  
237
                  
238
                  
239
                  // handle each verb
240
                  if (httpVerb == GET) {
241
                  	if (extra == null) {
242
                  		// list the formats collection
243
                  		listFormats();
244
                  	} else {
245
                  		// get the specified format
246
                  		getFormat(extra);
247
                  	}
248
                  	status = true;
249
                  }
250
                  
251
                } else if (resource.startsWith(RESOURCE_LOG)) {
252
                    logMetacat.debug("Using resource: " + RESOURCE_LOG);
253
                    //handle log events
254
                    if (httpVerb == GET) {
255
                        getLog();
256
                        status = true;
257
                    }
258

    
259
                } else if (resource.startsWith(RESOURCE_CHECKSUM)) {
260
                    logMetacat.debug("Using resource: " + RESOURCE_CHECKSUM);
261
                    //handle checksum requests
262
                    if (httpVerb == GET) {
263
                    
264
                        checksum(extra);
265
                        status = true;
266
                    }
267
                } 
268
                    
269
                if (!status) {
270
                	throw new ServiceFailure("0000", "Unknown error, status = " + status);
271
                }
272
            } else {
273
            	throw new InvalidRequest("0000", "No resource matched for " + resource);
274
            }
275
        } catch (BaseException be) {
276
        	// report Exceptions as clearly and generically as possible
277
        	OutputStream out = null;
278
			try {
279
				out = response.getOutputStream();
280
			} catch (IOException ioe) {
281
				logMetacat.error("Could not get output stream from response", ioe);
282
			}
283
            serializeException(be, out);
284
        } catch (Exception e) {
285
            // report Exceptions as clearly and generically as possible
286
            logMetacat.error(e.getClass() + ": " + e.getMessage(), e);
287
        	OutputStream out = null;
288
			try {
289
				out = response.getOutputStream();
290
			} catch (IOException ioe) {
291
				logMetacat.error("Could not get output stream from response", ioe);
292
			}
293
			ServiceFailure se = new ServiceFailure("0000", e.getMessage());
294
            serializeException(se, out);
295
        }
296
    }
297
    
298
    /**
299
     * Get the checksum for the given guid
300
     * 
301
     * @param guid
302
     * @throws NotImplemented 
303
     * @throws InvalidRequest 
304
     * @throws NotFound 
305
     * @throws NotAuthorized 
306
     * @throws ServiceFailure 
307
     * @throws InvalidToken 
308
     * @throws IOException 
309
     * @throws JiBXException 
310
     */
311
    private void checksum(String guid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, InvalidRequest, NotImplemented, JiBXException, IOException {
312
    	Identifier guidid = new Identifier();
313
        guidid.setValue(guid);
314
        logMetacat.debug("getting checksum for object " + guid);
315
        Checksum c = CNodeService.getInstance().getChecksum(session, guidid);
316
        logMetacat.debug("got checksum " + c.getValue());
317
        response.setStatus(200);
318
        logMetacat.debug("serializing response");
319
        TypeMarshaller.marshalTypeToOutputStream(c, response.getOutputStream());
320
        logMetacat.debug("done serializing response.");
321
        
322
    }
323
    
324
	/**
325
     * get the logs based on passed params.  Available 
326
     * params are token, fromDate, toDate, event.  See 
327
     * http://mule1.dataone.org/ArchitectureDocs/mn_api_crud.html#MN_crud.getLogRecords
328
     * for more info
329
	 * @throws NotImplemented 
330
	 * @throws InvalidRequest 
331
	 * @throws NotAuthorized 
332
	 * @throws ServiceFailure 
333
	 * @throws InvalidToken 
334
	 * @throws IOException 
335
	 * @throws JiBXException 
336
     */
337
    private void getLog() throws InvalidToken, ServiceFailure, NotAuthorized, InvalidRequest, NotImplemented, IOException, JiBXException
338
    {
339
        
340
        Date fromDate = null;
341
        Date toDate = null;
342
        Event event = null;
343
        Integer start = null;
344
        Integer count = null;
345
        
346
        try {
347
        	String fromDateS = params.get("fromDate")[0];
348
            logMetacat.debug("param fromDateS: " + fromDateS);
349
            fromDate = parseDateAndConvertToGMT(fromDateS);
350
        } catch (Exception e) {
351
        	logMetacat.warn("Could not parse fromDate: " + e.getMessage());
352
        }
353
        try {
354
        	String toDateS = params.get("toDate")[0];
355
            logMetacat.debug("param toDateS: " + toDateS);
356
            toDate = parseDateAndConvertToGMT(toDateS);
357
        } catch (Exception e) {
358
        	logMetacat.warn("Could not parse toDate: " + e.getMessage());
359
		}
360
        try {
361
        	String eventS = params.get("event")[0];
362
            event = Event.convert(eventS);
363
        } catch (Exception e) {
364
        	logMetacat.warn("Could not parse event: " + e.getMessage());
365
		}
366
        logMetacat.debug("fromDate: " + fromDate + " toDate: " + toDate);
367
        
368
        try {
369
        	start =  Integer.parseInt(params.get("start")[0]);
370
        } catch (Exception e) {
371
			logMetacat.warn("Could not parse start: " + e.getMessage());
372
		}
373
        try {
374
        	count =  Integer.parseInt(params.get("count")[0]);
375
        } catch (Exception e) {
376
			logMetacat.warn("Could not parse count: " + e.getMessage());
377
		}
378
        
379
        logMetacat.debug("calling getLogRecords");
380
        Log log = CNodeService.getInstance().getLogRecords(session, fromDate, toDate, event, start, count);
381
        
382
        OutputStream out = response.getOutputStream();
383
        response.setStatus(200);
384
        response.setContentType("text/xml");
385
        
386
        TypeMarshaller.marshalTypeToOutputStream(log, out);
387
  
388
    }
389

    
390
    /**
391
     * Implements REST version of DataONE CRUD API --> get
392
     * @param guid ID of data object to be read
393
     * @throws NotImplemented 
394
     * @throws InvalidRequest 
395
     * @throws NotFound 
396
     * @throws NotAuthorized 
397
     * @throws ServiceFailure 
398
     * @throws InvalidToken 
399
     * @throws IOException 
400
     */
401
    protected void getObject(String guid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, InvalidRequest, NotImplemented, IOException {
402

    
403
        Identifier id = new Identifier();
404
        id.setValue(guid);
405
            
406
        SystemMetadata sm = CNodeService.getInstance().getSystemMetadata(session, id);
407
        
408
        //set the content type
409
        if(sm.getFmtid().getValue().trim().equals(
410
        		ObjectFormatCache.getInstance().getFormat("text/csv").getFmtid().getValue()))
411
        {
412
            response.setContentType("text/csv");
413
            response.setHeader("Content-Disposition", "inline; filename=" + id.getValue() + ".csv");
414
        }
415
        else if(sm.getFmtid().getValue().trim().equals(
416
        		ObjectFormatCache.getInstance().getFormat("text/plain").getFmtid().getValue()))
417
        {
418
            response.setContentType("text/plain");
419
            response.setHeader("Content-Disposition", "inline; filename=" + id.getValue() + ".txt");
420
        } 
421
        else if(sm.getFmtid().getValue().trim().equals(
422
        		ObjectFormatCache.getInstance().getFormat("application/octet-stream").getFmtid().getValue()))
423
        {
424
            response.setContentType("application/octet-stream");
425
        }
426
        else
427
        {
428
            response.setContentType("text/xml");
429
            response.setHeader("Content-Disposition", "inline; filename=" + id.getValue() + ".xml");
430
        }
431
        
432
        InputStream data = CNodeService.getInstance().get(session, id);
433
        
434
        OutputStream out = response.getOutputStream();
435
        response.setStatus(200);
436
        IOUtils.copyLarge(data, out);
437
            
438
    }
439
    
440

    
441
    /**
442
     * Implements REST version of DataONE CRUD API --> getSystemMetadata
443
     * @param guid ID of data object to be read
444
     * @throws NotImplemented 
445
     * @throws InvalidRequest 
446
     * @throws NotFound 
447
     * @throws NotAuthorized 
448
     * @throws ServiceFailure 
449
     * @throws InvalidToken 
450
     * @throws IOException 
451
     * @throws JiBXException 
452
     */
453
    protected void getSystemMetadataObject(String guid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, InvalidRequest, NotImplemented, IOException, JiBXException {
454

    
455
        Identifier id = new Identifier();
456
        id.setValue(guid);
457
        SystemMetadata sysmeta = CNodeService.getInstance().getSystemMetadata(session, id);
458
        
459
        response.setContentType("text/xml");
460
        response.setStatus(200);
461
        OutputStream out = response.getOutputStream();
462
        
463
        // Serialize and write it to the output stream
464
        TypeMarshaller.marshalTypeToOutputStream(sysmeta, out);
465
   }
466
    
467
    /**
468
     * Earthgrid API > Put Service >Put Function : calls MetacatHandler > handleInsertOrUpdateAction 
469
     * 
470
     * @param guid - ID of data object to be inserted or updated.  If action is update, the pid
471
     *               is the existing pid.  If insert, the pid is the new one
472
     * @throws InvalidRequest 
473
     * @throws ServiceFailure 
474
     * @throws IdentifierNotUnique 
475
     * @throws JiBXException 
476
     * @throws NotImplemented 
477
     * @throws InvalidSystemMetadata 
478
     * @throws InsufficientResources 
479
     * @throws UnsupportedType 
480
     * @throws NotAuthorized 
481
     * @throws InvalidToken 
482
     * @throws IOException 
483
     * @throws IllegalAccessException 
484
     * @throws InstantiationException 
485
     */
486
    protected void putObject(String pid, String action) throws ServiceFailure, InvalidRequest, IdentifierNotUnique, JiBXException, InvalidToken, NotAuthorized, UnsupportedType, InsufficientResources, InvalidSystemMetadata, NotImplemented, IOException, InstantiationException, IllegalAccessException {
487
        logMetacat.debug("Entering putObject: " + pid + "/" + action);
488
        
489
        // Read the incoming data from its Mime Multipart encoding
490
    	Map<String, File> files = collectMultipartFiles();
491
        InputStream object = null;
492
        InputStream sysmeta = null;
493

    
494
        File smFile = files.get("sysmeta");
495
        sysmeta = new FileInputStream(smFile);
496
        File objFile = files.get("object");
497
        object = new FileInputStream(objFile);
498
       
499
        if (action.equals(FUNCTION_NAME_INSERT)) { //handle inserts
500

    
501
            logMetacat.debug("Commence creation...");
502
            SystemMetadata smd = TypeMarshaller.unmarshalTypeFromStream(SystemMetadata.class, sysmeta);
503

    
504
            Identifier id = new Identifier();
505
            id.setValue(pid);
506
            logMetacat.debug("creating object with pid " + id.getValue());
507
            Identifier rId = CNodeService.getInstance().create(session, id, object, smd);
508
            
509
            OutputStream out = response.getOutputStream();
510
            response.setStatus(200);
511
            response.setContentType("text/xml");
512
            
513
            TypeMarshaller.marshalTypeToOutputStream(rId, out);
514
            
515
        } else {
516
            throw new InvalidRequest("1000", "Operation must be create.");
517
        }
518
    }
519

    
520
    /**
521
     * List the object formats registered with the system
522
     * @throws NotImplemented 
523
     * @throws InsufficientResources 
524
     * @throws NotFound 
525
     * @throws ServiceFailure 
526
     * @throws InvalidRequest 
527
     * @throws IOException 
528
     * @throws JiBXException 
529
     */
530
	private void listFormats() throws InvalidRequest, ServiceFailure, NotFound, InsufficientResources, NotImplemented, IOException, JiBXException {
531
      logMetacat.debug("Entering listFormats()");
532

    
533
      ObjectFormatList objectFormatList = CNodeService.getInstance().listFormats();
534
      // get the response output stream
535
      OutputStream out = response.getOutputStream();
536
      response.setStatus(200);
537
      response.setContentType("text/xml");
538
      
539
      TypeMarshaller.marshalTypeToOutputStream(objectFormatList, out);
540
            
541
    }
542

    
543
		/**
544
     * Return the requested object format
545
     * 
546
     * @param fmtidStr the requested format identifier as a string
547
		 * @throws NotImplemented 
548
		 * @throws InsufficientResources 
549
		 * @throws NotFound 
550
		 * @throws ServiceFailure 
551
		 * @throws InvalidRequest 
552
		 * @throws IOException 
553
		 * @throws JiBXException 
554
     */
555
    private void getFormat(String fmtidStr) throws InvalidRequest, ServiceFailure, NotFound, InsufficientResources, NotImplemented, IOException, JiBXException {
556
      logMetacat.debug("Entering listFormats()");
557
      
558
      ObjectFormatIdentifier fmtid = new ObjectFormatIdentifier();
559
      fmtid.setValue(fmtidStr);
560
      
561
	  // get the specified object format
562
      ObjectFormat objectFormat = CNodeService.getInstance().getFormat(fmtid);
563
      
564
      OutputStream out = response.getOutputStream();
565
      response.setStatus(200);
566
      response.setContentType("text/xml");
567
      
568
      TypeMarshaller.marshalTypeToOutputStream(objectFormat, out);
569
      
570
    }
571
    
572
    /**
573
     * Reserve the given Identifier
574
     * @throws InvalidToken
575
     * @throws ServiceFailure
576
     * @throws NotAuthorized
577
     * @throws IdentifierNotUnique
578
     * @throws NotImplemented
579
     * @throws InvalidRequest
580
     * @throws IOException 
581
     * @throws JiBXException 
582
     */
583
    private void reserve() throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, NotImplemented, InvalidRequest, IOException, JiBXException {
584
		Identifier pid = null;
585
		String scope = null;
586
    	String format = null;
587
    	// gather the params
588
		try {
589
	    	String id = params.get("pid")[0];
590
			pid = new Identifier();
591
			pid.setValue(id);
592
		} catch (Exception e) {
593
			logMetacat.warn("pid not specified");
594
		}
595
		try {
596
			scope = params.get("scope")[0];
597
		} catch (Exception e) {
598
			logMetacat.warn("pid not specified");
599
		}
600
		try {
601
			format = params.get("format")[0];
602
		} catch (Exception e) {
603
			logMetacat.warn("pid not specified");
604
		} 
605
		// call the implementation
606
		boolean result = CNodeService.getInstance().reserveIdentifier(session, pid);
607
		OutputStream out = response.getOutputStream();
608
		response.setStatus(200);
609
		response.setContentType("text/xml");
610
		// nothing to send back
611
    }
612
    
613
    /**
614
     * 
615
     * @param id
616
     * @throws InvalidRequest
617
     * @throws InvalidToken
618
     * @throws ServiceFailure
619
     * @throws NotAuthorized
620
     * @throws NotFound
621
     * @throws NotImplemented
622
     * @throws IOException
623
     * @throws JiBXException 
624
     */
625
    private void resolve(String id) throws InvalidRequest, InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented, IOException, JiBXException {
626
		Identifier pid = new Identifier();
627
		pid.setValue(id);
628
		ObjectLocationList locationList = CNodeService.getInstance().resolve(session, pid);
629
	    OutputStream out = response.getOutputStream();
630
		response.setStatus(200);
631
		response.setContentType("text/xml");
632
		TypeMarshaller.marshalTypeToOutputStream(locationList, out);
633
		
634
    }
635

    
636
    /**
637
     * Assert that a relationship exists between two resources
638
     * @param id
639
     * @return
640
     * @throws InvalidToken
641
     * @throws ServiceFailure
642
     * @throws NotAuthorized
643
     * @throws NotFound
644
     * @throws InvalidRequest
645
     * @throws NotImplemented
646
     */
647
    private boolean assertRelation(String id) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, InvalidRequest, NotImplemented {
648
		Identifier pidOfSubject = new Identifier();
649
		pidOfSubject.setValue(id);
650
		String relationship = null;
651
		try {
652
			relationship = params.get("relationship")[0];
653
		} catch (Exception e) {
654
			logMetacat.warn("relationship not specified");
655
		}
656
		Identifier pidOfObject = new Identifier();
657
		try {
658
			String objPid = params.get("pidOfObject")[0];
659
			pidOfObject.setValue(objPid);
660
		} catch (Exception e) {
661
			logMetacat.warn("pidOfObject not specified");
662
		}
663
		boolean result = CNodeService.getInstance().assertRelation(session, pidOfSubject, relationship, pidOfObject);
664
		response.setStatus(200);
665
		response.setContentType("text/xml");
666
		return result;
667
    }
668
    
669
    /**
670
     * Set the owner of a resource
671
     * @param id
672
     * @throws JiBXException
673
     * @throws InvalidToken
674
     * @throws ServiceFailure
675
     * @throws NotFound
676
     * @throws NotAuthorized
677
     * @throws NotImplemented
678
     * @throws InvalidRequest
679
     * @throws IOException
680
     * @throws IllegalAccessException 
681
     * @throws InstantiationException 
682
     */
683
    private void owner(String id) throws JiBXException, InvalidToken, ServiceFailure, NotFound, NotAuthorized, NotImplemented, InvalidRequest, IOException, InstantiationException, IllegalAccessException {
684
		Identifier pid = new Identifier();
685
		pid.setValue(id);
686
		String subjectStr = params.get("subject")[0];
687
		Subject subject = TypeMarshaller.unmarshalTypeFromStream(Subject.class, new ByteArrayInputStream(subjectStr.getBytes("UTF-8")));
688
		Identifier retPid = CNodeService.getInstance().setOwner(session, pid, subject);
689
		OutputStream out = response.getOutputStream();
690
		response.setStatus(200);
691
		response.setContentType("text/xml");
692
		TypeMarshaller.marshalTypeToOutputStream(retPid, out);		
693
    }
694
    
695
    /**
696
     * Processes the authorization check for given id
697
     * @param id
698
     * @return
699
     * @throws ServiceFailure
700
     * @throws InvalidToken
701
     * @throws NotFound
702
     * @throws NotAuthorized
703
     * @throws NotImplemented
704
     * @throws InvalidRequest
705
     */
706
    private boolean isAuthorized(String id) throws ServiceFailure, InvalidToken, NotFound, NotAuthorized, NotImplemented, InvalidRequest {
707
		Identifier pid = new Identifier();
708
		pid.setValue(id);
709
		String permission = params.get("permission")[0];
710
		boolean result = CNodeService.getInstance().isAuthorized(session, pid, Permission.convert(permission));
711
		response.setStatus(200);
712
		response.setContentType("text/xml");
713
		return result;
714
    }
715
    
716
    /**
717
     * Register System Metadata without data or metadata object
718
     * @param pid identifier for System Metadata entry
719
     * @throws JiBXException 
720
     * @throws FileUploadException 
721
     * @throws IOException 
722
     * @throws InvalidRequest 
723
     * @throws ServiceFailure 
724
     * @throws InvalidSystemMetadata 
725
     * @throws NotAuthorized 
726
     * @throws NotImplemented 
727
     * @throws IllegalAccessException 
728
     * @throws InstantiationException 
729
     */
730
    protected boolean registerSystemMetadata(String pid) throws ServiceFailure, InvalidRequest, IOException, FileUploadException, JiBXException, NotImplemented, NotAuthorized, InvalidSystemMetadata, InstantiationException, IllegalAccessException {
731
		logMetacat.debug("Entering registerSystemMetadata: " + pid);
732

    
733
		// get the system metadata from the request
734
		SystemMetadata systemMetadata = collectSystemMetadata();
735

    
736
		Identifier guid = new Identifier();
737
		guid.setValue(pid);
738
		logMetacat.debug("registering system metadata with pid " + guid.getValue());
739
		boolean result = CNodeService.getInstance().registerSystemMetadata(session, guid, systemMetadata);
740
		
741
		response.setStatus(200);
742
		response.setContentType("text/xml");
743
		return result;
744
			
745
	}
746
    
747
    /**
748
     * set the access perms on a document
749
     * @throws JiBXException 
750
     * @throws InvalidRequest 
751
     * @throws NotImplemented 
752
     * @throws NotAuthorized 
753
     * @throws NotFound 
754
     * @throws ServiceFailure 
755
     * @throws InvalidToken 
756
     * @throws IllegalAccessException 
757
     * @throws InstantiationException 
758
     * @throws IOException 
759
     */
760
    protected void setAccess() throws JiBXException, InvalidToken, ServiceFailure, NotFound, NotAuthorized, NotImplemented, InvalidRequest, IOException, InstantiationException, IllegalAccessException {
761

    
762
        String guid = params.get("guid")[0];
763
        Identifier id = new Identifier();
764
        id.setValue(guid);
765
        String accesspolicy = params.get("accesspolicy")[0];
766
        AccessPolicy accessPolicy = TypeMarshaller.unmarshalTypeFromStream(AccessPolicy.class, new ByteArrayInputStream(accesspolicy.getBytes("UTF-8")));
767
        CNodeService.getInstance().setAccessPolicy(session, id, accessPolicy);
768

    
769
    }
770
    
771
    /**
772
     *	Pass to the CN search service
773
     *
774
     * @throws NotImplemented 
775
     * @throws InvalidRequest 
776
     * @throws NotAuthorized 
777
     * @throws ServiceFailure 
778
     * @throws InvalidToken 
779
     * @throws Exception
780
     */
781
    private void query() throws InvalidToken, ServiceFailure, NotAuthorized, InvalidRequest, NotImplemented {
782
        
783
    	String query = null;
784
		QueryType queryType = null;
785
		try {
786
			query = params.get("query")[0];
787
		} catch (Exception e) {
788
			logMetacat.warn("query not specified");
789
		}
790
		try {
791
			String qt = params.get("queryType")[0];
792
			queryType = QueryType.valueOf(qt);
793
		} catch (Exception e) {
794
			logMetacat.warn("queryType not specified");
795
		}
796
		
797
    	// expecting to throw NotImplemented
798
		CNodeService.getInstance().search(session, queryType, query);
799
    }
800

    
801
}
(1-1/11)