Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *  Copyright: 2000-2011 Regents of the University of California and the
4
 *              National Center for Ecological Analysis and Synthesis
5
 *
6
 *   '$Author:  $'
7
 *     '$Date:  $'
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

    
24
package edu.ucsb.nceas.metacat.dataone;
25

    
26
import java.io.ByteArrayInputStream;
27
import java.io.ByteArrayOutputStream;
28
import java.io.File;
29
import java.io.FileInputStream;
30
import java.io.FileOutputStream;
31
import java.io.IOException;
32
import java.io.InputStream;
33
import java.io.OutputStreamWriter;
34
import java.io.UnsupportedEncodingException;
35
import java.io.Writer;
36
import java.math.BigInteger;
37
import java.net.URISyntaxException;
38
import java.security.NoSuchAlgorithmException;
39
import java.sql.SQLException;
40
import java.util.ArrayList;
41
import java.util.Calendar;
42
import java.util.Date;
43
import java.util.HashSet;
44
import java.util.Hashtable;
45
import java.util.List;
46
import java.util.Map;
47
import java.util.Set;
48
import java.util.Timer;
49
import java.util.UUID;
50
import java.util.Vector;
51

    
52
import javax.servlet.http.HttpServletRequest;
53

    
54
import org.apache.commons.io.IOUtils;
55
import org.apache.log4j.Logger;
56
import org.dataone.client.CNode;
57
import org.dataone.client.D1Client;
58
import org.dataone.client.MNode;
59
import org.dataone.client.auth.CertificateManager;
60
import org.dataone.client.formats.ObjectFormatInfo;
61
import org.dataone.configuration.Settings;
62
import org.dataone.ore.ResourceMapFactory;
63
import org.dataone.service.exceptions.BaseException;
64
import org.dataone.service.exceptions.IdentifierNotUnique;
65
import org.dataone.service.exceptions.InsufficientResources;
66
import org.dataone.service.exceptions.InvalidRequest;
67
import org.dataone.service.exceptions.InvalidSystemMetadata;
68
import org.dataone.service.exceptions.InvalidToken;
69
import org.dataone.service.exceptions.NotAuthorized;
70
import org.dataone.service.exceptions.NotFound;
71
import org.dataone.service.exceptions.NotImplemented;
72
import org.dataone.service.exceptions.ServiceFailure;
73
import org.dataone.service.exceptions.SynchronizationFailed;
74
import org.dataone.service.exceptions.UnsupportedType;
75
import org.dataone.service.mn.tier1.v1.MNCore;
76
import org.dataone.service.mn.tier1.v1.MNRead;
77
import org.dataone.service.mn.tier2.v1.MNAuthorization;
78
import org.dataone.service.mn.tier3.v1.MNStorage;
79
import org.dataone.service.mn.tier4.v1.MNReplication;
80
import org.dataone.service.mn.v1.MNQuery;
81
import org.dataone.service.types.v1.Checksum;
82
import org.dataone.service.types.v1.DescribeResponse;
83
import org.dataone.service.types.v1.Event;
84
import org.dataone.service.types.v1.Identifier;
85
import org.dataone.service.types.v1.Log;
86
import org.dataone.service.types.v1.LogEntry;
87
import org.dataone.service.types.v1.MonitorInfo;
88
import org.dataone.service.types.v1.MonitorList;
89
import org.dataone.service.types.v1.Node;
90
import org.dataone.service.types.v1.NodeList;
91
import org.dataone.service.types.v1.NodeReference;
92
import org.dataone.service.types.v1.NodeState;
93
import org.dataone.service.types.v1.NodeType;
94
import org.dataone.service.types.v1.ObjectFormat;
95
import org.dataone.service.types.v1.ObjectFormatIdentifier;
96
import org.dataone.service.types.v1.ObjectList;
97
import org.dataone.service.types.v1.Permission;
98
import org.dataone.service.types.v1.Ping;
99
import org.dataone.service.types.v1.ReplicationStatus;
100
import org.dataone.service.types.v1.Schedule;
101
import org.dataone.service.types.v1.Service;
102
import org.dataone.service.types.v1.Services;
103
import org.dataone.service.types.v1.Session;
104
import org.dataone.service.types.v1.Subject;
105
import org.dataone.service.types.v1.Synchronization;
106
import org.dataone.service.types.v1.SystemMetadata;
107
import org.dataone.service.types.v1.util.AuthUtils;
108
import org.dataone.service.types.v1.util.ChecksumUtil;
109
import org.dataone.service.types.v1_1.QueryEngineDescription;
110
import org.dataone.service.types.v1_1.QueryEngineList;
111
import org.dataone.service.types.v1_1.QueryField;
112
import org.dataone.service.util.Constants;
113
import org.dspace.foresite.OREException;
114
import org.dspace.foresite.OREParserException;
115
import org.dspace.foresite.ORESerialiserException;
116
import org.dspace.foresite.ResourceMap;
117

    
118
import edu.ucsb.nceas.ezid.EZIDException;
119
import edu.ucsb.nceas.metacat.DBQuery;
120
import edu.ucsb.nceas.metacat.DBTransform;
121
import edu.ucsb.nceas.metacat.EventLog;
122
import edu.ucsb.nceas.metacat.IdentifierManager;
123
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
124
import edu.ucsb.nceas.metacat.MetaCatServlet;
125
import edu.ucsb.nceas.metacat.MetacatHandler;
126

    
127
import edu.ucsb.nceas.metacat.common.query.EnabledQueryEngines;
128
import edu.ucsb.nceas.metacat.common.query.stream.ContentTypeByteArrayInputStream;
129
import edu.ucsb.nceas.metacat.dataone.hazelcast.HazelcastService;
130
import edu.ucsb.nceas.metacat.index.MetacatSolrEngineDescriptionHandler;
131
import edu.ucsb.nceas.metacat.index.MetacatSolrIndex;
132
import edu.ucsb.nceas.metacat.properties.PropertyService;
133
import edu.ucsb.nceas.metacat.shared.MetacatUtilException;
134
import edu.ucsb.nceas.metacat.util.DocumentUtil;
135
import edu.ucsb.nceas.metacat.util.SystemUtil;
136
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
137
import gov.loc.repository.bagit.Bag;
138
import gov.loc.repository.bagit.BagFactory;
139
import gov.loc.repository.bagit.writer.impl.ZipWriter;
140

    
141
/**
142
 * Represents Metacat's implementation of the DataONE Member Node 
143
 * service API. Methods implement the various MN* interfaces, and methods common
144
 * to both Member Node and Coordinating Node interfaces are found in the
145
 * D1NodeService base class.
146
 * 
147
 * Implements:
148
 * MNCore.ping()
149
 * MNCore.getLogRecords()
150
 * MNCore.getObjectStatistics()
151
 * MNCore.getOperationStatistics()
152
 * MNCore.getStatus()
153
 * MNCore.getCapabilities()
154
 * MNRead.get()
155
 * MNRead.getSystemMetadata()
156
 * MNRead.describe()
157
 * MNRead.getChecksum()
158
 * MNRead.listObjects()
159
 * MNRead.synchronizationFailed()
160
 * MNAuthorization.isAuthorized()
161
 * MNAuthorization.setAccessPolicy()
162
 * MNStorage.create()
163
 * MNStorage.update()
164
 * MNStorage.delete()
165
 * MNReplication.replicate()
166
 * 
167
 */
168
public class MNodeService extends D1NodeService 
169
    implements MNAuthorization, MNCore, MNRead, MNReplication, MNStorage, MNQuery {
170

    
171
    //private static final String PATHQUERY = "pathquery";
172
	public static final String UUID_SCHEME = "UUID";
173
	public static final String DOI_SCHEME = "DOI";
174
	private static final String UUID_PREFIX = "urn:uuid:";
175

    
176
	/* the logger instance */
177
    private Logger logMetacat = null;
178
    
179
    /* A reference to a remote Memeber Node */
180
    private MNode mn;
181
    
182
    /* A reference to a Coordinating Node */
183
    private CNode cn;
184

    
185

    
186
    /**
187
     * Singleton accessor to get an instance of MNodeService.
188
     * 
189
     * @return instance - the instance of MNodeService
190
     */
191
    public static MNodeService getInstance(HttpServletRequest request) {
192
        return new MNodeService(request);
193
    }
194

    
195
    /**
196
     * Constructor, private for singleton access
197
     */
198
    private MNodeService(HttpServletRequest request) {
199
        super(request);
200
        logMetacat = Logger.getLogger(MNodeService.class);
201
        
202
        // set the Member Node certificate file location
203
        CertificateManager.getInstance().setCertificateLocation(Settings.getConfiguration().getString("D1Client.certificate.file"));
204
    }
205

    
206
    /**
207
     * Deletes an object from the Member Node, where the object is either a 
208
     * data object or a science metadata object.
209
     * 
210
     * @param session - the Session object containing the credentials for the Subject
211
     * @param pid - The object identifier to be deleted
212
     * 
213
     * @return pid - the identifier of the object used for the deletion
214
     * 
215
     * @throws InvalidToken
216
     * @throws ServiceFailure
217
     * @throws NotAuthorized
218
     * @throws NotFound
219
     * @throws NotImplemented
220
     * @throws InvalidRequest
221
     */
222
    @Override
223
    public Identifier delete(Session session, Identifier pid) 
224
        throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
225

    
226
    	// only admin of  the MN or the CN is allowed a full delete
227
        boolean allowed = false;
228
        allowed = isAdminAuthorized(session);
229
        if (!allowed) { 
230
            throw new NotAuthorized("1320", "The provided identity does not have " + "permission to delete objects on the Node.");
231
        }
232
    	
233
    	// defer to superclass implementation
234
        return super.delete(session, pid);
235
    }
236

    
237
    /**
238
     * Updates an existing object by creating a new object identified by 
239
     * newPid on the Member Node which explicitly obsoletes the object 
240
     * identified by pid through appropriate changes to the SystemMetadata 
241
     * of pid and newPid
242
     * 
243
     * @param session - the Session object containing the credentials for the Subject
244
     * @param pid - The identifier of the object to be updated
245
     * @param object - the new object bytes
246
     * @param sysmeta - the new system metadata describing the object
247
     * 
248
     * @return newPid - the identifier of the new object
249
     * 
250
     * @throws InvalidToken
251
     * @throws ServiceFailure
252
     * @throws NotAuthorized
253
     * @throws NotFound
254
     * @throws NotImplemented
255
     * @throws IdentifierNotUnique
256
     * @throws UnsupportedType
257
     * @throws InsufficientResources
258
     * @throws InvalidSystemMetadata
259
     * @throws InvalidRequest
260
     */
261
    @Override
262
    public Identifier update(Session session, Identifier pid, InputStream object, 
263
        Identifier newPid, SystemMetadata sysmeta) 
264
        throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, 
265
        UnsupportedType, InsufficientResources, NotFound, 
266
        InvalidSystemMetadata, NotImplemented, InvalidRequest {
267

    
268
        String localId = null;
269
        boolean allowed = false;
270
        boolean isScienceMetadata = false;
271
        
272
        if (session == null) {
273
        	throw new InvalidToken("1210", "No session has been provided");
274
        }
275
        Subject subject = session.getSubject();
276

    
277
        // verify the pid is valid format
278
        if (!isValidIdentifier(pid)) {
279
        	throw new InvalidRequest("1202", "The provided identifier is invalid.");
280
        }
281

    
282
        // check for the existing identifier
283
        try {
284
            localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
285
            
286
        } catch (McdbDocNotFoundException e) {
287
            throw new InvalidRequest("1202", "The object with the provided " + 
288
                "identifier was not found.");
289
            
290
        }
291
        
292
        // set the originating node
293
        NodeReference originMemberNode = this.getCapabilities().getIdentifier();
294
        sysmeta.setOriginMemberNode(originMemberNode);
295
        
296
        // set the submitter to match the certificate
297
        sysmeta.setSubmitter(subject);
298
        // set the dates
299
        Date now = Calendar.getInstance().getTime();
300
        sysmeta.setDateSysMetadataModified(now);
301
        sysmeta.setDateUploaded(now);
302
        
303
        // make sure serial version is set to something
304
        BigInteger serialVersion = sysmeta.getSerialVersion();
305
        if (serialVersion == null) {
306
        	sysmeta.setSerialVersion(BigInteger.ZERO);
307
        }
308

    
309
        // does the subject have WRITE ( == update) priveleges on the pid?
310
        allowed = isAuthorized(session, pid, Permission.WRITE);
311

    
312
        if (allowed) {
313
        	
314
        	// check quality of SM
315
        	if (sysmeta.getObsoletedBy() != null) {
316
        		throw new InvalidSystemMetadata("1300", "Cannot include obsoletedBy when updating object");
317
        	}
318
        	if (sysmeta.getObsoletes() != null && !sysmeta.getObsoletes().getValue().equals(pid.getValue())) {
319
        		throw new InvalidSystemMetadata("1300", "The identifier provided in obsoletes does not match old Identifier");
320
        	}
321

    
322
            // get the existing system metadata for the object
323
            SystemMetadata existingSysMeta = getSystemMetadata(session, pid);
324

    
325
            // check for previous update
326
            // see: https://redmine.dataone.org/issues/3336
327
            Identifier existingObsoletedBy = existingSysMeta.getObsoletedBy();
328
            if (existingObsoletedBy != null) {
329
            	throw new InvalidRequest("1202", 
330
            			"The previous identifier has already been made obsolete by: " + existingObsoletedBy.getValue());
331
            }
332
            
333
            // add the newPid to the obsoletedBy list for the existing sysmeta
334
            existingSysMeta.setObsoletedBy(newPid);
335

    
336
            // then update the existing system metadata
337
            updateSystemMetadata(existingSysMeta);
338

    
339
            // prep the new system metadata, add pid to the affected lists
340
            sysmeta.setObsoletes(pid);
341
            //sysmeta.addDerivedFrom(pid);
342

    
343
            isScienceMetadata = isScienceMetadata(sysmeta);
344

    
345
            // do we have XML metadata or a data object?
346
            if (isScienceMetadata) {
347

    
348
                // update the science metadata XML document
349
                // TODO: handle non-XML metadata/data documents (like netCDF)
350
                // TODO: don't put objects into memory using stream to string
351
                String objectAsXML = "";
352
                try {
353
                    objectAsXML = IOUtils.toString(object, "UTF-8");
354
                    // give the old pid so we can calculate the new local id 
355
                    localId = insertOrUpdateDocument(objectAsXML, pid, session, "update");
356
                    // register the newPid and the generated localId
357
                    if (newPid != null) {
358
                        IdentifierManager.getInstance().createMapping(newPid.getValue(), localId);
359

    
360
                    }
361

    
362
                } catch (IOException e) {
363
                    String msg = "The Node is unable to create the object. " + "There was a problem converting the object to XML";
364
                    logMetacat.info(msg);
365
                    throw new ServiceFailure("1310", msg + ": " + e.getMessage());
366

    
367
                }
368

    
369
            } else {
370

    
371
                // update the data object
372
                localId = insertDataObject(object, newPid, session);
373

    
374
            }
375

    
376
            // and insert the new system metadata
377
            insertSystemMetadata(sysmeta);
378

    
379
            // log the update event
380
            EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), subject.getValue(), localId, Event.UPDATE.toString());
381
            
382
            // attempt to register the identifier - it checks if it is a doi
383
            try {
384
    			DOIService.getInstance().registerDOI(sysmeta);
385
    		} catch (EZIDException e) {
386
                throw new ServiceFailure("1190", "Could not register DOI: " + e.getMessage());
387
    		}
388

    
389
        } else {
390
            throw new NotAuthorized("1200", "The provided identity does not have " + "permission to UPDATE the object identified by " + pid.getValue()
391
                    + " on the Member Node.");
392
        }
393

    
394
        return newPid;
395
    }
396

    
397
    public Identifier create(Session session, Identifier pid, InputStream object, SystemMetadata sysmeta) throws InvalidToken, ServiceFailure, NotAuthorized,
398
            IdentifierNotUnique, UnsupportedType, InsufficientResources, InvalidSystemMetadata, NotImplemented, InvalidRequest {
399

    
400
        // check for null session
401
        if (session == null) {
402
          throw new InvalidToken("1110", "Session is required to WRITE to the Node.");
403
        }
404
        // set the submitter to match the certificate
405
        sysmeta.setSubmitter(session.getSubject());
406
        // set the originating node
407
        NodeReference originMemberNode = this.getCapabilities().getIdentifier();
408
        sysmeta.setOriginMemberNode(originMemberNode);
409
        sysmeta.setArchived(false);
410

    
411
        // set the dates
412
        Date now = Calendar.getInstance().getTime();
413
        sysmeta.setDateSysMetadataModified(now);
414
        sysmeta.setDateUploaded(now);
415
        
416
        // set the serial version
417
        sysmeta.setSerialVersion(BigInteger.ZERO);
418

    
419
        // check that we are not attempting to subvert versioning
420
        if (sysmeta.getObsoletes() != null && sysmeta.getObsoletes().getValue() != null) {
421
            throw new InvalidSystemMetadata("1180", 
422
              "The supplied system metadata is invalid. " +
423
              "The obsoletes field cannot have a value when creating entries.");
424
        }
425
        
426
        if (sysmeta.getObsoletedBy() != null && sysmeta.getObsoletedBy().getValue() != null) {
427
            throw new InvalidSystemMetadata("1180", 
428
              "The supplied system metadata is invalid. " +
429
              "The obsoletedBy field cannot have a value when creating entries.");
430
        }
431

    
432
        // call the shared impl
433
        Identifier resultPid = super.create(session, pid, object, sysmeta);
434
        
435
        // attempt to register the identifier - it checks if it is a doi
436
        try {
437
			DOIService.getInstance().registerDOI(sysmeta);
438
		} catch (EZIDException e) {
439
			ServiceFailure sf = new ServiceFailure("1190", "Could not register DOI: " + e.getMessage());
440
			sf.initCause(e);
441
            throw sf;
442
		}
443
        
444
        // return 
445
		return resultPid ;
446
    }
447

    
448
    /**
449
     * Called by a Coordinating Node to request that the Member Node create a 
450
     * copy of the specified object by retrieving it from another Member 
451
     * Node and storing it locally so that it can be made accessible to 
452
     * the DataONE system.
453
     * 
454
     * @param session - the Session object containing the credentials for the Subject
455
     * @param sysmeta - Copy of the CN held system metadata for the object
456
     * @param sourceNode - A reference to node from which the content should be 
457
     *                     retrieved. The reference should be resolved by 
458
     *                     checking the CN node registry.
459
     * 
460
     * @return true if the replication succeeds
461
     * 
462
     * @throws ServiceFailure
463
     * @throws NotAuthorized
464
     * @throws NotImplemented
465
     * @throws UnsupportedType
466
     * @throws InsufficientResources
467
     * @throws InvalidRequest
468
     */
469
    @Override
470
    public boolean replicate(Session session, SystemMetadata sysmeta,
471
            NodeReference sourceNode) throws NotImplemented, ServiceFailure,
472
            NotAuthorized, InvalidRequest, InsufficientResources,
473
            UnsupportedType {
474

    
475
        if (session != null && sysmeta != null && sourceNode != null) {
476
            logMetacat.info("MNodeService.replicate() called with parameters: \n" +
477
                            "\tSession.Subject      = "                           +
478
                            session.getSubject().getValue() + "\n"                +
479
                            "\tidentifier           = "                           + 
480
                            sysmeta.getIdentifier().getValue()                    +
481
                            "\n" + "\tSource NodeReference ="                     +
482
                            sourceNode.getValue());
483
        }
484
        boolean result = false;
485
        String nodeIdStr = null;
486
        NodeReference nodeId = null;
487

    
488
        // get the referenced object
489
        Identifier pid = sysmeta.getIdentifier();
490

    
491
        // get from the membernode
492
        // TODO: switch credentials for the server retrieval?
493
        this.mn = D1Client.getMN(sourceNode);
494
        this.cn = D1Client.getCN();
495
        InputStream object = null;
496
        Session thisNodeSession = null;
497
        SystemMetadata localSystemMetadata = null;
498
        BaseException failure = null;
499
        String localId = null;
500
        
501
        // TODO: check credentials
502
        // cannot be called by public
503
        if (session == null || session.getSubject() == null) {
504
            String msg = "No session was provided to replicate identifier " +
505
            sysmeta.getIdentifier().getValue();
506
            logMetacat.info(msg);
507
            throw new NotAuthorized("2152", msg);
508
            
509
        }
510

    
511

    
512
        // get the local node id
513
        try {
514
            nodeIdStr = PropertyService.getProperty("dataone.nodeId");
515
            nodeId = new NodeReference();
516
            nodeId.setValue(nodeIdStr);
517

    
518
        } catch (PropertyNotFoundException e1) {
519
            String msg = "Couldn't get dataone.nodeId property: " + e1.getMessage();
520
            failure = new ServiceFailure("2151", msg);
521
            setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
522
            logMetacat.error(msg);
523
            return true;
524

    
525
        }
526
        
527

    
528
        try {
529
            // do we already have a replica?
530
            try {
531
                localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
532
                // if we have a local id, get the local object
533
                try {
534
                    object = MetacatHandler.read(localId);
535
                } catch (Exception e) {
536
                	// NOTE: we may already know about this ID because it could be a data file described by a metadata file
537
                	// https://redmine.dataone.org/issues/2572
538
                	// TODO: fix this so that we don't prevent ourselves from getting replicas
539
                	
540
                    // let the CN know that the replication failed
541
                	logMetacat.warn("Object content not found on this node despite having localId: " + localId);
542
                	String msg = "Can't read the object bytes properly, replica is invalid.";
543
                    ServiceFailure serviceFailure = new ServiceFailure("2151", msg);
544
                    setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, serviceFailure);
545
                    logMetacat.warn(msg);
546
                    throw serviceFailure;
547
                    
548
                }
549

    
550
            } catch (McdbDocNotFoundException e) {
551
                logMetacat.info("No replica found. Continuing.");
552
                
553
            }
554
            
555
            // no local replica, get a replica
556
            if ( object == null ) {
557
                // session should be null to use the default certificate
558
                // location set in the Certificate manager
559
                object = mn.getReplica(thisNodeSession, pid);
560
                logMetacat.info("MNodeService.getReplica() called for identifier "
561
                                + pid.getValue());
562

    
563
            }
564

    
565
        } catch (InvalidToken e) {            
566
            String msg = "Could not retrieve object to replicate (InvalidToken): "+ e.getMessage();
567
            failure = new ServiceFailure("2151", msg);
568
            setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
569
            logMetacat.error(msg);
570
            throw new ServiceFailure("2151", msg);
571

    
572
        } catch (NotFound e) {
573
            String msg = "Could not retrieve object to replicate (NotFound): "+ e.getMessage();
574
            failure = new ServiceFailure("2151", msg);
575
            setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
576
            logMetacat.error(msg);
577
            throw new ServiceFailure("2151", msg);
578

    
579
        }
580

    
581
        // verify checksum on the object, if supported
582
        if (object.markSupported()) {
583
            Checksum givenChecksum = sysmeta.getChecksum();
584
            Checksum computedChecksum = null;
585
            try {
586
                computedChecksum = ChecksumUtil.checksum(object, givenChecksum.getAlgorithm());
587
                object.reset();
588

    
589
            } catch (Exception e) {
590
                String msg = "Error computing checksum on replica: " + e.getMessage();
591
                logMetacat.error(msg);
592
                ServiceFailure sf = new ServiceFailure("2151", msg);
593
                sf.initCause(e);
594
                throw sf;
595
            }
596
            if (!givenChecksum.getValue().equals(computedChecksum.getValue())) {
597
                logMetacat.error("Given    checksum for " + pid.getValue() + 
598
                    "is " + givenChecksum.getValue());
599
                logMetacat.error("Computed checksum for " + pid.getValue() + 
600
                    "is " + computedChecksum.getValue());
601
                throw new ServiceFailure("2151",
602
                        "Computed checksum does not match declared checksum");
603
            }
604
        }
605

    
606
        // add it to local store
607
        Identifier retPid;
608
        try {
609
            // skip the MN.create -- this mutates the system metadata and we don't want it to
610
            if ( localId == null ) {
611
                // TODO: this will fail if we already "know" about the identifier
612
            	// FIXME: see https://redmine.dataone.org/issues/2572
613
                retPid = super.create(session, pid, object, sysmeta);
614
                result = (retPid.getValue().equals(pid.getValue()));
615
            }
616
            
617
        } catch (Exception e) {
618
            String msg = "Could not save object to local store (" + e.getClass().getName() + "): " + e.getMessage();
619
            failure = new ServiceFailure("2151", msg);
620
            setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
621
            logMetacat.error(msg);
622
            throw new ServiceFailure("2151", msg);
623
            
624
        }
625

    
626
        // finish by setting the replication status
627
        setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.COMPLETED, null);
628
        return result;
629

    
630
    }
631

    
632
    /**
633
     * Return the object identified by the given object identifier
634
     * 
635
     * @param session - the Session object containing the credentials for the Subject
636
     * @param pid - the object identifier for the given object
637
     * 
638
     * @return inputStream - the input stream of the given object
639
     * 
640
     * @throws InvalidToken
641
     * @throws ServiceFailure
642
     * @throws NotAuthorized
643
     * @throws InvalidRequest
644
     * @throws NotImplemented
645
     */
646
    @Override
647
    public InputStream get(Session session, Identifier pid) 
648
    throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
649

    
650
        return super.get(session, pid);
651

    
652
    }
653

    
654
    /**
655
     * Returns a Checksum for the specified object using an accepted hashing algorithm
656
     * 
657
     * @param session - the Session object containing the credentials for the Subject
658
     * @param pid - the object identifier for the given object
659
     * @param algorithm -  the name of an algorithm that will be used to compute 
660
     *                     a checksum of the bytes of the object
661
     * 
662
     * @return checksum - the checksum of the given object
663
     * 
664
     * @throws InvalidToken
665
     * @throws ServiceFailure
666
     * @throws NotAuthorized
667
     * @throws NotFound
668
     * @throws InvalidRequest
669
     * @throws NotImplemented
670
     */
671
    @Override
672
    public Checksum getChecksum(Session session, Identifier pid, String algorithm) 
673
        throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
674
        InvalidRequest, NotImplemented {
675

    
676
        Checksum checksum = null;
677

    
678
        InputStream inputStream = get(session, pid);
679

    
680
        try {
681
            checksum = ChecksumUtil.checksum(inputStream, algorithm);
682

    
683
        } catch (NoSuchAlgorithmException e) {
684
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned due to an internal error: "
685
                    + e.getMessage());
686
        } catch (IOException e) {
687
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned due to an internal error: "
688
                    + e.getMessage());
689
        }
690

    
691
        if (checksum == null) {
692
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned.");
693
        }
694

    
695
        return checksum;
696
    }
697

    
698
    /**
699
     * Return the system metadata for a given object
700
     * 
701
     * @param session - the Session object containing the credentials for the Subject
702
     * @param pid - the object identifier for the given object
703
     * 
704
     * @return inputStream - the input stream of the given system metadata object
705
     * 
706
     * @throws InvalidToken
707
     * @throws ServiceFailure
708
     * @throws NotAuthorized
709
     * @throws NotFound
710
     * @throws InvalidRequest
711
     * @throws NotImplemented
712
     */
713
    @Override
714
    public SystemMetadata getSystemMetadata(Session session, Identifier pid) 
715
        throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
716
        NotImplemented {
717

    
718
        return super.getSystemMetadata(session, pid);
719
    }
720

    
721
    /**
722
     * Retrieve the list of objects present on the MN that match the calling parameters
723
     * 
724
     * @param session - the Session object containing the credentials for the Subject
725
     * @param startTime - Specifies the beginning of the time range from which 
726
     *                    to return object (>=)
727
     * @param endTime - Specifies the beginning of the time range from which 
728
     *                  to return object (>=)
729
     * @param objectFormat - Restrict results to the specified object format
730
     * @param replicaStatus - Indicates if replicated objects should be returned in the list
731
     * @param start - The zero-based index of the first value, relative to the 
732
     *                first record of the resultset that matches the parameters.
733
     * @param count - The maximum number of entries that should be returned in 
734
     *                the response. The Member Node may return less entries 
735
     *                than specified in this value.
736
     * 
737
     * @return objectList - the list of objects matching the criteria
738
     * 
739
     * @throws InvalidToken
740
     * @throws ServiceFailure
741
     * @throws NotAuthorized
742
     * @throws InvalidRequest
743
     * @throws NotImplemented
744
     */
745
    @Override
746
    public ObjectList listObjects(Session session, Date startTime, Date endTime, ObjectFormatIdentifier objectFormatId, Boolean replicaStatus, Integer start,
747
            Integer count) throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken {
748

    
749
        ObjectList objectList = null;
750

    
751
        try {
752
        	// safeguard against large requests
753
            if (count == null || count > MAXIMUM_DB_RECORD_COUNT) {
754
            	count = MAXIMUM_DB_RECORD_COUNT;
755
            }
756
            objectList = IdentifierManager.getInstance().querySystemMetadata(startTime, endTime, objectFormatId, replicaStatus, start, count);
757
        } catch (Exception e) {
758
            throw new ServiceFailure("1580", "Error querying system metadata: " + e.getMessage());
759
        }
760

    
761
        return objectList;
762
    }
763

    
764
    /**
765
     * Return a description of the node's capabilities and services.
766
     * 
767
     * @return node - the technical capabilities of the Member Node
768
     * 
769
     * @throws ServiceFailure
770
     * @throws NotAuthorized
771
     * @throws InvalidRequest
772
     * @throws NotImplemented
773
     */
774
    @Override
775
    public Node getCapabilities() 
776
        throws NotImplemented, ServiceFailure {
777

    
778
        String nodeName = null;
779
        String nodeId = null;
780
        String subject = null;
781
        String contactSubject = null;
782
        String nodeDesc = null;
783
        String nodeTypeString = null;
784
        NodeType nodeType = null;
785
        String mnCoreServiceVersion = null;
786
        String mnReadServiceVersion = null;
787
        String mnAuthorizationServiceVersion = null;
788
        String mnStorageServiceVersion = null;
789
        String mnReplicationServiceVersion = null;
790

    
791
        boolean nodeSynchronize = false;
792
        boolean nodeReplicate = false;
793
        boolean mnCoreServiceAvailable = false;
794
        boolean mnReadServiceAvailable = false;
795
        boolean mnAuthorizationServiceAvailable = false;
796
        boolean mnStorageServiceAvailable = false;
797
        boolean mnReplicationServiceAvailable = false;
798

    
799
        try {
800
            // get the properties of the node based on configuration information
801
            nodeName = PropertyService.getProperty("dataone.nodeName");
802
            nodeId = PropertyService.getProperty("dataone.nodeId");
803
            subject = PropertyService.getProperty("dataone.subject");
804
            contactSubject = PropertyService.getProperty("dataone.contactSubject");
805
            nodeDesc = PropertyService.getProperty("dataone.nodeDescription");
806
            nodeTypeString = PropertyService.getProperty("dataone.nodeType");
807
            nodeType = NodeType.convert(nodeTypeString);
808
            nodeSynchronize = new Boolean(PropertyService.getProperty("dataone.nodeSynchronize")).booleanValue();
809
            nodeReplicate = new Boolean(PropertyService.getProperty("dataone.nodeReplicate")).booleanValue();
810

    
811
            mnCoreServiceVersion = PropertyService.getProperty("dataone.mnCore.serviceVersion");
812
            mnReadServiceVersion = PropertyService.getProperty("dataone.mnRead.serviceVersion");
813
            mnAuthorizationServiceVersion = PropertyService.getProperty("dataone.mnAuthorization.serviceVersion");
814
            mnStorageServiceVersion = PropertyService.getProperty("dataone.mnStorage.serviceVersion");
815
            mnReplicationServiceVersion = PropertyService.getProperty("dataone.mnReplication.serviceVersion");
816

    
817
            mnCoreServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnCore.serviceAvailable")).booleanValue();
818
            mnReadServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnRead.serviceAvailable")).booleanValue();
819
            mnAuthorizationServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnAuthorization.serviceAvailable")).booleanValue();
820
            mnStorageServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnStorage.serviceAvailable")).booleanValue();
821
            mnReplicationServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnReplication.serviceAvailable")).booleanValue();
822

    
823
            // Set the properties of the node based on configuration information and
824
            // calls to current status methods
825
            String serviceName = SystemUtil.getSecureContextURL() + "/" + PropertyService.getProperty("dataone.serviceName");
826
            Node node = new Node();
827
            node.setBaseURL(serviceName + "/" + nodeTypeString);
828
            node.setDescription(nodeDesc);
829

    
830
            // set the node's health information
831
            node.setState(NodeState.UP);
832
            
833
            // set the ping response to the current value
834
            Ping canPing = new Ping();
835
            canPing.setSuccess(false);
836
            try {
837
            	Date pingDate = ping();
838
                canPing.setSuccess(pingDate != null);
839
            } catch (BaseException e) {
840
                e.printStackTrace();
841
                // guess it can't be pinged
842
            }
843
            
844
            node.setPing(canPing);
845

    
846
            NodeReference identifier = new NodeReference();
847
            identifier.setValue(nodeId);
848
            node.setIdentifier(identifier);
849
            Subject s = new Subject();
850
            s.setValue(subject);
851
            node.addSubject(s);
852
            Subject contact = new Subject();
853
            contact.setValue(contactSubject);
854
            node.addContactSubject(contact);
855
            node.setName(nodeName);
856
            node.setReplicate(nodeReplicate);
857
            node.setSynchronize(nodeSynchronize);
858

    
859
            // services: MNAuthorization, MNCore, MNRead, MNReplication, MNStorage
860
            Services services = new Services();
861

    
862
            Service sMNCore = new Service();
863
            sMNCore.setName("MNCore");
864
            sMNCore.setVersion(mnCoreServiceVersion);
865
            sMNCore.setAvailable(mnCoreServiceAvailable);
866

    
867
            Service sMNRead = new Service();
868
            sMNRead.setName("MNRead");
869
            sMNRead.setVersion(mnReadServiceVersion);
870
            sMNRead.setAvailable(mnReadServiceAvailable);
871

    
872
            Service sMNAuthorization = new Service();
873
            sMNAuthorization.setName("MNAuthorization");
874
            sMNAuthorization.setVersion(mnAuthorizationServiceVersion);
875
            sMNAuthorization.setAvailable(mnAuthorizationServiceAvailable);
876

    
877
            Service sMNStorage = new Service();
878
            sMNStorage.setName("MNStorage");
879
            sMNStorage.setVersion(mnStorageServiceVersion);
880
            sMNStorage.setAvailable(mnStorageServiceAvailable);
881

    
882
            Service sMNReplication = new Service();
883
            sMNReplication.setName("MNReplication");
884
            sMNReplication.setVersion(mnReplicationServiceVersion);
885
            sMNReplication.setAvailable(mnReplicationServiceAvailable);
886

    
887
            services.addService(sMNRead);
888
            services.addService(sMNCore);
889
            services.addService(sMNAuthorization);
890
            services.addService(sMNStorage);
891
            services.addService(sMNReplication);
892
            node.setServices(services);
893

    
894
            // Set the schedule for synchronization
895
            Synchronization synchronization = new Synchronization();
896
            Schedule schedule = new Schedule();
897
            Date now = new Date();
898
            schedule.setYear(PropertyService.getProperty("dataone.nodeSynchronization.schedule.year"));
899
            schedule.setMon(PropertyService.getProperty("dataone.nodeSynchronization.schedule.mon"));
900
            schedule.setMday(PropertyService.getProperty("dataone.nodeSynchronization.schedule.mday"));
901
            schedule.setWday(PropertyService.getProperty("dataone.nodeSynchronization.schedule.wday"));
902
            schedule.setHour(PropertyService.getProperty("dataone.nodeSynchronization.schedule.hour"));
903
            schedule.setMin(PropertyService.getProperty("dataone.nodeSynchronization.schedule.min"));
904
            schedule.setSec(PropertyService.getProperty("dataone.nodeSynchronization.schedule.sec"));
905
            synchronization.setSchedule(schedule);
906
            synchronization.setLastHarvested(now);
907
            synchronization.setLastCompleteHarvest(now);
908
            node.setSynchronization(synchronization);
909

    
910
            node.setType(nodeType);
911
            return node;
912

    
913
        } catch (PropertyNotFoundException pnfe) {
914
            String msg = "MNodeService.getCapabilities(): " + "property not found: " + pnfe.getMessage();
915
            logMetacat.error(msg);
916
            throw new ServiceFailure("2162", msg);
917
        }
918
    }
919

    
920
    /**
921
     * Returns the number of operations that have been serviced by the node 
922
     * over time periods of one and 24 hours.
923
     * 
924
     * @param session - the Session object containing the credentials for the Subject
925
     * @param period - An ISO8601 compatible DateTime range specifying the time 
926
     *                 range for which to return operation statistics.
927
     * @param requestor - Limit to operations performed by given requestor identity.
928
     * @param event -  Enumerated value indicating the type of event being examined
929
     * @param format - Limit to events involving objects of the specified format
930
     * 
931
     * @return the desired log records
932
     * 
933
     * @throws InvalidToken
934
     * @throws ServiceFailure
935
     * @throws NotAuthorized
936
     * @throws InvalidRequest
937
     * @throws NotImplemented
938
     */
939
    public MonitorList getOperationStatistics(Session session, Date startTime, 
940
        Date endTime, Subject requestor, Event event, ObjectFormatIdentifier formatId)
941
        throws NotImplemented, ServiceFailure, NotAuthorized, InsufficientResources, UnsupportedType {
942

    
943
        MonitorList monitorList = new MonitorList();
944

    
945
        try {
946

    
947
            // get log records first
948
            Log logs = getLogRecords(session, startTime, endTime, event, null, 0, null);
949

    
950
            // TODO: aggregate by day or hour -- needs clarification
951
            int count = 1;
952
            for (LogEntry logEntry : logs.getLogEntryList()) {
953
                Identifier pid = logEntry.getIdentifier();
954
                Date logDate = logEntry.getDateLogged();
955
                // if we are filtering by format
956
                if (formatId != null) {
957
                    SystemMetadata sysmeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
958
                    if (!sysmeta.getFormatId().getValue().equals(formatId.getValue())) {
959
                        // does not match
960
                        continue;
961
                    }
962
                }
963
                MonitorInfo item = new MonitorInfo();
964
                item.setCount(count);
965
                item.setDate(new java.sql.Date(logDate.getTime()));
966
                monitorList.addMonitorInfo(item);
967

    
968
            }
969
        } catch (Exception e) {
970
            e.printStackTrace();
971
            throw new ServiceFailure("2081", "Could not retrieve statistics: " + e.getMessage());
972
        }
973

    
974
        return monitorList;
975

    
976
    }
977

    
978
    /**
979
     * A callback method used by a CN to indicate to a MN that it cannot 
980
     * complete synchronization of the science metadata identified by pid.  Log
981
     * the event in the metacat event log.
982
     * 
983
     * @param session
984
     * @param syncFailed
985
     * 
986
     * @throws ServiceFailure
987
     * @throws NotAuthorized
988
     * @throws NotImplemented
989
     */
990
    @Override
991
    public boolean synchronizationFailed(Session session, SynchronizationFailed syncFailed) 
992
        throws NotImplemented, ServiceFailure, NotAuthorized {
993

    
994
        String localId;
995
        Identifier pid;
996
        if ( syncFailed.getPid() != null ) {
997
            pid = new Identifier();
998
            pid.setValue(syncFailed.getPid());
999
            boolean allowed;
1000
            
1001
            //are we allowed? only CNs
1002
            try {
1003
                allowed = isAdminAuthorized(session);
1004
                if ( !allowed ){
1005
                    throw new NotAuthorized("2162", 
1006
                            "Not allowed to call synchronizationFailed() on this node.");
1007
                }
1008
            } catch (InvalidToken e) {
1009
                throw new NotAuthorized("2162", 
1010
                        "Not allowed to call synchronizationFailed() on this node.");
1011

    
1012
            }
1013
            
1014
        } else {
1015
            throw new ServiceFailure("2161", "The identifier cannot be null.");
1016

    
1017
        }
1018
        
1019
        try {
1020
            localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
1021
        } catch (McdbDocNotFoundException e) {
1022
            throw new ServiceFailure("2161", "The identifier specified by " + 
1023
                    syncFailed.getPid() + " was not found on this node.");
1024

    
1025
        }
1026
        // TODO: update the CN URL below when the CNRead.SynchronizationFailed
1027
        // method is changed to include the URL as a parameter
1028
        logMetacat.debug("Synchronization for the object identified by " + 
1029
                pid.getValue() + " failed from " + syncFailed.getNodeId() + 
1030
                " Logging the event to the Metacat EventLog as a 'syncFailed' event.");
1031
        // TODO: use the event type enum when the SYNCHRONIZATION_FAILED event is added
1032
        String principal = Constants.SUBJECT_PUBLIC;
1033
        if (session != null && session.getSubject() != null) {
1034
          principal = session.getSubject().getValue();
1035
        }
1036
        try {
1037
          EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), principal, localId, "synchronization_failed");
1038
        } catch (Exception e) {
1039
            throw new ServiceFailure("2161", "Could not log the error for: " + pid.getValue());
1040
        }
1041
        //EventLog.getInstance().log("CN URL WILL GO HERE", 
1042
        //  session.getSubject().getValue(), localId, Event.SYNCHRONIZATION_FAILED);
1043
        return true;
1044

    
1045
    }
1046

    
1047
    /**
1048
     * Essentially a get() but with different logging behavior
1049
     */
1050
    @Override
1051
    public InputStream getReplica(Session session, Identifier pid) 
1052
        throws NotAuthorized, NotImplemented, ServiceFailure, InvalidToken {
1053

    
1054
        logMetacat.info("MNodeService.getReplica() called.");
1055

    
1056
        // cannot be called by public
1057
        if (session == null) {
1058
        	throw new InvalidToken("2183", "No session was provided.");
1059
        }
1060
        
1061
        logMetacat.info("MNodeService.getReplica() called with parameters: \n" +
1062
             "\tSession.Subject      = " + session.getSubject().getValue() + "\n" +
1063
             "\tIdentifier           = " + pid.getValue());
1064

    
1065
        InputStream inputStream = null; // bytes to be returned
1066
        handler = new MetacatHandler(new Timer());
1067
        boolean allowed = false;
1068
        String localId; // the metacat docid for the pid
1069

    
1070
        // get the local docid from Metacat
1071
        try {
1072
            localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
1073
        } catch (McdbDocNotFoundException e) {
1074
            throw new ServiceFailure("2181", "The object specified by " + 
1075
                    pid.getValue() + " does not exist at this node.");
1076
            
1077
        }
1078

    
1079
        Subject targetNodeSubject = session.getSubject();
1080

    
1081
        // check for authorization to replicate, null session to act as this source MN
1082
        try {
1083
            allowed = D1Client.getCN().isNodeAuthorized(null, targetNodeSubject, pid);
1084
        } catch (InvalidToken e1) {
1085
            throw new ServiceFailure("2181", "Could not determine if node is authorized: " 
1086
                + e1.getMessage());
1087
            
1088
        } catch (NotFound e1) {
1089
            throw new ServiceFailure("2181", "Could not determine if node is authorized: " 
1090
                    + e1.getMessage());
1091

    
1092
        } catch (InvalidRequest e1) {
1093
            throw new ServiceFailure("2181", "Could not determine if node is authorized: " 
1094
                    + e1.getMessage());
1095

    
1096
        }
1097

    
1098
        logMetacat.info("Called D1Client.isNodeAuthorized(). Allowed = " + allowed +
1099
            " for identifier " + pid.getValue());
1100

    
1101
        // if the person is authorized, perform the read
1102
        if (allowed) {
1103
            try {
1104
                inputStream = MetacatHandler.read(localId);
1105
            } catch (Exception e) {
1106
                throw new ServiceFailure("1020", "The object specified by " + 
1107
                    pid.getValue() + "could not be returned due to error: " + e.getMessage());
1108
            }
1109
        }
1110

    
1111
        // if we fail to set the input stream
1112
        if (inputStream == null) {
1113
            throw new ServiceFailure("2181", "The object specified by " + 
1114
                pid.getValue() + "does not exist at this node.");
1115
        }
1116

    
1117
        // log the replica event
1118
        String principal = null;
1119
        if (session.getSubject() != null) {
1120
            principal = session.getSubject().getValue();
1121
        }
1122
        EventLog.getInstance().log(request.getRemoteAddr(), 
1123
            request.getHeader("User-Agent"), principal, localId, "replicate");
1124

    
1125
        return inputStream;
1126
    }
1127

    
1128
    /**
1129
     * A method to notify the Member Node that the authoritative copy of 
1130
     * system metadata on the Coordinating Nodes has changed.
1131
     * 
1132
     * @param session   Session information that contains the identity of the 
1133
     *                  calling user as retrieved from the X.509 certificate 
1134
     *                  which must be traceable to the CILogon service.
1135
     * @param serialVersion   The serialVersion of the system metadata
1136
     * @param dateSysMetaLastModified  The time stamp for when the system metadata was changed
1137
     * @throws NotImplemented
1138
     * @throws ServiceFailure
1139
     * @throws NotAuthorized
1140
     * @throws InvalidRequest
1141
     * @throws InvalidToken
1142
     */
1143
    public boolean systemMetadataChanged(Session session, Identifier pid,
1144
        long serialVersion, Date dateSysMetaLastModified) 
1145
        throws NotImplemented, ServiceFailure, NotAuthorized, InvalidRequest,
1146
        InvalidToken {
1147
        
1148
        // cannot be called by public
1149
        if (session == null) {
1150
        	throw new InvalidToken("2183", "No session was provided.");
1151
        }
1152

    
1153
        SystemMetadata currentLocalSysMeta = null;
1154
        SystemMetadata newSysMeta = null;
1155
        CNode cn = D1Client.getCN();
1156
        NodeList nodeList = null;
1157
        Subject callingSubject = null;
1158
        boolean allowed = false;
1159
        
1160
        // are we allowed to call this?
1161
        callingSubject = session.getSubject();
1162
        nodeList = cn.listNodes();
1163
        
1164
        for(Node node : nodeList.getNodeList()) {
1165
            // must be a CN
1166
            if ( node.getType().equals(NodeType.CN)) {
1167
               List<Subject> subjectList = node.getSubjectList();
1168
               // the calling subject must be in the subject list
1169
               if ( subjectList.contains(callingSubject)) {
1170
                   allowed = true;
1171
                   
1172
               }
1173
               
1174
            }
1175
        }
1176
        
1177
        if (!allowed ) {
1178
            String msg = "The subject identified by " + callingSubject.getValue() +
1179
              " is not authorized to call this service.";
1180
            throw new NotAuthorized("1331", msg);
1181
            
1182
        }
1183
        
1184
        // compare what we have locally to what is sent in the change notification
1185
        try {
1186
            currentLocalSysMeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
1187
             
1188
        } catch (RuntimeException e) {
1189
            String msg = "SystemMetadata for pid " + pid.getValue() +
1190
              " couldn't be updated because it couldn't be found locally: " +
1191
              e.getMessage();
1192
            logMetacat.error(msg);
1193
            ServiceFailure sf = new ServiceFailure("1333", msg);
1194
            sf.initCause(e);
1195
            throw sf; 
1196
        }
1197
        
1198
        if (currentLocalSysMeta.getSerialVersion().longValue() < serialVersion ) {
1199
            try {
1200
                newSysMeta = cn.getSystemMetadata(null, pid);
1201
            } catch (NotFound e) {
1202
                // huh? you just said you had it
1203
            	String msg = "On updating the local copy of system metadata " + 
1204
                "for pid " + pid.getValue() +", the CN reports it is not found." +
1205
                " The error message was: " + e.getMessage();
1206
                logMetacat.error(msg);
1207
                ServiceFailure sf = new ServiceFailure("1333", msg);
1208
                sf.initCause(e);
1209
                throw sf;
1210
            }
1211
            
1212
            // update the local copy of system metadata for the pid
1213
            try {
1214
                HazelcastService.getInstance().getSystemMetadataMap().put(newSysMeta.getIdentifier(), newSysMeta);
1215
                // submit for indexing
1216
                HazelcastService.getInstance().getIndexQueue().add(newSysMeta);
1217
                logMetacat.info("Updated local copy of system metadata for pid " +
1218
                    pid.getValue() + " after change notification from the CN.");
1219
                
1220
            } catch (RuntimeException e) {
1221
                String msg = "SystemMetadata for pid " + pid.getValue() +
1222
                  " couldn't be updated: " +
1223
                  e.getMessage();
1224
                logMetacat.error(msg);
1225
                ServiceFailure sf = new ServiceFailure("1333", msg);
1226
                sf.initCause(e);
1227
                throw sf;
1228
            }
1229
        }
1230
        
1231
        return true;
1232
        
1233
    }
1234
    
1235
    /*
1236
     * Set the replication status for the object on the Coordinating Node
1237
     * 
1238
     * @param session - the session for the this target node
1239
     * @param pid - the identifier of the object being updated
1240
     * @param nodeId - the identifier of this target node
1241
     * @param status - the replication status to set
1242
     * @param failure - the exception to include, if any
1243
     */
1244
    private void setReplicationStatus(Session session, Identifier pid, 
1245
        NodeReference nodeId, ReplicationStatus status, BaseException failure) 
1246
        throws ServiceFailure, NotImplemented, NotAuthorized, 
1247
        InvalidRequest {
1248
        
1249
        // call the CN as the MN to set the replication status
1250
        try {
1251
            this.cn = D1Client.getCN();
1252
            this.cn.setReplicationStatus(session, pid, nodeId,
1253
                    status, failure);
1254
            
1255
        } catch (InvalidToken e) {
1256
        	String msg = "Could not set the replication status for " + pid.getValue() + " on the CN (InvalidToken): " + e.getMessage();
1257
            logMetacat.error(msg);
1258
        	throw new ServiceFailure("2151",
1259
                    msg);
1260
            
1261
        } catch (NotFound e) {
1262
        	String msg = "Could not set the replication status for " + pid.getValue() + " on the CN (NotFound): " + e.getMessage();
1263
            logMetacat.error(msg);
1264
        	throw new ServiceFailure("2151",
1265
                    msg);
1266
            
1267
        }
1268
    }
1269

    
1270
	@Override
1271
	public Identifier generateIdentifier(Session session, String scheme, String fragment)
1272
			throws InvalidToken, ServiceFailure, NotAuthorized, NotImplemented,
1273
			InvalidRequest {
1274
		
1275
		Identifier identifier = new Identifier();
1276
		
1277
		// handle different schemes
1278
		if (scheme.equalsIgnoreCase(UUID_SCHEME)) {
1279
			// UUID
1280
			UUID uuid = UUID.randomUUID();
1281
            identifier.setValue(UUID_PREFIX + uuid.toString());
1282
		} else if (scheme.equalsIgnoreCase(DOI_SCHEME)) {
1283
			// generate a DOI
1284
			try {
1285
				identifier = DOIService.getInstance().generateDOI();
1286
			} catch (EZIDException e) {
1287
				ServiceFailure sf = new ServiceFailure("2191", "Could not generate DOI: " + e.getMessage());
1288
				sf.initCause(e);
1289
				throw sf;
1290
			}
1291
		} else {
1292
			// default if we don't know the scheme
1293
			if (fragment != null) {
1294
				// for now, just autogen with fragment
1295
				String autogenId = DocumentUtil.generateDocumentId(fragment, 0);
1296
				identifier.setValue(autogenId);			
1297
			} else {
1298
				// autogen with no fragment
1299
				String autogenId = DocumentUtil.generateDocumentId(0);
1300
				identifier.setValue(autogenId);
1301
			}
1302
		}
1303
		
1304
		// TODO: reserve the identifier with the CN. We can only do this when
1305
		// 1) the MN is part of a CN cluster
1306
		// 2) the request is from an authenticated user
1307
		
1308
		return identifier;
1309
	}
1310

    
1311
	@Override
1312
	public boolean isAuthorized(Identifier pid, Permission permission)
1313
			throws ServiceFailure, InvalidRequest, InvalidToken, NotFound,
1314
			NotAuthorized, NotImplemented {
1315

    
1316
		return isAuthorized(null, pid, permission);
1317
	}
1318

    
1319
	@Override
1320
	public boolean systemMetadataChanged(Identifier pid, long serialVersion, Date dateSysMetaLastModified)
1321
			throws InvalidToken, ServiceFailure, NotAuthorized, NotImplemented,
1322
			InvalidRequest {
1323

    
1324
		return systemMetadataChanged(null, pid, serialVersion, dateSysMetaLastModified);
1325
	}
1326

    
1327
	@Override
1328
	public Log getLogRecords(Date fromDate, Date toDate, Event event, String pidFilter,
1329
			Integer start, Integer count) throws InvalidRequest, InvalidToken,
1330
			NotAuthorized, NotImplemented, ServiceFailure {
1331

    
1332
		return getLogRecords(null, fromDate, toDate, event, pidFilter, start, count);
1333
	}
1334

    
1335
	@Override
1336
	public DescribeResponse describe(Identifier pid) throws InvalidToken,
1337
			NotAuthorized, NotImplemented, ServiceFailure, NotFound {
1338

    
1339
		return describe(null, pid);
1340
	}
1341

    
1342
	@Override
1343
	public InputStream get(Identifier pid) throws InvalidToken, NotAuthorized,
1344
			NotImplemented, ServiceFailure, NotFound, InsufficientResources {
1345

    
1346
		return get(null, pid);
1347
	}
1348

    
1349
	@Override
1350
	public Checksum getChecksum(Identifier pid, String algorithm)
1351
			throws InvalidRequest, InvalidToken, NotAuthorized, NotImplemented,
1352
			ServiceFailure, NotFound {
1353

    
1354
		return getChecksum(null, pid, algorithm);
1355
	}
1356

    
1357
	@Override
1358
	public SystemMetadata getSystemMetadata(Identifier pid)
1359
			throws InvalidToken, NotAuthorized, NotImplemented, ServiceFailure,
1360
			NotFound {
1361

    
1362
		return getSystemMetadata(null, pid);
1363
	}
1364

    
1365
	@Override
1366
	public ObjectList listObjects(Date startTime, Date endTime,
1367
			ObjectFormatIdentifier objectFormatId, Boolean replicaStatus, Integer start,
1368
			Integer count) throws InvalidRequest, InvalidToken, NotAuthorized,
1369
			NotImplemented, ServiceFailure {
1370

    
1371
		return listObjects(null, startTime, endTime, objectFormatId, replicaStatus, start, count);
1372
	}
1373

    
1374
	@Override
1375
	public boolean synchronizationFailed(SynchronizationFailed syncFailed)
1376
			throws InvalidToken, NotAuthorized, NotImplemented, ServiceFailure {
1377

    
1378
		return synchronizationFailed(null, syncFailed);
1379
	}
1380

    
1381
	@Override
1382
	public InputStream getReplica(Identifier pid) throws InvalidToken,
1383
			NotAuthorized, NotImplemented, ServiceFailure, NotFound,
1384
			InsufficientResources {
1385

    
1386
		return getReplica(null, pid);
1387
	}
1388

    
1389
	@Override
1390
	public boolean replicate(SystemMetadata sysmeta, NodeReference sourceNode)
1391
			throws NotImplemented, ServiceFailure, NotAuthorized,
1392
			InvalidRequest, InvalidToken, InsufficientResources,
1393
			UnsupportedType {
1394

    
1395
		return replicate(null, sysmeta, sourceNode);
1396
	}
1397

    
1398
	@Override
1399
	public Identifier create(Identifier pid, InputStream object,
1400
			SystemMetadata sysmeta) throws IdentifierNotUnique,
1401
			InsufficientResources, InvalidRequest, InvalidSystemMetadata,
1402
			InvalidToken, NotAuthorized, NotImplemented, ServiceFailure,
1403
			UnsupportedType {
1404

    
1405
		return create(null, pid, object, sysmeta);
1406
	}
1407

    
1408
	@Override
1409
	public Identifier delete(Identifier pid) throws InvalidToken,
1410
			ServiceFailure, NotAuthorized, NotFound, NotImplemented {
1411

    
1412
		return delete(null, pid);
1413
	}
1414

    
1415
	@Override
1416
	public Identifier generateIdentifier(String scheme, String fragment)
1417
			throws InvalidToken, ServiceFailure, NotAuthorized, NotImplemented,
1418
			InvalidRequest {
1419

    
1420
		return generateIdentifier(null, scheme, fragment);
1421
	}
1422

    
1423
	@Override
1424
	public Identifier update(Identifier pid, InputStream object,
1425
			Identifier newPid, SystemMetadata sysmeta) throws IdentifierNotUnique,
1426
			InsufficientResources, InvalidRequest, InvalidSystemMetadata,
1427
			InvalidToken, NotAuthorized, NotImplemented, ServiceFailure,
1428
			UnsupportedType, NotFound {
1429

    
1430
		return update(null, pid, object, newPid, sysmeta);
1431
	}
1432

    
1433
	@Override
1434
	public QueryEngineDescription getQueryEngineDescription(String engine)
1435
			throws InvalidToken, ServiceFailure, NotAuthorized, NotImplemented,
1436
			NotFound {
1437
	    if(engine != null && engine.equals(EnabledQueryEngines.PATHQUERYENGINE)) {
1438
	        QueryEngineDescription qed = new QueryEngineDescription();
1439
	        qed.setName(EnabledQueryEngines.PATHQUERYENGINE);
1440
	        qed.setQueryEngineVersion("1.0");
1441
	        qed.addAdditionalInfo("This is the traditional structured query for Metacat");
1442
	        Vector<String> pathsForIndexing = null;
1443
	        try {
1444
	            pathsForIndexing = SystemUtil.getPathsForIndexing();
1445
	        } catch (MetacatUtilException e) {
1446
	            logMetacat.warn("Could not get index paths", e);
1447
	        }
1448
	        for (String fieldName: pathsForIndexing) {
1449
	            QueryField field = new QueryField();
1450
	            field.addDescription("Indexed field for path '" + fieldName + "'");
1451
	            field.setName(fieldName);
1452
	            field.setReturnable(true);
1453
	            field.setSearchable(true);
1454
	            field.setSortable(false);
1455
	            // TODO: determine type and multivaluedness
1456
	            field.setType(String.class.getName());
1457
	            //field.setMultivalued(true);
1458
	            qed.addQueryField(field);
1459
	        }
1460
	        return qed;
1461
	    } else if (engine != null && engine.equals(EnabledQueryEngines.SOLRENGINE)) {
1462
	        if(!EnabledQueryEngines.getInstance().isEnabled(EnabledQueryEngines.SOLRENGINE)) {
1463
                throw new NotImplemented("0000", "MNodeService.getQueryEngineDescription - the query engine "+engine +" hasn't been implemented or has been disabled.");
1464
            }
1465
	        try {
1466
	            QueryEngineDescription qed = MetacatSolrEngineDescriptionHandler.getInstance().getQueryEngineDescritpion();
1467
	            return qed;
1468
	        } catch (Exception e) {
1469
	            e.printStackTrace();
1470
	            throw new ServiceFailure("Solr server error", e.getMessage());
1471
	        }
1472
	    } else {
1473
	        throw new NotFound("404", "The Metacat member node can't find the query engine - "+engine);
1474
	    }
1475
		
1476
	}
1477

    
1478
	@Override
1479
	public QueryEngineList listQueryEngines() throws InvalidToken,
1480
			ServiceFailure, NotAuthorized, NotImplemented {
1481
		QueryEngineList qel = new QueryEngineList();
1482
		//qel.addQueryEngine(EnabledQueryEngines.PATHQUERYENGINE);
1483
		//qel.addQueryEngine(EnabledQueryEngines.SOLRENGINE);
1484
		List<String> enables = EnabledQueryEngines.getInstance().getEnabled();
1485
		for(String name : enables) {
1486
		    qel.addQueryEngine(name);
1487
		}
1488
		return qel;
1489
	}
1490

    
1491
	@Override
1492
	public InputStream query(String engine, String query) throws InvalidToken,
1493
			ServiceFailure, NotAuthorized, InvalidRequest, NotImplemented,
1494
			NotFound {
1495
	    String user = Constants.SUBJECT_PUBLIC;
1496
        String[] groups= null;
1497
        Set<Subject> subjects = null;
1498
        if (session != null) {
1499
            user = session.getSubject().getValue();
1500
            subjects = AuthUtils.authorizedClientSubjects(session);
1501
            if (subjects != null) {
1502
                List<String> groupList = new ArrayList<String>();
1503
                for (Subject subject: subjects) {
1504
                    groupList.add(subject.getValue());
1505
                }
1506
                groups = groupList.toArray(new String[0]);
1507
            }
1508
        } else {
1509
            //add the public user subject to the set 
1510
            Subject subject = new Subject();
1511
            subject.setValue(Constants.SUBJECT_PUBLIC);
1512
            subjects = new HashSet<Subject>();
1513
            subjects.add(subject);
1514
        }
1515
        //System.out.println("====== user is "+user);
1516
        //System.out.println("====== groups are "+groups);
1517
		if (engine != null && engine.equals(EnabledQueryEngines.PATHQUERYENGINE)) {
1518
			try {
1519
				DBQuery queryobj = new DBQuery();
1520
				
1521
				String results = queryobj.performPathquery(query, user, groups);
1522
				ContentTypeByteArrayInputStream ctbais = new ContentTypeByteArrayInputStream(results.getBytes(MetaCatServlet.DEFAULT_ENCODING));
1523
				ctbais.setContentType("text/xml");
1524
				return ctbais;
1525

    
1526
			} catch (Exception e) {
1527
				throw new ServiceFailure("Pathquery error", e.getMessage());
1528
			}
1529
			
1530
		} else if (engine != null && engine.equals(EnabledQueryEngines.SOLRENGINE)) {
1531
		    if(!EnabledQueryEngines.getInstance().isEnabled(EnabledQueryEngines.SOLRENGINE)) {
1532
		        throw new NotImplemented("0000", "MNodeService.query - the query engine "+engine +" hasn't been implemented or has been disabled.");
1533
		    }
1534
		    logMetacat.info("The query is ==================================== \n"+query);
1535
		    try {
1536
		        
1537
                return MetacatSolrIndex.getInstance().query(query, subjects);
1538
            } catch (Exception e) {
1539
                // TODO Auto-generated catch block
1540
                throw new ServiceFailure("Solr server error", e.getMessage());
1541
            } 
1542
		}
1543
		return null;
1544
	}
1545
	
1546
	/**
1547
	 * Given an existing Science Metadata PID, this method mints a DOI
1548
	 * and updates the original object "publishing" the update with the DOI.
1549
	 * This includes updating the ORE map that describes the Science Metadata+data.
1550
	 * TODO: ensure all referenced objects allow public read
1551
	 * 
1552
	 * @see https://projects.ecoinformatics.org/ecoinfo/issues/6014
1553
	 * 
1554
	 * @param originalIdentifier
1555
	 * @param request
1556
	 * @throws InvalidRequest
1557
	 * @throws EZIDException
1558
	 * @throws InvalidToken
1559
	 * @throws NotAuthorized
1560
	 * @throws NotImplemented
1561
	 * @throws ServiceFailure
1562
	 * @throws NotFound
1563
	 * @throws InsufficientResources
1564
	 * @throws IdentifierNotUnique
1565
	 * @throws InvalidSystemMetadata
1566
	 * @throws UnsupportedType
1567
	 * @throws McdbDocNotFoundException 
1568
	 * @throws OREParserException 
1569
	 * @throws URISyntaxException 
1570
	 * @throws OREException 
1571
	 * @throws UnsupportedEncodingException 
1572
	 * @throws ORESerialiserException 
1573
	 * @throws NoSuchAlgorithmException 
1574
	 */
1575
	public Identifier publish(Session session, Identifier originalIdentifier) throws InvalidRequest, EZIDException, InvalidToken, NotAuthorized, NotImplemented, ServiceFailure, NotFound, InsufficientResources, IdentifierNotUnique, InvalidSystemMetadata, UnsupportedType, McdbDocNotFoundException, UnsupportedEncodingException, OREException, URISyntaxException, OREParserException, ORESerialiserException, NoSuchAlgorithmException {
1576
		
1577
		// mint a DOI for the new revision
1578
		Identifier newIdentifier = this.generateIdentifier(session, MNodeService.DOI_SCHEME, null);
1579
		
1580
		// get the original SM and update the values
1581
		SystemMetadata sysmeta = this.getSystemMetadata(session, originalIdentifier);
1582
		sysmeta.setIdentifier(newIdentifier);
1583
		sysmeta.setObsoletes(originalIdentifier);
1584
		sysmeta.setObsoletedBy(null);
1585
		
1586
		// get the bytes
1587
		InputStream inputStream = this.get(session, originalIdentifier);
1588
		
1589
		// update the object
1590
		this.update(session, originalIdentifier, inputStream , newIdentifier, sysmeta);
1591
		
1592
		// TODO: update ORE that references the scimeta
1593
		String localId = IdentifierManager.getInstance().getLocalId(originalIdentifier.getValue());
1594
		Identifier potentialOreIdentifier = new Identifier();
1595
		potentialOreIdentifier.setValue(SystemMetadataFactory.RESOURCE_MAP_PREFIX + localId);
1596
		
1597
		InputStream oreInputStream = null;
1598
		try {
1599
			oreInputStream = this.get(session, potentialOreIdentifier);
1600
		} catch (NotFound nf) {
1601
			// this is probably okay for many sci meta data docs
1602
			logMetacat.warn("No potential ORE map found for: " + potentialOreIdentifier.getValue());
1603
		}
1604
		if (oreInputStream != null) {
1605
			Identifier newOreIdentifier = MNodeService.getInstance(request).generateIdentifier(session, MNodeService.UUID_SCHEME, null);
1606

    
1607
			Map<Identifier, Map<Identifier, List<Identifier>>> resourceMapStructure = ResourceMapFactory.getInstance().parseResourceMap(oreInputStream);
1608
			Map<Identifier, List<Identifier>> sciMetaMap = resourceMapStructure.get(potentialOreIdentifier);
1609
			List<Identifier> dataIdentifiers = sciMetaMap.get(originalIdentifier);
1610
			
1611
			// TODO: ensure all data package objects allow public read
1612

    
1613
			// reconstruct the ORE with the new identifiers
1614
			sciMetaMap.remove(originalIdentifier);
1615
			sciMetaMap.put(newIdentifier, dataIdentifiers);
1616
			
1617
			ResourceMap resourceMap = ResourceMapFactory.getInstance().createResourceMap(newOreIdentifier, sciMetaMap);
1618
			String resourceMapString = ResourceMapFactory.getInstance().serializeResourceMap(resourceMap);
1619
			
1620
			// get the original ORE SM and update the values
1621
			SystemMetadata oreSysMeta = this.getSystemMetadata(session, potentialOreIdentifier);
1622
			oreSysMeta.setIdentifier(newOreIdentifier);
1623
			oreSysMeta.setObsoletes(potentialOreIdentifier);
1624
			oreSysMeta.setObsoletedBy(null);
1625
			oreSysMeta.setSize(BigInteger.valueOf(resourceMapString.getBytes("UTF-8").length));
1626
			oreSysMeta.setChecksum(ChecksumUtil.checksum(resourceMapString.getBytes("UTF-8"), oreSysMeta.getChecksum().getAlgorithm()));
1627
			
1628
			// save the updated ORE
1629
			this.update(
1630
					session, 
1631
					potentialOreIdentifier, 
1632
					new ByteArrayInputStream(resourceMapString.getBytes("UTF-8")), 
1633
					newOreIdentifier, 
1634
					oreSysMeta);
1635
			
1636
		}
1637
		
1638
		return newIdentifier;
1639
	}
1640
	
1641
	/**
1642
	 * Packages the given package in a Bagit collection for download
1643
	 * @param pid
1644
	 * @throws NotImplemented 
1645
	 * @throws NotFound 
1646
	 * @throws NotAuthorized 
1647
	 * @throws ServiceFailure 
1648
	 * @throws InvalidToken 
1649
	 */
1650
	public InputStream getPackage(Session session, Identifier pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
1651
		
1652
		InputStream bagInputStream = null;
1653
		BagFactory bagFactory = new BagFactory();
1654
		Bag bag = bagFactory.createBag();
1655
		
1656
		// track the temp files we use so we can delete them when finished
1657
		List<File> tempFiles = new ArrayList<File>();
1658
		
1659
		// the pids to include in the package
1660
		List<Identifier> packagePids = new ArrayList<Identifier>();
1661
		
1662
		// catch non-D1 service errors and throw as ServiceFailures
1663
		try {
1664
			
1665
			// find the package contents
1666
			SystemMetadata sysMeta = this.getSystemMetadata(session, pid);
1667
			if (ObjectFormatService.getInstance().getFormat(sysMeta.getFormatId()).getFormatType().equals("RESOURCE")) {
1668
				InputStream oreInputStream = this.get(session, pid);
1669
				Map<Identifier, Map<Identifier, List<Identifier>>> resourceMapStructure = ResourceMapFactory.getInstance().parseResourceMap(oreInputStream);
1670
				packagePids.addAll(resourceMapStructure.keySet());
1671
				for (Map<Identifier, List<Identifier>> entries: resourceMapStructure.values()) {
1672
					packagePids.addAll(entries.keySet());
1673
					for (List<Identifier> dataPids: entries.values()) {
1674
						packagePids.addAll(dataPids);
1675
					}
1676
				}
1677
			} else {
1678
				// just the lone pid in this package
1679
				packagePids.add(pid);
1680
			}
1681
	
1682
			// track the pid-to-file mapping
1683
			StringBuffer pidMapping = new StringBuffer();
1684
			// loop through the package contents
1685
			for (Identifier entryPid: packagePids) {
1686
				SystemMetadata entrySysMeta = this.getSystemMetadata(session, entryPid);
1687
				String extension = ObjectFormatInfo.instance().getExtension(entrySysMeta.getFormatId().getValue());
1688
		        String prefix = entryPid.getValue();
1689
		        prefix = "entry";
1690
				File tempFile = File.createTempFile(prefix + ".", extension);
1691
				tempFiles.add(tempFile);
1692
				InputStream entryInputStream = this.get(session, entryPid);
1693
				IOUtils.copy(entryInputStream, new FileOutputStream(tempFile));
1694
				bag.addFileToPayload(tempFile);
1695
				pidMapping.append(entryPid.getValue() + "\t" + "data/" + tempFile.getName() + "\n");
1696
			}
1697
			
1698
			//add the the pid to data file map
1699
			File pidMappingFile = File.createTempFile("pid-mapping.", ".txt");
1700
			IOUtils.write(pidMapping.toString(), new FileOutputStream(pidMappingFile));
1701
			bag.addFileAsTag(pidMappingFile);
1702
	
1703
			bag = bag.makeComplete();
1704
			File bagFile = File.createTempFile("bag.", ".zip");
1705
			// TODO: delete more confidently
1706
			bagFile.deleteOnExit();
1707
			bag.setFile(bagFile);
1708
			ZipWriter zipWriter = new ZipWriter(bagFactory);
1709
			bag.write(zipWriter, bagFile);
1710
			bagFile = bag.getFile();
1711
			bagInputStream = new FileInputStream(bagFile);
1712
			
1713
			// clean up temp entry files
1714
			for (File tf: tempFiles) {
1715
				tf.delete();
1716
			}
1717
		} catch (IOException e) {
1718
			// report as service failure
1719
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
1720
			sf.initCause(e);
1721
			throw sf;
1722
		} catch (OREException e) {
1723
			// report as service failure
1724
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
1725
			sf.initCause(e);
1726
			throw sf;
1727
		} catch (URISyntaxException e) {
1728
			// report as service failure
1729
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
1730
			sf.initCause(e);
1731
			throw sf;
1732
		} catch (OREParserException e) {
1733
			// report as service failure
1734
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
1735
			sf.initCause(e);
1736
			throw sf;
1737
		}
1738
		
1739
		return bagInputStream;
1740

    
1741
	}
1742
	
1743
	/**
1744
	 * Get a rendered view of the object identified by pid.
1745
	 * Uses the registered format given by the format parameter.
1746
	 * Typically, this is structured HTML that can be styled with CSS.
1747
	 * @param session
1748
	 * @param pid
1749
	 * @param format
1750
	 * @return
1751
	 * @throws InvalidToken
1752
	 * @throws ServiceFailure
1753
	 * @throws NotAuthorized
1754
	 * @throws NotFound
1755
	 * @throws NotImplemented
1756
	 */
1757
	public InputStream getView(Session session, Identifier pid, String format) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
1758
		InputStream resultInputStream = null;
1759
		
1760
		SystemMetadata sysMeta = this.getSystemMetadata(session, pid);
1761
		InputStream object = this.get(session, pid);
1762

    
1763
		try {
1764
			// can only transform metadata, really
1765
			ObjectFormat objectFormat = ObjectFormatService.getInstance().getFormat(sysMeta.getFormatId());
1766
			if (objectFormat.getFormatType().equals("METADATA")) {
1767
				// transform
1768
				DBTransform transformer = new DBTransform();
1769
	            String documentContent = IOUtils.toString(object, "UTF-8");
1770
	            String sourceType = objectFormat.getFormatId().getValue();
1771
	            String targetType = "-//W3C//HTML//EN";
1772
	            ByteArrayOutputStream baos = new ByteArrayOutputStream();
1773
	            Writer writer = new OutputStreamWriter(baos , "UTF-8");
1774
	            // TODO: include more params?
1775
	            Hashtable<String, String[]> params = new Hashtable<String, String[]>();
1776
	            params.put("qformat", new String[] {format});
1777
	            transformer.transformXMLDocument(
1778
	                    documentContent , 
1779
	                    sourceType, 
1780
	                    targetType , 
1781
	                    format, 
1782
	                    writer, 
1783
	                    params, 
1784
	                    null //sessionid
1785
	                    );
1786
	            
1787
	            // finally, get the HTML back
1788
	            resultInputStream = new ContentTypeByteArrayInputStream(baos.toByteArray());
1789
	            ((ContentTypeByteArrayInputStream) resultInputStream).setContentType("text/html");
1790
	
1791
			} else {
1792
				// just return the raw bytes
1793
				resultInputStream = object;
1794
			}
1795
		} catch (IOException e) {
1796
			// report as service failure
1797
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
1798
			sf.initCause(e);
1799
			throw sf;
1800
		} catch (PropertyNotFoundException e) {
1801
			// report as service failure
1802
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
1803
			sf.initCause(e);
1804
			throw sf;
1805
		} catch (SQLException e) {
1806
			// report as service failure
1807
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
1808
			sf.initCause(e);
1809
			throw sf;
1810
		} catch (ClassNotFoundException e) {
1811
			// report as service failure
1812
			ServiceFailure sf = new ServiceFailure("1030", e.getMessage());
1813
			sf.initCause(e);
1814
			throw sf;
1815
		}
1816
		
1817
		return resultInputStream;
1818
		
1819
	}
1820
    
1821
}
(4-4/6)