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: 2012-03-06 14:03:14 -0800 (Tue, 06 Mar 2012) $'
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.Enumeration;
33
import java.util.Map;
34

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

    
40
import org.apache.commons.fileupload.FileUploadException;
41
import org.apache.commons.io.IOUtils;
42
import org.apache.log4j.Logger;
43
import org.dataone.client.ObjectFormatCache;
44
import org.dataone.service.exceptions.BaseException;
45
import org.dataone.service.exceptions.IdentifierNotUnique;
46
import org.dataone.service.exceptions.InsufficientResources;
47
import org.dataone.service.exceptions.InvalidRequest;
48
import org.dataone.service.exceptions.InvalidSystemMetadata;
49
import org.dataone.service.exceptions.InvalidToken;
50
import org.dataone.service.exceptions.NotAuthorized;
51
import org.dataone.service.exceptions.NotFound;
52
import org.dataone.service.exceptions.NotImplemented;
53
import org.dataone.service.exceptions.ServiceFailure;
54
import org.dataone.service.exceptions.UnsupportedType;
55
import org.dataone.service.exceptions.VersionMismatch;
56
import org.dataone.service.types.v1.AccessPolicy;
57
import org.dataone.service.types.v1.Checksum;
58
import org.dataone.service.types.v1.ChecksumAlgorithmList;
59
import org.dataone.service.types.v1.DescribeResponse;
60
import org.dataone.service.types.v1.Event;
61
import org.dataone.service.types.v1.Identifier;
62
import org.dataone.service.types.v1.Log;
63
import org.dataone.service.types.v1.NodeReference;
64
import org.dataone.service.types.v1.ObjectFormat;
65
import org.dataone.service.types.v1.ObjectFormatIdentifier;
66
import org.dataone.service.types.v1.ObjectFormatList;
67
import org.dataone.service.types.v1.ObjectList;
68
import org.dataone.service.types.v1.ObjectLocationList;
69
import org.dataone.service.types.v1.Permission;
70
import org.dataone.service.types.v1.Replica;
71
import org.dataone.service.types.v1.ReplicationPolicy;
72
import org.dataone.service.types.v1.ReplicationStatus;
73
import org.dataone.service.types.v1.Subject;
74
import org.dataone.service.types.v1.SystemMetadata;
75
import org.dataone.service.util.Constants;
76
import org.dataone.service.util.DateTimeMarshaller;
77
import org.dataone.service.util.TypeMarshaller;
78
import org.jibx.runtime.JiBXException;
79
import org.xml.sax.SAXException;
80

    
81
import edu.ucsb.nceas.metacat.dataone.CNodeService;
82
import edu.ucsb.nceas.metacat.properties.PropertyService;
83
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
84

    
85
/**
86
 * CN REST service implementation handler
87
 * 
88
 * ****************** CNCore -- DONE create() - POST /d1/cn/object/PID
89
 * listFormats() - GET /d1/cn/formats getFormat() - GET /d1/cn/formats/FMTID
90
 * getLogRecords - GET /d1/cn/log reserveIdentifier() - POST /d1/cn/reserve
91
 * listNodes() - Not implemented registerSystemMetadata() - POST /d1/meta/PID
92
 * 
93
 * CNRead -- DONE get() - GET /d1/cn/object/PID getSystemMetadata() - GET
94
 * /d1/cn/meta/PID resolve() - GET /d1/cn/resolve/PID assertRelation() - GET
95
 * /d1/cn/assertRelation/PID getChecksum() - GET /d1/cn/checksum search() - Not
96
 * implemented in Metacat
97
 * 
98
 * CNAuthorization setOwner() - PUT /d1/cn/owner/PID isAuthorized() - GET
99
 * /d1/cn/isAuthorized/PID setAccessPolicy() - POST /d1/cn/accessRules
100
 * 
101
 * CNIdentity - not implemented at all on Metacat
102
 * 
103
 * CNReplication setReplicationStatus() - PUT /replicaNotifications/PID
104
 * updateReplicationMetadata() - PUT /replicaMetadata/PID setReplicationPolicy()
105
 * - PUT /replicaPolicies/PID isNodeAuthorized() - GET
106
 * /replicaAuthorizations/PID
107
 * 
108
 * CNRegister -- not implemented at all in Metacat ******************
109
 * 
110
 * @author leinfelder
111
 * 
112
 */
113
public class CNResourceHandler extends D1ResourceHandler {
114

    
115
    /** CN-specific operations **/
116
    protected static final String RESOURCE_RESERVE = "reserve";
117
    protected static final String RESOURCE_FORMATS = "formats";
118
    protected static final String RESOURCE_RESOLVE = "resolve";
119
    protected static final String RESOURCE_OWNER = "owner";
120
    protected static final String RESOURCE_REPLICATION_POLICY = "replicaPolicies";
121
    protected static final String RESOURCE_REPLICATION_META = "replicaMetadata";
122
    protected static final String RESOURCE_REPLICATION_AUTHORIZED = "replicaAuthorizations";
123
    protected static final String RESOURCE_REPLICATION_NOTIFY = "replicaNotifications";
124

    
125
    public CNResourceHandler(ServletContext servletContext,
126
            HttpServletRequest request, HttpServletResponse response) {
127
        super(servletContext, request, response);
128
        logMetacat = Logger.getLogger(CNResourceHandler.class);
129
    }
130

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

    
143
        try {
144

    
145
        	// only service requests if we have D1 configured
146
        	if (!isD1Enabled()) {
147
        		ServiceFailure se = new ServiceFailure("0000", "DataONE services are not enabled on this node");
148
                serializeException(se, response.getOutputStream());
149
                return;
150
        	}
151
        	
152
            // get the resource
153
            String resource = request.getPathInfo();
154
            resource = resource.substring(resource.indexOf("/") + 1);
155

    
156
            // for the rest of the resouce
157
            String extra = null;
158

    
159
            logMetacat.debug("handling verb " + httpVerb
160
                    + " request with resource '" + resource + "'");
161
            boolean status = false;
162

    
163
            if (resource != null) {
164

    
165
                if (resource.startsWith(RESOURCE_ACCESS_RULES)
166
                        && httpVerb == PUT) {
167
                    logMetacat.debug("Setting access policy");
168
                    // after the command
169
                    extra = parseTrailing(resource, RESOURCE_ACCESS_RULES);
170
                    setAccess(extra);
171
                    status = true;
172
                    logMetacat.debug("done setting access");
173

    
174
                } else if (resource.startsWith(RESOURCE_META)) {
175
                    logMetacat.debug("Using resource: " + RESOURCE_META);
176

    
177
                    // after the command
178
                    extra = parseTrailing(resource, RESOURCE_META);
179

    
180
                    // get
181
                    if (httpVerb == GET) {
182
                        getSystemMetadataObject(extra);
183
                        status = true;
184
                    }
185
                    // post to register system metadata
186
                    if (httpVerb == POST) {
187
                        registerSystemMetadata();
188
                        status = true;
189
                    }
190

    
191
                } else if (resource.startsWith(RESOURCE_RESERVE)) {
192
                    // reserve the ID (in params)
193
                    if (httpVerb == POST) {
194
                        reserve();
195
                        status = true;
196
                    }
197
                } else if (resource.startsWith(RESOURCE_RESOLVE)) {
198

    
199
                    // after the command
200
                    extra = parseTrailing(resource, RESOURCE_RESOLVE);
201

    
202
                    // resolve the object location
203
                    if (httpVerb == GET) {
204
                        resolve(extra);
205
                        status = true;
206
                    }
207
                } else if (resource.startsWith(RESOURCE_OWNER)) {
208

    
209
                    // after the command
210
                    extra = parseTrailing(resource, RESOURCE_OWNER);
211

    
212
                    // set the owner
213
                    if (httpVerb == PUT) {
214
                        owner(extra);
215
                        status = true;
216
                    }
217
                } else if (resource.startsWith(RESOURCE_IS_AUTHORIZED)) {
218

    
219
                    // after the command
220
                    extra = parseTrailing(resource, RESOURCE_IS_AUTHORIZED);
221

    
222
                    // authorized?
223
                    if (httpVerb == GET) {
224
                        isAuthorized(extra);
225
                        status = true;
226
                    }
227
                } else if (resource.startsWith(RESOURCE_OBJECTS)) {
228
                    logMetacat.debug("Using resource 'object'");
229
                    logMetacat
230
                            .debug("D1 Rest: Starting resource processing...");
231

    
232
                    // after the command
233
                    extra = parseTrailing(resource, RESOURCE_OBJECTS);
234

    
235
                    logMetacat.debug("objectId: " + extra);
236
                    logMetacat.debug("verb:" + httpVerb);
237

    
238
                    if (httpVerb == GET) {
239
                        if (extra != null) {
240
                            getObject(extra);
241
                        } else {
242
                            listObjects();
243
                        }
244
                        status = true;
245
                    } else if (httpVerb == POST) {
246
                        putObject(FUNCTION_NAME_INSERT);
247
                        status = true;
248
                    } else if (httpVerb == HEAD) {
249
                        describeObject(extra);
250
                        status = true;
251
                    }
252

    
253
                } else if (resource.startsWith(RESOURCE_FORMATS)) {
254
                    logMetacat.debug("Using resource: " + RESOURCE_FORMATS);
255

    
256
                    // after the command
257
                    extra = parseTrailing(resource, RESOURCE_FORMATS);
258

    
259
                    // handle each verb
260
                    if (httpVerb == GET) {
261
                        if (extra == null) {
262
                            // list the formats collection
263
                            listFormats();
264
                        } else {
265
                            // get the specified format
266
                            getFormat(extra);
267
                        }
268
                        status = true;
269
                    }
270

    
271
                } else if (resource.startsWith(RESOURCE_LOG)) {
272
                    logMetacat.debug("Using resource: " + RESOURCE_LOG);
273
                    // handle log events
274
                    if (httpVerb == GET) {
275
                        getLog();
276
                        status = true;
277
                    }
278

    
279
                } else if (resource.startsWith(Constants.RESOURCE_CHECKSUM)) {
280
                    logMetacat.debug("Using resource: " + Constants.RESOURCE_CHECKSUM);
281

    
282
                    // after the command
283
                    extra = parseTrailing(resource, Constants.RESOURCE_CHECKSUM);
284

    
285
                    // handle checksum requests
286
                    if (httpVerb == GET) {
287

    
288
                    	if (extra != null && extra.length() > 0) {
289
	                        checksum(extra);
290
	                        status = true;
291
                    	} else {
292
                    		listChecksumAlgorithms();
293
                    		status = true;
294
                    	}
295

    
296
                    }
297

    
298
                } else if (resource.startsWith(RESOURCE_REPLICATION_POLICY)
299
                        && httpVerb == PUT) {
300

    
301
                    logMetacat.debug("Using resource: "
302
                            + RESOURCE_REPLICATION_POLICY);
303
                    // get the trailing pid
304
                    extra = parseTrailing(resource, RESOURCE_REPLICATION_POLICY);
305
                    setReplicationPolicy(extra);
306
                    status = true;
307

    
308
                } else if (resource.startsWith(RESOURCE_REPLICATION_META)
309
                        && httpVerb == PUT) {
310

    
311
                    logMetacat.debug("Using resource: "
312
                            + RESOURCE_REPLICATION_META);
313
                    // get the trailing pid
314
                    extra = parseTrailing(resource, RESOURCE_REPLICATION_META);
315
                    updateReplicationMetadata(extra);
316
                    status = true;
317

    
318
                } else if (resource.startsWith(RESOURCE_REPLICATION_NOTIFY)
319
                        && httpVerb == PUT) {
320

    
321
                    logMetacat.debug("Using resource: "
322
                            + RESOURCE_REPLICATION_NOTIFY);
323
                    // get the trailing pid
324
                    extra = parseTrailing(resource, RESOURCE_REPLICATION_NOTIFY);
325
                    setReplicationStatus(extra);
326
                    status = true;
327

    
328
                } else if (resource.startsWith(RESOURCE_REPLICATION_AUTHORIZED)
329
                        && httpVerb == GET) {
330

    
331
                    logMetacat.debug("Using resource: "
332
                            + RESOURCE_REPLICATION_AUTHORIZED);
333
                    // get the trailing pid
334
                    extra = parseTrailing(resource,
335
                            RESOURCE_REPLICATION_AUTHORIZED);
336
                    isNodeAuthorized(extra);
337
                    status = true;
338

    
339
                } else if (resource.startsWith(Constants.RESOURCE_MONITOR_PING)) {
340
                    if (httpVerb == GET) {
341
                    	// after the command
342
                        extra = parseTrailing(resource, Constants.RESOURCE_MONITOR_PING);
343
                        
344
                        logMetacat.debug("processing ping request");
345
                        Date result = CNodeService.getInstance(request).ping();
346
                        // TODO: send to output	
347
                        status = true;
348
                    }
349
                } else if (resource.startsWith(Constants.RESOURCE_META_OBSOLETEDBY)
350
                        && httpVerb == PUT) {
351

    
352
                    logMetacat.debug("Using resource: "
353
                            + Constants.RESOURCE_META_OBSOLETEDBY);
354
                    // get the trailing pid
355
                    extra = parseTrailing(resource, Constants.RESOURCE_META_OBSOLETEDBY);
356
                    setObsoletedBy(extra);
357
                    status = true;
358
                } else if (resource.startsWith(Constants.RESOURCE_REPLICATION_DELETE_REPLICA)
359
                        && httpVerb == PUT) {
360

    
361
                    logMetacat.debug("Using resource: "
362
                            + Constants.RESOURCE_REPLICATION_DELETE_REPLICA);
363
                    // get the trailing pid
364
                    extra = parseTrailing(resource, Constants.RESOURCE_REPLICATION_DELETE_REPLICA);
365
                    deleteReplica(extra);
366
                    status = true;
367
                }
368

    
369
                if (!status) {
370
                    throw new ServiceFailure("0000", "Unknown error, status = "
371
                            + status);
372
                }
373
            } else {
374
                throw new InvalidRequest("0000", "No resource matched for "
375
                        + resource);
376
            }
377
        } catch (BaseException be) {
378
            // report Exceptions as clearly and generically as possible
379
            OutputStream out = null;
380
            try {
381
                out = response.getOutputStream();
382
            } catch (IOException ioe) {
383
                logMetacat.error("Could not get output stream from response",
384
                        ioe);
385
            }
386
            serializeException(be, out);
387
        } catch (Exception e) {
388
            // report Exceptions as clearly and generically as possible
389
            logMetacat.error(e.getClass() + ": " + e.getMessage(), e);
390
            OutputStream out = null;
391
            try {
392
                out = response.getOutputStream();
393
            } catch (IOException ioe) {
394
                logMetacat.error("Could not get output stream from response",
395
                        ioe);
396
            }
397
            ServiceFailure se = new ServiceFailure("0000", e.getMessage());
398
            serializeException(se, out);
399
        }
400
    }
401

    
402
    /**
403
     * Get the checksum for the given guid
404
     * 
405
     * @param guid
406
     * @throws NotImplemented
407
     * @throws InvalidRequest
408
     * @throws NotFound
409
     * @throws NotAuthorized
410
     * @throws ServiceFailure
411
     * @throws InvalidToken
412
     * @throws IOException
413
     * @throws JiBXException
414
     */
415
    private void checksum(String guid) throws InvalidToken, ServiceFailure,
416
            NotAuthorized, NotFound, InvalidRequest, NotImplemented,
417
            JiBXException, IOException {
418
        Identifier guidid = new Identifier();
419
        guidid.setValue(guid);
420
        logMetacat.debug("getting checksum for object " + guid);
421
        Checksum c = CNodeService.getInstance(request).getChecksum(session,
422
                guidid);
423
        logMetacat.debug("got checksum " + c.getValue());
424
        response.setStatus(200);
425
        logMetacat.debug("serializing response");
426
        TypeMarshaller.marshalTypeToOutputStream(c, response.getOutputStream());
427
        logMetacat.debug("done serializing response.");
428

    
429
    }
430

    
431
    /**
432
     * get the logs based on passed params. Available params are token,
433
     * fromDate, toDate, event. See
434
     * http://mule1.dataone.org/ArchitectureDocs/mn_api_crud
435
     * .html#MN_crud.getLogRecords for more info
436
     * 
437
     * @throws NotImplemented
438
     * @throws InvalidRequest
439
     * @throws NotAuthorized
440
     * @throws ServiceFailure
441
     * @throws InvalidToken
442
     * @throws IOException
443
     * @throws JiBXException
444
     */
445
    private void getLog() throws InvalidToken, ServiceFailure, NotAuthorized,
446
            InvalidRequest, NotImplemented, IOException, JiBXException {
447

    
448
        Date fromDate = null;
449
        Date toDate = null;
450
        Event event = null;
451
        Integer start = null;
452
        Integer count = null;
453

    
454
        try {
455
            String fromDateS = params.get("fromDate")[0];
456
            logMetacat.debug("param fromDateS: " + fromDateS);
457
            fromDate = DateTimeMarshaller.deserializeDateToUTC(fromDateS);
458
        } catch (Exception e) {
459
            logMetacat.warn("Could not parse fromDate: " + e.getMessage());
460
        }
461
        try {
462
            String toDateS = params.get("toDate")[0];
463
            logMetacat.debug("param toDateS: " + toDateS);
464
            toDate = DateTimeMarshaller.deserializeDateToUTC(toDateS);
465
        } catch (Exception e) {
466
            logMetacat.warn("Could not parse toDate: " + e.getMessage());
467
        }
468
        try {
469
            String eventS = params.get("event")[0];
470
            event = Event.convert(eventS);
471
        } catch (Exception e) {
472
            logMetacat.warn("Could not parse event: " + e.getMessage());
473
        }
474
        logMetacat.debug("fromDate: " + fromDate + " toDate: " + toDate);
475

    
476
        try {
477
            start = Integer.parseInt(params.get("start")[0]);
478
        } catch (Exception e) {
479
            logMetacat.warn("Could not parse start: " + e.getMessage());
480
        }
481
        try {
482
            count = Integer.parseInt(params.get("count")[0]);
483
        } catch (Exception e) {
484
            logMetacat.warn("Could not parse count: " + e.getMessage());
485
        }
486

    
487
        logMetacat.debug("calling getLogRecords");
488
        Log log = CNodeService.getInstance(request).getLogRecords(session,
489
                fromDate, toDate, event, start, count);
490

    
491
        OutputStream out = response.getOutputStream();
492
        response.setStatus(200);
493
        response.setContentType("text/xml");
494

    
495
        TypeMarshaller.marshalTypeToOutputStream(log, out);
496

    
497
    }
498

    
499
    /**
500
     * Implements REST version of DataONE CRUD API --> get
501
     * 
502
     * @param guid
503
     *            ID of data object to be read
504
     * @throws NotImplemented
505
     * @throws InvalidRequest
506
     * @throws NotFound
507
     * @throws NotAuthorized
508
     * @throws ServiceFailure
509
     * @throws InvalidToken
510
     * @throws IOException
511
     */
512
    protected void getObject(String guid) throws InvalidToken, ServiceFailure,
513
            NotAuthorized, NotFound, InvalidRequest, NotImplemented,
514
            IOException {
515

    
516
        Identifier id = new Identifier();
517
        id.setValue(guid);
518

    
519
        SystemMetadata sm = CNodeService.getInstance(request)
520
                .getSystemMetadata(session, id);
521

    
522
        // set the content type
523
        if (sm.getFormatId()
524
                .getValue()
525
                .trim()
526
                .equals(ObjectFormatCache.getInstance().getFormat("text/csv")
527
                        .getFormatId().getValue())) {
528
            response.setContentType("text/csv");
529
            response.setHeader("Content-Disposition",
530
                    "inline; filename=" + id.getValue() + ".csv");
531
        } else if (sm
532
                .getFormatId()
533
                .getValue()
534
                .trim()
535
                .equals(ObjectFormatCache.getInstance().getFormat("text/plain")
536
                        .getFormatId().getValue())) {
537
            response.setContentType("text/plain");
538
            response.setHeader("Content-Disposition",
539
                    "inline; filename=" + id.getValue() + ".txt");
540
        } else if (sm
541
                .getFormatId()
542
                .getValue()
543
                .trim()
544
                .equals(ObjectFormatCache.getInstance()
545
                        .getFormat("application/octet-stream").getFormatId()
546
                        .getValue())) {
547
            response.setContentType("application/octet-stream");
548
        } else {
549
            response.setContentType("text/xml");
550
            response.setHeader("Content-Disposition",
551
                    "inline; filename=" + id.getValue() + ".xml");
552
        }
553

    
554
        InputStream data = CNodeService.getInstance(request).get(session, id);
555

    
556
        OutputStream out = response.getOutputStream();
557
        response.setStatus(200);
558
        IOUtils.copyLarge(data, out);
559

    
560
    }
561

    
562
    /**
563
     * Implements REST version of DataONE CRUD API --> getSystemMetadata
564
     * 
565
     * @param guid
566
     *            ID of data object to be read
567
     * @throws NotImplemented
568
     * @throws InvalidRequest
569
     * @throws NotFound
570
     * @throws NotAuthorized
571
     * @throws ServiceFailure
572
     * @throws InvalidToken
573
     * @throws IOException
574
     * @throws JiBXException
575
     */
576
    protected void getSystemMetadataObject(String guid) throws InvalidToken,
577
            ServiceFailure, NotAuthorized, NotFound, InvalidRequest,
578
            NotImplemented, IOException, JiBXException {
579

    
580
        Identifier id = new Identifier();
581
        id.setValue(guid);
582
        SystemMetadata sysmeta = CNodeService.getInstance(request)
583
                .getSystemMetadata(session, id);
584

    
585
        response.setContentType("text/xml");
586
        response.setStatus(200);
587
        OutputStream out = response.getOutputStream();
588

    
589
        // Serialize and write it to the output stream
590
        TypeMarshaller.marshalTypeToOutputStream(sysmeta, out);
591
    }
592

    
593
    /**
594
     * Earthgrid API > Put Service >Put Function : calls MetacatHandler >
595
     * handleInsertOrUpdateAction
596
     * 
597
     * @param guid
598
     *            - ID of data object to be inserted or updated. If action is
599
     *            update, the pid is the existing pid. If insert, the pid is the
600
     *            new one
601
     * @throws InvalidRequest
602
     * @throws ServiceFailure
603
     * @throws IdentifierNotUnique
604
     * @throws JiBXException
605
     * @throws NotImplemented
606
     * @throws InvalidSystemMetadata
607
     * @throws InsufficientResources
608
     * @throws UnsupportedType
609
     * @throws NotAuthorized
610
     * @throws InvalidToken
611
     * @throws IOException
612
     * @throws IllegalAccessException
613
     * @throws InstantiationException
614
     */
615
    protected void putObject(String action) throws ServiceFailure,
616
            InvalidRequest, IdentifierNotUnique, JiBXException, InvalidToken,
617
            NotAuthorized, UnsupportedType, InsufficientResources,
618
            InvalidSystemMetadata, NotImplemented, IOException,
619
            InstantiationException, IllegalAccessException {
620
    	
621
        // Read the incoming data from its Mime Multipart encoding
622
        Map<String, File> files = collectMultipartFiles();
623
        
624
	    // get the encoded pid string from the body and make the object
625
        String pidString = multipartparams.get("pid").get(0);
626
        Identifier pid = new Identifier();
627
        pid.setValue(pidString);
628
        
629
        logMetacat.debug("putObject: " + pid.getValue() + "/" + action);
630
        
631
        InputStream object = null;
632
        InputStream sysmeta = null;
633

    
634
        File smFile = files.get("sysmeta");
635
        sysmeta = new FileInputStream(smFile);
636
        File objFile = files.get("object");
637
        object = new FileInputStream(objFile);
638

    
639
        if (action.equals(FUNCTION_NAME_INSERT)) { // handle inserts
640

    
641
            logMetacat.debug("Commence creation...");
642
            SystemMetadata smd = TypeMarshaller.unmarshalTypeFromStream(
643
                    SystemMetadata.class, sysmeta);
644

    
645
           
646
            logMetacat.debug("creating object with pid " + pid.getValue());
647
            Identifier rId = CNodeService.getInstance(request).create(session, pid, object, smd);
648

    
649
            OutputStream out = response.getOutputStream();
650
            response.setStatus(200);
651
            response.setContentType("text/xml");
652

    
653
            TypeMarshaller.marshalTypeToOutputStream(rId, out);
654

    
655
        } else {
656
            throw new InvalidRequest("1000", "Operation must be create.");
657
        }
658
    }
659

    
660
    /**
661
     * List the object formats registered with the system
662
     * 
663
     * @throws NotImplemented
664
     * @throws InsufficientResources
665
     * @throws NotFound
666
     * @throws ServiceFailure
667
     * @throws InvalidRequest
668
     * @throws IOException
669
     * @throws JiBXException
670
     */
671
    private void listFormats() throws InvalidRequest, ServiceFailure, NotFound,
672
            InsufficientResources, NotImplemented, IOException, JiBXException {
673
        logMetacat.debug("Entering listFormats()");
674

    
675
        ObjectFormatList objectFormatList = CNodeService.getInstance(request)
676
                .listFormats();
677
        // get the response output stream
678
        OutputStream out = response.getOutputStream();
679
        response.setStatus(200);
680
        response.setContentType("text/xml");
681

    
682
        // style the object with a processing directive
683
        String stylesheet = null;
684
        try {
685
            stylesheet = PropertyService.getProperty("dataone.types.xsl");
686
        } catch (PropertyNotFoundException e) {
687
            logMetacat.warn("Could not locate DataONE types XSLT: "
688
                    + e.getMessage());
689
        }
690

    
691
        TypeMarshaller.marshalTypeToOutputStream(objectFormatList, out,
692
                stylesheet);
693

    
694
    }
695
    
696
    private void listChecksumAlgorithms() throws IOException, ServiceFailure,
697
			NotImplemented, JiBXException {
698
		logMetacat.debug("Entering listFormats()");
699

    
700
		ChecksumAlgorithmList result = CNodeService.getInstance(request).listChecksumAlgorithms();
701

    
702
		// get the response output stream
703
		OutputStream out = response.getOutputStream();
704
		response.setStatus(200);
705
		response.setContentType("text/xml");
706

    
707
		TypeMarshaller.marshalTypeToOutputStream(result, out);
708

    
709
	}
710
    
711
    /**
712
     * http://mule1.dataone.org/ArchitectureDocs-current/apis/CN_APIs.html#CNRead.describe
713
     * @param pid
714
     * @throws InvalidToken
715
     * @throws ServiceFailure
716
     * @throws NotAuthorized
717
     * @throws NotFound
718
     * @throws NotImplemented
719
     * @throws InvalidRequest
720
     */
721
    private void describeObject(String pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented, InvalidRequest
722
    {
723
        response.setContentType("text/xml");
724
        
725
        Identifier id = new Identifier();
726
        id.setValue(pid);
727
        
728
        DescribeResponse dr = null;
729
        try {
730
            dr = CNodeService.getInstance(request).describe(session, id);
731
        } catch (BaseException e) {
732
        	response.setStatus(e.getCode());
733
        	response.addHeader("DataONE-Exception-Name", e.getClass().getName());
734
            response.addHeader("DataONE-Exception-DetailCode", e.getDetail_code());
735
            response.addHeader("DataONE-Exception-Description", e.getDescription());
736
            response.addHeader("DataONE-Exception-PID", id.getValue());
737
            return;
738
		}
739
        
740
        response.setStatus(200);
741
        //response.addHeader("pid", pid);
742
        response.addHeader("DataONE-Checksum", dr.getDataONE_Checksum().getAlgorithm() + "," + dr.getDataONE_Checksum().getValue());
743
        response.addHeader("Content-Length", dr.getContent_Length() + "");
744
        response.addHeader("Last-Modified", DateTimeMarshaller.serializeDateToUTC(dr.getLast_Modified()));
745
        response.addHeader("DataONE-ObjectFormat", dr.getDataONE_ObjectFormatIdentifier().getValue());
746
        response.addHeader("DataONE-SerialVersion", dr.getSerialVersion().toString());
747

    
748
    }
749

    
750
    /**
751
     * Return the requested object format
752
     * 
753
     * @param fmtidStr
754
     *            the requested format identifier as a string
755
     * @throws NotImplemented
756
     * @throws InsufficientResources
757
     * @throws NotFound
758
     * @throws ServiceFailure
759
     * @throws InvalidRequest
760
     * @throws IOException
761
     * @throws JiBXException
762
     */
763
    private void getFormat(String fmtidStr) throws InvalidRequest,
764
            ServiceFailure, NotFound, InsufficientResources, NotImplemented,
765
            IOException, JiBXException {
766
        logMetacat.debug("Entering listFormats()");
767

    
768
        ObjectFormatIdentifier fmtid = new ObjectFormatIdentifier();
769
        fmtid.setValue(fmtidStr);
770

    
771
        // get the specified object format
772
        ObjectFormat objectFormat = CNodeService.getInstance(request)
773
                .getFormat(fmtid);
774

    
775
        OutputStream out = response.getOutputStream();
776
        response.setStatus(200);
777
        response.setContentType("text/xml");
778

    
779
        TypeMarshaller.marshalTypeToOutputStream(objectFormat, out);
780

    
781
    }
782

    
783
    /**
784
     * Reserve the given Identifier
785
     * 
786
     * @throws InvalidToken
787
     * @throws ServiceFailure
788
     * @throws NotAuthorized
789
     * @throws IdentifierNotUnique
790
     * @throws NotImplemented
791
     * @throws InvalidRequest
792
     * @throws IOException
793
     * @throws JiBXException
794
     */
795
    private void reserve() throws InvalidToken, ServiceFailure, NotAuthorized,
796
            IdentifierNotUnique, NotImplemented, InvalidRequest, IOException,
797
            JiBXException {
798
        Identifier pid = null;
799
        String scope = null;
800
        String format = null;
801
        // gather the params
802
        try {
803
            String id = params.get("pid")[0];
804
            pid = new Identifier();
805
            pid.setValue(id);
806
        } catch (Exception e) {
807
            logMetacat.warn("pid not specified");
808
        }
809
        try {
810
            scope = params.get("scope")[0];
811
        } catch (Exception e) {
812
            logMetacat.warn("pid not specified");
813
        }
814
        try {
815
            format = params.get("format")[0];
816
        } catch (Exception e) {
817
            logMetacat.warn("pid not specified");
818
        }
819
        // call the implementation
820
        Identifier resultPid = CNodeService.getInstance(request)
821
                .reserveIdentifier(session, pid);
822
        OutputStream out = response.getOutputStream();
823
        response.setStatus(200);
824
        response.setContentType("text/xml");
825
        // send back the reserved pid
826
        TypeMarshaller.marshalTypeToOutputStream(resultPid, out);
827
    }
828

    
829
    /**
830
     * 
831
     * @param id
832
     * @throws InvalidRequest
833
     * @throws InvalidToken
834
     * @throws ServiceFailure
835
     * @throws NotAuthorized
836
     * @throws NotFound
837
     * @throws NotImplemented
838
     * @throws IOException
839
     * @throws JiBXException
840
     */
841
    private void resolve(String id) throws InvalidRequest, InvalidToken,
842
            ServiceFailure, NotAuthorized, NotFound, NotImplemented,
843
            IOException, JiBXException {
844
        Identifier pid = new Identifier();
845
        pid.setValue(id);
846
        ObjectLocationList locationList = CNodeService.getInstance(request)
847
                .resolve(session, pid);
848
        OutputStream out = response.getOutputStream();
849
        response.setStatus(200);
850
        response.setContentType("text/xml");
851
        TypeMarshaller.marshalTypeToOutputStream(locationList, out);
852

    
853
    }
854

    
855
    /**
856
     * Set the owner of a resource
857
     * 
858
     * @param id
859
     * @throws JiBXException
860
     * @throws InvalidToken
861
     * @throws ServiceFailure
862
     * @throws NotFound
863
     * @throws NotAuthorized
864
     * @throws NotImplemented
865
     * @throws InvalidRequest
866
     * @throws IOException
867
     * @throws IllegalAccessException
868
     * @throws InstantiationException
869
     * @throws VersionMismatch 
870
     */
871
    private void owner(String id) throws JiBXException, InvalidToken,
872
            ServiceFailure, NotFound, NotAuthorized, NotImplemented,
873
            InvalidRequest, IOException, InstantiationException,
874
            IllegalAccessException, VersionMismatch {
875

    
876
        Identifier pid = new Identifier();
877
        pid.setValue(id);
878

    
879
        long serialVersion = 0L;
880
        String serialVersionStr = null;
881

    
882
        // get the serialVersion
883
        try {
884
            serialVersionStr = params.get("serialVersion")[0];
885
            serialVersion = new Long(serialVersionStr).longValue();
886

    
887
        } catch (NullPointerException e) {
888
            String msg = "The 'serialVersion' must be provided as a parameter and was not.";
889
            logMetacat.error(msg);
890
            throw new InvalidRequest("4442", msg);
891

    
892
        }
893

    
894
        // get the subject
895
        String subjectStr = params.get("subject")[0];
896
        Subject subject = TypeMarshaller.unmarshalTypeFromStream(Subject.class,
897
                new ByteArrayInputStream(subjectStr.getBytes("UTF-8")));
898

    
899
        Identifier retPid = CNodeService.getInstance(request).setRightsHolder(session, pid, subject, serialVersion);
900
        OutputStream out = response.getOutputStream();
901
        response.setStatus(200);
902
        response.setContentType("text/xml");
903
        TypeMarshaller.marshalTypeToOutputStream(retPid, out);
904
    }
905

    
906
    /**
907
     * Processes the authorization check for given id
908
     * 
909
     * @param id
910
     * @return
911
     * @throws ServiceFailure
912
     * @throws InvalidToken
913
     * @throws NotFound
914
     * @throws NotAuthorized
915
     * @throws NotImplemented
916
     * @throws InvalidRequest
917
     */
918
    private boolean isAuthorized(String id) throws ServiceFailure,
919
            InvalidToken, NotFound, NotAuthorized, NotImplemented,
920
            InvalidRequest {
921
        Identifier pid = new Identifier();
922
        pid.setValue(id);
923
        String permission = params.get("action")[0];
924
        boolean result = CNodeService.getInstance(request).isAuthorized(
925
                session, pid, Permission.convert(permission));
926
        response.setStatus(200);
927
        response.setContentType("text/xml");
928
        return result;
929
    }
930

    
931
    /**
932
     * Register System Metadata without data or metadata object
933
     * 
934
     * @param pid
935
     *            identifier for System Metadata entry
936
     * @throws JiBXException
937
     * @throws FileUploadException
938
     * @throws IOException
939
     * @throws InvalidRequest
940
     * @throws ServiceFailure
941
     * @throws InvalidSystemMetadata
942
     * @throws NotAuthorized
943
     * @throws NotImplemented
944
     * @throws IllegalAccessException
945
     * @throws InstantiationException
946
     */
947
    protected void registerSystemMetadata()
948
            throws ServiceFailure, InvalidRequest, IOException,
949
            FileUploadException, JiBXException, NotImplemented, NotAuthorized,
950
            InvalidSystemMetadata, InstantiationException,
951
            IllegalAccessException {
952
    	
953
    	// Read the incoming data from its Mime Multipart encoding
954
        Map<String, File> files = collectMultipartFiles();
955
        
956
    	// get the encoded pid string from the body and make the object
957
        String pidString = multipartparams.get("pid").get(0);
958
        Identifier pid = new Identifier();
959
        pid.setValue(pidString);
960
        
961
        logMetacat.debug("registerSystemMetadata: " + pid);
962

    
963
        // get the system metadata from the request
964
        File smFile = files.get("sysmeta");
965
        FileInputStream sysmeta = new FileInputStream(smFile);
966
        SystemMetadata systemMetadata = TypeMarshaller.unmarshalTypeFromStream(SystemMetadata.class, sysmeta);
967

    
968
        logMetacat.debug("registering system metadata with pid " + pid.getValue());
969
        Identifier retGuid = CNodeService.getInstance(request).registerSystemMetadata(session, pid, systemMetadata);
970

    
971
        OutputStream out = response.getOutputStream();
972
        response.setStatus(200);
973
        response.setContentType("text/xml");
974
        
975
        TypeMarshaller.marshalTypeToOutputStream(retGuid, out);
976

    
977
    }
978

    
979
    /**
980
     * set the access perms on a document
981
     * 
982
     * @throws JiBXException
983
     * @throws InvalidRequest
984
     * @throws NotImplemented
985
     * @throws NotAuthorized
986
     * @throws NotFound
987
     * @throws ServiceFailure
988
     * @throws InvalidToken
989
     * @throws IllegalAccessException
990
     * @throws InstantiationException
991
     * @throws IOException
992
     * @throws SAXException
993
     * @throws ParserConfigurationException
994
     * @throws VersionMismatch 
995
     */
996
    protected void setAccess(String pid) throws JiBXException, InvalidToken,
997
            ServiceFailure, NotFound, NotAuthorized, NotImplemented,
998
            InvalidRequest, IOException, InstantiationException,
999
            IllegalAccessException, ParserConfigurationException, SAXException, VersionMismatch {
1000

    
1001
        long serialVersion = 0L;
1002
        String serialVersionStr = null;
1003

    
1004
        // get the serialVersion
1005
        try {
1006
            serialVersionStr = params.get("serialVersion")[0];
1007
            serialVersion = new Long(serialVersionStr).longValue();
1008

    
1009
        } catch (NullPointerException e) {
1010
            String msg = "The 'serialVersion' must be provided as a parameter and was not.";
1011
            logMetacat.error(msg);
1012
            throw new InvalidRequest("4402", msg);
1013

    
1014
        }
1015

    
1016
        Identifier id = new Identifier();
1017
        id.setValue(pid);
1018

    
1019
        AccessPolicy accessPolicy = collectAccessPolicy();
1020
        CNodeService.getInstance(request).setAccessPolicy(session, id,
1021
                accessPolicy, serialVersion);
1022

    
1023
    }
1024

    
1025
    /**
1026
     * List the objects
1027
     * 
1028
     * @throws NotImplemented
1029
     * @throws InvalidRequest
1030
     * @throws NotAuthorized
1031
     * @throws ServiceFailure
1032
     * @throws InvalidToken
1033
     * @throws NotFound
1034
     * @throws IOException
1035
     * @throws JiBXException
1036
     * @throws Exception
1037
     */
1038
    private void listObjects() throws InvalidToken, ServiceFailure,
1039
            NotAuthorized, InvalidRequest, NotImplemented, NotFound,
1040
            IOException, JiBXException {
1041

    
1042
        Date startTime = null;
1043
        Date endTime = null;
1044
        ObjectFormat objectFormat = null;
1045
        boolean replicaStatus = false;
1046
        int start = 0;
1047
        int count = -1;
1048
        Enumeration<String> paramlist = request.getParameterNames();
1049
        while (paramlist.hasMoreElements()) {
1050
            // parse the params and make the call
1051
            String name = paramlist.nextElement();
1052
            String[] value = request.getParameterValues(name);
1053

    
1054
            if (name.equals("startTime") && value != null) {
1055
                try {
1056
                    startTime = DateTimeMarshaller
1057
                            .deserializeDateToUTC(value[0]);
1058
                } catch (Exception e) {
1059
                    // if we can't parse it, just don't use the startTime param
1060
                    logMetacat.warn("Could not parse startTime: " + value[0]);
1061
                    startTime = null;
1062
                }
1063
            } else if (name.equals("endTime") && value != null) {
1064
                try {
1065
                    endTime = DateTimeMarshaller.deserializeDateToUTC(value[0]);
1066
                } catch (Exception e) {
1067
                    // if we can't parse it, just don't use the endTime param
1068
                    logMetacat.warn("Could not parse endTime: " + value[0]);
1069
                    endTime = null;
1070
                }
1071
            } else if (name.equals("objectFormat") && value != null) {
1072
                objectFormat = ObjectFormatCache.getInstance().getFormat(
1073
                        value[0]);
1074
            } else if (name.equals("replicaStatus") && value != null) {
1075
                replicaStatus = Boolean.parseBoolean(value[0]);
1076
            } else if (name.equals("start") && value != null) {
1077
                start = Integer.valueOf(value[0]);
1078
            } else if (name.equals("count") && value != null) {
1079
                count = Integer.valueOf(value[0]);
1080
            }
1081
        }
1082
        // make the call
1083
        logMetacat.debug("session: " + session + " startTime: " + startTime
1084
                + " endtime: " + endTime + " objectFormat: " + objectFormat
1085
                + " replicaStatus: " + replicaStatus + " start: " + start
1086
                + " count: " + count);
1087

    
1088
        ObjectFormatIdentifier fmtid = null;
1089
        if (objectFormat != null) {
1090
            fmtid = objectFormat.getFormatId();
1091
        }
1092

    
1093
        // get the list
1094
        ObjectList ol = CNodeService.getInstance(request).listObjects(session,
1095
                startTime, endTime, fmtid, replicaStatus, start, count);
1096

    
1097
        // send it
1098
        OutputStream out = response.getOutputStream();
1099
        response.setStatus(200);
1100
        response.setContentType("text/xml");
1101

    
1102
        // style the object with a processing directive
1103
        String stylesheet = null;
1104
        try {
1105
            stylesheet = PropertyService.getProperty("dataone.types.xsl");
1106
        } catch (PropertyNotFoundException e) {
1107
            logMetacat.warn("Could not locate DataONE types XSLT: "
1108
                    + e.getMessage());
1109
        }
1110

    
1111
        // Serialize and write it to the output stream
1112
        TypeMarshaller.marshalTypeToOutputStream(ol, out, stylesheet);
1113
    }
1114

    
1115
    /**
1116
     * Pass the request to get node replication authorization to CNodeService
1117
     * 
1118
     * @param pid
1119
     *            the identifier of the object to get authorization to replicate
1120
     * 
1121
     * @throws NotImplemented
1122
     * @throws NotAuthorized
1123
     * @throws InvalidToken
1124
     * @throws ServiceFailure
1125
     * @throws NotFound
1126
     * @throws InvalidRequest
1127
     */
1128
    public boolean isNodeAuthorized(String pid) throws NotImplemented,
1129
            NotAuthorized, InvalidToken, ServiceFailure, NotFound,
1130
            InvalidRequest {
1131

    
1132
        boolean result = false;
1133
        Subject targetNodeSubject = new Subject();
1134
        String nodeSubject = null;
1135
        String replPermission = null;
1136

    
1137
        // get the pid
1138
        Identifier identifier = new Identifier();
1139
        identifier.setValue(pid);
1140

    
1141
        // get the target node subject
1142
        try {
1143
            nodeSubject = params.get("targetNodeSubject")[0];
1144
            targetNodeSubject.setValue(nodeSubject);
1145

    
1146
        } catch (NullPointerException e) {
1147
            String msg = "The 'targetNodeSubject' must be provided as a parameter and was not.";
1148
            logMetacat.error(msg);
1149
            throw new InvalidRequest("4873", msg);
1150

    
1151
        }
1152

    
1153
        result = CNodeService.getInstance(request).isNodeAuthorized(session, targetNodeSubject, identifier);
1154

    
1155
        response.setStatus(200);
1156
        response.setContentType("text/xml");
1157
        return result;
1158

    
1159
    }
1160

    
1161
    /**
1162
     * Pass the request to set the replication policy to CNodeService
1163
     * 
1164
     * @param pid
1165
     *            the identifier of the object to set the replication policy on
1166
     * 
1167
     * @throws NotImplemented
1168
     * @throws NotFound
1169
     * @throws NotAuthorized
1170
     * @throws ServiceFailure
1171
     * @throws InvalidRequest
1172
     * @throws InvalidToken
1173
     * @throws IOException
1174
     * @throws InstantiationException
1175
     * @throws IllegalAccessException
1176
     * @throws JiBXException
1177
     * @throws VersionMismatch 
1178
     */
1179
    public boolean setReplicationPolicy(String pid) throws NotImplemented,
1180
            NotFound, NotAuthorized, ServiceFailure, InvalidRequest,
1181
            InvalidToken, IOException, InstantiationException,
1182
            IllegalAccessException, JiBXException, VersionMismatch {
1183

    
1184
        boolean result = false;
1185
        ReplicationPolicy policy = null;
1186
        long serialVersion = 0L;
1187
        String serialVersionStr = null;
1188

    
1189
        Identifier identifier = new Identifier();
1190
        identifier.setValue(pid);
1191

    
1192
        policy = collectReplicationPolicy();
1193

    
1194
        // get the serialVersion
1195
        try {
1196
            serialVersionStr = multipartparams.get("serialVersion").get(0);
1197
            serialVersion = new Long(serialVersionStr).longValue();
1198

    
1199
        } catch (NullPointerException e) {
1200
            String msg = "The 'serialVersion' must be provided as a parameter and was not.";
1201
            logMetacat.error(msg);
1202
            throw new InvalidRequest("4883", msg);
1203

    
1204
        }
1205
        result = CNodeService.getInstance(request).setReplicationPolicy(
1206
                session, identifier, policy, serialVersion);
1207
        response.setStatus(200);
1208
        response.setContentType("text/xml");
1209
        return result;
1210

    
1211
    }
1212
    
1213
    public boolean setObsoletedBy(String pid) throws NotImplemented,
1214
	    NotFound, NotAuthorized, ServiceFailure, InvalidRequest,
1215
	    InvalidToken, IOException, InstantiationException,
1216
	    IllegalAccessException, JiBXException, VersionMismatch {
1217
	
1218
		boolean result = false;
1219
		long serialVersion = 0L;
1220
		String serialVersionStr = null;
1221
		
1222
		Identifier identifier = new Identifier();
1223
		identifier.setValue(pid);
1224
		
1225
		Identifier obsoletedByPid = null;
1226
		try {
1227
			String obsoletedByPidString = params.get("obsoletedByPid")[0];
1228
			obsoletedByPid = new Identifier();
1229
			obsoletedByPid.setValue(obsoletedByPidString);
1230
		} catch (NullPointerException e) {
1231
		    String msg = "The 'obsoletedByPid' must be provided as a parameter and was not.";
1232
		    logMetacat.error(msg);
1233
		    throw new InvalidRequest("4883", msg);
1234
		}
1235
		
1236
		// get the serialVersion
1237
		try {
1238
		    serialVersionStr = params.get("serialVersion")[0];
1239
		    serialVersion = new Long(serialVersionStr).longValue();
1240
		
1241
		} catch (NullPointerException e) {
1242
		    String msg = "The 'serialVersion' must be provided as a parameter and was not.";
1243
		    logMetacat.error(msg);
1244
		    throw new InvalidRequest("4883", msg);
1245
		
1246
		}
1247
		result = CNodeService.getInstance(request).setObsoletedBy(
1248
		        session, identifier, obsoletedByPid, serialVersion);
1249
		response.setStatus(200);
1250
		response.setContentType("text/xml");
1251
		return result;
1252
	
1253
	}
1254
    
1255
    public boolean deleteReplica(String pid) throws NotImplemented, NotFound,
1256
			NotAuthorized, ServiceFailure, InvalidRequest, InvalidToken,
1257
			IOException, InstantiationException, IllegalAccessException,
1258
			JiBXException, VersionMismatch {
1259

    
1260
		boolean result = false;
1261
		long serialVersion = 0L;
1262
		String serialVersionStr = null;
1263

    
1264
		Identifier identifier = new Identifier();
1265
		identifier.setValue(pid);
1266

    
1267
		NodeReference nodeId = null;
1268
		try {
1269
			String nodeIdString = params.get("nodeId")[0];
1270
			nodeId = new NodeReference();
1271
			nodeId.setValue(nodeIdString);
1272
		} catch (NullPointerException e) {
1273
			String msg = "The 'nodeId' must be provided as a parameter and was not.";
1274
			logMetacat.error(msg);
1275
			throw new InvalidRequest("4883", msg);
1276
		}
1277

    
1278
		// get the serialVersion
1279
		try {
1280
			serialVersionStr = params.get("serialVersion")[0];
1281
			serialVersion = new Long(serialVersionStr).longValue();
1282

    
1283
		} catch (NullPointerException e) {
1284
			String msg = "The 'serialVersion' must be provided as a parameter and was not.";
1285
			logMetacat.error(msg);
1286
			throw new InvalidRequest("4883", msg);
1287

    
1288
		}
1289
		result = CNodeService.getInstance(request).deleteReplicationMetadata(session, identifier, nodeId, serialVersion);
1290
		response.setStatus(200);
1291
		response.setContentType("text/xml");
1292
		return result;
1293

    
1294
	}
1295

    
1296
    /**
1297
     * Pass the request to set the replication status to CNodeService
1298
     * 
1299
     * @param pid
1300
     *            the identifier of the object to set the replication status on
1301
     * 
1302
     * @throws ServiceFailure
1303
     * @throws NotImplemented
1304
     * @throws InvalidToken
1305
     * @throws NotAuthorized
1306
     * @throws InvalidRequest
1307
     * @throws NotFound
1308
     * @throws JiBXException 
1309
     * @throws IllegalAccessException 
1310
     * @throws InstantiationException 
1311
     * @throws IOException 
1312
     */
1313
    public boolean setReplicationStatus(String pid) throws ServiceFailure,
1314
            NotImplemented, InvalidToken, NotAuthorized, InvalidRequest,
1315
            NotFound {
1316
        
1317
        boolean result = false;
1318
        Identifier identifier = new Identifier();
1319
        identifier.setValue(pid);
1320
        BaseException failure = null;
1321
        ReplicationStatus status = null;
1322
        String replicationStatus = null;
1323
        NodeReference targetNodeRef = null;
1324
        String targetNode = null;
1325

    
1326
        // Parse the params out of the multipart form data
1327
        // Read the incoming data from its Mime Multipart encoding
1328
        logMetacat.debug("Parsing ReplicaStatus from the mime multipart entity");
1329

    
1330
        try {
1331
            failure = collectReplicationStatus();
1332
            
1333
        } catch (IOException e2) {
1334
            throw new ServiceFailure("4700", "Couldn't resolve the multipart request: " +
1335
                e2.getMessage());
1336
            
1337
        } catch (InstantiationException e2) {
1338
            throw new ServiceFailure("4700", "Couldn't resolve the multipart request: " +
1339
                e2.getMessage());
1340
            
1341
        } catch (IllegalAccessException e2) {
1342
            throw new ServiceFailure("4700", "Couldn't resolve the multipart request: " +
1343
                    e2.getMessage());
1344
            
1345
        } catch (JiBXException e2) {
1346
            throw new ServiceFailure("4700", "Couldn't resolve the multipart request: " +
1347
                    e2.getMessage());
1348
            
1349
        }
1350
        
1351
        // get the replication status param
1352
        try {
1353
            replicationStatus = multipartparams.get("status").get(0);
1354
            status = ReplicationStatus.convert(replicationStatus);
1355

    
1356
        } catch (NullPointerException npe) {
1357

    
1358
            logMetacat.debug("The 'status' parameter was not found in the "
1359
                    + "multipartparams map.  Trying the params map.");
1360

    
1361
            try {
1362
                replicationStatus = params.get("status")[0];
1363
                status = ReplicationStatus.convert(replicationStatus
1364
                        .toLowerCase());
1365

    
1366
            } catch (Exception e) {
1367
                String msg = "The 'status' must be provided as a parameter and was not.";
1368
                logMetacat.error(msg);
1369
                throw new InvalidRequest("4730", msg);
1370

    
1371
            }
1372

    
1373
        }
1374

    
1375
        // get the target node reference param
1376
        try {
1377
            targetNode = multipartparams.get("nodeRef").get(0);
1378
            targetNodeRef = new NodeReference();
1379
            targetNodeRef.setValue(targetNode);
1380

    
1381
        } catch (NullPointerException e) {
1382
            logMetacat.debug("The 'nodeRef' parameter was not found in the "
1383
                    + "multipartparams map.  Trying the params map.");
1384

    
1385
            try {
1386
                targetNode = params.get("nodeRef")[0];
1387
                targetNodeRef = new NodeReference();
1388
                targetNodeRef.setValue(targetNode);
1389

    
1390
            } catch (Exception e1) {
1391
                String msg = "The 'nodeRef' must be provided as a parameter and was not.";
1392
                logMetacat.error(msg);
1393
                throw new InvalidRequest("4730", msg);
1394

    
1395
            }
1396

    
1397
        }
1398

    
1399
        result = CNodeService.getInstance(request).setReplicationStatus(
1400
                session, identifier, targetNodeRef, status, failure);
1401
        response.setStatus(200);
1402
        response.setContentType("text/xml");
1403
        return result;
1404

    
1405
    }
1406

    
1407
    /**
1408
     * Pass the request to update the replication metadata to CNodeService
1409
     * 
1410
     * @param pid
1411
     *            the identifier of the object to update the replication
1412
     *            metadata on
1413
     * 
1414
     * @throws ServiceFailure
1415
     * @throws NotImplemented
1416
     * @throws InvalidToken
1417
     * @throws NotAuthorized
1418
     * @throws InvalidRequest
1419
     * @throws NotFound
1420
     * @throws VersionMismatch 
1421
     */
1422
    public boolean updateReplicationMetadata(String pid) throws ServiceFailure,
1423
            NotImplemented, InvalidToken, NotAuthorized, InvalidRequest,
1424
            NotFound, VersionMismatch {
1425

    
1426
        boolean result = false;
1427
        long serialVersion = 0L;
1428
        String serialVersionStr = null;
1429
        Replica replica = null;
1430
        Identifier identifier = new Identifier();
1431
        identifier.setValue(pid);
1432

    
1433
        replica = collectReplicaMetadata();
1434

    
1435
        // get the serialVersion
1436
        try {
1437
            serialVersionStr = multipartparams.get("serialVersion").get(0);
1438
            serialVersion = new Long(serialVersionStr).longValue();
1439

    
1440
        } catch (NullPointerException e) {
1441
            String msg = "The 'serialVersion' must be provided as a parameter and was not.";
1442
            logMetacat.error(msg);
1443
            throw new InvalidRequest("4853", msg);
1444

    
1445
        }
1446

    
1447
        result = CNodeService.getInstance(request).updateReplicationMetadata(
1448
                session, identifier, replica, serialVersion);
1449
        response.setStatus(200);
1450
        response.setContentType("text/xml");
1451
        return result;
1452

    
1453
    }
1454

    
1455
}
(1-1/9)