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: tao $'
7
 *     '$Date: 2017-12-08 14:11:23 -0800 (Fri, 08 Dec 2017) $'
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.v2;
24

    
25
import java.io.File;
26
import java.io.FileInputStream;
27
import java.io.FileNotFoundException;
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.v2.formats.ObjectFormatInfo;
44
import org.dataone.exceptions.MarshallingException;
45
import org.dataone.service.exceptions.BaseException;
46
import org.dataone.service.exceptions.IdentifierNotUnique;
47
import org.dataone.service.exceptions.InsufficientResources;
48
import org.dataone.service.exceptions.InvalidRequest;
49
import org.dataone.service.exceptions.InvalidSystemMetadata;
50
import org.dataone.service.exceptions.InvalidToken;
51
import org.dataone.service.exceptions.NotAuthorized;
52
import org.dataone.service.exceptions.NotFound;
53
import org.dataone.service.exceptions.NotImplemented;
54
import org.dataone.service.exceptions.ServiceFailure;
55
import org.dataone.service.exceptions.UnsupportedType;
56
import org.dataone.service.exceptions.VersionMismatch;
57
import org.dataone.service.types.v1.AccessPolicy;
58
import org.dataone.service.types.v1.Checksum;
59
import org.dataone.service.types.v1.ChecksumAlgorithmList;
60
import org.dataone.service.types.v1.DescribeResponse;
61
import org.dataone.service.types.v1.Event;
62
import org.dataone.service.types.v1.Identifier;
63
import org.dataone.service.types.v2.Log;
64
import org.dataone.service.types.v2.OptionList;
65
import org.dataone.service.types.v1.NodeReference;
66
import org.dataone.service.types.v2.ObjectFormat;
67
import org.dataone.service.types.v1.ObjectFormatIdentifier;
68
import org.dataone.service.types.v2.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.v2.SystemMetadata;
77
import org.dataone.service.util.Constants;
78
import org.dataone.service.util.DateTimeMarshaller;
79
import org.dataone.service.util.EncodingUtilities;
80
import org.dataone.service.util.ExceptionHandler;
81
import org.dataone.service.util.TypeMarshaller;
82
import org.xml.sax.SAXException;
83

    
84
import edu.ucsb.nceas.metacat.common.query.stream.ContentTypeInputStream;
85
import edu.ucsb.nceas.metacat.dataone.CNodeService;
86
import edu.ucsb.nceas.metacat.properties.PropertyService;
87
import edu.ucsb.nceas.metacat.restservice.D1ResourceHandler;
88
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
89

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

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

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

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

    
148
        try {
149

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

    
161
            // for the rest of the resouce
162
            String extra = null;
163

    
164
            logMetacat.debug("handling verb " + httpVerb
165
                    + " request with resource '" + resource + "'");
166
            boolean status = false;
167

    
168
            if (resource != null) {
169

    
170
                if (resource.startsWith(RESOURCE_ACCESS_RULES)
171
                        && httpVerb == PUT) {
172
                    logMetacat.debug("Setting access policy");
173
                    // after the command
174
                    extra = parseTrailing(resource, RESOURCE_ACCESS_RULES);
175
                    extra = decode(extra);
176
                    setAccess(extra);
177
                    status = true;
178
                    logMetacat.debug("done setting access");
179

    
180
                } else if (resource.startsWith(RESOURCE_META)) {
181
                    logMetacat.debug("Using resource: " + RESOURCE_META);
182

    
183
                    // after the command
184
                    extra = parseTrailing(resource, RESOURCE_META);
185
                    extra = decode(extra);
186
                    // get
187
                    if (httpVerb == GET) {
188
                        getSystemMetadataObject(extra);
189
                        status = true;
190
                    }
191
                    // post to register system metadata
192
                    if (httpVerb == POST) {
193
                        registerSystemMetadata();
194
                        status = true;
195
                    }
196
                    else if (httpVerb == PUT) {
197
                        logMetacat.debug("Using resource 'meta' for PUT");
198
                        updateSystemMetadata();
199
                        status = true;
200
                    }
201

    
202
                } else if (resource.startsWith(RESOURCE_RESERVE)) {
203
                    // reserve the ID (in params)
204
                    if (httpVerb == POST) {
205
                        reserve();
206
                        status = true;
207
                    }
208
                } else if (resource.startsWith(RESOURCE_RESOLVE)) {
209

    
210
                    // after the command
211
                    extra = parseTrailing(resource, RESOURCE_RESOLVE);
212
                    extra = decode(extra);
213
                    // resolve the object location
214
                    if (httpVerb == GET) {
215
                        resolve(extra);
216
                        status = true;
217
                    }
218
                } else if (resource.startsWith(RESOURCE_OWNER)) {
219

    
220
                    // after the command
221
                    extra = parseTrailing(resource, RESOURCE_OWNER);
222
                    extra = decode(extra);
223
                    // set the owner
224
                    if (httpVerb == PUT) {
225
                        owner(extra);
226
                        status = true;
227
                    }
228
                } else if (resource.startsWith(RESOURCE_IS_AUTHORIZED)) {
229

    
230
                    // after the command
231
                    extra = parseTrailing(resource, RESOURCE_IS_AUTHORIZED);
232
                    extra = decode(extra);
233
                    // authorized?
234
                    if (httpVerb == GET) {
235
                        isAuthorized(extra);
236
                        status = true;
237
                    }
238
                } else if (resource.startsWith(RESOURCE_OBJECTS)) {
239
                    logMetacat.debug("Using resource 'object'");
240
                    logMetacat
241
                            .debug("D1 Rest: Starting resource processing...");
242

    
243
                    // after the command
244
                    extra = parseTrailing(resource, RESOURCE_OBJECTS);
245
                    extra = decode(extra);
246
                    logMetacat.debug("objectId: " + extra);
247
                    logMetacat.debug("verb:" + httpVerb);
248

    
249
                    if (httpVerb == GET) {
250
                        if (extra != null) {
251
                            getObject(extra);
252
                        } else {
253
                            listObjects();
254
                        }
255
                        status = true;
256
                    } else if (httpVerb == POST) {
257
                        putObject(FUNCTION_NAME_INSERT);
258
                        status = true;
259
                    } else if (httpVerb == HEAD) {
260
                        describeObject(extra);
261
                        status = true;
262
                    } else if (httpVerb == DELETE) {
263
                        deleteObject(extra);
264
                        status = true;
265
                    } 
266

    
267
                } else if (resource.startsWith(RESOURCE_FORMATS)) {
268
                    logMetacat.debug("Using resource: " + RESOURCE_FORMATS);
269

    
270
                    // after the command
271
                    extra = parseTrailing(resource, RESOURCE_FORMATS);
272
                    extra = decode(extra);
273
                    // handle each verb
274
                    if (httpVerb == GET) {
275
                        if (extra == null) {
276
                            // list the formats collection
277
                            listFormats();
278
                        } else {
279
                            // get the specified format
280
                            getFormat(extra);
281
                        }
282
                        status = true;
283
                    } else if (httpVerb == PUT) {
284
                        addFormat(extra);
285
                    }
286

    
287
                } else if (resource.startsWith(RESOURCE_LOG)) {
288
                    logMetacat.debug("Using resource: " + RESOURCE_LOG);
289
                    // handle log events
290
                    if (httpVerb == GET) {
291
                        getLog();
292
                        status = true;
293
                    }
294

    
295
                } else if (resource.startsWith(Constants.RESOURCE_ARCHIVE)) {
296
                    logMetacat.debug("Using resource " + Constants.RESOURCE_ARCHIVE);
297
                    // handle archive events
298
                    if (httpVerb == PUT) {
299
                        extra = parseTrailing(resource, Constants.RESOURCE_ARCHIVE);
300
                        extra = decode(extra);
301
                        archive(extra);
302
                        status = true;
303
                    }
304
                } else if (resource.startsWith(Constants.RESOURCE_CHECKSUM)) {
305
                    logMetacat.debug("Using resource: " + Constants.RESOURCE_CHECKSUM);
306

    
307
                    // after the command
308
                    extra = parseTrailing(resource, Constants.RESOURCE_CHECKSUM);
309
                    extra = decode(extra);
310
                    // handle checksum requests
311
                    if (httpVerb == GET) {
312

    
313
                    	if (extra != null && extra.length() > 0) {
314
	                        checksum(extra);
315
	                        status = true;
316
                    	} else {
317
                    		listChecksumAlgorithms();
318
                    		status = true;
319
                    	}
320

    
321
                    }
322

    
323
                } else if (resource.startsWith(RESOURCE_REPLICATION_POLICY)
324
                        && httpVerb == PUT) {
325

    
326
                    logMetacat.debug("Using resource: "
327
                            + RESOURCE_REPLICATION_POLICY);
328
                    // get the trailing pid
329
                    extra = parseTrailing(resource, RESOURCE_REPLICATION_POLICY);
330
                    extra = decode(extra);
331
                    setReplicationPolicy(extra);
332
                    status = true;
333

    
334
                } else if (resource.startsWith(RESOURCE_REPLICATION_META)
335
                        && httpVerb == PUT) {
336

    
337
                    logMetacat.debug("Using resource: "
338
                            + RESOURCE_REPLICATION_META);
339
                    // get the trailing pid
340
                    extra = parseTrailing(resource, RESOURCE_REPLICATION_META);
341
                    extra = decode(extra);
342
                    updateReplicationMetadata(extra);
343
                    status = true;
344

    
345
                } else if (resource.startsWith(RESOURCE_REPLICATION_NOTIFY)
346
                        && httpVerb == PUT) {
347

    
348
                    logMetacat.debug("Using resource: "
349
                            + RESOURCE_REPLICATION_NOTIFY);
350
                    // get the trailing pid
351
                    extra = parseTrailing(resource, RESOURCE_REPLICATION_NOTIFY);
352
                    extra = decode(extra);
353
                    setReplicationStatus(extra);
354
                    status = true;
355

    
356
                } else if (resource.startsWith(RESOURCE_REPLICATION_AUTHORIZED)
357
                        && httpVerb == GET) {
358

    
359
                    logMetacat.debug("Using resource: "
360
                            + RESOURCE_REPLICATION_AUTHORIZED);
361
                    // get the trailing pid
362
                    extra = parseTrailing(resource,
363
                            RESOURCE_REPLICATION_AUTHORIZED);
364
                    extra = decode(extra);
365
                    isNodeAuthorized(extra);
366
                    status = true;
367

    
368
                } else if (resource.startsWith(Constants.RESOURCE_MONITOR_PING)) {
369
                    if (httpVerb == GET) {
370
                    	// after the command
371
                        extra = parseTrailing(resource, Constants.RESOURCE_MONITOR_PING);
372
                        extra = decode(extra);
373
                        logMetacat.debug("processing ping request");
374
                        Date result = CNodeService.getInstance(request).ping();
375
                        // TODO: send to output	
376
                        status = true;
377
                    }
378
                } else if (resource.startsWith(Constants.RESOURCE_META_OBSOLETEDBY)
379
                        && httpVerb == PUT) {
380

    
381
                    logMetacat.debug("Using resource: "
382
                            + Constants.RESOURCE_META_OBSOLETEDBY);
383
                    // get the trailing pid
384
                    extra = parseTrailing(resource, Constants.RESOURCE_META_OBSOLETEDBY);
385
                    extra = decode(extra);
386
                    setObsoletedBy(extra);
387
                    status = true;
388
                } else if (resource.startsWith(Constants.RESOURCE_REPLICATION_DELETE_REPLICA)
389
                        && httpVerb == PUT) {
390

    
391
                    logMetacat.debug("Using resource: "
392
                            + Constants.RESOURCE_REPLICATION_DELETE_REPLICA);
393
                    // get the trailing pid
394
                    extra = parseTrailing(resource, Constants.RESOURCE_REPLICATION_DELETE_REPLICA);
395
                    extra = decode(extra);
396
                    deleteReplica(extra);
397
                    status = true;
398
                } else if (resource.startsWith(RESOURCE_VIEWS)) {
399
                    logMetacat.info("Using resource " + RESOURCE_VIEWS);
400
                    // after the command
401
                    extra = parseTrailing(resource, RESOURCE_VIEWS);
402
                    logMetacat.info("view extra: " + extra);
403

    
404
                    String format = null;
405
                    String pid = null;
406

    
407
                    if (extra != null) {
408
                        // get the format
409
                        int formatIndex = extra.length();
410
                        if (extra.indexOf("/") > -1) {
411
                            formatIndex = extra.indexOf("/");
412
                            format = extra.substring(0, formatIndex);
413
                        } else {
414
                            throw new InvalidRequest("2853", "The request doesn't specify the name of theme.");
415
                        }
416
                        format = decode(format);
417
                        logMetacat.info("view format: " + format);
418
                        
419
                        // get the pid if it is there
420
                        pid = extra.substring(formatIndex, extra.length());
421
                        if (pid != null && pid.length() == 0) {
422
                            pid = null;
423
                        } else {
424
                            if (pid.startsWith("/")) {
425
                                pid = pid.substring(1);
426
                            }
427
                        }
428
                        pid=decode(pid);
429
                        logMetacat.debug("pid: " + pid);
430

    
431
                    }
432
                    logMetacat.debug("verb:" + httpVerb);
433
                    if (httpVerb == GET) {
434
                        doViews(format, pid);
435
                        status = true;
436
                    }
437
                } 
438

    
439
                if (!status) {
440
                    throw new ServiceFailure("0000", "Unknown error, status = "
441
                            + status);
442
                }
443
            } else {
444
                throw new InvalidRequest("0000", "No resource matched for "
445
                        + resource);
446
            }
447
        } catch (BaseException be) {
448
            // report Exceptions as clearly and generically as possible
449
            OutputStream out = null;
450
            try {
451
                out = response.getOutputStream();
452
            } catch (IOException ioe) {
453
                logMetacat.error("Could not get output stream from response",
454
                        ioe);
455
            }
456
            serializeException(be, out);
457
        } catch (Exception e) {
458
            // report Exceptions as clearly and generically as possible
459
            logMetacat.error(e.getClass() + ": " + e.getMessage(), e);
460
            OutputStream out = null;
461
            try {
462
                out = response.getOutputStream();
463
            } catch (IOException ioe) {
464
                logMetacat.error("Could not get output stream from response",
465
                        ioe);
466
            }
467
            ServiceFailure se = new ServiceFailure("0000", e.getMessage());
468
            serializeException(se, out);
469
        }
470
    }
471

    
472
    /**
473
     * Get the checksum for the given guid
474
     * 
475
     * @param guid
476
     * @throws NotImplemented
477
     * @throws InvalidRequest
478
     * @throws NotFound
479
     * @throws NotAuthorized
480
     * @throws ServiceFailure
481
     * @throws InvalidToken
482
     * @throws IOException
483
     * @throws MarshallingException
484
     */
485
    private void checksum(String guid) throws InvalidToken, ServiceFailure,
486
            NotAuthorized, NotFound, InvalidRequest, NotImplemented,
487
            MarshallingException, IOException {
488
        Identifier guidid = new Identifier();
489
        guidid.setValue(guid);
490
        logMetacat.debug("getting checksum for object " + guid);
491
        Checksum c = CNodeService.getInstance(request).getChecksum(session,
492
                guidid);
493
        logMetacat.debug("got checksum " + c.getValue());
494
        response.setStatus(200);
495
        logMetacat.debug("serializing response");
496
        TypeMarshaller.marshalTypeToOutputStream(c, response.getOutputStream());
497
        logMetacat.debug("done serializing response.");
498

    
499
    }
500

    
501
    /**
502
     * get the logs based on passed params. Available params are token,
503
     * fromDate, toDate, event. See
504
     * http://mule1.dataone.org/ArchitectureDocs/mn_api_crud
505
     * .html#MN_crud.getLogRecords for more info
506
     * 
507
     * @throws NotImplemented
508
     * @throws InvalidRequest
509
     * @throws NotAuthorized
510
     * @throws ServiceFailure
511
     * @throws InvalidToken
512
     * @throws IOException
513
     * @throws MarshallingException
514
     */
515
    private void getLog() throws InvalidToken, ServiceFailure, NotAuthorized,
516
            InvalidRequest, NotImplemented, IOException, MarshallingException {
517

    
518
        Date fromDate = null;
519
        Date toDate = null;
520
        String event = null;
521
        Integer start = null;
522
        Integer count = null;
523
        String pidFilter = null;
524

    
525
        try {
526
            String fromDateS = params.get("fromDate")[0];
527
            logMetacat.debug("param fromDateS: " + fromDateS);
528
            fromDate = DateTimeMarshaller.deserializeDateToUTC(fromDateS);
529
        } catch (Exception e) {
530
            logMetacat.warn("Could not parse fromDate: " + e.getMessage());
531
        }
532
        try {
533
            String toDateS = params.get("toDate")[0];
534
            logMetacat.debug("param toDateS: " + toDateS);
535
            toDate = DateTimeMarshaller.deserializeDateToUTC(toDateS);
536
        } catch (Exception e) {
537
            logMetacat.warn("Could not parse toDate: " + e.getMessage());
538
        }
539
        try {
540
            event = params.get("event")[0];
541
        } catch (Exception e) {
542
            logMetacat.warn("Could not parse event: " + e.getMessage());
543
        }
544
        logMetacat.debug("fromDate: " + fromDate + " toDate: " + toDate);
545

    
546
        try {
547
            start = Integer.parseInt(params.get("start")[0]);
548
        } catch (Exception e) {
549
            logMetacat.warn("Could not parse start: " + e.getMessage());
550
        }
551
        try {
552
            count = Integer.parseInt(params.get("count")[0]);
553
        } catch (Exception e) {
554
            logMetacat.warn("Could not parse count: " + e.getMessage());
555
        }
556

    
557
        try {
558
            pidFilter = params.get("idFilter")[0];
559
        } catch (Exception e) {
560
            logMetacat.warn("Could not parse pidFilter: " + e.getMessage());
561
        }
562
        
563
        logMetacat.debug("calling getLogRecords");
564
        Log log = CNodeService.getInstance(request).getLogRecords(session,
565
                fromDate, toDate, event, pidFilter, start, count);
566

    
567
        OutputStream out = response.getOutputStream();
568
        response.setStatus(200);
569
        response.setContentType("text/xml");
570

    
571
        TypeMarshaller.marshalTypeToOutputStream(log, out);
572

    
573
    }
574

    
575
    /**
576
     * Implements REST version of DataONE CRUD API --> get
577
     * 
578
     * @param guid
579
     *            ID of data object to be read
580
     * @throws NotImplemented
581
     * @throws InvalidRequest
582
     * @throws NotFound
583
     * @throws NotAuthorized
584
     * @throws ServiceFailure
585
     * @throws InvalidToken
586
     * @throws IOException
587
     */
588
    protected void getObject(String guid) throws InvalidToken, ServiceFailure,
589
            NotAuthorized, NotFound, InvalidRequest, NotImplemented,
590
            IOException {
591

    
592
        Identifier id = new Identifier();
593
        id.setValue(guid);
594

    
595
        SystemMetadata sm = CNodeService.getInstance(request)
596
                .getSystemMetadata(session, id);
597

    
598
        // set the headers for the content
599
        String mimeType = ObjectFormatInfo.instance().getMimeType(sm.getFormatId().getValue());
600
        if (mimeType == null) {
601
        	mimeType = "application/octet-stream";
602
        }
603
       
604
        String filename = sm.getFileName();
605
        if(filename == null || filename.trim().equals("")) {
606
            filename = id.getValue();
607
            String extension = ObjectFormatInfo.instance().getExtension(sm.getFormatId().getValue());
608
            if (extension != null && filename != null && !filename.endsWith(extension)) {
609
                filename = id.getValue() + extension;
610
            }
611
        }
612
        
613
        response.setContentType(mimeType);
614
        response.setHeader("Content-Disposition", "inline; filename=" + filename);
615

    
616
        InputStream data = CNodeService.getInstance(request).get(session, id);
617

    
618
        OutputStream out = response.getOutputStream();
619
        response.setStatus(200);
620
        IOUtils.copyLarge(data, out);
621

    
622
    }
623

    
624
    /**
625
     * Implements REST version of DataONE CRUD API --> getSystemMetadata
626
     * 
627
     * @param guid
628
     *            ID of data object to be read
629
     * @throws NotImplemented
630
     * @throws InvalidRequest
631
     * @throws NotFound
632
     * @throws NotAuthorized
633
     * @throws ServiceFailure
634
     * @throws InvalidToken
635
     * @throws IOException
636
     * @throws MarshallingException
637
     */
638
    protected void getSystemMetadataObject(String guid) throws InvalidToken,
639
            ServiceFailure, NotAuthorized, NotFound, InvalidRequest,
640
            NotImplemented, IOException, MarshallingException {
641

    
642
        Identifier id = new Identifier();
643
        id.setValue(guid);
644
        SystemMetadata sysmeta = CNodeService.getInstance(request)
645
                .getSystemMetadata(session, id);
646

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

    
651
        // Serialize and write it to the output stream
652
        TypeMarshaller.marshalTypeToOutputStream(sysmeta, out);
653
    }
654

    
655
    /**
656
     * Earthgrid API > Put Service >Put Function : calls MetacatHandler >
657
     * handleInsertOrUpdateAction
658
     * 
659
     * @param guid
660
     *            - ID of data object to be inserted or updated. If action is
661
     *            update, the pid is the existing pid. If insert, the pid is the
662
     *            new one
663
     * @throws InvalidRequest
664
     * @throws ServiceFailure
665
     * @throws IdentifierNotUnique
666
     * @throws MarshallingException
667
     * @throws NotImplemented
668
     * @throws InvalidSystemMetadata
669
     * @throws InsufficientResources
670
     * @throws UnsupportedType
671
     * @throws NotAuthorized
672
     * @throws InvalidToken
673
     * @throws IOException
674
     * @throws IllegalAccessException
675
     * @throws InstantiationException
676
     */
677
    protected void putObject(String action) throws ServiceFailure,
678
            InvalidRequest, IdentifierNotUnique, MarshallingException, InvalidToken,
679
            NotAuthorized, UnsupportedType, InsufficientResources,
680
            InvalidSystemMetadata, NotImplemented, IOException,
681
            InstantiationException, IllegalAccessException {
682
    	
683
        // Read the incoming data from its Mime Multipart encoding
684
        Map<String, File> files = collectMultipartFiles();
685
        
686
	    // get the encoded pid string from the body and make the object
687
        String pidString = multipartparams.get("pid").get(0);
688
        Identifier pid = new Identifier();
689
        pid.setValue(pidString);
690
        
691
        logMetacat.debug("putObject: " + pid.getValue() + "/" + action);
692
        
693
        InputStream object = null;
694
        InputStream sysmeta = null;
695

    
696
        File smFile = files.get("sysmeta");
697
        sysmeta = new FileInputStream(smFile);
698
        File objFile = files.get("object");
699
        object = new FileInputStream(objFile);
700

    
701
        if (action.equals(FUNCTION_NAME_INSERT)) { // handle inserts
702

    
703
            logMetacat.debug("Commence creation...");
704
            SystemMetadata smd = TypeMarshaller.unmarshalTypeFromStream(
705
                    SystemMetadata.class, sysmeta);
706

    
707
           
708
            logMetacat.debug("creating object with pid " + pid.getValue());
709
            Identifier rId = CNodeService.getInstance(request).create(session, pid, object, smd);
710

    
711
            OutputStream out = response.getOutputStream();
712
            response.setStatus(200);
713
            response.setContentType("text/xml");
714

    
715
            TypeMarshaller.marshalTypeToOutputStream(rId, out);
716

    
717
        } else {
718
            throw new InvalidRequest("1000", "Operation must be create.");
719
        }
720
    }
721

    
722
    /**
723
     * List the object formats registered with the system
724
     * 
725
     * @throws NotImplemented
726
     * @throws InsufficientResources
727
     * @throws NotFound
728
     * @throws ServiceFailure
729
     * @throws InvalidRequest
730
     * @throws IOException
731
     * @throws MarshallingException
732
     */
733
    private void listFormats() throws InvalidRequest, ServiceFailure, NotFound,
734
            InsufficientResources, NotImplemented, IOException, MarshallingException {
735
        logMetacat.debug("Entering listFormats()");
736

    
737
        ObjectFormatList objectFormatList = CNodeService.getInstance(request)
738
                .listFormats();
739
        // get the response output stream
740
        OutputStream out = response.getOutputStream();
741
        response.setStatus(200);
742
        response.setContentType("text/xml");
743

    
744
        // style the object with a processing directive
745
        String stylesheet = null;
746
        try {
747
            stylesheet = PropertyService.getProperty("dataone.types.xsl.v2");
748
        } catch (PropertyNotFoundException e) {
749
            logMetacat.warn("Could not locate DataONE types XSLT: "
750
                    + e.getMessage());
751
        }
752

    
753
        TypeMarshaller.marshalTypeToOutputStream(objectFormatList, out,
754
                stylesheet);
755

    
756
    }
757
    
758
    private void listChecksumAlgorithms() throws IOException, ServiceFailure,
759
			NotImplemented, MarshallingException {
760
		logMetacat.debug("Entering listFormats()");
761

    
762
		ChecksumAlgorithmList result = CNodeService.getInstance(request).listChecksumAlgorithms();
763

    
764
		// get the response output stream
765
		OutputStream out = response.getOutputStream();
766
		response.setStatus(200);
767
		response.setContentType("text/xml");
768

    
769
		TypeMarshaller.marshalTypeToOutputStream(result, out);
770

    
771
	}
772
    
773
    /**
774
     * http://mule1.dataone.org/ArchitectureDocs-current/apis/CN_APIs.html#CNRead.describe
775
     * @param pid
776
     * @throws InvalidToken
777
     * @throws ServiceFailure
778
     * @throws NotAuthorized
779
     * @throws NotFound
780
     * @throws NotImplemented
781
     * @throws InvalidRequest
782
     */
783
    private void describeObject(String pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented, InvalidRequest
784
    {
785
        response.setContentType("text/xml");
786
        
787
        Identifier id = new Identifier();
788
        id.setValue(pid);
789
        
790
        DescribeResponse dr = null;
791
        try {
792
            dr = CNodeService.getInstance(request).describe(session, id);
793
        } catch (BaseException e) {
794
        	response.setStatus(e.getCode());
795
        	response.addHeader("DataONE-Exception-Name", e.getClass().getName());
796
            response.addHeader("DataONE-Exception-DetailCode", e.getDetail_code());
797
            response.addHeader("DataONE-Exception-Description", e.getDescription());
798
            response.addHeader("DataONE-Exception-PID", id.getValue());
799
            return;
800
		}
801
        
802
        response.setStatus(200);
803
        //response.addHeader("pid", pid);
804
        response.addHeader("DataONE-Checksum", dr.getDataONE_Checksum().getAlgorithm() + "," + dr.getDataONE_Checksum().getValue());
805
        response.addHeader("Content-Length", dr.getContent_Length() + "");
806
        response.addHeader("Last-Modified", DateTimeMarshaller.serializeDateToUTC(dr.getLast_Modified()));
807
        response.addHeader("DataONE-ObjectFormat", dr.getDataONE_ObjectFormatIdentifier().getValue());
808
        response.addHeader("DataONE-SerialVersion", dr.getSerialVersion().toString());
809

    
810
    }
811
    
812
    /**
813
     * Handle delete 
814
     * @param pid ID of data object to be deleted
815
     * @throws IOException
816
     * @throws InvalidRequest 
817
     * @throws NotImplemented 
818
     * @throws NotFound 
819
     * @throws NotAuthorized 
820
     * @throws ServiceFailure 
821
     * @throws InvalidToken 
822
     * @throws MarshallingException 
823
     */
824
    private void deleteObject(String pid) throws IOException, InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented, InvalidRequest, MarshallingException 
825
    {
826

    
827
        OutputStream out = response.getOutputStream();
828
        response.setStatus(200);
829
        response.setContentType("text/xml");
830

    
831
        Identifier id = new Identifier();
832
        id.setValue(pid);
833

    
834
        logMetacat.debug("Calling delete for identifier " + pid);
835
        CNodeService.getInstance(request).delete(session, id);
836
        TypeMarshaller.marshalTypeToOutputStream(id, out);
837
        
838
    }
839
    
840
    /**
841
     * Archives the given pid
842
     * @param pid
843
     * @throws InvalidToken
844
     * @throws ServiceFailure
845
     * @throws NotAuthorized
846
     * @throws NotFound
847
     * @throws NotImplemented
848
     * @throws IOException
849
     * @throws MarshallingException
850
     */
851
    private void archive(String pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented, IOException, MarshallingException {
852

    
853
        OutputStream out = response.getOutputStream();
854
        response.setStatus(200);
855
        response.setContentType("text/xml");
856

    
857
        Identifier id = new Identifier();
858
        id.setValue(pid);
859

    
860
        logMetacat.debug("Calling archive");
861
        CNodeService.getInstance(request).archive(session, id);
862
        
863
        TypeMarshaller.marshalTypeToOutputStream(id, out);
864
        
865
    }
866

    
867
    /**
868
     * Return the requested object format
869
     * 
870
     * @param fmtidStr
871
     *            the requested format identifier as a string
872
     * @throws NotImplemented
873
     * @throws InsufficientResources
874
     * @throws NotFound
875
     * @throws ServiceFailure
876
     * @throws InvalidRequest
877
     * @throws IOException
878
     * @throws MarshallingException
879
     */
880
    private void getFormat(String fmtidStr) throws InvalidRequest,
881
            ServiceFailure, NotFound, InsufficientResources, NotImplemented,
882
            IOException, MarshallingException {
883
        logMetacat.debug("Entering listFormats()");
884

    
885
        ObjectFormatIdentifier fmtid = new ObjectFormatIdentifier();
886
        fmtid.setValue(fmtidStr);
887

    
888
        // get the specified object format
889
        ObjectFormat objectFormat = CNodeService.getInstance(request)
890
                .getFormat(fmtid);
891

    
892
        OutputStream out = response.getOutputStream();
893
        response.setStatus(200);
894
        response.setContentType("text/xml");
895

    
896
        TypeMarshaller.marshalTypeToOutputStream(objectFormat, out);
897

    
898
    }
899

    
900
    /**
901
     * Adds a new {@link ObjectFormat} to the object format list.
902
     * 
903
     * @param formatIdStr the format identifier
904
     * 
905
     * @throws NotImplemented 
906
     * @throws InvalidRequest 
907
     * @throws ServiceFailure 
908
     * @throws MarshallingException 
909
     * @throws IOException 
910
     * @throws IllegalAccessException 
911
     * @throws InstantiationException 
912
     * @throws NotFound 
913
     * @throws NotAuthorized 
914
     * @throws InvalidToken 
915
     */
916
    private void addFormat(String formatIdStr) 
917
            throws NotImplemented, ServiceFailure, InvalidRequest, InstantiationException, 
918
            IllegalAccessException, IOException, MarshallingException, NotFound, NotAuthorized, InvalidToken {
919
        
920
        logMetacat.debug("addFormat: " + formatIdStr);
921
        
922
        Map<String, File> files = collectMultipartFiles();
923
        File formatFile = files.get("format");
924
        FileInputStream formatStream = new FileInputStream(formatFile);
925
        ObjectFormat objectFormat = TypeMarshaller.unmarshalTypeFromStream(ObjectFormat.class, formatStream);
926
        ObjectFormatIdentifier formatId = new ObjectFormatIdentifier();
927
        formatId.setValue(formatIdStr);
928
        
929
        ObjectFormatIdentifier formatID = CNodeService.getInstance(request).addFormat(session, formatId, objectFormat);
930
        
931
        OutputStream out = response.getOutputStream();
932
        response.setStatus(200);
933
        response.setContentType("text/xml");
934
        TypeMarshaller.marshalTypeToOutputStream(formatID, out);
935
    }
936
    
937
    /**
938
     * Reserve the given Identifier
939
     * 
940
     * @throws InvalidToken
941
     * @throws ServiceFailure
942
     * @throws NotAuthorized
943
     * @throws IdentifierNotUnique
944
     * @throws NotImplemented
945
     * @throws InvalidRequest
946
     */
947
    private void reserve() 
948
        throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, 
949
        NotImplemented, InvalidRequest {
950
        Identifier pid = null;
951
        String scope = null;
952
        String format = null;
953

    
954
        // Parse the params out of the multipart form data
955
        logMetacat.debug("Parsing reserve parameters from the mime multipart entity");
956
        try {
957
            collectMultipartParams();
958
            
959
        } catch (FileUploadException e1) {
960
            String msg = "FileUploadException: Couldn't parse the mime multipart information: " +
961
            e1.getMessage();
962
            logMetacat.debug(msg);
963
            throw new ServiceFailure("4210", msg);
964

    
965
        } catch (IOException e1) {
966
            String msg = "IOException: Couldn't parse the mime multipart information: " +
967
            e1.getMessage();
968
            logMetacat.debug(msg);
969
            throw new ServiceFailure("4210", msg);
970
        
971
        } catch (Exception e1) {
972
            String msg = "Exception: Couldn't parse the mime multipart information: " +
973
            e1.getMessage();
974
            logMetacat.debug(msg);
975
            throw new ServiceFailure("4210", msg);
976

    
977
        }
978
        
979
        // gather the params
980
        try {
981
            String id = multipartparams.get("pid").get(0);
982
            pid = new Identifier();
983
            pid.setValue(id);
984
            
985
        } catch (NullPointerException e) {
986
            String msg = "The 'pid' must be provided as a parameter and was not.";
987
            logMetacat.error(msg);
988
            throw new InvalidRequest("4200", msg);
989
 
990
        }
991
        
992
        // call the implementation
993
        try {
994
            Identifier resultPid = CNodeService.getInstance(request).reserveIdentifier(session, pid);
995
            OutputStream out = response.getOutputStream();
996
            response.setStatus(200);
997
            response.setContentType("text/xml");
998
            // send back the reserved pid
999
            TypeMarshaller.marshalTypeToOutputStream(resultPid, out);
1000
            
1001
        } catch (IOException e) {
1002
            String msg = "Couldn't write the identifier to the response output stream: " +
1003
                e.getMessage();
1004
            logMetacat.debug(msg);
1005
            throw new ServiceFailure("4210", msg);
1006
        
1007
        } catch (MarshallingException e) {
1008
            String msg = "Couldn't marshall the identifier to the response output stream: " +
1009
            e.getMessage();
1010
            logMetacat.debug(msg);
1011
            throw new ServiceFailure("4210", msg);
1012
            
1013
        }
1014
    }
1015

    
1016
    /**
1017
     * 
1018
     * @param id
1019
     * @throws InvalidRequest
1020
     * @throws InvalidToken
1021
     * @throws ServiceFailure
1022
     * @throws NotAuthorized
1023
     * @throws NotFound
1024
     * @throws NotImplemented
1025
     * @throws IOException
1026
     * @throws MarshallingException
1027
     */
1028
    private void resolve(String id) throws InvalidRequest, InvalidToken,
1029
            ServiceFailure, NotAuthorized, NotFound, NotImplemented,
1030
            IOException, MarshallingException {
1031
        Identifier pid = new Identifier();
1032
        pid.setValue(id);
1033
        ObjectLocationList locationList = CNodeService.getInstance(request)
1034
                .resolve(session, pid);
1035
        OutputStream out = response.getOutputStream();
1036
        response.setStatus(200);
1037
        response.setContentType("text/xml");
1038
        TypeMarshaller.marshalTypeToOutputStream(locationList, out);
1039

    
1040
    }
1041

    
1042
    /**
1043
     * Set the owner of a resource
1044
     * 
1045
     * @param id
1046
     * @throws InvalidToken
1047
     * @throws ServiceFailure
1048
     * @throws NotFound
1049
     * @throws NotAuthorized
1050
     * @throws NotImplemented
1051
     * @throws InvalidRequest
1052
     * @throws IllegalAccessException
1053
     * @throws InstantiationException
1054
     * @throws VersionMismatch 
1055
     */
1056
    private void owner(String id) 
1057
        throws InvalidToken, ServiceFailure, NotFound, NotAuthorized, 
1058
        NotImplemented, InvalidRequest, InstantiationException, 
1059
        IllegalAccessException, VersionMismatch {
1060

    
1061
        Identifier pid = new Identifier();
1062
        pid.setValue(id);
1063

    
1064
        long serialVersion = 0L;
1065
        String serialVersionStr = null;
1066
        String userIdStr = null;
1067
        Subject userId = null;
1068
        
1069
        // Parse the params out of the multipart form data
1070
        // Read the incoming data from its Mime Multipart encoding
1071
        logMetacat.debug("Parsing rights holder parameters from the mime multipart entity");
1072
        try {
1073
            collectMultipartParams();
1074
            
1075
        } catch (FileUploadException e1) {
1076
            String msg = "FileUploadException: Couldn't parse the mime multipart information: " +
1077
            e1.getMessage();
1078
            logMetacat.debug(msg);
1079
            throw new ServiceFailure("4490", msg);
1080

    
1081
        } catch (IOException e1) {
1082
            String msg = "IOException: Couldn't parse the mime multipart information: " +
1083
            e1.getMessage();
1084
            logMetacat.debug(msg);
1085
            throw new ServiceFailure("4490", msg);
1086
        
1087
        } catch (Exception e1) {
1088
            String msg = "Exception: Couldn't parse the mime multipart information: " +
1089
            e1.getMessage();
1090
            logMetacat.debug(msg);
1091
            throw new ServiceFailure("4490", msg);
1092

    
1093
        }
1094
        
1095
        // get the serialVersion
1096
        try {
1097
            serialVersionStr = multipartparams.get("serialVersion").get(0);
1098
            serialVersion = new Long(serialVersionStr).longValue();
1099
            
1100
        } catch (NumberFormatException nfe) {
1101
            String msg = "The 'serialVersion' must be provided as a positive integer and was not.";
1102
            logMetacat.error(msg);
1103
            throw new InvalidRequest("4442", msg);
1104
                        
1105
        } catch (NullPointerException e) {
1106
            String msg = "The 'serialVersion' must be provided as a parameter and was not.";
1107
            logMetacat.error(msg);
1108
            throw new InvalidRequest("4442", msg);
1109
            
1110
        }
1111

    
1112
        // get the subject userId that will become the rights holder
1113
        try {
1114
            userIdStr = multipartparams.get("userId").get(0);
1115
            userId = new Subject();
1116
            userId.setValue(userIdStr);
1117
                                    
1118
        } catch (NullPointerException e) {
1119
            String msg = "The 'serialVersion' must be provided as a parameter and was not.";
1120
            logMetacat.error(msg);
1121
            throw new InvalidRequest("4442", msg);
1122
            
1123
        }
1124

    
1125
        // set the rights holder
1126
        Identifier retPid = CNodeService.getInstance(request).setRightsHolder(session, pid, userId, serialVersion);
1127
        
1128
        try {
1129
            OutputStream out = response.getOutputStream();
1130
            response.setStatus(200);
1131
            response.setContentType("text/xml");
1132
            TypeMarshaller.marshalTypeToOutputStream(retPid, out);
1133
            
1134
        } catch (IOException e) {
1135
            String msg = "Couldn't write the identifier to the response output stream: " +
1136
                e.getMessage();
1137
            logMetacat.debug(msg);
1138
            throw new ServiceFailure("4490", msg);
1139
        
1140
        } catch (MarshallingException e) {
1141
            String msg = "Couldn't marshall the identifier to the response output stream: " +
1142
            e.getMessage();
1143
            logMetacat.debug(msg);
1144
            throw new ServiceFailure("4490", msg);
1145
            
1146
        }
1147
    }
1148

    
1149
    /**
1150
     * Processes the authorization check for given id
1151
     * 
1152
     * @param id
1153
     * @return
1154
     * @throws ServiceFailure
1155
     * @throws InvalidToken
1156
     * @throws NotFound
1157
     * @throws NotAuthorized
1158
     * @throws NotImplemented
1159
     * @throws InvalidRequest
1160
     */
1161
    private boolean isAuthorized(String id) throws ServiceFailure,
1162
            InvalidToken, NotFound, NotAuthorized, NotImplemented,
1163
            InvalidRequest {
1164
        Identifier pid = new Identifier();
1165
        pid.setValue(id);
1166
        String permission = params.get("action")[0];
1167
        boolean result = CNodeService.getInstance(request).isAuthorized(
1168
                session, pid, Permission.convert(permission));
1169
        response.setStatus(200);
1170
        response.setContentType("text/xml");
1171
        return result;
1172
    }
1173

    
1174
    /**
1175
     * Register System Metadata without data or metadata object
1176
     * 
1177
     * @param pid
1178
     *            identifier for System Metadata entry
1179
     * @throws MarshallingException
1180
     * @throws FileUploadException
1181
     * @throws IOException
1182
     * @throws InvalidRequest
1183
     * @throws ServiceFailure
1184
     * @throws InvalidSystemMetadata
1185
     * @throws NotAuthorized
1186
     * @throws NotImplemented
1187
     * @throws IllegalAccessException
1188
     * @throws InstantiationException
1189
     */
1190
    protected void registerSystemMetadata()
1191
            throws ServiceFailure, InvalidRequest, IOException,
1192
            FileUploadException, MarshallingException, NotImplemented, NotAuthorized,
1193
            InvalidSystemMetadata, InstantiationException,
1194
            IllegalAccessException {
1195
    	
1196
    	// Read the incoming data from its Mime Multipart encoding
1197
        Map<String, File> files = collectMultipartFiles();
1198
        
1199
    	// get the encoded pid string from the body and make the object
1200
        String pidString = multipartparams.get("pid").get(0);
1201
        Identifier pid = new Identifier();
1202
        pid.setValue(pidString);
1203
        
1204
        logMetacat.debug("registerSystemMetadata: " + pid);
1205

    
1206
        // get the system metadata from the request
1207
        File smFile = files.get("sysmeta");
1208
        FileInputStream sysmeta = new FileInputStream(smFile);
1209
        SystemMetadata systemMetadata = TypeMarshaller.unmarshalTypeFromStream(SystemMetadata.class, sysmeta);
1210

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

    
1214
        OutputStream out = response.getOutputStream();
1215
        response.setStatus(200);
1216
        response.setContentType("text/xml");
1217
        
1218
        TypeMarshaller.marshalTypeToOutputStream(retGuid, out);
1219

    
1220
    }
1221

    
1222
    /**
1223
     * set the access perms on a document
1224
     * 
1225
     * @throws MarshallingException
1226
     * @throws InvalidRequest
1227
     * @throws NotImplemented
1228
     * @throws NotAuthorized
1229
     * @throws NotFound
1230
     * @throws ServiceFailure
1231
     * @throws InvalidToken
1232
     * @throws IllegalAccessException
1233
     * @throws InstantiationException
1234
     * @throws IOException
1235
     * @throws SAXException
1236
     * @throws ParserConfigurationException
1237
     * @throws VersionMismatch 
1238
     */
1239
    protected void setAccess(String pid) throws MarshallingException, InvalidToken,
1240
            ServiceFailure, NotFound, NotAuthorized, NotImplemented,
1241
            InvalidRequest, IOException, InstantiationException,
1242
            IllegalAccessException, ParserConfigurationException, SAXException, VersionMismatch {
1243

    
1244
        long serialVersion = 0L;
1245
        String serialVersionStr = null;
1246
        
1247
        // parse the accessPolicy
1248
        Map<String, File> files = collectMultipartFiles();        
1249
        AccessPolicy accessPolicy = TypeMarshaller.unmarshalTypeFromFile(AccessPolicy.class, files.get("accessPolicy"));;
1250

    
1251
        // get the serialVersion
1252
        try {
1253
            serialVersionStr = multipartparams.get("serialVersion").get(0);
1254
            serialVersion = new Long(serialVersionStr).longValue();
1255

    
1256
        } catch (NumberFormatException nfe) {
1257
            String msg = "The 'serialVersion' must be provided as a positive integer and was not.";
1258
            logMetacat.error(msg);
1259
            throw new InvalidRequest("4402", msg);
1260
            
1261
        } catch (NullPointerException e) {
1262
            String msg = "The 'serialVersion' must be provided as a parameter and was not.";
1263
            logMetacat.error(msg);
1264
            throw new InvalidRequest("4402", msg);
1265

    
1266
        }
1267

    
1268
        Identifier id = new Identifier();
1269
        id.setValue(pid);
1270

    
1271
        CNodeService.getInstance(request).setAccessPolicy(session, id,
1272
                accessPolicy, serialVersion);
1273

    
1274
    }
1275

    
1276
    /**
1277
     * List the objects
1278
     * 
1279
     * @throws NotImplemented
1280
     * @throws InvalidRequest
1281
     * @throws NotAuthorized
1282
     * @throws ServiceFailure
1283
     * @throws InvalidToken
1284
     * @throws NotFound
1285
     * @throws IOException
1286
     * @throws MarshallingException
1287
     * @throws Exception
1288
     */
1289
    private void listObjects() throws InvalidToken, ServiceFailure,
1290
            NotAuthorized, InvalidRequest, NotImplemented, NotFound,
1291
            IOException, MarshallingException {
1292

    
1293
        Date startTime = null;
1294
        Date endTime = null;
1295
        ObjectFormatIdentifier formatId = null;
1296
        Identifier identifier = null;
1297
        //boolean replicaStatus = true;
1298
        NodeReference nodeId = null;
1299
        int start = 0;
1300
        int count = 1000;
1301
        Enumeration<String> paramlist = request.getParameterNames();
1302
        while (paramlist.hasMoreElements()) {
1303
            // parse the params and make the call
1304
            String name = paramlist.nextElement();
1305
            String[] values = request.getParameterValues(name);
1306
            String value = null;
1307
            if (values != null && values.length > 0) {
1308
            	value = values[0];
1309
            	value = EncodingUtilities.decodeString(value);
1310
            }
1311

    
1312
            if (name.equals("fromDate") && value != null) {
1313
                try {
1314
                    startTime = DateTimeMarshaller.deserializeDateToUTC(value);
1315
                } catch (Exception e) {
1316
                    // if we can't parse it, just don't use the startTime param
1317
                    logMetacat.warn("Could not parse fromDate: " + value, e);
1318
                    throw new InvalidRequest("1540", "Could not parse fromDate: " + value+" since "+e.getMessage());
1319
                    //startTime = null;
1320
                }
1321
            } else if (name.equals("toDate") && value != null) {
1322
                try {
1323
                    endTime = DateTimeMarshaller.deserializeDateToUTC(value);
1324
                } catch (Exception e) {
1325
                    // if we can't parse it, just don't use the endTime param
1326
                    logMetacat.warn("Could not parse toDate: " + value, e);
1327
                    throw new InvalidRequest("1540", "Could not parse toDate: " + value+" since "+e.getMessage());
1328
                    //endTime = null;
1329
                }
1330
            } else if (name.equals("formatId") && value != null) {
1331
            	formatId = new ObjectFormatIdentifier();
1332
            	formatId.setValue(value);
1333
            } else if (name.equals("identifier") && value != null) {
1334
            	identifier = new Identifier();
1335
            	identifier.setValue(value);
1336
            /*} else if (name.equals("replicaStatus") && value != null) {
1337
                replicaStatus = Boolean.parseBoolean(value);*/
1338
            } else if (name.equals("nodeId") && value != null) {
1339
                nodeId = new NodeReference();
1340
                nodeId.setValue(value);
1341
                logMetacat.debug("the nodeId value is "+nodeId.getValue());
1342
            } else if (name.equals("start") && value != null) {
1343
                start = Integer.valueOf(value);
1344
            } else if (name.equals("count") && value != null) {
1345
                count = Integer.valueOf(value);
1346
            }
1347
        }
1348
        // make the call
1349
        logMetacat.debug("session: " + session + " fromDate: " + startTime
1350
                + " toDate: " + endTime + " formatId: " + formatId
1351
                + " start: " + start
1352
                + " count: " + count);        
1353

    
1354
        // get the list
1355
        ObjectList ol = CNodeService.getInstance(request).listObjects(session,
1356
                startTime, endTime, formatId, identifier, nodeId, start, count);
1357

    
1358
        // send it
1359
        OutputStream out = response.getOutputStream();
1360
        response.setStatus(200);
1361
        response.setContentType("text/xml");
1362

    
1363
        // style the object with a processing directive
1364
        String stylesheet = null;
1365
        try {
1366
            stylesheet = PropertyService.getProperty("dataone.types.xsl.v2");
1367
        } catch (PropertyNotFoundException e) {
1368
            logMetacat.warn("Could not locate DataONE types XSLT: "
1369
                    + e.getMessage());
1370
        }
1371

    
1372
        // Serialize and write it to the output stream
1373
        TypeMarshaller.marshalTypeToOutputStream(ol, out, stylesheet);
1374
    }
1375

    
1376
    /**
1377
     * Pass the request to get node replication authorization to CNodeService
1378
     * 
1379
     * @param pid
1380
     *            the identifier of the object to get authorization to replicate
1381
     * 
1382
     * @throws NotImplemented
1383
     * @throws NotAuthorized
1384
     * @throws InvalidToken
1385
     * @throws ServiceFailure
1386
     * @throws NotFound
1387
     * @throws InvalidRequest
1388
     */
1389
    public boolean isNodeAuthorized(String pid) throws NotImplemented,
1390
            NotAuthorized, InvalidToken, ServiceFailure, NotFound,
1391
            InvalidRequest {
1392

    
1393
        boolean result = false;
1394
        Subject targetNodeSubject = new Subject();
1395
        String nodeSubject = null;
1396
        String replPermission = null;
1397

    
1398
        // get the pid
1399
        Identifier identifier = new Identifier();
1400
        identifier.setValue(pid);
1401

    
1402
        // get the target node subject
1403
        try {
1404
            nodeSubject = params.get("targetNodeSubject")[0];
1405
            targetNodeSubject.setValue(nodeSubject);
1406

    
1407
        } catch (NullPointerException e) {
1408
            String msg = "The 'targetNodeSubject' must be provided as a parameter and was not.";
1409
            logMetacat.error(msg);
1410
            throw new InvalidRequest("4873", msg);
1411

    
1412
        }
1413

    
1414
        result = CNodeService.getInstance(request).isNodeAuthorized(session, targetNodeSubject, identifier);
1415

    
1416
        response.setStatus(200);
1417
        response.setContentType("text/xml");
1418
        return result;
1419

    
1420
    }
1421

    
1422
    /**
1423
     * Pass the request to set the replication policy to CNodeService
1424
     * 
1425
     * @param pid
1426
     *            the identifier of the object to set the replication policy on
1427
     * 
1428
     * @throws NotImplemented
1429
     * @throws NotFound
1430
     * @throws NotAuthorized
1431
     * @throws ServiceFailure
1432
     * @throws InvalidRequest
1433
     * @throws InvalidToken
1434
     * @throws IOException
1435
     * @throws InstantiationException
1436
     * @throws IllegalAccessException
1437
     * @throws MarshallingException
1438
     * @throws VersionMismatch 
1439
     */
1440
    public boolean setReplicationPolicy(String pid) throws NotImplemented,
1441
            NotFound, NotAuthorized, ServiceFailure, InvalidRequest,
1442
            InvalidToken, IOException, InstantiationException,
1443
            IllegalAccessException, MarshallingException, VersionMismatch {
1444

    
1445
        boolean result = false;
1446
        long serialVersion = 0L;
1447
        String serialVersionStr = null;
1448

    
1449
        Identifier identifier = new Identifier();
1450
        identifier.setValue(pid);
1451

    
1452
        // parse the policy
1453
        Map<String, File> files = collectMultipartFiles();        
1454
        ReplicationPolicy policy = TypeMarshaller.unmarshalTypeFromFile(ReplicationPolicy.class, files.get("policy"));
1455

    
1456
        // get the serialVersion
1457
        try {
1458
            serialVersionStr = multipartparams.get("serialVersion").get(0);
1459
            serialVersion = new Long(serialVersionStr).longValue();
1460

    
1461
        } catch (NullPointerException e) {
1462
            String msg = "The 'serialVersion' must be provided as a parameter and was not.";
1463
            logMetacat.error(msg);
1464
            throw new InvalidRequest("4883", msg);
1465

    
1466
        }
1467
        result = CNodeService.getInstance(request).setReplicationPolicy(
1468
                session, identifier, policy, serialVersion);
1469
        response.setStatus(200);
1470
        response.setContentType("text/xml");
1471
        return result;
1472

    
1473
    }
1474
    
1475
    /**
1476
     * Update the system metadata for a given pid, setting it to be obsoleted
1477
     * by the obsoletedByPid
1478
     *  
1479
     * @param pid
1480
     * @return
1481
     * @throws NotImplemented
1482
     * @throws NotFound
1483
     * @throws NotAuthorized
1484
     * @throws ServiceFailure
1485
     * @throws InvalidRequest
1486
     * @throws InvalidToken
1487
     * @throws InstantiationException
1488
     * @throws IllegalAccessException
1489
     * @throws VersionMismatch
1490
     */
1491
    public boolean setObsoletedBy(String pid) 
1492
        throws NotImplemented, NotFound, NotAuthorized, ServiceFailure, 
1493
        InvalidRequest, InvalidToken, InstantiationException, 
1494
        IllegalAccessException, VersionMismatch {
1495

    
1496
        boolean result = false;
1497
        long serialVersion = 0L;
1498
        String serialVersionStr = null;
1499

    
1500
        Identifier identifier = new Identifier();
1501
        identifier.setValue(pid);
1502
        String obsoletedByPidString = null;
1503
        Identifier obsoletedByPid = null;
1504

    
1505
        // Parse the params out of the multipart form data
1506
        // Read the incoming data from its Mime Multipart encoding
1507
        logMetacat.debug("Parsing rights holder parameters from the mime multipart entity");
1508
        try {
1509
            collectMultipartParams();
1510
            
1511
        } catch (FileUploadException e1) {
1512
            String msg = "FileUploadException: Couldn't parse the mime multipart information: " +
1513
            e1.getMessage();
1514
            logMetacat.debug(msg);
1515
            throw new ServiceFailure("4941", msg);
1516

    
1517
        } catch (IOException e1) {
1518
            String msg = "IOException: Couldn't parse the mime multipart information: " +
1519
            e1.getMessage();
1520
            logMetacat.debug(msg);
1521
            throw new ServiceFailure("4941", msg);
1522
        
1523
        } catch (Exception e1) {
1524
            String msg = "Exception: Couldn't parse the mime multipart information: " +
1525
            e1.getMessage();
1526
            logMetacat.debug(msg);
1527
            throw new ServiceFailure("4941", msg);
1528

    
1529
        }
1530

    
1531
        // get the obsoletedByPid
1532
        try {
1533
            obsoletedByPidString = multipartparams.get("obsoletedByPid").get(0);
1534
            obsoletedByPid = new Identifier();
1535
            obsoletedByPid.setValue(obsoletedByPidString);
1536
        } catch (NullPointerException e) {
1537
            String msg = "The 'obsoletedByPid' must be provided as a parameter and was not.";
1538
            logMetacat.error(msg);
1539
            throw new InvalidRequest("4883", msg);
1540
        }
1541

    
1542
        // get the serialVersion
1543
        try {
1544
            serialVersionStr = multipartparams.get("serialVersion").get(0);
1545
            serialVersion = new Long(serialVersionStr).longValue();
1546
            
1547
        } catch (NumberFormatException nfe) {
1548
            String msg = "The 'serialVersion' must be provided as a positive integer and was not.";
1549
            logMetacat.error(msg);
1550
            throw new InvalidRequest("4942", msg);
1551
                        
1552
        } catch (NullPointerException e) {
1553
            String msg = "The 'serialVersion' must be provided as a parameter and was not.";
1554
            logMetacat.error(msg);
1555
            throw new InvalidRequest("4942", msg);
1556
            
1557
        }
1558
        result = CNodeService.getInstance(request).setObsoletedBy(session,
1559
            identifier, obsoletedByPid, serialVersion);
1560
        response.setStatus(200);
1561
        response.setContentType("text/xml");
1562
        return result;
1563

    
1564
    }
1565
    
1566
    /**
1567
     * Delete the replica entry with the given nodeId for the given pid
1568
     * 
1569
     * @param pid
1570
     * @return
1571
     * @throws NotImplemented
1572
     * @throws NotFound
1573
     * @throws NotAuthorized
1574
     * @throws ServiceFailure
1575
     * @throws InvalidRequest
1576
     * @throws InvalidToken
1577
     * @throws InstantiationException
1578
     * @throws IllegalAccessException
1579
     * @throws VersionMismatch
1580
     */
1581
    public boolean deleteReplica(String pid) 
1582
        throws NotImplemented, NotFound, NotAuthorized, ServiceFailure, 
1583
        InvalidRequest, InvalidToken, InstantiationException, 
1584
        IllegalAccessException, VersionMismatch {
1585

    
1586
        boolean result = false;
1587
        long serialVersion = 0L;
1588
        String serialVersionStr = null;
1589

    
1590
        Identifier identifier = new Identifier();
1591
        identifier.setValue(pid);
1592

    
1593
        NodeReference nodeId = null;
1594
        
1595
        // Parse the params out of the multipart form data
1596
        // Read the incoming data from its Mime Multipart encoding
1597
        logMetacat.debug("Parsing delete replica parameters from the mime multipart entity");
1598
        try {
1599
            collectMultipartParams();
1600
            
1601
        } catch (FileUploadException e1) {
1602
            String msg = "FileUploadException: Couldn't parse the mime multipart information: " +
1603
            e1.getMessage();
1604
            logMetacat.debug(msg);
1605
            throw new ServiceFailure("4951", msg);
1606

    
1607
        } catch (IOException e1) {
1608
            String msg = "IOException: Couldn't parse the mime multipart information: " +
1609
            e1.getMessage();
1610
            logMetacat.debug(msg);
1611
            throw new ServiceFailure("4951", msg);
1612
        
1613
        } catch (Exception e1) {
1614
            String msg = "Exception: Couldn't parse the mime multipart information: " +
1615
            e1.getMessage();
1616
            logMetacat.debug(msg);
1617
            throw new ServiceFailure("4951", msg);
1618

    
1619
        }
1620
        
1621
        // get the nodeId param
1622
        try {
1623
            String nodeIdString = multipartparams.get("nodeId").get(0);
1624
            nodeId = new NodeReference();
1625
            nodeId.setValue(nodeIdString);
1626
            
1627
        } catch (NullPointerException e) {
1628
            String msg = "The 'nodeId' must be provided as a parameter and was not.";
1629
            logMetacat.error(msg);
1630
            throw new InvalidRequest("4952", msg);
1631
        }
1632

    
1633
        // get the serialVersion
1634
        try {
1635
            serialVersionStr = multipartparams.get("serialVersion").get(0);
1636
            serialVersion = new Long(serialVersionStr).longValue();
1637
            
1638
        } catch (NumberFormatException nfe) {
1639
            String msg = "The 'serialVersion' must be provided as a positive integer and was not.";
1640
            logMetacat.error(msg);
1641
            throw new InvalidRequest("4952", msg);
1642
                        
1643
        } catch (NullPointerException e) {
1644
            String msg = "The 'serialVersion' must be provided as a parameter and was not.";
1645
            logMetacat.error(msg);
1646
            throw new InvalidRequest("4952", msg);
1647
            
1648
        }
1649
        result = CNodeService.getInstance(request).deleteReplicationMetadata(
1650
                session, identifier, nodeId, serialVersion);
1651
        response.setStatus(200);
1652
        response.setContentType("text/xml");
1653
        return result;
1654

    
1655
    }
1656

    
1657
    /**
1658
     * Pass the request to set the replication status to CNodeService
1659
     * 
1660
     * @param pid
1661
     *            the identifier of the object to set the replication status on
1662
     * 
1663
     * @throws ServiceFailure
1664
     * @throws NotImplemented
1665
     * @throws InvalidToken
1666
     * @throws NotAuthorized
1667
     * @throws InvalidRequest
1668
     * @throws NotFound
1669
     * @throws MarshallingException 
1670
     * @throws IllegalAccessException 
1671
     * @throws InstantiationException 
1672
     * @throws IOException 
1673
     */
1674
    public boolean setReplicationStatus(String pid) throws ServiceFailure,
1675
            NotImplemented, InvalidToken, NotAuthorized, InvalidRequest,
1676
            NotFound {
1677
        
1678
        boolean result = false;
1679
        Identifier identifier = new Identifier();
1680
        identifier.setValue(pid);
1681
        BaseException failure = null;
1682
        ReplicationStatus status = null;
1683
        String replicationStatus = null;
1684
        NodeReference targetNodeRef = null;
1685
        String targetNode = null;
1686

    
1687
        // Parse the params out of the multipart form data
1688
        // Read the incoming data from its Mime Multipart encoding
1689
        logMetacat.debug("Parsing ReplicaStatus from the mime multipart entity");
1690

    
1691
        try {
1692
        	// parse the failure, if we have it
1693
            Map<String, File> files = collectMultipartFiles();        
1694
            if (files.containsKey("failure")) {
1695
            	failure = ExceptionHandler.deserializeXml(new FileInputStream(files.get("failure")), 
1696
                        "Replication failed for an unknown reason.");
1697
            }
1698
            
1699
        } catch (Exception e2) {
1700
            throw new ServiceFailure("4700", "Couldn't resolve the multipart request: " +
1701
                e2.getMessage());
1702
            
1703
        }
1704
        
1705
        // get the replication status param
1706
        try {
1707
            replicationStatus = multipartparams.get("status").get(0);
1708
            status = ReplicationStatus.convert(replicationStatus);
1709

    
1710
        } catch (NullPointerException npe) {
1711

    
1712
            logMetacat.debug("The 'status' parameter was not found in the "
1713
                    + "multipartparams map.  Trying the params map.");
1714

    
1715
            try {
1716
                replicationStatus = params.get("status")[0];
1717
                status = ReplicationStatus.convert(replicationStatus
1718
                        .toLowerCase());
1719

    
1720
            } catch (Exception e) {
1721
                String msg = "The 'status' must be provided as a parameter and was not.";
1722
                logMetacat.error(msg);
1723
                throw new InvalidRequest("4730", msg);
1724

    
1725
            }
1726

    
1727
        }
1728

    
1729
        // get the target node reference param
1730
        try {
1731
            targetNode = multipartparams.get("nodeRef").get(0);
1732
            targetNodeRef = new NodeReference();
1733
            targetNodeRef.setValue(targetNode);
1734

    
1735
        } catch (NullPointerException e) {
1736
            logMetacat.debug("The 'nodeRef' parameter was not found in the "
1737
                    + "multipartparams map.  Trying the params map.");
1738

    
1739
            try {
1740
                targetNode = params.get("nodeRef")[0];
1741
                targetNodeRef = new NodeReference();
1742
                targetNodeRef.setValue(targetNode);
1743

    
1744
            } catch (Exception e1) {
1745
                String msg = "The 'nodeRef' must be provided as a parameter and was not.";
1746
                logMetacat.error(msg);
1747
                throw new InvalidRequest("4730", msg);
1748

    
1749
            }
1750

    
1751
        }
1752

    
1753
        result = CNodeService.getInstance(request).setReplicationStatus(
1754
                session, identifier, targetNodeRef, status, failure);
1755
        response.setStatus(200);
1756
        response.setContentType("text/xml");
1757
        return result;
1758

    
1759
    }
1760

    
1761
    /**
1762
     * Pass the request to update the replication metadata to CNodeService
1763
     * 
1764
     * @param pid
1765
     *            the identifier of the object to update the replication
1766
     *            metadata on
1767
     * 
1768
     * @throws ServiceFailure
1769
     * @throws NotImplemented
1770
     * @throws InvalidToken
1771
     * @throws NotAuthorized
1772
     * @throws InvalidRequest
1773
     * @throws NotFound
1774
     * @throws VersionMismatch 
1775
     * @throws MarshallingException 
1776
     * @throws IOException 
1777
     * @throws IllegalAccessException 
1778
     * @throws InstantiationException 
1779
     */
1780
    public boolean updateReplicationMetadata(String pid) throws ServiceFailure,
1781
            NotImplemented, InvalidToken, NotAuthorized, InvalidRequest,
1782
            NotFound, VersionMismatch, InstantiationException, IllegalAccessException, IOException, MarshallingException {
1783

    
1784
        boolean result = false;
1785
        long serialVersion = 0L;
1786
        String serialVersionStr = null;
1787
        Identifier identifier = new Identifier();
1788
        identifier.setValue(pid);
1789

    
1790
        // parse the replica
1791
        Map<String, File> files = collectMultipartFiles();        
1792
        Replica replica = TypeMarshaller.unmarshalTypeFromFile(Replica.class, files.get("replicaMetadata"));
1793

    
1794
        // get the serialVersion
1795
        try {
1796
            serialVersionStr = multipartparams.get("serialVersion").get(0);
1797
            serialVersion = new Long(serialVersionStr).longValue();
1798

    
1799
        } catch (NullPointerException e) {
1800
            String msg = "The 'serialVersion' must be provided as a parameter and was not.";
1801
            logMetacat.error(msg);
1802
            throw new InvalidRequest("4853", msg);
1803

    
1804
        }
1805

    
1806
        result = CNodeService.getInstance(request).updateReplicationMetadata(
1807
                session, identifier, replica, serialVersion);
1808
        response.setStatus(200);
1809
        response.setContentType("text/xml");
1810
        return result;
1811

    
1812
    }
1813
    
1814
    /**
1815
     * Update the system metadata for a specified pid
1816
     * @throws ServiceFailure
1817
     * @throws InvalidRequest
1818
     * @throws InstantiationException
1819
     * @throws IllegalAccessException
1820
     * @throws IOException
1821
     * @throws MarshallingException
1822
     * @throws NotImplemented
1823
     * @throws NotAuthorized
1824
     * @throws InvalidSystemMetadata
1825
     * @throws InvalidToken
1826
     */
1827
    protected void updateSystemMetadata() throws ServiceFailure, InvalidRequest, InstantiationException, 
1828
                        IllegalAccessException, IOException, MarshallingException, NotImplemented, NotAuthorized, InvalidSystemMetadata, InvalidToken {
1829
        // Read the incoming data from its Mime Multipart encoding
1830
        Map<String, File> files = collectMultipartFiles();
1831
        
1832
        // get the encoded pid string from the body and make the object
1833
        String pidString = multipartparams.get("pid").get(0);
1834
        Identifier pid = new Identifier();
1835
        pid.setValue(pidString);
1836
        
1837
        logMetacat.debug("updateSystemMetadata: " + pid);
1838

    
1839
        // get the system metadata from the request
1840
        File smFile = files.get("sysmeta");
1841
        FileInputStream sysmeta = new FileInputStream(smFile);
1842
        SystemMetadata systemMetadata = TypeMarshaller.unmarshalTypeFromStream(SystemMetadata.class, sysmeta);
1843

    
1844
        logMetacat.debug("updating system metadata with pid " + pid.getValue());
1845
        
1846
        CNodeService.getInstance(request).updateSystemMetadata(session, pid, systemMetadata);
1847
    }
1848
    
1849
    private void doViews(String format, String pid) {
1850
        
1851
        OutputStream out = null;
1852
        CNodeService cnode = CNodeService.getInstance(request);
1853

    
1854
        try {
1855
            // get a list of views
1856
            if (pid != null) {
1857
                Identifier identifier = new Identifier();
1858
                identifier.setValue(pid);
1859
                InputStream stream = cnode.view(session, format, identifier);
1860

    
1861
                // set the content-type if we have it from the implementation
1862
                if (stream instanceof ContentTypeInputStream) {
1863
                    response.setContentType(((ContentTypeInputStream) stream).getContentType());
1864
                }
1865
                response.setStatus(200);
1866
                out = response.getOutputStream();
1867
                // write the results to the output stream
1868
                IOUtils.copyLarge(stream, out);
1869
                return;
1870
            } else {
1871
                // TODO: list the registered views
1872
                //BaseException ni = new NotImplemented("9999", "MN.listViews() is not implemented at this node");
1873
                //throw ni;
1874
                OptionList list = cnode.listViews(session);
1875
                
1876
                response.setContentType("text/xml");
1877
                response.setStatus(200);
1878
                TypeMarshaller.marshalTypeToOutputStream(list, response.getOutputStream());
1879
            }
1880
            
1881
            
1882
        } catch (BaseException be) {
1883
            // report Exceptions as clearly as possible
1884
            try {
1885
                out = response.getOutputStream();
1886
            } catch (IOException e) {
1887
                logMetacat.error("Could not get output stream from response", e);
1888
            }
1889
            serializeException(be, out);
1890
        } catch (Exception e) {
1891
            // report Exceptions as clearly and generically as possible
1892
            logMetacat.error(e.getClass() + ": " + e.getMessage(), e);
1893
            try {
1894
                out = response.getOutputStream();
1895
            } catch (IOException ioe) {
1896
                logMetacat.error("Could not get output stream from response", ioe);
1897
            }
1898
            ServiceFailure se = new ServiceFailure("0000", e.getMessage());
1899
            serializeException(se, out);
1900
        }
1901
    }
1902

    
1903
}
(1-1/4)