Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *  Copyright: 2011 Regents of the University of California and the
4
 *              National Center for Ecological Analysis and Synthesis
5
 *
6
 *   '$Author: cjones $'
7
 *     '$Date: 2012-01-09 17:08:10 -0800 (Mon, 09 Jan 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.mimemultipart.MultipartRequest;
45
import org.dataone.mimemultipart.MultipartRequestResolver;
46
import org.dataone.service.exceptions.BaseException;
47
import org.dataone.service.exceptions.IdentifierNotUnique;
48
import org.dataone.service.exceptions.InsufficientResources;
49
import org.dataone.service.exceptions.InvalidRequest;
50
import org.dataone.service.exceptions.InvalidSystemMetadata;
51
import org.dataone.service.exceptions.InvalidToken;
52
import org.dataone.service.exceptions.NotAuthorized;
53
import org.dataone.service.exceptions.NotFound;
54
import org.dataone.service.exceptions.NotImplemented;
55
import org.dataone.service.exceptions.ServiceFailure;
56
import org.dataone.service.exceptions.UnsupportedType;
57
import org.dataone.service.exceptions.VersionMismatch;
58
import org.dataone.service.types.v1.AccessPolicy;
59
import org.dataone.service.types.v1.Checksum;
60
import org.dataone.service.types.v1.ChecksumAlgorithmList;
61
import org.dataone.service.types.v1.DescribeResponse;
62
import org.dataone.service.types.v1.Event;
63
import org.dataone.service.types.v1.Identifier;
64
import org.dataone.service.types.v1.Log;
65
import org.dataone.service.types.v1.NodeReference;
66
import org.dataone.service.types.v1.ObjectFormat;
67
import org.dataone.service.types.v1.ObjectFormatIdentifier;
68
import org.dataone.service.types.v1.ObjectFormatList;
69
import org.dataone.service.types.v1.ObjectList;
70
import org.dataone.service.types.v1.ObjectLocationList;
71
import org.dataone.service.types.v1.Permission;
72
import org.dataone.service.types.v1.Replica;
73
import org.dataone.service.types.v1.ReplicationPolicy;
74
import org.dataone.service.types.v1.ReplicationStatus;
75
import org.dataone.service.types.v1.Subject;
76
import org.dataone.service.types.v1.SystemMetadata;
77
import org.dataone.service.util.Constants;
78
import org.dataone.service.util.DateTimeMarshaller;
79
import org.dataone.service.util.TypeMarshaller;
80
import org.jibx.runtime.JiBXException;
81
import org.xml.sax.SAXException;
82

    
83
import edu.ucsb.nceas.metacat.dataone.CNodeService;
84
import edu.ucsb.nceas.metacat.dataone.MNodeService;
85
import edu.ucsb.nceas.metacat.properties.PropertyService;
86
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
87

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

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

    
129
    public CNResourceHandler(ServletContext servletContext,
130
            HttpServletRequest request, HttpServletResponse response) {
131
        super(servletContext, request, response);
132
        logMetacat = Logger.getLogger(CNResourceHandler.class);
133
    }
134

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

    
147
        try {
148

    
149
            // get the resource
150
            String resource = request.getPathInfo();
151
            resource = resource.substring(resource.indexOf("/") + 1);
152

    
153
            // for the rest of the resouce
154
            String extra = null;
155

    
156
            logMetacat.debug("handling verb " + httpVerb
157
                    + " request with resource '" + resource + "'");
158
            boolean status = false;
159

    
160
            if (resource != null) {
161

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

    
171
                } else if (resource.startsWith(RESOURCE_META)) {
172
                    logMetacat.debug("Using resource: " + RESOURCE_META);
173

    
174
                    // after the command
175
                    extra = parseTrailing(resource, RESOURCE_META);
176

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

    
188
                } else if (resource.startsWith(RESOURCE_RESERVE)) {
189
                    // reserve the ID (in params)
190
                    if (httpVerb == POST) {
191
                        reserve();
192
                        status = true;
193
                    }
194
                } else if (resource.startsWith(RESOURCE_ASSERT_RELATION)) {
195

    
196
                    // after the command
197
                    extra = parseTrailing(resource, RESOURCE_ASSERT_RELATION);
198

    
199
                    // reserve the ID (in params)
200
                    if (httpVerb == GET) {
201
                        assertRelation(extra);
202
                        status = true;
203
                    }
204
                } else if (resource.startsWith(RESOURCE_RESOLVE)) {
205

    
206
                    // after the command
207
                    extra = parseTrailing(resource, RESOURCE_RESOLVE);
208

    
209
                    // resolve the object location
210
                    if (httpVerb == GET) {
211
                        resolve(extra);
212
                        status = true;
213
                    }
214
                } else if (resource.startsWith(RESOURCE_OWNER)) {
215

    
216
                    // after the command
217
                    extra = parseTrailing(resource, RESOURCE_OWNER);
218

    
219
                    // set the owner
220
                    if (httpVerb == PUT) {
221
                        owner(extra);
222
                        status = true;
223
                    }
224
                } else if (resource.startsWith(RESOURCE_IS_AUTHORIZED)) {
225

    
226
                    // after the command
227
                    extra = parseTrailing(resource, RESOURCE_IS_AUTHORIZED);
228

    
229
                    // authorized?
230
                    if (httpVerb == GET) {
231
                        isAuthorized(extra);
232
                        status = true;
233
                    }
234
                } else if (resource.startsWith(RESOURCE_OBJECTS)) {
235
                    logMetacat.debug("Using resource 'object'");
236
                    logMetacat
237
                            .debug("D1 Rest: Starting resource processing...");
238

    
239
                    // after the command
240
                    extra = parseTrailing(resource, RESOURCE_OBJECTS);
241

    
242
                    logMetacat.debug("objectId: " + extra);
243
                    logMetacat.debug("verb:" + httpVerb);
244

    
245
                    if (httpVerb == GET) {
246
                        if (extra != null) {
247
                            getObject(extra);
248
                        } else {
249
                            listObjects();
250
                        }
251
                        status = true;
252
                    } else if (httpVerb == POST) {
253
                        putObject(extra, FUNCTION_NAME_INSERT);
254
                        status = true;
255
                    } else if (httpVerb == HEAD) {
256
                        describeObject(extra);
257
                        status = true;
258
                    }
259

    
260
                } else if (resource.startsWith(RESOURCE_FORMATS)) {
261
                    logMetacat.debug("Using resource: " + RESOURCE_FORMATS);
262

    
263
                    // after the command
264
                    extra = parseTrailing(resource, RESOURCE_FORMATS);
265

    
266
                    // handle each verb
267
                    if (httpVerb == GET) {
268
                        if (extra == null) {
269
                            // list the formats collection
270
                            listFormats();
271
                        } else {
272
                            // get the specified format
273
                            getFormat(extra);
274
                        }
275
                        status = true;
276
                    }
277

    
278
                } else if (resource.startsWith(RESOURCE_LOG)) {
279
                    logMetacat.debug("Using resource: " + RESOURCE_LOG);
280
                    // handle log events
281
                    if (httpVerb == GET) {
282
                        getLog();
283
                        status = true;
284
                    }
285

    
286
                } else if (resource.startsWith(RESOURCE_CHECKSUM)) {
287
                    logMetacat.debug("Using resource: " + RESOURCE_CHECKSUM);
288

    
289
                    // after the command
290
                    extra = parseTrailing(resource, RESOURCE_CHECKSUM);
291

    
292
                    // handle checksum requests
293
                    if (httpVerb == GET) {
294

    
295
                        checksum(extra);
296
                        status = true;
297

    
298
                    }
299

    
300
                } else if (resource.startsWith(RESOURCE_REPLICATION_POLICY)
301
                        && httpVerb == PUT) {
302

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

    
310
                } else if (resource.startsWith(RESOURCE_REPLICATION_META)
311
                        && httpVerb == PUT) {
312

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

    
320
                } else if (resource.startsWith(RESOURCE_REPLICATION_NOTIFY)
321
                        && httpVerb == PUT) {
322

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

    
330
                } else if (resource.startsWith(RESOURCE_REPLICATION_AUTHORIZED)
331
                        && httpVerb == GET) {
332

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

    
341
                } else if (resource.startsWith(Constants.RESOURCE_MONITOR_PING)) {
342
                    if (httpVerb == GET) {
343
                    	// after the command
344
                        extra = parseTrailing(resource, Constants.RESOURCE_MONITOR_PING);
345
                        
346
                        logMetacat.debug("processing ping request");
347
                        Date result = CNodeService.getInstance(request).ping();
348
                        // TODO: send to output	
349
                        status = true;
350
                    }
351
                } else if (resource.startsWith(Constants.RESOURCE_CHECKSUM)) {
352
                    if (httpVerb == GET) {
353
                        listChecksumAlgorithms();
354
                        status = true;
355
                    }
356
                }
357

    
358
                if (!status) {
359
                    throw new ServiceFailure("0000", "Unknown error, status = "
360
                            + status);
361
                }
362
            } else {
363
                throw new InvalidRequest("0000", "No resource matched for "
364
                        + resource);
365
            }
366
        } catch (BaseException be) {
367
            // report Exceptions as clearly and generically as possible
368
            OutputStream out = null;
369
            try {
370
                out = response.getOutputStream();
371
            } catch (IOException ioe) {
372
                logMetacat.error("Could not get output stream from response",
373
                        ioe);
374
            }
375
            serializeException(be, out);
376
        } catch (Exception e) {
377
            // report Exceptions as clearly and generically as possible
378
            logMetacat.error(e.getClass() + ": " + e.getMessage(), e);
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
            ServiceFailure se = new ServiceFailure("0000", e.getMessage());
387
            serializeException(se, out);
388
        }
389
    }
390

    
391
    /**
392
     * Get the checksum for the given guid
393
     * 
394
     * @param guid
395
     * @throws NotImplemented
396
     * @throws InvalidRequest
397
     * @throws NotFound
398
     * @throws NotAuthorized
399
     * @throws ServiceFailure
400
     * @throws InvalidToken
401
     * @throws IOException
402
     * @throws JiBXException
403
     */
404
    private void checksum(String guid) throws InvalidToken, ServiceFailure,
405
            NotAuthorized, NotFound, InvalidRequest, NotImplemented,
406
            JiBXException, IOException {
407
        Identifier guidid = new Identifier();
408
        guidid.setValue(guid);
409
        logMetacat.debug("getting checksum for object " + guid);
410
        Checksum c = CNodeService.getInstance(request).getChecksum(session,
411
                guidid);
412
        logMetacat.debug("got checksum " + c.getValue());
413
        response.setStatus(200);
414
        logMetacat.debug("serializing response");
415
        TypeMarshaller.marshalTypeToOutputStream(c, response.getOutputStream());
416
        logMetacat.debug("done serializing response.");
417

    
418
    }
419

    
420
    /**
421
     * get the logs based on passed params. Available params are token,
422
     * fromDate, toDate, event. See
423
     * http://mule1.dataone.org/ArchitectureDocs/mn_api_crud
424
     * .html#MN_crud.getLogRecords for more info
425
     * 
426
     * @throws NotImplemented
427
     * @throws InvalidRequest
428
     * @throws NotAuthorized
429
     * @throws ServiceFailure
430
     * @throws InvalidToken
431
     * @throws IOException
432
     * @throws JiBXException
433
     */
434
    private void getLog() throws InvalidToken, ServiceFailure, NotAuthorized,
435
            InvalidRequest, NotImplemented, IOException, JiBXException {
436

    
437
        Date fromDate = null;
438
        Date toDate = null;
439
        Event event = null;
440
        Integer start = null;
441
        Integer count = null;
442

    
443
        try {
444
            String fromDateS = params.get("fromDate")[0];
445
            logMetacat.debug("param fromDateS: " + fromDateS);
446
            fromDate = DateTimeMarshaller.deserializeDateToUTC(fromDateS);
447
        } catch (Exception e) {
448
            logMetacat.warn("Could not parse fromDate: " + e.getMessage());
449
        }
450
        try {
451
            String toDateS = params.get("toDate")[0];
452
            logMetacat.debug("param toDateS: " + toDateS);
453
            toDate = DateTimeMarshaller.deserializeDateToUTC(toDateS);
454
        } catch (Exception e) {
455
            logMetacat.warn("Could not parse toDate: " + e.getMessage());
456
        }
457
        try {
458
            String eventS = params.get("event")[0];
459
            event = Event.convert(eventS);
460
        } catch (Exception e) {
461
            logMetacat.warn("Could not parse event: " + e.getMessage());
462
        }
463
        logMetacat.debug("fromDate: " + fromDate + " toDate: " + toDate);
464

    
465
        try {
466
            start = Integer.parseInt(params.get("start")[0]);
467
        } catch (Exception e) {
468
            logMetacat.warn("Could not parse start: " + e.getMessage());
469
        }
470
        try {
471
            count = Integer.parseInt(params.get("count")[0]);
472
        } catch (Exception e) {
473
            logMetacat.warn("Could not parse count: " + e.getMessage());
474
        }
475

    
476
        logMetacat.debug("calling getLogRecords");
477
        Log log = CNodeService.getInstance(request).getLogRecords(session,
478
                fromDate, toDate, event, start, count);
479

    
480
        OutputStream out = response.getOutputStream();
481
        response.setStatus(200);
482
        response.setContentType("text/xml");
483

    
484
        TypeMarshaller.marshalTypeToOutputStream(log, out);
485

    
486
    }
487

    
488
    /**
489
     * Implements REST version of DataONE CRUD API --> get
490
     * 
491
     * @param guid
492
     *            ID of data object to be read
493
     * @throws NotImplemented
494
     * @throws InvalidRequest
495
     * @throws NotFound
496
     * @throws NotAuthorized
497
     * @throws ServiceFailure
498
     * @throws InvalidToken
499
     * @throws IOException
500
     */
501
    protected void getObject(String guid) throws InvalidToken, ServiceFailure,
502
            NotAuthorized, NotFound, InvalidRequest, NotImplemented,
503
            IOException {
504

    
505
        Identifier id = new Identifier();
506
        id.setValue(guid);
507

    
508
        SystemMetadata sm = CNodeService.getInstance(request)
509
                .getSystemMetadata(session, id);
510

    
511
        // set the content type
512
        if (sm.getFormatId()
513
                .getValue()
514
                .trim()
515
                .equals(ObjectFormatCache.getInstance().getFormat("text/csv")
516
                        .getFormatId().getValue())) {
517
            response.setContentType("text/csv");
518
            response.setHeader("Content-Disposition",
519
                    "inline; filename=" + id.getValue() + ".csv");
520
        } else if (sm
521
                .getFormatId()
522
                .getValue()
523
                .trim()
524
                .equals(ObjectFormatCache.getInstance().getFormat("text/plain")
525
                        .getFormatId().getValue())) {
526
            response.setContentType("text/plain");
527
            response.setHeader("Content-Disposition",
528
                    "inline; filename=" + id.getValue() + ".txt");
529
        } else if (sm
530
                .getFormatId()
531
                .getValue()
532
                .trim()
533
                .equals(ObjectFormatCache.getInstance()
534
                        .getFormat("application/octet-stream").getFormatId()
535
                        .getValue())) {
536
            response.setContentType("application/octet-stream");
537
        } else {
538
            response.setContentType("text/xml");
539
            response.setHeader("Content-Disposition",
540
                    "inline; filename=" + id.getValue() + ".xml");
541
        }
542

    
543
        InputStream data = CNodeService.getInstance(request).get(session, id);
544

    
545
        OutputStream out = response.getOutputStream();
546
        response.setStatus(200);
547
        IOUtils.copyLarge(data, out);
548

    
549
    }
550

    
551
    /**
552
     * Implements REST version of DataONE CRUD API --> getSystemMetadata
553
     * 
554
     * @param guid
555
     *            ID of data object to be read
556
     * @throws NotImplemented
557
     * @throws InvalidRequest
558
     * @throws NotFound
559
     * @throws NotAuthorized
560
     * @throws ServiceFailure
561
     * @throws InvalidToken
562
     * @throws IOException
563
     * @throws JiBXException
564
     */
565
    protected void getSystemMetadataObject(String guid) throws InvalidToken,
566
            ServiceFailure, NotAuthorized, NotFound, InvalidRequest,
567
            NotImplemented, IOException, JiBXException {
568

    
569
        Identifier id = new Identifier();
570
        id.setValue(guid);
571
        SystemMetadata sysmeta = CNodeService.getInstance(request)
572
                .getSystemMetadata(session, id);
573

    
574
        response.setContentType("text/xml");
575
        response.setStatus(200);
576
        OutputStream out = response.getOutputStream();
577

    
578
        // Serialize and write it to the output stream
579
        TypeMarshaller.marshalTypeToOutputStream(sysmeta, out);
580
    }
581

    
582
    /**
583
     * Earthgrid API > Put Service >Put Function : calls MetacatHandler >
584
     * handleInsertOrUpdateAction
585
     * 
586
     * @param guid
587
     *            - ID of data object to be inserted or updated. If action is
588
     *            update, the pid is the existing pid. If insert, the pid is the
589
     *            new one
590
     * @throws InvalidRequest
591
     * @throws ServiceFailure
592
     * @throws IdentifierNotUnique
593
     * @throws JiBXException
594
     * @throws NotImplemented
595
     * @throws InvalidSystemMetadata
596
     * @throws InsufficientResources
597
     * @throws UnsupportedType
598
     * @throws NotAuthorized
599
     * @throws InvalidToken
600
     * @throws IOException
601
     * @throws IllegalAccessException
602
     * @throws InstantiationException
603
     */
604
    protected void putObject(String pid, String action) throws ServiceFailure,
605
            InvalidRequest, IdentifierNotUnique, JiBXException, InvalidToken,
606
            NotAuthorized, UnsupportedType, InsufficientResources,
607
            InvalidSystemMetadata, NotImplemented, IOException,
608
            InstantiationException, IllegalAccessException {
609
        logMetacat.debug("Entering putObject: " + pid + "/" + action);
610

    
611
        // Read the incoming data from its Mime Multipart encoding
612
        Map<String, File> files = collectMultipartFiles();
613
        InputStream object = null;
614
        InputStream sysmeta = null;
615

    
616
        File smFile = files.get("sysmeta");
617
        sysmeta = new FileInputStream(smFile);
618
        File objFile = files.get("object");
619
        object = new FileInputStream(objFile);
620

    
621
        if (action.equals(FUNCTION_NAME_INSERT)) { // handle inserts
622

    
623
            logMetacat.debug("Commence creation...");
624
            SystemMetadata smd = TypeMarshaller.unmarshalTypeFromStream(
625
                    SystemMetadata.class, sysmeta);
626

    
627
            Identifier id = new Identifier();
628
            id.setValue(pid);
629
            logMetacat.debug("creating object with pid " + id.getValue());
630
            Identifier rId = CNodeService.getInstance(request).create(session,
631
                    id, object, smd);
632

    
633
            OutputStream out = response.getOutputStream();
634
            response.setStatus(200);
635
            response.setContentType("text/xml");
636

    
637
            TypeMarshaller.marshalTypeToOutputStream(rId, out);
638

    
639
        } else {
640
            throw new InvalidRequest("1000", "Operation must be create.");
641
        }
642
    }
643

    
644
    /**
645
     * List the object formats registered with the system
646
     * 
647
     * @throws NotImplemented
648
     * @throws InsufficientResources
649
     * @throws NotFound
650
     * @throws ServiceFailure
651
     * @throws InvalidRequest
652
     * @throws IOException
653
     * @throws JiBXException
654
     */
655
    private void listFormats() throws InvalidRequest, ServiceFailure, NotFound,
656
            InsufficientResources, NotImplemented, IOException, JiBXException {
657
        logMetacat.debug("Entering listFormats()");
658

    
659
        ObjectFormatList objectFormatList = CNodeService.getInstance(request)
660
                .listFormats();
661
        // get the response output stream
662
        OutputStream out = response.getOutputStream();
663
        response.setStatus(200);
664
        response.setContentType("text/xml");
665

    
666
        // style the object with a processing directive
667
        String stylesheet = null;
668
        try {
669
            stylesheet = PropertyService.getProperty("dataone.types.xsl");
670
        } catch (PropertyNotFoundException e) {
671
            logMetacat.warn("Could not locate DataONE types XSLT: "
672
                    + e.getMessage());
673
        }
674

    
675
        TypeMarshaller.marshalTypeToOutputStream(objectFormatList, out,
676
                stylesheet);
677

    
678
    }
679
    
680
    private void listChecksumAlgorithms() throws IOException, ServiceFailure,
681
			NotImplemented, JiBXException {
682
		logMetacat.debug("Entering listFormats()");
683

    
684
		ChecksumAlgorithmList result = CNodeService.getInstance(request).listChecksumAlgorithms();
685

    
686
		// get the response output stream
687
		OutputStream out = response.getOutputStream();
688
		response.setStatus(200);
689
		response.setContentType("text/xml");
690

    
691
		// style the object with a processing directive
692
		String stylesheet = null;
693
		try {
694
			stylesheet = PropertyService.getProperty("dataone.types.xsl");
695
		} catch (PropertyNotFoundException e) {
696
			logMetacat.warn("Could not locate DataONE types XSLT: "
697
					+ e.getMessage());
698
		}
699

    
700
		TypeMarshaller.marshalTypeToOutputStream(result, out, stylesheet);
701

    
702
	}
703
    
704
    /**
705
     * http://mule1.dataone.org/ArchitectureDocs-current/apis/CN_APIs.html#CNRead.describe
706
     * @param pid
707
     * @throws InvalidToken
708
     * @throws ServiceFailure
709
     * @throws NotAuthorized
710
     * @throws NotFound
711
     * @throws NotImplemented
712
     * @throws InvalidRequest
713
     */
714
    private void describeObject(String pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented, InvalidRequest
715
    {
716
        response.setStatus(200);
717
        response.setContentType("text/xml");
718
        
719
        Identifier id = new Identifier();
720
        id.setValue(pid);
721

    
722
        DescribeResponse dr = CNodeService.getInstance(request).describe(session, id);
723
        //response.addHeader("pid", pid);
724
        response.addHeader("DataONE-Checksum", dr.getDataONE_Checksum().getAlgorithm() + "," + dr.getDataONE_Checksum().getValue());
725
        response.addHeader("Content-Length", dr.getContent_Length() + "");
726
        response.addHeader("Last-Modified", DateTimeMarshaller.serializeDateToUTC(dr.getLast_Modified()));
727
        response.addHeader("DataONE-ObjectFormat", dr.getDataONE_ObjectFormatIdentifier().getValue());
728
        response.addHeader("DataONE-SerialVersion", dr.getSerialVersion().toString());
729

    
730
    }
731

    
732
    /**
733
     * Return the requested object format
734
     * 
735
     * @param fmtidStr
736
     *            the requested format identifier as a string
737
     * @throws NotImplemented
738
     * @throws InsufficientResources
739
     * @throws NotFound
740
     * @throws ServiceFailure
741
     * @throws InvalidRequest
742
     * @throws IOException
743
     * @throws JiBXException
744
     */
745
    private void getFormat(String fmtidStr) throws InvalidRequest,
746
            ServiceFailure, NotFound, InsufficientResources, NotImplemented,
747
            IOException, JiBXException {
748
        logMetacat.debug("Entering listFormats()");
749

    
750
        ObjectFormatIdentifier fmtid = new ObjectFormatIdentifier();
751
        fmtid.setValue(fmtidStr);
752

    
753
        // get the specified object format
754
        ObjectFormat objectFormat = CNodeService.getInstance(request)
755
                .getFormat(fmtid);
756

    
757
        OutputStream out = response.getOutputStream();
758
        response.setStatus(200);
759
        response.setContentType("text/xml");
760

    
761
        TypeMarshaller.marshalTypeToOutputStream(objectFormat, out);
762

    
763
    }
764

    
765
    /**
766
     * Reserve the given Identifier
767
     * 
768
     * @throws InvalidToken
769
     * @throws ServiceFailure
770
     * @throws NotAuthorized
771
     * @throws IdentifierNotUnique
772
     * @throws NotImplemented
773
     * @throws InvalidRequest
774
     * @throws IOException
775
     * @throws JiBXException
776
     */
777
    private void reserve() throws InvalidToken, ServiceFailure, NotAuthorized,
778
            IdentifierNotUnique, NotImplemented, InvalidRequest, IOException,
779
            JiBXException {
780
        Identifier pid = null;
781
        String scope = null;
782
        String format = null;
783
        // gather the params
784
        try {
785
            String id = params.get("pid")[0];
786
            pid = new Identifier();
787
            pid.setValue(id);
788
        } catch (Exception e) {
789
            logMetacat.warn("pid not specified");
790
        }
791
        try {
792
            scope = params.get("scope")[0];
793
        } catch (Exception e) {
794
            logMetacat.warn("pid not specified");
795
        }
796
        try {
797
            format = params.get("format")[0];
798
        } catch (Exception e) {
799
            logMetacat.warn("pid not specified");
800
        }
801
        // call the implementation
802
        Identifier resultPid = CNodeService.getInstance(request)
803
                .reserveIdentifier(session, pid);
804
        OutputStream out = response.getOutputStream();
805
        response.setStatus(200);
806
        response.setContentType("text/xml");
807
        // send back the reserved pid
808
        TypeMarshaller.marshalTypeToOutputStream(resultPid, out);
809
    }
810

    
811
    /**
812
     * 
813
     * @param id
814
     * @throws InvalidRequest
815
     * @throws InvalidToken
816
     * @throws ServiceFailure
817
     * @throws NotAuthorized
818
     * @throws NotFound
819
     * @throws NotImplemented
820
     * @throws IOException
821
     * @throws JiBXException
822
     */
823
    private void resolve(String id) throws InvalidRequest, InvalidToken,
824
            ServiceFailure, NotAuthorized, NotFound, NotImplemented,
825
            IOException, JiBXException {
826
        Identifier pid = new Identifier();
827
        pid.setValue(id);
828
        ObjectLocationList locationList = CNodeService.getInstance(request)
829
                .resolve(session, pid);
830
        OutputStream out = response.getOutputStream();
831
        response.setStatus(200);
832
        response.setContentType("text/xml");
833
        TypeMarshaller.marshalTypeToOutputStream(locationList, out);
834

    
835
    }
836

    
837
    /**
838
     * Assert that a relationship exists between two resources
839
     * 
840
     * @param id
841
     * @return
842
     * @throws InvalidToken
843
     * @throws ServiceFailure
844
     * @throws NotAuthorized
845
     * @throws NotFound
846
     * @throws InvalidRequest
847
     * @throws NotImplemented
848
     */
849
    private boolean assertRelation(String id) throws InvalidToken,
850
            ServiceFailure, NotAuthorized, NotFound, InvalidRequest,
851
            NotImplemented {
852
        Identifier pidOfSubject = new Identifier();
853
        pidOfSubject.setValue(id);
854
        String relationship = null;
855
        try {
856
            relationship = params.get("relationship")[0];
857
        } catch (Exception e) {
858
            logMetacat.warn("relationship not specified");
859
        }
860
        Identifier pidOfObject = new Identifier();
861
        try {
862
            String objPid = params.get("pidOfObject")[0];
863
            pidOfObject.setValue(objPid);
864
        } catch (Exception e) {
865
            logMetacat.warn("pidOfObject not specified");
866
        }
867
        boolean result = CNodeService.getInstance(request).assertRelation(
868
                session, pidOfSubject, relationship, pidOfObject);
869
        response.setStatus(200);
870
        response.setContentType("text/xml");
871
        return result;
872
    }
873

    
874
    /**
875
     * Set the owner of a resource
876
     * 
877
     * @param id
878
     * @throws JiBXException
879
     * @throws InvalidToken
880
     * @throws ServiceFailure
881
     * @throws NotFound
882
     * @throws NotAuthorized
883
     * @throws NotImplemented
884
     * @throws InvalidRequest
885
     * @throws IOException
886
     * @throws IllegalAccessException
887
     * @throws InstantiationException
888
     * @throws VersionMismatch 
889
     */
890
    private void owner(String id) throws JiBXException, InvalidToken,
891
            ServiceFailure, NotFound, NotAuthorized, NotImplemented,
892
            InvalidRequest, IOException, InstantiationException,
893
            IllegalAccessException, VersionMismatch {
894

    
895
        Identifier pid = new Identifier();
896
        pid.setValue(id);
897

    
898
        long serialVersion = 0L;
899
        String serialVersionStr = null;
900

    
901
        // get the serialVersion
902
        try {
903
            serialVersionStr = params.get("serialVersion")[0];
904
            serialVersion = new Long(serialVersionStr).longValue();
905

    
906
        } catch (NullPointerException e) {
907
            String msg = "The 'serialVersion' must be provided as a parameter and was not.";
908
            logMetacat.error(msg);
909
            throw new InvalidRequest("4442", msg);
910

    
911
        }
912

    
913
        // get the subject
914
        String subjectStr = params.get("subject")[0];
915
        Subject subject = TypeMarshaller.unmarshalTypeFromStream(Subject.class,
916
                new ByteArrayInputStream(subjectStr.getBytes("UTF-8")));
917

    
918
        Identifier retPid = CNodeService.getInstance(request).setRightsHolder(session, pid, subject, serialVersion);
919
        OutputStream out = response.getOutputStream();
920
        response.setStatus(200);
921
        response.setContentType("text/xml");
922
        TypeMarshaller.marshalTypeToOutputStream(retPid, out);
923
    }
924

    
925
    /**
926
     * Processes the authorization check for given id
927
     * 
928
     * @param id
929
     * @return
930
     * @throws ServiceFailure
931
     * @throws InvalidToken
932
     * @throws NotFound
933
     * @throws NotAuthorized
934
     * @throws NotImplemented
935
     * @throws InvalidRequest
936
     */
937
    private boolean isAuthorized(String id) throws ServiceFailure,
938
            InvalidToken, NotFound, NotAuthorized, NotImplemented,
939
            InvalidRequest {
940
        Identifier pid = new Identifier();
941
        pid.setValue(id);
942
        String permission = params.get("action")[0];
943
        boolean result = CNodeService.getInstance(request).isAuthorized(
944
                session, pid, Permission.convert(permission));
945
        response.setStatus(200);
946
        response.setContentType("text/xml");
947
        return result;
948
    }
949

    
950
    /**
951
     * Register System Metadata without data or metadata object
952
     * 
953
     * @param pid
954
     *            identifier for System Metadata entry
955
     * @throws JiBXException
956
     * @throws FileUploadException
957
     * @throws IOException
958
     * @throws InvalidRequest
959
     * @throws ServiceFailure
960
     * @throws InvalidSystemMetadata
961
     * @throws NotAuthorized
962
     * @throws NotImplemented
963
     * @throws IllegalAccessException
964
     * @throws InstantiationException
965
     */
966
    protected Identifier registerSystemMetadata(String pid)
967
            throws ServiceFailure, InvalidRequest, IOException,
968
            FileUploadException, JiBXException, NotImplemented, NotAuthorized,
969
            InvalidSystemMetadata, InstantiationException,
970
            IllegalAccessException {
971
        logMetacat.debug("Entering registerSystemMetadata: " + pid);
972

    
973
        // get the system metadata from the request
974
        SystemMetadata systemMetadata = collectSystemMetadata();
975

    
976
        Identifier guid = new Identifier();
977
        guid.setValue(pid);
978
        logMetacat.debug("registering system metadata with pid "
979
                + guid.getValue());
980
        Identifier retGuid = CNodeService.getInstance(request)
981
                .registerSystemMetadata(session, guid, systemMetadata);
982

    
983
        response.setStatus(200);
984
        response.setContentType("text/xml");
985
        return retGuid;
986

    
987
    }
988

    
989
    /**
990
     * set the access perms on a document
991
     * 
992
     * @throws JiBXException
993
     * @throws InvalidRequest
994
     * @throws NotImplemented
995
     * @throws NotAuthorized
996
     * @throws NotFound
997
     * @throws ServiceFailure
998
     * @throws InvalidToken
999
     * @throws IllegalAccessException
1000
     * @throws InstantiationException
1001
     * @throws IOException
1002
     * @throws SAXException
1003
     * @throws ParserConfigurationException
1004
     * @throws VersionMismatch 
1005
     */
1006
    protected void setAccess(String pid) throws JiBXException, InvalidToken,
1007
            ServiceFailure, NotFound, NotAuthorized, NotImplemented,
1008
            InvalidRequest, IOException, InstantiationException,
1009
            IllegalAccessException, ParserConfigurationException, SAXException, VersionMismatch {
1010

    
1011
        long serialVersion = 0L;
1012
        String serialVersionStr = null;
1013

    
1014
        // get the serialVersion
1015
        try {
1016
            serialVersionStr = params.get("serialVersion")[0];
1017
            serialVersion = new Long(serialVersionStr).longValue();
1018

    
1019
        } catch (NullPointerException e) {
1020
            String msg = "The 'serialVersion' must be provided as a parameter and was not.";
1021
            logMetacat.error(msg);
1022
            throw new InvalidRequest("4402", msg);
1023

    
1024
        }
1025

    
1026
        Identifier id = new Identifier();
1027
        id.setValue(pid);
1028

    
1029
        AccessPolicy accessPolicy = collectAccessPolicy();
1030
        CNodeService.getInstance(request).setAccessPolicy(session, id,
1031
                accessPolicy, serialVersion);
1032

    
1033
    }
1034

    
1035
    /**
1036
     * List the objects
1037
     * 
1038
     * @throws NotImplemented
1039
     * @throws InvalidRequest
1040
     * @throws NotAuthorized
1041
     * @throws ServiceFailure
1042
     * @throws InvalidToken
1043
     * @throws NotFound
1044
     * @throws IOException
1045
     * @throws JiBXException
1046
     * @throws Exception
1047
     */
1048
    private void listObjects() throws InvalidToken, ServiceFailure,
1049
            NotAuthorized, InvalidRequest, NotImplemented, NotFound,
1050
            IOException, JiBXException {
1051

    
1052
        Date startTime = null;
1053
        Date endTime = null;
1054
        ObjectFormat objectFormat = null;
1055
        boolean replicaStatus = false;
1056
        int start = 0;
1057
        int count = -1;
1058
        Enumeration<String> paramlist = request.getParameterNames();
1059
        while (paramlist.hasMoreElements()) {
1060
            // parse the params and make the call
1061
            String name = paramlist.nextElement();
1062
            String[] value = request.getParameterValues(name);
1063

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

    
1098
        ObjectFormatIdentifier fmtid = null;
1099
        if (objectFormat != null) {
1100
            fmtid = objectFormat.getFormatId();
1101
        }
1102

    
1103
        // get the list
1104
        ObjectList ol = CNodeService.getInstance(request).listObjects(session,
1105
                startTime, endTime, fmtid, replicaStatus, start, count);
1106

    
1107
        // send it
1108
        OutputStream out = response.getOutputStream();
1109
        response.setStatus(200);
1110
        response.setContentType("text/xml");
1111

    
1112
        // style the object with a processing directive
1113
        String stylesheet = null;
1114
        try {
1115
            stylesheet = PropertyService.getProperty("dataone.types.xsl");
1116
        } catch (PropertyNotFoundException e) {
1117
            logMetacat.warn("Could not locate DataONE types XSLT: "
1118
                    + e.getMessage());
1119
        }
1120

    
1121
        // Serialize and write it to the output stream
1122
        TypeMarshaller.marshalTypeToOutputStream(ol, out, stylesheet);
1123
    }
1124

    
1125
    /**
1126
     * Pass the request to get node replication authorization to CNodeService
1127
     * 
1128
     * @param pid
1129
     *            the identifier of the object to get authorization to replicate
1130
     * 
1131
     * @throws NotImplemented
1132
     * @throws NotAuthorized
1133
     * @throws InvalidToken
1134
     * @throws ServiceFailure
1135
     * @throws NotFound
1136
     * @throws InvalidRequest
1137
     */
1138
    public boolean isNodeAuthorized(String pid) throws NotImplemented,
1139
            NotAuthorized, InvalidToken, ServiceFailure, NotFound,
1140
            InvalidRequest {
1141

    
1142
        boolean result = false;
1143
        Subject targetNodeSubject = new Subject();
1144
        String nodeSubject = null;
1145
        String replPermission = null;
1146

    
1147
        // get the pid
1148
        Identifier identifier = new Identifier();
1149
        identifier.setValue(pid);
1150

    
1151
        // get the target node subject
1152
        try {
1153
            nodeSubject = params.get("targetNodeSubject")[0];
1154
            targetNodeSubject.setValue(nodeSubject);
1155

    
1156
        } catch (NullPointerException e) {
1157
            String msg = "The 'targetNodeSubject' must be provided as a parameter and was not.";
1158
            logMetacat.error(msg);
1159
            throw new InvalidRequest("4873", msg);
1160

    
1161
        }
1162

    
1163
        result = CNodeService.getInstance(request).isNodeAuthorized(session, targetNodeSubject, identifier);
1164

    
1165
        response.setStatus(200);
1166
        response.setContentType("text/xml");
1167
        return result;
1168

    
1169
    }
1170

    
1171
    /**
1172
     * Pass the request to set the replication policy to CNodeService
1173
     * 
1174
     * @param pid
1175
     *            the identifier of the object to set the replication policy on
1176
     * 
1177
     * @throws NotImplemented
1178
     * @throws NotFound
1179
     * @throws NotAuthorized
1180
     * @throws ServiceFailure
1181
     * @throws InvalidRequest
1182
     * @throws InvalidToken
1183
     * @throws IOException
1184
     * @throws InstantiationException
1185
     * @throws IllegalAccessException
1186
     * @throws JiBXException
1187
     * @throws VersionMismatch 
1188
     */
1189
    public boolean setReplicationPolicy(String pid) throws NotImplemented,
1190
            NotFound, NotAuthorized, ServiceFailure, InvalidRequest,
1191
            InvalidToken, IOException, InstantiationException,
1192
            IllegalAccessException, JiBXException, VersionMismatch {
1193

    
1194
        boolean result = false;
1195
        ReplicationPolicy policy = null;
1196
        long serialVersion = 0L;
1197
        String serialVersionStr = null;
1198

    
1199
        Identifier identifier = new Identifier();
1200
        identifier.setValue(pid);
1201

    
1202
        policy = collectReplicationPolicy();
1203

    
1204
        // get the serialVersion
1205
        try {
1206
            serialVersionStr = multipartparams.get("serialVersion").get(0);
1207
            serialVersion = new Long(serialVersionStr).longValue();
1208

    
1209
        } catch (NullPointerException e) {
1210
            String msg = "The 'serialVersion' must be provided as a parameter and was not.";
1211
            logMetacat.error(msg);
1212
            throw new InvalidRequest("4883", msg);
1213

    
1214
        }
1215
        result = CNodeService.getInstance(request).setReplicationPolicy(
1216
                session, identifier, policy, serialVersion);
1217
        response.setStatus(200);
1218
        response.setContentType("text/xml");
1219
        return result;
1220

    
1221
    }
1222

    
1223
    /**
1224
     * Pass the request to set the replication status to CNodeService
1225
     * 
1226
     * @param pid
1227
     *            the identifier of the object to set the replication status on
1228
     * 
1229
     * @throws ServiceFailure
1230
     * @throws NotImplemented
1231
     * @throws InvalidToken
1232
     * @throws NotAuthorized
1233
     * @throws InvalidRequest
1234
     * @throws NotFound
1235
     * @throws JiBXException 
1236
     * @throws IllegalAccessException 
1237
     * @throws InstantiationException 
1238
     * @throws IOException 
1239
     */
1240
    public boolean setReplicationStatus(String pid) throws ServiceFailure,
1241
            NotImplemented, InvalidToken, NotAuthorized, InvalidRequest,
1242
            NotFound {
1243
        
1244
        boolean result = false;
1245
        Identifier identifier = new Identifier();
1246
        identifier.setValue(pid);
1247
        BaseException failure = null;
1248
        ReplicationStatus status = null;
1249
        String replicationStatus = null;
1250
        NodeReference targetNodeRef = null;
1251
        String targetNode = null;
1252

    
1253
        // Parse the params out of the multipart form data
1254
        // Read the incoming data from its Mime Multipart encoding
1255
        logMetacat.debug("Parsing ReplicaStatus from the mime multipart entity");
1256

    
1257
        try {
1258
            failure = collectReplicationStatus();
1259
            
1260
        } catch (IOException e2) {
1261
            throw new ServiceFailure("4700", "Couldn't resolve the multipart request: " +
1262
                e2.getMessage());
1263
            
1264
        } catch (InstantiationException e2) {
1265
            throw new ServiceFailure("4700", "Couldn't resolve the multipart request: " +
1266
                e2.getMessage());
1267
            
1268
        } catch (IllegalAccessException e2) {
1269
            throw new ServiceFailure("4700", "Couldn't resolve the multipart request: " +
1270
                    e2.getMessage());
1271
            
1272
        } catch (JiBXException e2) {
1273
            throw new ServiceFailure("4700", "Couldn't resolve the multipart request: " +
1274
                    e2.getMessage());
1275
            
1276
        }
1277
        
1278
        // get the replication status param
1279
        try {
1280
            replicationStatus = multipartparams.get("status").get(0);
1281
            status = ReplicationStatus.convert(replicationStatus);
1282

    
1283
        } catch (NullPointerException npe) {
1284

    
1285
            logMetacat.debug("The 'status' parameter was not found in the "
1286
                    + "multipartparams map.  Trying the params map.");
1287

    
1288
            try {
1289
                replicationStatus = params.get("status")[0];
1290
                status = ReplicationStatus.convert(replicationStatus
1291
                        .toLowerCase());
1292

    
1293
            } catch (Exception e) {
1294
                String msg = "The 'status' must be provided as a parameter and was not.";
1295
                logMetacat.error(msg);
1296
                throw new InvalidRequest("4730", msg);
1297

    
1298
            }
1299

    
1300
        }
1301

    
1302
        // get the target node reference param
1303
        try {
1304
            targetNode = multipartparams.get("nodeRef").get(0);
1305
            targetNodeRef = new NodeReference();
1306
            targetNodeRef.setValue(targetNode);
1307

    
1308
        } catch (NullPointerException e) {
1309
            logMetacat.debug("The 'nodeRef' parameter was not found in the "
1310
                    + "multipartparams map.  Trying the params map.");
1311

    
1312
            try {
1313
                targetNode = params.get("nodeRef")[0];
1314
                targetNodeRef = new NodeReference();
1315
                targetNodeRef.setValue(targetNode);
1316

    
1317
            } catch (Exception e1) {
1318
                String msg = "The 'nodeRef' must be provided as a parameter and was not.";
1319
                logMetacat.error(msg);
1320
                throw new InvalidRequest("4730", msg);
1321

    
1322
            }
1323

    
1324
        }
1325

    
1326
        result = CNodeService.getInstance(request).setReplicationStatus(
1327
                session, identifier, targetNodeRef, status, failure);
1328
        response.setStatus(200);
1329
        response.setContentType("text/xml");
1330
        return result;
1331

    
1332
    }
1333

    
1334
    /**
1335
     * Pass the request to update the replication metadata to CNodeService
1336
     * 
1337
     * @param pid
1338
     *            the identifier of the object to update the replication
1339
     *            metadata on
1340
     * 
1341
     * @throws ServiceFailure
1342
     * @throws NotImplemented
1343
     * @throws InvalidToken
1344
     * @throws NotAuthorized
1345
     * @throws InvalidRequest
1346
     * @throws NotFound
1347
     * @throws VersionMismatch 
1348
     */
1349
    public boolean updateReplicationMetadata(String pid) throws ServiceFailure,
1350
            NotImplemented, InvalidToken, NotAuthorized, InvalidRequest,
1351
            NotFound, VersionMismatch {
1352

    
1353
        boolean result = false;
1354
        long serialVersion = 0L;
1355
        String serialVersionStr = null;
1356
        Replica replica = null;
1357
        Identifier identifier = new Identifier();
1358
        identifier.setValue(pid);
1359

    
1360
        replica = collectReplicaMetadata();
1361

    
1362
        // get the serialVersion
1363
        try {
1364
            serialVersionStr = multipartparams.get("serialVersion").get(0);
1365
            serialVersion = new Long(serialVersionStr).longValue();
1366

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

    
1372
        }
1373

    
1374
        result = CNodeService.getInstance(request).updateReplicationMetadata(
1375
                session, identifier, replica, serialVersion);
1376
        response.setStatus(200);
1377
        response.setContentType("text/xml");
1378
        return result;
1379

    
1380
    }
1381

    
1382
}
(1-1/9)