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

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

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

    
145
    private static final String PATHQUERY = "pathquery";
146
    public static final String SOLRQUERY = "solrquery";
147
	private static final String UUID_SCHEME = "UUID";
148
	private static final String DOI_SCHEME = "DOI";
149
	private static final String UUID_PREFIX = "urn:uuid:";
150

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

    
160

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

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

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

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

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

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

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

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

    
284
        // does the subject have WRITE ( == update) priveleges on the pid?
285
        allowed = isAuthorized(session, pid, Permission.WRITE);
286

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

    
297
            // get the existing system metadata for the object
298
            SystemMetadata existingSysMeta = getSystemMetadata(session, pid);
299

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

    
311
            // then update the existing system metadata
312
            updateSystemMetadata(existingSysMeta);
313

    
314
            // prep the new system metadata, add pid to the affected lists
315
            sysmeta.setObsoletes(pid);
316
            //sysmeta.addDerivedFrom(pid);
317

    
318
            isScienceMetadata = isScienceMetadata(sysmeta);
319

    
320
            // do we have XML metadata or a data object?
321
            if (isScienceMetadata) {
322

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

    
335
                    }
336

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

    
342
                }
343

    
344
            } else {
345

    
346
                // update the data object
347
                localId = insertDataObject(object, newPid, session);
348

    
349
            }
350

    
351
            // and insert the new system metadata
352
            insertSystemMetadata(sysmeta);
353

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

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

    
369
        return newPid;
370
    }
371

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

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

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

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

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

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

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

    
463
        // get the referenced object
464
        Identifier pid = sysmeta.getIdentifier();
465

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

    
486

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

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

    
500
        }
501
        
502

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

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

    
538
            }
539

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

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

    
554
        }
555

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

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

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

    
601
        // finish by setting the replication status
602
        setReplicationStatus(thisNodeSession, pid, nodeId, ReplicationStatus.COMPLETED, null);
603
        return result;
604

    
605
    }
606

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

    
625
        return super.get(session, pid);
626

    
627
    }
628

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

    
651
        Checksum checksum = null;
652

    
653
        InputStream inputStream = get(session, pid);
654

    
655
        try {
656
            checksum = ChecksumUtil.checksum(inputStream, algorithm);
657

    
658
        } catch (NoSuchAlgorithmException 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
        } catch (IOException e) {
662
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned due to an internal error: "
663
                    + e.getMessage());
664
        }
665

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

    
670
        return checksum;
671
    }
672

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

    
693
        return super.getSystemMetadata(session, pid);
694
    }
695

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

    
724
        ObjectList objectList = null;
725

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

    
736
        return objectList;
737
    }
738

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

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

    
766
        boolean nodeSynchronize = false;
767
        boolean nodeReplicate = false;
768
        boolean mnCoreServiceAvailable = false;
769
        boolean mnReadServiceAvailable = false;
770
        boolean mnAuthorizationServiceAvailable = false;
771
        boolean mnStorageServiceAvailable = false;
772
        boolean mnReplicationServiceAvailable = false;
773

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

    
786
            mnCoreServiceVersion = PropertyService.getProperty("dataone.mnCore.serviceVersion");
787
            mnReadServiceVersion = PropertyService.getProperty("dataone.mnRead.serviceVersion");
788
            mnAuthorizationServiceVersion = PropertyService.getProperty("dataone.mnAuthorization.serviceVersion");
789
            mnStorageServiceVersion = PropertyService.getProperty("dataone.mnStorage.serviceVersion");
790
            mnReplicationServiceVersion = PropertyService.getProperty("dataone.mnReplication.serviceVersion");
791

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

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

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

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

    
834
            // services: MNAuthorization, MNCore, MNRead, MNReplication, MNStorage
835
            Services services = new Services();
836

    
837
            Service sMNCore = new Service();
838
            sMNCore.setName("MNCore");
839
            sMNCore.setVersion(mnCoreServiceVersion);
840
            sMNCore.setAvailable(mnCoreServiceAvailable);
841

    
842
            Service sMNRead = new Service();
843
            sMNRead.setName("MNRead");
844
            sMNRead.setVersion(mnReadServiceVersion);
845
            sMNRead.setAvailable(mnReadServiceAvailable);
846

    
847
            Service sMNAuthorization = new Service();
848
            sMNAuthorization.setName("MNAuthorization");
849
            sMNAuthorization.setVersion(mnAuthorizationServiceVersion);
850
            sMNAuthorization.setAvailable(mnAuthorizationServiceAvailable);
851

    
852
            Service sMNStorage = new Service();
853
            sMNStorage.setName("MNStorage");
854
            sMNStorage.setVersion(mnStorageServiceVersion);
855
            sMNStorage.setAvailable(mnStorageServiceAvailable);
856

    
857
            Service sMNReplication = new Service();
858
            sMNReplication.setName("MNReplication");
859
            sMNReplication.setVersion(mnReplicationServiceVersion);
860
            sMNReplication.setAvailable(mnReplicationServiceAvailable);
861

    
862
            services.addService(sMNRead);
863
            services.addService(sMNCore);
864
            services.addService(sMNAuthorization);
865
            services.addService(sMNStorage);
866
            services.addService(sMNReplication);
867
            node.setServices(services);
868

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

    
885
            node.setType(nodeType);
886
            return node;
887

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

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

    
918
        MonitorList monitorList = new MonitorList();
919

    
920
        try {
921

    
922
            // get log records first
923
            Log logs = getLogRecords(session, startTime, endTime, event, null, 0, null);
924

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

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

    
949
        return monitorList;
950

    
951
    }
952

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

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

    
987
            }
988
            
989
        } else {
990
            throw new ServiceFailure("2161", "The identifier cannot be null.");
991

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

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

    
1020
    }
1021

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

    
1029
        logMetacat.info("MNodeService.getReplica() called.");
1030

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

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

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

    
1054
        Subject targetNodeSubject = session.getSubject();
1055

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

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

    
1071
        }
1072

    
1073
        logMetacat.info("Called D1Client.isNodeAuthorized(). Allowed = " + allowed +
1074
            " for identifier " + pid.getValue());
1075

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

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

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

    
1100
        return inputStream;
1101
    }
1102

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

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

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

    
1284
	@Override
1285
	public boolean isAuthorized(Identifier pid, Permission permission)
1286
			throws ServiceFailure, InvalidRequest, InvalidToken, NotFound,
1287
			NotAuthorized, NotImplemented {
1288

    
1289
		return isAuthorized(null, pid, permission);
1290
	}
1291

    
1292
	@Override
1293
	public boolean systemMetadataChanged(Identifier pid, long serialVersion, Date dateSysMetaLastModified)
1294
			throws InvalidToken, ServiceFailure, NotAuthorized, NotImplemented,
1295
			InvalidRequest {
1296

    
1297
		return systemMetadataChanged(null, pid, serialVersion, dateSysMetaLastModified);
1298
	}
1299

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

    
1305
		return getLogRecords(null, fromDate, toDate, event, pidFilter, start, count);
1306
	}
1307

    
1308
	@Override
1309
	public DescribeResponse describe(Identifier pid) throws InvalidToken,
1310
			NotAuthorized, NotImplemented, ServiceFailure, NotFound {
1311

    
1312
		return describe(null, pid);
1313
	}
1314

    
1315
	@Override
1316
	public InputStream get(Identifier pid) throws InvalidToken, NotAuthorized,
1317
			NotImplemented, ServiceFailure, NotFound, InsufficientResources {
1318

    
1319
		return get(null, pid);
1320
	}
1321

    
1322
	@Override
1323
	public Checksum getChecksum(Identifier pid, String algorithm)
1324
			throws InvalidRequest, InvalidToken, NotAuthorized, NotImplemented,
1325
			ServiceFailure, NotFound {
1326

    
1327
		return getChecksum(null, pid, algorithm);
1328
	}
1329

    
1330
	@Override
1331
	public SystemMetadata getSystemMetadata(Identifier pid)
1332
			throws InvalidToken, NotAuthorized, NotImplemented, ServiceFailure,
1333
			NotFound {
1334

    
1335
		return getSystemMetadata(null, pid);
1336
	}
1337

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

    
1344
		return listObjects(null, startTime, endTime, objectFormatId, replicaStatus, start, count);
1345
	}
1346

    
1347
	@Override
1348
	public boolean synchronizationFailed(SynchronizationFailed syncFailed)
1349
			throws InvalidToken, NotAuthorized, NotImplemented, ServiceFailure {
1350

    
1351
		return synchronizationFailed(null, syncFailed);
1352
	}
1353

    
1354
	@Override
1355
	public InputStream getReplica(Identifier pid) throws InvalidToken,
1356
			NotAuthorized, NotImplemented, ServiceFailure, NotFound,
1357
			InsufficientResources {
1358

    
1359
		return getReplica(null, pid);
1360
	}
1361

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

    
1368
		return replicate(null, sysmeta, sourceNode);
1369
	}
1370

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

    
1378
		return create(null, pid, object, sysmeta);
1379
	}
1380

    
1381
	@Override
1382
	public Identifier delete(Identifier pid) throws InvalidToken,
1383
			ServiceFailure, NotAuthorized, NotFound, NotImplemented {
1384

    
1385
		return delete(null, pid);
1386
	}
1387

    
1388
	@Override
1389
	public Identifier generateIdentifier(String scheme, String fragment)
1390
			throws InvalidToken, ServiceFailure, NotAuthorized, NotImplemented,
1391
			InvalidRequest {
1392

    
1393
		return generateIdentifier(null, scheme, fragment);
1394
	}
1395

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

    
1403
		return update(null, pid, object, newPid, sysmeta);
1404
	}
1405

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

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

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

    
1469
			} catch (Exception e) {
1470
				
1471
			}
1472
			
1473
		} else if (engine != null && engine.equals(SOLRQUERY)) {
1474
		    System.out.println("The query is ==================================== \n"+query);
1475
		    try {
1476
		        MetacatSolrIndex solrIndex = new MetacatSolrIndex();
1477
                return solrIndex.query(query);
1478
            } catch (Exception e) {
1479
                // TODO Auto-generated catch block
1480
                throw new ServiceFailure("Solr server error", e.getMessage());
1481
            } 
1482
		}
1483
		return null;
1484
	}
1485
    
1486
}
(4-4/6)