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.IOException;
28
import java.io.InputStream;
29
import java.math.BigInteger;
30
import java.security.NoSuchAlgorithmException;
31
import java.util.ArrayList;
32
import java.util.Calendar;
33
import java.util.Date;
34
import java.util.List;
35
import java.util.Set;
36
import java.util.Timer;
37
import java.util.UUID;
38
import java.util.Vector;
39

    
40
import javax.servlet.http.HttpServletRequest;
41

    
42
import org.apache.commons.io.IOUtils;
43
import org.apache.log4j.Logger;
44
import org.dataone.client.CNode;
45
import org.dataone.client.D1Client;
46
import org.dataone.client.MNode;
47
import org.dataone.client.auth.CertificateManager;
48
import org.dataone.configuration.Settings;
49
import org.dataone.service.exceptions.BaseException;
50
import org.dataone.service.exceptions.IdentifierNotUnique;
51
import org.dataone.service.exceptions.InsufficientResources;
52
import org.dataone.service.exceptions.InvalidRequest;
53
import org.dataone.service.exceptions.InvalidSystemMetadata;
54
import org.dataone.service.exceptions.InvalidToken;
55
import org.dataone.service.exceptions.NotAuthorized;
56
import org.dataone.service.exceptions.NotFound;
57
import org.dataone.service.exceptions.NotImplemented;
58
import org.dataone.service.exceptions.ServiceFailure;
59
import org.dataone.service.exceptions.SynchronizationFailed;
60
import org.dataone.service.exceptions.UnsupportedType;
61
import org.dataone.service.mn.tier1.v1.MNCore;
62
import org.dataone.service.mn.tier1.v1.MNRead;
63
import org.dataone.service.mn.tier2.v1.MNAuthorization;
64
import org.dataone.service.mn.tier3.v1.MNStorage;
65
import org.dataone.service.mn.tier4.v1.MNReplication;
66
import org.dataone.service.mn.v1.MNQuery;
67
import org.dataone.service.types.v1.Checksum;
68
import org.dataone.service.types.v1.DescribeResponse;
69
import org.dataone.service.types.v1.Event;
70
import org.dataone.service.types.v1.Identifier;
71
import org.dataone.service.types.v1.Log;
72
import org.dataone.service.types.v1.LogEntry;
73
import org.dataone.service.types.v1.MonitorInfo;
74
import org.dataone.service.types.v1.MonitorList;
75
import org.dataone.service.types.v1.Node;
76
import org.dataone.service.types.v1.NodeList;
77
import org.dataone.service.types.v1.NodeReference;
78
import org.dataone.service.types.v1.NodeState;
79
import org.dataone.service.types.v1.NodeType;
80
import org.dataone.service.types.v1.ObjectFormatIdentifier;
81
import org.dataone.service.types.v1.ObjectList;
82
import org.dataone.service.types.v1.Permission;
83
import org.dataone.service.types.v1.Ping;
84
import org.dataone.service.types.v1.ReplicationStatus;
85
import org.dataone.service.types.v1.Schedule;
86
import org.dataone.service.types.v1.Service;
87
import org.dataone.service.types.v1.Services;
88
import org.dataone.service.types.v1.Session;
89
import org.dataone.service.types.v1.Subject;
90
import org.dataone.service.types.v1.Synchronization;
91
import org.dataone.service.types.v1.SystemMetadata;
92
import org.dataone.service.types.v1.util.AuthUtils;
93
import org.dataone.service.types.v1.util.ChecksumUtil;
94
import org.dataone.service.types.v1_1.QueryEngineDescription;
95
import org.dataone.service.types.v1_1.QueryEngineList;
96
import org.dataone.service.types.v1_1.QueryField;
97
import org.dataone.service.util.Constants;
98

    
99
import edu.ucsb.nceas.ezid.EZIDException;
100
import edu.ucsb.nceas.metacat.DBQuery;
101
import edu.ucsb.nceas.metacat.EventLog;
102
import edu.ucsb.nceas.metacat.IdentifierManager;
103
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
104
import edu.ucsb.nceas.metacat.MetaCatServlet;
105
import edu.ucsb.nceas.metacat.MetacatHandler;
106
import edu.ucsb.nceas.metacat.dataone.hazelcast.HazelcastService;
107
import edu.ucsb.nceas.metacat.properties.PropertyService;
108
import edu.ucsb.nceas.metacat.shared.MetacatUtilException;
109
import edu.ucsb.nceas.metacat.util.DocumentUtil;
110
import edu.ucsb.nceas.metacat.util.SystemUtil;
111
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
112

    
113
/**
114
 * Represents Metacat's implementation of the DataONE Member Node 
115
 * service API. Methods implement the various MN* interfaces, and methods common
116
 * to both Member Node and Coordinating Node interfaces are found in the
117
 * D1NodeService base class.
118
 * 
119
 * Implements:
120
 * MNCore.ping()
121
 * MNCore.getLogRecords()
122
 * MNCore.getObjectStatistics()
123
 * MNCore.getOperationStatistics()
124
 * MNCore.getStatus()
125
 * MNCore.getCapabilities()
126
 * MNRead.get()
127
 * MNRead.getSystemMetadata()
128
 * MNRead.describe()
129
 * MNRead.getChecksum()
130
 * MNRead.listObjects()
131
 * MNRead.synchronizationFailed()
132
 * MNAuthorization.isAuthorized()
133
 * MNAuthorization.setAccessPolicy()
134
 * MNStorage.create()
135
 * MNStorage.update()
136
 * MNStorage.delete()
137
 * MNReplication.replicate()
138
 * 
139
 */
140
public class MNodeService extends D1NodeService 
141
    implements MNAuthorization, MNCore, MNRead, MNReplication, MNStorage, MNQuery {
142

    
143
    private static final String PATHQUERY = "pathquery";
144
	private static final String UUID_SCHEME = "UUID";
145
	private static final String DOI_SCHEME = "DOI";
146
	private static final String UUID_PREFIX = "urn:uuid:";
147

    
148
	/* the logger instance */
149
    private Logger logMetacat = null;
150
    
151
    /* A reference to a remote Memeber Node */
152
    private MNode mn;
153
    
154
    /* A reference to a Coordinating Node */
155
    private CNode cn;
156

    
157

    
158
    /**
159
     * Singleton accessor to get an instance of MNodeService.
160
     * 
161
     * @return instance - the instance of MNodeService
162
     */
163
    public static MNodeService getInstance(HttpServletRequest request) {
164
        return new MNodeService(request);
165
    }
166

    
167
    /**
168
     * Constructor, private for singleton access
169
     */
170
    private MNodeService(HttpServletRequest request) {
171
        super(request);
172
        logMetacat = Logger.getLogger(MNodeService.class);
173
        
174
        // set the Member Node certificate file location
175
        CertificateManager.getInstance().setCertificateLocation(Settings.getConfiguration().getString("D1Client.certificate.file"));
176
    }
177

    
178
    /**
179
     * Deletes an object from the Member Node, where the object is either a 
180
     * data object or a science metadata object.
181
     * 
182
     * @param session - the Session object containing the credentials for the Subject
183
     * @param pid - The object identifier to be deleted
184
     * 
185
     * @return pid - the identifier of the object used for the deletion
186
     * 
187
     * @throws InvalidToken
188
     * @throws ServiceFailure
189
     * @throws NotAuthorized
190
     * @throws NotFound
191
     * @throws NotImplemented
192
     * @throws InvalidRequest
193
     */
194
    @Override
195
    public Identifier delete(Session session, Identifier pid) 
196
        throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
197

    
198
    	// only admin of  the MN or the CN is allowed a full delete
199
        boolean allowed = false;
200
        allowed = isAdminAuthorized(session);
201
        if (!allowed) { 
202
            throw new NotAuthorized("1320", "The provided identity does not have " + "permission to delete objects on the Node.");
203
        }
204
    	
205
    	// defer to superclass implementation
206
        return super.delete(session, pid);
207
    }
208

    
209
    /**
210
     * Updates an existing object by creating a new object identified by 
211
     * newPid on the Member Node which explicitly obsoletes the object 
212
     * identified by pid through appropriate changes to the SystemMetadata 
213
     * of pid and newPid
214
     * 
215
     * @param session - the Session object containing the credentials for the Subject
216
     * @param pid - The identifier of the object to be updated
217
     * @param object - the new object bytes
218
     * @param sysmeta - the new system metadata describing the object
219
     * 
220
     * @return newPid - the identifier of the new object
221
     * 
222
     * @throws InvalidToken
223
     * @throws ServiceFailure
224
     * @throws NotAuthorized
225
     * @throws NotFound
226
     * @throws NotImplemented
227
     * @throws IdentifierNotUnique
228
     * @throws UnsupportedType
229
     * @throws InsufficientResources
230
     * @throws InvalidSystemMetadata
231
     * @throws InvalidRequest
232
     */
233
    @Override
234
    public Identifier update(Session session, Identifier pid, InputStream object, 
235
        Identifier newPid, SystemMetadata sysmeta) 
236
        throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, 
237
        UnsupportedType, InsufficientResources, NotFound, 
238
        InvalidSystemMetadata, NotImplemented, InvalidRequest {
239

    
240
        String localId = null;
241
        boolean allowed = false;
242
        boolean isScienceMetadata = false;
243
        
244
        if (session == null) {
245
        	throw new InvalidToken("1210", "No session has been provided");
246
        }
247
        Subject subject = session.getSubject();
248

    
249
        // verify the pid is valid format
250
        if (!isValidIdentifier(pid)) {
251
        	throw new InvalidRequest("1202", "The provided identifier is invalid.");
252
        }
253

    
254
        // check for the existing identifier
255
        try {
256
            localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
257
            
258
        } catch (McdbDocNotFoundException e) {
259
            throw new InvalidRequest("1202", "The object with the provided " + 
260
                "identifier was not found.");
261
            
262
        }
263
        
264
        // set the originating node
265
        NodeReference originMemberNode = this.getCapabilities().getIdentifier();
266
        sysmeta.setOriginMemberNode(originMemberNode);
267
        
268
        // set the submitter to match the certificate
269
        sysmeta.setSubmitter(subject);
270
        // set the dates
271
        Date now = Calendar.getInstance().getTime();
272
        sysmeta.setDateSysMetadataModified(now);
273
        sysmeta.setDateUploaded(now);
274
        
275
        // make sure serial version is set to something
276
        BigInteger serialVersion = sysmeta.getSerialVersion();
277
        if (serialVersion == null) {
278
        	sysmeta.setSerialVersion(BigInteger.ZERO);
279
        }
280

    
281
        // does the subject have WRITE ( == update) priveleges on the pid?
282
        allowed = isAuthorized(session, pid, Permission.WRITE);
283

    
284
        if (allowed) {
285
        	
286
        	// check quality of SM
287
        	if (sysmeta.getObsoletedBy() != null) {
288
        		throw new InvalidSystemMetadata("1300", "Cannot include obsoletedBy when updating object");
289
        	}
290
        	if (sysmeta.getObsoletes() != null && !sysmeta.getObsoletes().getValue().equals(pid.getValue())) {
291
        		throw new InvalidSystemMetadata("1300", "The identifier provided in obsoletes does not match old Identifier");
292
        	}
293

    
294
            // get the existing system metadata for the object
295
            SystemMetadata existingSysMeta = getSystemMetadata(session, pid);
296

    
297
            // check for previous update
298
            // see: https://redmine.dataone.org/issues/3336
299
            Identifier existingObsoletedBy = existingSysMeta.getObsoletedBy();
300
            if (existingObsoletedBy != null) {
301
            	throw new InvalidRequest("1202", 
302
            			"The previous identifier has already been made obsolete by: " + existingObsoletedBy.getValue());
303
            }
304
            
305
            // add the newPid to the obsoletedBy list for the existing sysmeta
306
            existingSysMeta.setObsoletedBy(newPid);
307

    
308
            // then update the existing system metadata
309
            updateSystemMetadata(existingSysMeta);
310

    
311
            // prep the new system metadata, add pid to the affected lists
312
            sysmeta.setObsoletes(pid);
313
            //sysmeta.addDerivedFrom(pid);
314

    
315
            isScienceMetadata = isScienceMetadata(sysmeta);
316

    
317
            // do we have XML metadata or a data object?
318
            if (isScienceMetadata) {
319

    
320
                // update the science metadata XML document
321
                // TODO: handle non-XML metadata/data documents (like netCDF)
322
                // TODO: don't put objects into memory using stream to string
323
                String objectAsXML = "";
324
                try {
325
                    objectAsXML = IOUtils.toString(object, "UTF-8");
326
                    // give the old pid so we can calculate the new local id 
327
                    localId = insertOrUpdateDocument(objectAsXML, pid, session, "update");
328
                    // register the newPid and the generated localId
329
                    if (newPid != null) {
330
                        IdentifierManager.getInstance().createMapping(newPid.getValue(), localId);
331

    
332
                    }
333

    
334
                } catch (IOException e) {
335
                    String msg = "The Node is unable to create the object. " + "There was a problem converting the object to XML";
336
                    logMetacat.info(msg);
337
                    throw new ServiceFailure("1310", msg + ": " + e.getMessage());
338

    
339
                }
340

    
341
            } else {
342

    
343
                // update the data object
344
                localId = insertDataObject(object, newPid, session);
345

    
346
            }
347

    
348
            // and insert the new system metadata
349
            insertSystemMetadata(sysmeta);
350

    
351
            // log the update event
352
            EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), subject.getValue(), localId, Event.UPDATE.toString());
353
            
354
            // attempt to register the identifier - it checks if it is a doi
355
            try {
356
    			DOIService.getInstance().registerDOI(sysmeta);
357
    		} catch (EZIDException e) {
358
                throw new ServiceFailure("1190", "Could not register DOI: " + e.getMessage());
359
    		}
360

    
361
        } else {
362
            throw new NotAuthorized("1200", "The provided identity does not have " + "permission to UPDATE the object identified by " + pid.getValue()
363
                    + " on the Member Node.");
364
        }
365

    
366
        return newPid;
367
    }
368

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

    
372
        // check for null session
373
        if (session == null) {
374
          throw new InvalidToken("1110", "Session is required to WRITE to the Node.");
375
        }
376
        // set the submitter to match the certificate
377
        sysmeta.setSubmitter(session.getSubject());
378
        // set the originating node
379
        NodeReference originMemberNode = this.getCapabilities().getIdentifier();
380
        sysmeta.setOriginMemberNode(originMemberNode);
381
        sysmeta.setArchived(false);
382

    
383
        // set the dates
384
        Date now = Calendar.getInstance().getTime();
385
        sysmeta.setDateSysMetadataModified(now);
386
        sysmeta.setDateUploaded(now);
387
        
388
        // set the serial version
389
        sysmeta.setSerialVersion(BigInteger.ZERO);
390

    
391
        // check that we are not attempting to subvert versioning
392
        if (sysmeta.getObsoletes() != null && sysmeta.getObsoletes().getValue() != null) {
393
            throw new InvalidSystemMetadata("1180", 
394
              "The supplied system metadata is invalid. " +
395
              "The obsoletes field cannot have a value when creating entries.");
396
        }
397
        
398
        if (sysmeta.getObsoletedBy() != null && sysmeta.getObsoletedBy().getValue() != null) {
399
            throw new InvalidSystemMetadata("1180", 
400
              "The supplied system metadata is invalid. " +
401
              "The obsoletedBy field cannot have a value when creating entries.");
402
        }
403

    
404
        // call the shared impl
405
        Identifier resultPid = super.create(session, pid, object, sysmeta);
406
        
407
        // attempt to register the identifier - it checks if it is a doi
408
        try {
409
			DOIService.getInstance().registerDOI(sysmeta);
410
		} catch (EZIDException e) {
411
			ServiceFailure sf = new ServiceFailure("1190", "Could not register DOI: " + e.getMessage());
412
			sf.initCause(e);
413
            throw sf;
414
		}
415
        
416
        // return 
417
		return resultPid ;
418
    }
419

    
420
    /**
421
     * Called by a Coordinating Node to request that the Member Node create a 
422
     * copy of the specified object by retrieving it from another Member 
423
     * Node and storing it locally so that it can be made accessible to 
424
     * the DataONE system.
425
     * 
426
     * @param session - the Session object containing the credentials for the Subject
427
     * @param sysmeta - Copy of the CN held system metadata for the object
428
     * @param sourceNode - A reference to node from which the content should be 
429
     *                     retrieved. The reference should be resolved by 
430
     *                     checking the CN node registry.
431
     * 
432
     * @return true if the replication succeeds
433
     * 
434
     * @throws ServiceFailure
435
     * @throws NotAuthorized
436
     * @throws NotImplemented
437
     * @throws UnsupportedType
438
     * @throws InsufficientResources
439
     * @throws InvalidRequest
440
     */
441
    @Override
442
    public boolean replicate(Session session, SystemMetadata sysmeta,
443
            NodeReference sourceNode) throws NotImplemented, ServiceFailure,
444
            NotAuthorized, InvalidRequest, InsufficientResources,
445
            UnsupportedType {
446

    
447
        if (session != null && sysmeta != null && sourceNode != null) {
448
            logMetacat.info("MNodeService.replicate() called with parameters: \n" +
449
                            "\tSession.Subject      = "                           +
450
                            session.getSubject().getValue() + "\n"                +
451
                            "\tidentifier           = "                           + 
452
                            sysmeta.getIdentifier().getValue()                    +
453
                            "\n" + "\tSource NodeReference ="                     +
454
                            sourceNode.getValue());
455
        }
456
        boolean result = false;
457
        String nodeIdStr = null;
458
        NodeReference nodeId = null;
459

    
460
        // get the referenced object
461
        Identifier pid = sysmeta.getIdentifier();
462

    
463
        // get from the membernode
464
        // TODO: switch credentials for the server retrieval?
465
        this.mn = D1Client.getMN(sourceNode);
466
        this.cn = D1Client.getCN();
467
        InputStream object = null;
468
        Session thisNodeSession = null;
469
        SystemMetadata localSystemMetadata = null;
470
        BaseException failure = null;
471
        String localId = null;
472
        
473
        // TODO: check credentials
474
        // cannot be called by public
475
        if (session == null || session.getSubject() == null) {
476
            String msg = "No session was provided to replicate identifier " +
477
            sysmeta.getIdentifier().getValue();
478
            logMetacat.info(msg);
479
            throw new NotAuthorized("2152", msg);
480
            
481
        }
482

    
483

    
484
        // get the local node id
485
        try {
486
            nodeIdStr = PropertyService.getProperty("dataone.nodeId");
487
            nodeId = new NodeReference();
488
            nodeId.setValue(nodeIdStr);
489

    
490
        } catch (PropertyNotFoundException e1) {
491
            String msg = "Couldn't get dataone.nodeId property: " + e1.getMessage();
492
            failure = new ServiceFailure("2151", msg);
493
            setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
494
            logMetacat.error(msg);
495
            return true;
496

    
497
        }
498
        
499

    
500
        try {
501
            // do we already have a replica?
502
            try {
503
                localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
504
                // if we have a local id, get the local object
505
                try {
506
                    object = MetacatHandler.read(localId);
507
                } catch (Exception e) {
508
                	// NOTE: we may already know about this ID because it could be a data file described by a metadata file
509
                	// https://redmine.dataone.org/issues/2572
510
                	// TODO: fix this so that we don't prevent ourselves from getting replicas
511
                	
512
                    // let the CN know that the replication failed
513
                	logMetacat.warn("Object content not found on this node despite having localId: " + localId);
514
                	String msg = "Can't read the object bytes properly, replica is invalid.";
515
                    ServiceFailure serviceFailure = new ServiceFailure("2151", msg);
516
                    setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, serviceFailure);
517
                    logMetacat.warn(msg);
518
                    throw serviceFailure;
519
                    
520
                }
521

    
522
            } catch (McdbDocNotFoundException e) {
523
                logMetacat.info("No replica found. Continuing.");
524
                
525
            }
526
            
527
            // no local replica, get a replica
528
            if ( object == null ) {
529
                // session should be null to use the default certificate
530
                // location set in the Certificate manager
531
                object = mn.getReplica(thisNodeSession, pid);
532
                logMetacat.info("MNodeService.getReplica() called for identifier "
533
                                + pid.getValue());
534

    
535
            }
536

    
537
        } catch (InvalidToken e) {            
538
            String msg = "Could not retrieve object to replicate (InvalidToken): "+ e.getMessage();
539
            failure = new ServiceFailure("2151", msg);
540
            setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
541
            logMetacat.error(msg);
542
            throw new ServiceFailure("2151", msg);
543

    
544
        } catch (NotFound e) {
545
            String msg = "Could not retrieve object to replicate (NotFound): "+ e.getMessage();
546
            failure = new ServiceFailure("2151", msg);
547
            setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
548
            logMetacat.error(msg);
549
            throw new ServiceFailure("2151", msg);
550

    
551
        }
552

    
553
        // verify checksum on the object, if supported
554
        if (object.markSupported()) {
555
            Checksum givenChecksum = sysmeta.getChecksum();
556
            Checksum computedChecksum = null;
557
            try {
558
                computedChecksum = ChecksumUtil.checksum(object, givenChecksum.getAlgorithm());
559
                object.reset();
560

    
561
            } catch (Exception e) {
562
                String msg = "Error computing checksum on replica: " + e.getMessage();
563
                logMetacat.error(msg);
564
                ServiceFailure sf = new ServiceFailure("2151", msg);
565
                sf.initCause(e);
566
                throw sf;
567
            }
568
            if (!givenChecksum.getValue().equals(computedChecksum.getValue())) {
569
                logMetacat.error("Given    checksum for " + pid.getValue() + 
570
                    "is " + givenChecksum.getValue());
571
                logMetacat.error("Computed checksum for " + pid.getValue() + 
572
                    "is " + computedChecksum.getValue());
573
                throw new ServiceFailure("2151",
574
                        "Computed checksum does not match declared checksum");
575
            }
576
        }
577

    
578
        // add it to local store
579
        Identifier retPid;
580
        try {
581
            // skip the MN.create -- this mutates the system metadata and we don't want it to
582
            if ( localId == null ) {
583
                // TODO: this will fail if we already "know" about the identifier
584
            	// FIXME: see https://redmine.dataone.org/issues/2572
585
                retPid = super.create(session, pid, object, sysmeta);
586
                result = (retPid.getValue().equals(pid.getValue()));
587
            }
588
            
589
        } catch (Exception e) {
590
            String msg = "Could not save object to local store (" + e.getClass().getName() + "): " + e.getMessage();
591
            failure = new ServiceFailure("2151", msg);
592
            setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.FAILED, failure);
593
            logMetacat.error(msg);
594
            throw new ServiceFailure("2151", msg);
595
            
596
        }
597

    
598
        // finish by setting the replication status
599
        setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.COMPLETED, null);
600
        return result;
601

    
602
    }
603

    
604
    /**
605
     * Return the object identified by the given object identifier
606
     * 
607
     * @param session - the Session object containing the credentials for the Subject
608
     * @param pid - the object identifier for the given object
609
     * 
610
     * @return inputStream - the input stream of the given object
611
     * 
612
     * @throws InvalidToken
613
     * @throws ServiceFailure
614
     * @throws NotAuthorized
615
     * @throws InvalidRequest
616
     * @throws NotImplemented
617
     */
618
    @Override
619
    public InputStream get(Session session, Identifier pid) 
620
    throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
621

    
622
        return super.get(session, pid);
623

    
624
    }
625

    
626
    /**
627
     * Returns a Checksum for the specified object using an accepted hashing algorithm
628
     * 
629
     * @param session - the Session object containing the credentials for the Subject
630
     * @param pid - the object identifier for the given object
631
     * @param algorithm -  the name of an algorithm that will be used to compute 
632
     *                     a checksum of the bytes of the object
633
     * 
634
     * @return checksum - the checksum of the given object
635
     * 
636
     * @throws InvalidToken
637
     * @throws ServiceFailure
638
     * @throws NotAuthorized
639
     * @throws NotFound
640
     * @throws InvalidRequest
641
     * @throws NotImplemented
642
     */
643
    @Override
644
    public Checksum getChecksum(Session session, Identifier pid, String algorithm) 
645
        throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
646
        InvalidRequest, NotImplemented {
647

    
648
        Checksum checksum = null;
649

    
650
        InputStream inputStream = get(session, pid);
651

    
652
        try {
653
            checksum = ChecksumUtil.checksum(inputStream, algorithm);
654

    
655
        } catch (NoSuchAlgorithmException e) {
656
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned due to an internal error: "
657
                    + e.getMessage());
658
        } catch (IOException e) {
659
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned due to an internal error: "
660
                    + e.getMessage());
661
        }
662

    
663
        if (checksum == null) {
664
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned.");
665
        }
666

    
667
        return checksum;
668
    }
669

    
670
    /**
671
     * Return the system metadata for a given object
672
     * 
673
     * @param session - the Session object containing the credentials for the Subject
674
     * @param pid - the object identifier for the given object
675
     * 
676
     * @return inputStream - the input stream of the given system metadata object
677
     * 
678
     * @throws InvalidToken
679
     * @throws ServiceFailure
680
     * @throws NotAuthorized
681
     * @throws NotFound
682
     * @throws InvalidRequest
683
     * @throws NotImplemented
684
     */
685
    @Override
686
    public SystemMetadata getSystemMetadata(Session session, Identifier pid) 
687
        throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
688
        NotImplemented {
689

    
690
        return super.getSystemMetadata(session, pid);
691
    }
692

    
693
    /**
694
     * Retrieve the list of objects present on the MN that match the calling parameters
695
     * 
696
     * @param session - the Session object containing the credentials for the Subject
697
     * @param startTime - Specifies the beginning of the time range from which 
698
     *                    to return object (>=)
699
     * @param endTime - Specifies the beginning of the time range from which 
700
     *                  to return object (>=)
701
     * @param objectFormat - Restrict results to the specified object format
702
     * @param replicaStatus - Indicates if replicated objects should be returned in the list
703
     * @param start - The zero-based index of the first value, relative to the 
704
     *                first record of the resultset that matches the parameters.
705
     * @param count - The maximum number of entries that should be returned in 
706
     *                the response. The Member Node may return less entries 
707
     *                than specified in this value.
708
     * 
709
     * @return objectList - the list of objects matching the criteria
710
     * 
711
     * @throws InvalidToken
712
     * @throws ServiceFailure
713
     * @throws NotAuthorized
714
     * @throws InvalidRequest
715
     * @throws NotImplemented
716
     */
717
    @Override
718
    public ObjectList listObjects(Session session, Date startTime, Date endTime, ObjectFormatIdentifier objectFormatId, Boolean replicaStatus, Integer start,
719
            Integer count) throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken {
720

    
721
        ObjectList objectList = null;
722

    
723
        try {
724
        	// safeguard against large requests
725
            if (count == null || count > MAXIMUM_DB_RECORD_COUNT) {
726
            	count = MAXIMUM_DB_RECORD_COUNT;
727
            }
728
            objectList = IdentifierManager.getInstance().querySystemMetadata(startTime, endTime, objectFormatId, replicaStatus, start, count);
729
        } catch (Exception e) {
730
            throw new ServiceFailure("1580", "Error querying system metadata: " + e.getMessage());
731
        }
732

    
733
        return objectList;
734
    }
735

    
736
    /**
737
     * Return a description of the node's capabilities and services.
738
     * 
739
     * @return node - the technical capabilities of the Member Node
740
     * 
741
     * @throws ServiceFailure
742
     * @throws NotAuthorized
743
     * @throws InvalidRequest
744
     * @throws NotImplemented
745
     */
746
    @Override
747
    public Node getCapabilities() 
748
        throws NotImplemented, ServiceFailure {
749

    
750
        String nodeName = null;
751
        String nodeId = null;
752
        String subject = null;
753
        String contactSubject = null;
754
        String nodeDesc = null;
755
        String nodeTypeString = null;
756
        NodeType nodeType = null;
757
        String mnCoreServiceVersion = null;
758
        String mnReadServiceVersion = null;
759
        String mnAuthorizationServiceVersion = null;
760
        String mnStorageServiceVersion = null;
761
        String mnReplicationServiceVersion = null;
762

    
763
        boolean nodeSynchronize = false;
764
        boolean nodeReplicate = false;
765
        boolean mnCoreServiceAvailable = false;
766
        boolean mnReadServiceAvailable = false;
767
        boolean mnAuthorizationServiceAvailable = false;
768
        boolean mnStorageServiceAvailable = false;
769
        boolean mnReplicationServiceAvailable = false;
770

    
771
        try {
772
            // get the properties of the node based on configuration information
773
            nodeName = PropertyService.getProperty("dataone.nodeName");
774
            nodeId = PropertyService.getProperty("dataone.nodeId");
775
            subject = PropertyService.getProperty("dataone.subject");
776
            contactSubject = PropertyService.getProperty("dataone.contactSubject");
777
            nodeDesc = PropertyService.getProperty("dataone.nodeDescription");
778
            nodeTypeString = PropertyService.getProperty("dataone.nodeType");
779
            nodeType = NodeType.convert(nodeTypeString);
780
            nodeSynchronize = new Boolean(PropertyService.getProperty("dataone.nodeSynchronize")).booleanValue();
781
            nodeReplicate = new Boolean(PropertyService.getProperty("dataone.nodeReplicate")).booleanValue();
782

    
783
            mnCoreServiceVersion = PropertyService.getProperty("dataone.mnCore.serviceVersion");
784
            mnReadServiceVersion = PropertyService.getProperty("dataone.mnRead.serviceVersion");
785
            mnAuthorizationServiceVersion = PropertyService.getProperty("dataone.mnAuthorization.serviceVersion");
786
            mnStorageServiceVersion = PropertyService.getProperty("dataone.mnStorage.serviceVersion");
787
            mnReplicationServiceVersion = PropertyService.getProperty("dataone.mnReplication.serviceVersion");
788

    
789
            mnCoreServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnCore.serviceAvailable")).booleanValue();
790
            mnReadServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnRead.serviceAvailable")).booleanValue();
791
            mnAuthorizationServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnAuthorization.serviceAvailable")).booleanValue();
792
            mnStorageServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnStorage.serviceAvailable")).booleanValue();
793
            mnReplicationServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnReplication.serviceAvailable")).booleanValue();
794

    
795
            // Set the properties of the node based on configuration information and
796
            // calls to current status methods
797
            String serviceName = SystemUtil.getSecureContextURL() + "/" + PropertyService.getProperty("dataone.serviceName");
798
            Node node = new Node();
799
            node.setBaseURL(serviceName + "/" + nodeTypeString);
800
            node.setDescription(nodeDesc);
801

    
802
            // set the node's health information
803
            node.setState(NodeState.UP);
804
            
805
            // set the ping response to the current value
806
            Ping canPing = new Ping();
807
            canPing.setSuccess(false);
808
            try {
809
            	Date pingDate = ping();
810
                canPing.setSuccess(pingDate != null);
811
            } catch (BaseException e) {
812
                e.printStackTrace();
813
                // guess it can't be pinged
814
            }
815
            
816
            node.setPing(canPing);
817

    
818
            NodeReference identifier = new NodeReference();
819
            identifier.setValue(nodeId);
820
            node.setIdentifier(identifier);
821
            Subject s = new Subject();
822
            s.setValue(subject);
823
            node.addSubject(s);
824
            Subject contact = new Subject();
825
            contact.setValue(contactSubject);
826
            node.addContactSubject(contact);
827
            node.setName(nodeName);
828
            node.setReplicate(nodeReplicate);
829
            node.setSynchronize(nodeSynchronize);
830

    
831
            // services: MNAuthorization, MNCore, MNRead, MNReplication, MNStorage
832
            Services services = new Services();
833

    
834
            Service sMNCore = new Service();
835
            sMNCore.setName("MNCore");
836
            sMNCore.setVersion(mnCoreServiceVersion);
837
            sMNCore.setAvailable(mnCoreServiceAvailable);
838

    
839
            Service sMNRead = new Service();
840
            sMNRead.setName("MNRead");
841
            sMNRead.setVersion(mnReadServiceVersion);
842
            sMNRead.setAvailable(mnReadServiceAvailable);
843

    
844
            Service sMNAuthorization = new Service();
845
            sMNAuthorization.setName("MNAuthorization");
846
            sMNAuthorization.setVersion(mnAuthorizationServiceVersion);
847
            sMNAuthorization.setAvailable(mnAuthorizationServiceAvailable);
848

    
849
            Service sMNStorage = new Service();
850
            sMNStorage.setName("MNStorage");
851
            sMNStorage.setVersion(mnStorageServiceVersion);
852
            sMNStorage.setAvailable(mnStorageServiceAvailable);
853

    
854
            Service sMNReplication = new Service();
855
            sMNReplication.setName("MNReplication");
856
            sMNReplication.setVersion(mnReplicationServiceVersion);
857
            sMNReplication.setAvailable(mnReplicationServiceAvailable);
858

    
859
            services.addService(sMNRead);
860
            services.addService(sMNCore);
861
            services.addService(sMNAuthorization);
862
            services.addService(sMNStorage);
863
            services.addService(sMNReplication);
864
            node.setServices(services);
865

    
866
            // Set the schedule for synchronization
867
            Synchronization synchronization = new Synchronization();
868
            Schedule schedule = new Schedule();
869
            Date now = new Date();
870
            schedule.setYear(PropertyService.getProperty("dataone.nodeSynchronization.schedule.year"));
871
            schedule.setMon(PropertyService.getProperty("dataone.nodeSynchronization.schedule.mon"));
872
            schedule.setMday(PropertyService.getProperty("dataone.nodeSynchronization.schedule.mday"));
873
            schedule.setWday(PropertyService.getProperty("dataone.nodeSynchronization.schedule.wday"));
874
            schedule.setHour(PropertyService.getProperty("dataone.nodeSynchronization.schedule.hour"));
875
            schedule.setMin(PropertyService.getProperty("dataone.nodeSynchronization.schedule.min"));
876
            schedule.setSec(PropertyService.getProperty("dataone.nodeSynchronization.schedule.sec"));
877
            synchronization.setSchedule(schedule);
878
            synchronization.setLastHarvested(now);
879
            synchronization.setLastCompleteHarvest(now);
880
            node.setSynchronization(synchronization);
881

    
882
            node.setType(nodeType);
883
            return node;
884

    
885
        } catch (PropertyNotFoundException pnfe) {
886
            String msg = "MNodeService.getCapabilities(): " + "property not found: " + pnfe.getMessage();
887
            logMetacat.error(msg);
888
            throw new ServiceFailure("2162", msg);
889
        }
890
    }
891

    
892
    /**
893
     * Returns the number of operations that have been serviced by the node 
894
     * over time periods of one and 24 hours.
895
     * 
896
     * @param session - the Session object containing the credentials for the Subject
897
     * @param period - An ISO8601 compatible DateTime range specifying the time 
898
     *                 range for which to return operation statistics.
899
     * @param requestor - Limit to operations performed by given requestor identity.
900
     * @param event -  Enumerated value indicating the type of event being examined
901
     * @param format - Limit to events involving objects of the specified format
902
     * 
903
     * @return the desired log records
904
     * 
905
     * @throws InvalidToken
906
     * @throws ServiceFailure
907
     * @throws NotAuthorized
908
     * @throws InvalidRequest
909
     * @throws NotImplemented
910
     */
911
    public MonitorList getOperationStatistics(Session session, Date startTime, 
912
        Date endTime, Subject requestor, Event event, ObjectFormatIdentifier formatId)
913
        throws NotImplemented, ServiceFailure, NotAuthorized, InsufficientResources, UnsupportedType {
914

    
915
        MonitorList monitorList = new MonitorList();
916

    
917
        try {
918

    
919
            // get log records first
920
            Log logs = getLogRecords(session, startTime, endTime, event, null, 0, null);
921

    
922
            // TODO: aggregate by day or hour -- needs clarification
923
            int count = 1;
924
            for (LogEntry logEntry : logs.getLogEntryList()) {
925
                Identifier pid = logEntry.getIdentifier();
926
                Date logDate = logEntry.getDateLogged();
927
                // if we are filtering by format
928
                if (formatId != null) {
929
                    SystemMetadata sysmeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
930
                    if (!sysmeta.getFormatId().getValue().equals(formatId.getValue())) {
931
                        // does not match
932
                        continue;
933
                    }
934
                }
935
                MonitorInfo item = new MonitorInfo();
936
                item.setCount(count);
937
                item.setDate(new java.sql.Date(logDate.getTime()));
938
                monitorList.addMonitorInfo(item);
939

    
940
            }
941
        } catch (Exception e) {
942
            e.printStackTrace();
943
            throw new ServiceFailure("2081", "Could not retrieve statistics: " + e.getMessage());
944
        }
945

    
946
        return monitorList;
947

    
948
    }
949

    
950
    /**
951
     * A callback method used by a CN to indicate to a MN that it cannot 
952
     * complete synchronization of the science metadata identified by pid.  Log
953
     * the event in the metacat event log.
954
     * 
955
     * @param session
956
     * @param syncFailed
957
     * 
958
     * @throws ServiceFailure
959
     * @throws NotAuthorized
960
     * @throws NotImplemented
961
     */
962
    @Override
963
    public boolean synchronizationFailed(Session session, SynchronizationFailed syncFailed) 
964
        throws NotImplemented, ServiceFailure, NotAuthorized {
965

    
966
        String localId;
967
        Identifier pid;
968
        if ( syncFailed.getPid() != null ) {
969
            pid = new Identifier();
970
            pid.setValue(syncFailed.getPid());
971
            boolean allowed;
972
            
973
            //are we allowed? only CNs
974
            try {
975
                allowed = isAdminAuthorized(session);
976
                if ( !allowed ){
977
                    throw new NotAuthorized("2162", 
978
                            "Not allowed to call synchronizationFailed() on this node.");
979
                }
980
            } catch (InvalidToken e) {
981
                throw new NotAuthorized("2162", 
982
                        "Not allowed to call synchronizationFailed() on this node.");
983

    
984
            }
985
            
986
        } else {
987
            throw new ServiceFailure("2161", "The identifier cannot be null.");
988

    
989
        }
990
        
991
        try {
992
            localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
993
        } catch (McdbDocNotFoundException e) {
994
            throw new ServiceFailure("2161", "The identifier specified by " + 
995
                    syncFailed.getPid() + " was not found on this node.");
996

    
997
        }
998
        // TODO: update the CN URL below when the CNRead.SynchronizationFailed
999
        // method is changed to include the URL as a parameter
1000
        logMetacat.debug("Synchronization for the object identified by " + 
1001
                pid.getValue() + " failed from " + syncFailed.getNodeId() + 
1002
                " Logging the event to the Metacat EventLog as a 'syncFailed' event.");
1003
        // TODO: use the event type enum when the SYNCHRONIZATION_FAILED event is added
1004
        String principal = Constants.SUBJECT_PUBLIC;
1005
        if (session != null && session.getSubject() != null) {
1006
          principal = session.getSubject().getValue();
1007
        }
1008
        try {
1009
          EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), principal, localId, "synchronization_failed");
1010
        } catch (Exception e) {
1011
            throw new ServiceFailure("2161", "Could not log the error for: " + pid.getValue());
1012
        }
1013
        //EventLog.getInstance().log("CN URL WILL GO HERE", 
1014
        //  session.getSubject().getValue(), localId, Event.SYNCHRONIZATION_FAILED);
1015
        return true;
1016

    
1017
    }
1018

    
1019
    /**
1020
     * Essentially a get() but with different logging behavior
1021
     */
1022
    @Override
1023
    public InputStream getReplica(Session session, Identifier pid) 
1024
        throws NotAuthorized, NotImplemented, ServiceFailure, InvalidToken {
1025

    
1026
        logMetacat.info("MNodeService.getReplica() called.");
1027

    
1028
        // cannot be called by public
1029
        if (session == null) {
1030
        	throw new InvalidToken("2183", "No session was provided.");
1031
        }
1032
        
1033
        logMetacat.info("MNodeService.getReplica() called with parameters: \n" +
1034
             "\tSession.Subject      = " + session.getSubject().getValue() + "\n" +
1035
             "\tIdentifier           = " + pid.getValue());
1036

    
1037
        InputStream inputStream = null; // bytes to be returned
1038
        handler = new MetacatHandler(new Timer());
1039
        boolean allowed = false;
1040
        String localId; // the metacat docid for the pid
1041

    
1042
        // get the local docid from Metacat
1043
        try {
1044
            localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
1045
        } catch (McdbDocNotFoundException e) {
1046
            throw new ServiceFailure("2181", "The object specified by " + 
1047
                    pid.getValue() + " does not exist at this node.");
1048
            
1049
        }
1050

    
1051
        Subject targetNodeSubject = session.getSubject();
1052

    
1053
        // check for authorization to replicate, null session to act as this source MN
1054
        try {
1055
            allowed = D1Client.getCN().isNodeAuthorized(null, targetNodeSubject, pid);
1056
        } catch (InvalidToken e1) {
1057
            throw new ServiceFailure("2181", "Could not determine if node is authorized: " 
1058
                + e1.getMessage());
1059
            
1060
        } catch (NotFound e1) {
1061
            throw new ServiceFailure("2181", "Could not determine if node is authorized: " 
1062
                    + e1.getMessage());
1063

    
1064
        } catch (InvalidRequest e1) {
1065
            throw new ServiceFailure("2181", "Could not determine if node is authorized: " 
1066
                    + e1.getMessage());
1067

    
1068
        }
1069

    
1070
        logMetacat.info("Called D1Client.isNodeAuthorized(). Allowed = " + allowed +
1071
            " for identifier " + pid.getValue());
1072

    
1073
        // if the person is authorized, perform the read
1074
        if (allowed) {
1075
            try {
1076
                inputStream = MetacatHandler.read(localId);
1077
            } catch (Exception e) {
1078
                throw new ServiceFailure("1020", "The object specified by " + 
1079
                    pid.getValue() + "could not be returned due to error: " + e.getMessage());
1080
            }
1081
        }
1082

    
1083
        // if we fail to set the input stream
1084
        if (inputStream == null) {
1085
            throw new ServiceFailure("2181", "The object specified by " + 
1086
                pid.getValue() + "does not exist at this node.");
1087
        }
1088

    
1089
        // log the replica event
1090
        String principal = null;
1091
        if (session.getSubject() != null) {
1092
            principal = session.getSubject().getValue();
1093
        }
1094
        EventLog.getInstance().log(request.getRemoteAddr(), 
1095
            request.getHeader("User-Agent"), principal, localId, "replicate");
1096

    
1097
        return inputStream;
1098
    }
1099

    
1100
    /**
1101
     * A method to notify the Member Node that the authoritative copy of 
1102
     * system metadata on the Coordinating Nodes has changed.
1103
     * 
1104
     * @param session   Session information that contains the identity of the 
1105
     *                  calling user as retrieved from the X.509 certificate 
1106
     *                  which must be traceable to the CILogon service.
1107
     * @param serialVersion   The serialVersion of the system metadata
1108
     * @param dateSysMetaLastModified  The time stamp for when the system metadata was changed
1109
     * @throws NotImplemented
1110
     * @throws ServiceFailure
1111
     * @throws NotAuthorized
1112
     * @throws InvalidRequest
1113
     * @throws InvalidToken
1114
     */
1115
    public boolean systemMetadataChanged(Session session, Identifier pid,
1116
        long serialVersion, Date dateSysMetaLastModified) 
1117
        throws NotImplemented, ServiceFailure, NotAuthorized, InvalidRequest,
1118
        InvalidToken {
1119
        
1120
        // cannot be called by public
1121
        if (session == null) {
1122
        	throw new InvalidToken("2183", "No session was provided.");
1123
        }
1124

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

    
1240
	@Override
1241
	public Identifier generateIdentifier(Session session, String scheme, String fragment)
1242
			throws InvalidToken, ServiceFailure, NotAuthorized, NotImplemented,
1243
			InvalidRequest {
1244
		
1245
		Identifier identifier = new Identifier();
1246
		
1247
		// handle different schemes
1248
		if (scheme.equalsIgnoreCase(UUID_SCHEME)) {
1249
			// UUID
1250
			UUID uuid = UUID.randomUUID();
1251
            identifier.setValue(UUID_PREFIX + uuid.toString());
1252
		} else if (scheme.equalsIgnoreCase(DOI_SCHEME)) {
1253
			// generate a DOI
1254
			try {
1255
				identifier = DOIService.getInstance().generateDOI();
1256
			} catch (EZIDException e) {
1257
				ServiceFailure sf = new ServiceFailure("2191", "Could not generate DOI: " + e.getMessage());
1258
				sf.initCause(e);
1259
				throw sf;
1260
			}
1261
		} else {
1262
			// default if we don't know the scheme
1263
			if (fragment != null) {
1264
				// for now, just autogen with fragment
1265
				String autogenId = DocumentUtil.generateDocumentId(fragment, 0);
1266
				identifier.setValue(autogenId);			
1267
			} else {
1268
				// autogen with no fragment
1269
				String autogenId = DocumentUtil.generateDocumentId(0);
1270
				identifier.setValue(autogenId);
1271
			}
1272
		}
1273
		
1274
		// TODO: reserve the identifier with the CN. We can only do this when
1275
		// 1) the MN is part of a CN cluster
1276
		// 2) the request is from an authenticated user
1277
		
1278
		return identifier;
1279
	}
1280

    
1281
	@Override
1282
	public boolean isAuthorized(Identifier pid, Permission permission)
1283
			throws ServiceFailure, InvalidRequest, InvalidToken, NotFound,
1284
			NotAuthorized, NotImplemented {
1285

    
1286
		return isAuthorized(null, pid, permission);
1287
	}
1288

    
1289
	@Override
1290
	public boolean systemMetadataChanged(Identifier pid, long serialVersion, Date dateSysMetaLastModified)
1291
			throws InvalidToken, ServiceFailure, NotAuthorized, NotImplemented,
1292
			InvalidRequest {
1293

    
1294
		return systemMetadataChanged(null, pid, serialVersion, dateSysMetaLastModified);
1295
	}
1296

    
1297
	@Override
1298
	public Log getLogRecords(Date fromDate, Date toDate, Event event, String pidFilter,
1299
			Integer start, Integer count) throws InvalidRequest, InvalidToken,
1300
			NotAuthorized, NotImplemented, ServiceFailure {
1301

    
1302
		return getLogRecords(null, fromDate, toDate, event, pidFilter, start, count);
1303
	}
1304

    
1305
	@Override
1306
	public DescribeResponse describe(Identifier pid) throws InvalidToken,
1307
			NotAuthorized, NotImplemented, ServiceFailure, NotFound {
1308

    
1309
		return describe(null, pid);
1310
	}
1311

    
1312
	@Override
1313
	public InputStream get(Identifier pid) throws InvalidToken, NotAuthorized,
1314
			NotImplemented, ServiceFailure, NotFound, InsufficientResources {
1315

    
1316
		return get(null, pid);
1317
	}
1318

    
1319
	@Override
1320
	public Checksum getChecksum(Identifier pid, String algorithm)
1321
			throws InvalidRequest, InvalidToken, NotAuthorized, NotImplemented,
1322
			ServiceFailure, NotFound {
1323

    
1324
		return getChecksum(null, pid, algorithm);
1325
	}
1326

    
1327
	@Override
1328
	public SystemMetadata getSystemMetadata(Identifier pid)
1329
			throws InvalidToken, NotAuthorized, NotImplemented, ServiceFailure,
1330
			NotFound {
1331

    
1332
		return getSystemMetadata(null, pid);
1333
	}
1334

    
1335
	@Override
1336
	public ObjectList listObjects(Date startTime, Date endTime,
1337
			ObjectFormatIdentifier objectFormatId, Boolean replicaStatus, Integer start,
1338
			Integer count) throws InvalidRequest, InvalidToken, NotAuthorized,
1339
			NotImplemented, ServiceFailure {
1340

    
1341
		return listObjects(null, startTime, endTime, objectFormatId, replicaStatus, start, count);
1342
	}
1343

    
1344
	@Override
1345
	public boolean synchronizationFailed(SynchronizationFailed syncFailed)
1346
			throws InvalidToken, NotAuthorized, NotImplemented, ServiceFailure {
1347

    
1348
		return synchronizationFailed(null, syncFailed);
1349
	}
1350

    
1351
	@Override
1352
	public InputStream getReplica(Identifier pid) throws InvalidToken,
1353
			NotAuthorized, NotImplemented, ServiceFailure, NotFound,
1354
			InsufficientResources {
1355

    
1356
		return getReplica(null, pid);
1357
	}
1358

    
1359
	@Override
1360
	public boolean replicate(SystemMetadata sysmeta, NodeReference sourceNode)
1361
			throws NotImplemented, ServiceFailure, NotAuthorized,
1362
			InvalidRequest, InvalidToken, InsufficientResources,
1363
			UnsupportedType {
1364

    
1365
		return replicate(null, sysmeta, sourceNode);
1366
	}
1367

    
1368
	@Override
1369
	public Identifier create(Identifier pid, InputStream object,
1370
			SystemMetadata sysmeta) throws IdentifierNotUnique,
1371
			InsufficientResources, InvalidRequest, InvalidSystemMetadata,
1372
			InvalidToken, NotAuthorized, NotImplemented, ServiceFailure,
1373
			UnsupportedType {
1374

    
1375
		return create(null, pid, object, sysmeta);
1376
	}
1377

    
1378
	@Override
1379
	public Identifier delete(Identifier pid) throws InvalidToken,
1380
			ServiceFailure, NotAuthorized, NotFound, NotImplemented {
1381

    
1382
		return delete(null, pid);
1383
	}
1384

    
1385
	@Override
1386
	public Identifier generateIdentifier(String scheme, String fragment)
1387
			throws InvalidToken, ServiceFailure, NotAuthorized, NotImplemented,
1388
			InvalidRequest {
1389

    
1390
		return generateIdentifier(null, scheme, fragment);
1391
	}
1392

    
1393
	@Override
1394
	public Identifier update(Identifier pid, InputStream object,
1395
			Identifier newPid, SystemMetadata sysmeta) throws IdentifierNotUnique,
1396
			InsufficientResources, InvalidRequest, InvalidSystemMetadata,
1397
			InvalidToken, NotAuthorized, NotImplemented, ServiceFailure,
1398
			UnsupportedType, NotFound {
1399

    
1400
		return update(null, pid, object, newPid, sysmeta);
1401
	}
1402

    
1403
	@Override
1404
	public QueryEngineDescription getQueryEngineDescription(String engine)
1405
			throws InvalidToken, ServiceFailure, NotAuthorized, NotImplemented,
1406
			NotFound {
1407
		QueryEngineDescription qed = new QueryEngineDescription();
1408
		qed.setName(PATHQUERY);
1409
		qed.setQueryEngineVersion("1.0");
1410
		qed.addAdditionalInfo("This is the traditional structured query for Metacat");
1411
		Vector<String> pathsForIndexing = null;
1412
		try {
1413
			pathsForIndexing = SystemUtil.getPathsForIndexing();
1414
		} catch (MetacatUtilException e) {
1415
			logMetacat.warn("Could not get index paths", e);
1416
		}
1417
		for (String fieldName: pathsForIndexing) {
1418
			QueryField field = new QueryField();
1419
			field.addDescription("Indexed field for path '" + fieldName + "'");
1420
			field.setName(fieldName);
1421
			field.setReturnable(true);
1422
			field.setSearchable(true);
1423
			field.setSortable(false);
1424
			// TODO: determine type and multivaluedness
1425
			field.setType(String.class.getName());
1426
			//field.setMultivalued(true);
1427
			qed.addQueryField(field);
1428
		}
1429
		return qed;
1430
	}
1431

    
1432
	@Override
1433
	public QueryEngineList listQueryEngines() throws InvalidToken,
1434
			ServiceFailure, NotAuthorized, NotImplemented {
1435
		QueryEngineList qel = new QueryEngineList();
1436
		// support pathquery initially
1437
		qel.addQueryEngine(PATHQUERY);
1438
		// TODO: implement solr-based query
1439
		//qel.addQueryEngine("solr");
1440
		return qel;
1441
	}
1442

    
1443
	@Override
1444
	public InputStream query(String engine, String query) throws InvalidToken,
1445
			ServiceFailure, NotAuthorized, InvalidRequest, NotImplemented,
1446
			NotFound {
1447
		if (engine.equals(PATHQUERY)) {
1448
			try {
1449
				DBQuery queryobj = new DBQuery();
1450
				String user = Constants.SUBJECT_PUBLIC;
1451
				String[] groups= null;
1452
				if (session != null) {
1453
					user = session.getSubject().getValue();
1454
					Set<Subject> subjects = AuthUtils.authorizedClientSubjects(session);
1455
					if (subjects != null) {
1456
						List<String> groupList = new ArrayList<String>();
1457
						for (Subject subject: subjects) {
1458
							groupList.add(subject.getValue());
1459
						}
1460
						groups = groupList.toArray(new String[0]);
1461
					}
1462
				}
1463
				String results = queryobj.performPathquery(query, user, groups);
1464
				return new ByteArrayInputStream(results.getBytes(MetaCatServlet.DEFAULT_ENCODING));
1465

    
1466
			} catch (Exception e) {
1467
				
1468
			}
1469
			
1470
		}
1471
		return null;
1472
	}
1473
    
1474
}
(4-4/6)