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.util.Date;
33
import java.util.Map;
34

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

    
39
import org.apache.commons.fileupload.FileUploadException;
40
import org.apache.commons.io.IOUtils;
41
import org.apache.log4j.Logger;
42
import org.dataone.client.ObjectFormatCache;
43
import org.dataone.service.exceptions.BaseException;
44
import org.dataone.service.exceptions.IdentifierNotUnique;
45
import org.dataone.service.exceptions.InsufficientResources;
46
import org.dataone.service.exceptions.InvalidRequest;
47
import org.dataone.service.exceptions.InvalidSystemMetadata;
48
import org.dataone.service.exceptions.InvalidToken;
49
import org.dataone.service.exceptions.NotAuthorized;
50
import org.dataone.service.exceptions.NotFound;
51
import org.dataone.service.exceptions.NotImplemented;
52
import org.dataone.service.exceptions.ServiceFailure;
53
import org.dataone.service.exceptions.UnsupportedType;
54
import org.dataone.service.types.v1.AccessPolicy;
55
import org.dataone.service.types.v1.Checksum;
56
import org.dataone.service.types.v1.Event;
57
import org.dataone.service.types.v1.Identifier;
58
import org.dataone.service.types.v1.Log;
59
import org.dataone.service.types.v1.ObjectFormat;
60
import org.dataone.service.types.v1.ObjectFormatIdentifier;
61
import org.dataone.service.types.v1.ObjectFormatList;
62
import org.dataone.service.types.v1.ObjectLocationList;
63
import org.dataone.service.types.v1.Permission;
64
import org.dataone.service.types.v1.QueryType;
65
import org.dataone.service.types.v1.Subject;
66
import org.dataone.service.types.v1.SystemMetadata;
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
        serializeServiceType(Checksum.class, 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
        serializeServiceType(Log.class, 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.getObjectFormat().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.getObjectFormat().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.getObjectFormat().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
       serializeServiceType(SystemMetadata.class, 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
     */
484
    protected void putObject(String pid, String action) throws ServiceFailure, InvalidRequest, IdentifierNotUnique, JiBXException, InvalidToken, NotAuthorized, UnsupportedType, InsufficientResources, InvalidSystemMetadata, NotImplemented, IOException {
485
        logMetacat.debug("Entering putObject: " + pid + "/" + action);
486
        
487
        // Read the incoming data from its Mime Multipart encoding
488
    	Map<String, File> files = collectMultipartFiles();
489
        InputStream object = null;
490
        InputStream sysmeta = null;
491

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

    
499
            logMetacat.debug("Commence creation...");
500
            SystemMetadata smd = (SystemMetadata) deserializeServiceType(SystemMetadata.class, sysmeta);
501

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

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

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

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

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

    
728
		// get the system metadata from the request
729
		SystemMetadata systemMetadata = collectSystemMetadata();
730

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

    
755
        String guid = params.get("guid")[0];
756
        Identifier id = new Identifier();
757
        id.setValue(guid);
758
        String accesspolicy = params.get("accesspolicy")[0];
759
        AccessPolicy accessPolicy = (AccessPolicy) deserializeServiceType(AccessPolicy.class, new ByteArrayInputStream(accesspolicy.getBytes("UTF-8")));
760
        CNodeService.getInstance().setAccessPolicy(session, id, accessPolicy);
761

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

    
794
}
(1-1/11)