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.IOException;
27
import java.io.InputStream;
28
import java.security.NoSuchAlgorithmException;
29
import java.sql.SQLException;
30
import java.util.Calendar;
31
import java.util.Date;
32
import java.util.List;
33
import java.util.Timer;
34

    
35
import org.apache.commons.io.IOUtils;
36
import org.apache.log4j.Logger;
37
import org.dataone.client.CNode;
38
import org.dataone.client.D1Client;
39
import org.dataone.client.MNode;
40
import org.dataone.service.exceptions.IdentifierNotUnique;
41
import org.dataone.service.exceptions.InsufficientResources;
42
import org.dataone.service.exceptions.InvalidRequest;
43
import org.dataone.service.exceptions.InvalidSystemMetadata;
44
import org.dataone.service.exceptions.InvalidToken;
45
import org.dataone.service.exceptions.NotAuthorized;
46
import org.dataone.service.exceptions.NotFound;
47
import org.dataone.service.exceptions.NotImplemented;
48
import org.dataone.service.exceptions.ServiceFailure;
49
import org.dataone.service.exceptions.SynchronizationFailed;
50
import org.dataone.service.exceptions.UnsupportedType;
51
import org.dataone.service.mn.tier1.v1.MNCore;
52
import org.dataone.service.mn.tier1.v1.MNRead;
53
import org.dataone.service.mn.tier2.v1.MNAuthorization;
54
import org.dataone.service.mn.tier3.v1.MNStorage;
55
import org.dataone.service.mn.tier4.v1.MNReplication;
56
import org.dataone.service.types.v1.Checksum;
57
import org.dataone.service.types.v1.DescribeResponse;
58
import org.dataone.service.types.v1.Event;
59
import org.dataone.service.types.v1.Group;
60
import org.dataone.service.types.v1.Identifier;
61
import org.dataone.service.types.v1.Log;
62
import org.dataone.service.types.v1.LogEntry;
63
import org.dataone.service.types.v1.MonitorInfo;
64
import org.dataone.service.types.v1.MonitorList;
65
import org.dataone.service.types.v1.Node;
66
import org.dataone.service.types.v1.NodeReference;
67
import org.dataone.service.types.v1.NodeState;
68
import org.dataone.service.types.v1.NodeType;
69
import org.dataone.service.types.v1.ObjectFormatIdentifier;
70
import org.dataone.service.types.v1.ObjectList;
71
import org.dataone.service.types.v1.Permission;
72
import org.dataone.service.types.v1.Ping;
73
import org.dataone.service.types.v1.ReplicationStatus;
74
import org.dataone.service.types.v1.Schedule;
75
import org.dataone.service.types.v1.Service;
76
import org.dataone.service.types.v1.Services;
77
import org.dataone.service.types.v1.Session;
78
import org.dataone.service.types.v1.Subject;
79
import org.dataone.service.types.v1.Synchronization;
80
import org.dataone.service.types.v1.SystemMetadata;
81
import org.dataone.service.types.v1.util.ChecksumUtil;
82
import org.dataone.service.util.Constants;
83

    
84
import edu.ucsb.nceas.metacat.DocumentImpl;
85
import edu.ucsb.nceas.metacat.EventLog;
86
import edu.ucsb.nceas.metacat.IdentifierManager;
87
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
88
import edu.ucsb.nceas.metacat.MetacatHandler;
89
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
90
import edu.ucsb.nceas.metacat.database.DBConnection;
91
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
92
import edu.ucsb.nceas.metacat.properties.PropertyService;
93
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
94

    
95
/**
96
 * Represents Metacat's implementation of the DataONE Member Node 
97
 * service API. Methods implement the various MN* interfaces, and methods common
98
 * to both Member Node and Coordinating Node interfaces are found in the
99
 * D1NodeService base class.
100
 * 
101
 * Implements:
102
 * MNCore.ping()
103
 * MNCore.getLogRecords()
104
 * MNCore.getObjectStatistics()
105
 * MNCore.getOperationStatistics()
106
 * MNCore.getStatus()
107
 * MNCore.getCapabilities()
108
 * MNRead.get()
109
 * MNRead.getSystemMetadata()
110
 * MNRead.describe()
111
 * MNRead.getChecksum()
112
 * MNRead.listObjects()
113
 * MNRead.synchronizationFailed()
114
 * MNAuthorization.isAuthorized()
115
 * MNAuthorization.setAccessPolicy()
116
 * MNStorage.create()
117
 * MNStorage.update()
118
 * MNStorage.delete()
119
 * MNReplication.replicate()
120
 * 
121
 */
122
public class MNodeService extends D1NodeService implements MNAuthorization, MNCore, MNRead, MNReplication, MNStorage {
123

    
124
    /* the instance of the MNodeService object */
125
    private static MNodeService instance = null;
126

    
127
    /* the logger instance */
128
    private Logger logMetacat = null;
129

    
130
    /**
131
     * Singleton accessor to get an instance of MNodeService.
132
     * 
133
     * @return instance - the instance of MNodeService
134
     */
135
    public static MNodeService getInstance() {
136
        if (instance == null) {
137
            instance = new MNodeService();
138
        }
139
        return instance;
140
    }
141

    
142
    /**
143
     * Constructor, private for singleton access
144
     */
145
    private MNodeService() {
146
        super();
147
        logMetacat = Logger.getLogger(MNodeService.class);
148
    }
149

    
150
    /**
151
     * Deletes an object from the Member Node, where the object is either a 
152
     * data object or a science metadata object.
153
     * 
154
     * @param session - the Session object containing the credentials for the Subject
155
     * @param pid - The object identifier to be deleted
156
     * 
157
     * @return pid - the identifier of the object used for the deletion
158
     * 
159
     * @throws InvalidToken
160
     * @throws ServiceFailure
161
     * @throws NotAuthorized
162
     * @throws NotFound
163
     * @throws NotImplemented
164
     * @throws InvalidRequest
165
     */
166
    @Override
167
    public Identifier delete(Session session, Identifier pid) 
168
        throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented, InvalidRequest {
169

    
170
        String localId = null;
171
        boolean allowed = false;
172
        String username = Constants.SUBJECT_PUBLIC;
173
        String[] groupnames = null;
174
        if (session != null) {
175
            username = session.getSubject().getValue();
176
            if (session.getSubjectInfo() != null) {
177
                List<Group> groupList = session.getSubjectInfo().getGroupList();
178
                if (groupList != null) {
179
                    groupnames = new String[groupList.size()];
180
                    for (int i = 0; i > groupList.size(); i++) {
181
                        groupnames[i] = groupList.get(i).getGroupName();
182
                    }
183
                }
184
            }
185
        }
186

    
187
        // do we have a valid pid?
188
        if (pid == null || pid.getValue().trim().equals("")) {
189
            throw new InvalidRequest("1322", "The provided identifier was invalid.");
190
        }
191

    
192
        // check for the existing identifier
193
        try {
194
            localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
195
        } catch (McdbDocNotFoundException e) {
196
            throw new InvalidRequest("1322", "The object with the provided " + "identifier was not found.");
197
        }
198

    
199
        // does the subject have DELETE (a D1 CHANGE_PERMISSION level) priveleges on the pid?
200
        allowed = isAuthorized(session, pid, Permission.CHANGE_PERMISSION);
201

    
202
        if (allowed) {
203
            try {
204
                // delete the document
205
                DocumentImpl.delete(localId, username, groupnames, null);
206
                EventLog.getInstance().log(metacatUrl, username, localId, Event.DELETE.xmlValue());
207

    
208
            } catch (McdbDocNotFoundException e) {
209
                throw new InvalidRequest("1322", "The provided identifier was invalid.");
210

    
211
            } catch (SQLException e) {
212
                throw new ServiceFailure("1350", "There was a problem deleting the object." + "The error message was: " + e.getMessage());
213

    
214
            } catch (InsufficientKarmaException e) {
215
                throw new NotAuthorized("1320", "The provided identity does not have " + "permission to DELETE objects on the Member Node.");
216

    
217
            } catch (Exception e) { // for some reason DocumentImpl throws a general Exception
218
                throw new ServiceFailure("1350", "There was a problem deleting the object." + "The error message was: " + e.getMessage());
219
            }
220

    
221
        } else {
222
            throw new NotAuthorized("1320", "The provided identity does not have " + "permission to DELETE objects on the Member Node.");
223
        }
224

    
225
        return pid;
226
    }
227

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

    
257
        String localId = null;
258
        boolean allowed = false;
259
        boolean isScienceMetadata = false;
260
        Subject subject = session.getSubject();
261

    
262
        // do we have a valid pid?
263
        if (pid == null || pid.getValue().trim().equals("")) {
264
            throw new InvalidRequest("1202", "The provided identifier was invalid.");
265
        }
266

    
267
        // check for the existing identifier
268
        try {
269
            localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
270
        } catch (McdbDocNotFoundException e) {
271
            throw new InvalidRequest("1202", "The object with the provided " + "identifier was not found.");
272
        }
273
        
274
        // set the originating node
275
        NodeReference originMemberNode = this.getCapabilities().getIdentifier();
276
        sysmeta.setOriginMemberNode(originMemberNode);
277
        
278
        // set the submitter to match the certificate
279
        sysmeta.setSubmitter(subject);
280
        // set the dates
281
        Date now = Calendar.getInstance().getTime();
282
		sysmeta.setDateSysMetadataModified(now);
283
		sysmeta.setDateUploaded(now);
284

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

    
288
        if (allowed) {
289

    
290
            // get the existing system metadata for the object
291
            SystemMetadata existingSysMeta = getSystemMetadata(session, pid);
292

    
293
            // add the newPid to the obsoletedBy list for the existing sysmeta
294
            existingSysMeta.setObsoletedBy(newPid);
295

    
296
            // then update the existing system metadata
297
            updateSystemMetadata(existingSysMeta);
298

    
299
            // prep the new system metadata, add pid to the affected lists
300
            sysmeta.setObsoletes(pid);
301
            //sysmeta.addDerivedFrom(pid);
302

    
303
            isScienceMetadata = isScienceMetadata(sysmeta);
304

    
305
            // do we have XML metadata or a data object?
306
            if (isScienceMetadata) {
307

    
308
                // update the science metadata XML document
309
                // TODO: handle non-XML metadata/data documents (like netCDF)
310
                // TODO: don't put objects into memory using stream to string
311
                String objectAsXML = "";
312
                try {
313
                    objectAsXML = IOUtils.toString(object, "UTF-8");
314
                    localId = insertOrUpdateDocument(objectAsXML, newPid, session, "update");
315
                    // register the newPid and the generated localId
316
                    if (newPid != null) {
317
                        IdentifierManager.getInstance().createMapping(newPid.getValue(), localId);
318

    
319
                    }
320

    
321
                } catch (IOException e) {
322
                    String msg = "The Node is unable to create the object. " + "There was a problem converting the object to XML";
323
                    logMetacat.info(msg);
324
                    throw new ServiceFailure("1310", msg + ": " + e.getMessage());
325

    
326
                }
327

    
328
            } else {
329

    
330
                // update the data object
331
                localId = insertDataObject(object, newPid, session);
332

    
333
            }
334

    
335
            // and insert the new system metadata
336
            insertSystemMetadata(sysmeta);
337

    
338
            // log the update event
339
            EventLog.getInstance().log(metacatUrl, subject.getValue(), localId, "update");
340

    
341
        } else {
342
            throw new NotAuthorized("1200", "The provided identity does not have " + "permission to UPDATE the object identified by " + pid.getValue()
343
                    + " on the Member Node.");
344
        }
345

    
346
        return newPid;
347
    }
348

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

    
352
    	// check for null session
353
        if (session == null) {
354
        	throw new InvalidToken("1110", "Session is required to WRITE to the Node.");
355
        }
356
        // set the submitter to match the certificate
357
        sysmeta.setSubmitter(session.getSubject());
358
        // set the originating node
359
        NodeReference originMemberNode = this.getCapabilities().getIdentifier();
360
        sysmeta.setOriginMemberNode(originMemberNode);
361
        // set the dates
362
        Date now = Calendar.getInstance().getTime();
363
		sysmeta.setDateSysMetadataModified(now);
364
		sysmeta.setDateUploaded(now);
365
        // call the shared impl
366
        return super.create(session, pid, object, sysmeta);
367
    }
368

    
369
    /**
370
     * Called by a Coordinating Node to request that the Member Node create a 
371
     * copy of the specified object by retrieving it from another Member 
372
     * Node and storing it locally so that it can be made accessible to 
373
     * the DataONE system.
374
     * 
375
     * @param session - the Session object containing the credentials for the Subject
376
     * @param sysmeta - Copy of the CN held system metadata for the object
377
     * @param sourceNode - A reference to node from which the content should be 
378
     *                     retrieved. The reference should be resolved by 
379
     *                     checking the CN node registry.
380
     * 
381
     * @return true if the replication succeeds
382
     * 
383
     * @throws ServiceFailure
384
     * @throws NotAuthorized
385
     * @throws NotImplemented
386
     * @throws UnsupportedType
387
     * @throws InsufficientResources
388
     * @throws InvalidRequest
389
     */
390
    @Override
391
    public boolean replicate(Session session, SystemMetadata sysmeta, NodeReference sourceNode) 
392
        throws NotImplemented, ServiceFailure, NotAuthorized, InvalidRequest, 
393
        InsufficientResources, UnsupportedType {
394

    
395
        logMetacat.info("MNodeService.replicate() called with parameters: \n" +
396
            "\tSession.Subject      = " + session.getSubject().getValue() + "\n" +
397
            "\tSystemMetadata       = " + sysmeta.toString()              + "\n" +
398
            "\tSource NodeReference ="  + sourceNode.getValue());
399
        
400
        boolean result = false;
401

    
402
        // TODO: check credentials
403

    
404
        // get the referenced object
405
        Identifier pid = sysmeta.getIdentifier();
406

    
407
        // get from the membernode
408
        // TODO: switch credentials for the server retrieval?
409
        MNode mn = D1Client.getMN(sourceNode);
410
        CNode cn = D1Client.getCN();
411
        
412
        InputStream object = null;
413

    
414
        try {
415
            object = mn.getReplica(session, pid);
416
            logMetacat.info("MNodeService.replicate() called for identifier " + pid.getValue());
417

    
418
        } catch (InvalidToken e) {
419
            e.printStackTrace();
420
            throw new ServiceFailure("2151", "Could not retrieve object to replicate (InvalidToken): " + e.getMessage());
421
        } catch (NotFound e) {
422
            e.printStackTrace();
423
            throw new ServiceFailure("2151", "Could not retrieve object to replicate (NotFound): " + e.getMessage());
424
        }
425

    
426
        // add it to local store
427
        Identifier retPid;
428
        try {
429
            retPid = create(session, pid, object, sysmeta);
430
            result = (retPid.getValue().equals(pid.getValue()));
431
        } catch (InvalidToken e) {
432
            e.printStackTrace();
433
            throw new ServiceFailure("2151", "Could not save object to local store (InvalidToken): " + e.getMessage());
434
        } catch (IdentifierNotUnique e) {
435
            e.printStackTrace();
436
            throw new ServiceFailure("2151", "Could not save object to local store (IdentifierNotUnique): " + e.getMessage());
437
        } catch (InvalidSystemMetadata e) {
438
            e.printStackTrace();
439
            throw new ServiceFailure("2151", "Could not save object to local store (InvalidSystemMetadata): " + e.getMessage());
440
        }
441

    
442
        try {
443
            session = null;
444
            cn.setReplicationStatus(session, pid, sourceNode, ReplicationStatus.COMPLETED);
445
            
446
        } catch (InvalidToken e) {
447
            // TODO Auto-generated catch block
448
            e.printStackTrace();
449
        } catch (NotFound e) {
450
            // TODO Auto-generated catch block
451
            e.printStackTrace();
452
        }
453
        return result;
454

    
455
    }
456

    
457
    /**
458
     * This method provides a lighter weight mechanism than 
459
     * MN_read.getSystemMetadata() for a client to determine basic 
460
     * properties of the referenced object.
461
     * 
462
     * @param session - the Session object containing the credentials for the Subject
463
     * @param pid - the identifier of the object to be described
464
     * 
465
     * @return describeResponse - A set of values providing a basic description 
466
     *                            of the object.
467
     * 
468
     * @throws InvalidToken
469
     * @throws ServiceFailure
470
     * @throws NotAuthorized
471
     * @throws NotFound
472
     * @throws NotImplemented
473
     * @throws InvalidRequest
474
     */
475
    @Override
476
    public DescribeResponse describe(Session session, Identifier pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented,
477
            InvalidRequest {
478

    
479
    	// get system metadata and construct the describe response
480
        SystemMetadata sysmeta = getSystemMetadata(session, pid);
481
        DescribeResponse describeResponse = new DescribeResponse(sysmeta.getFmtid(), sysmeta.getSize(), sysmeta.getDateSysMetadataModified(),
482
                sysmeta.getChecksum());
483

    
484
        return describeResponse;
485

    
486
    }
487

    
488
    /**
489
     * Return the object identified by the given object identifier
490
     * 
491
     * @param session - the Session object containing the credentials for the Subject
492
     * @param pid - the object identifier for the given object
493
     * 
494
     * @return inputStream - the input stream of the given object
495
     * 
496
     * @throws InvalidToken
497
     * @throws ServiceFailure
498
     * @throws NotAuthorized
499
     * @throws InvalidRequest
500
     * @throws NotImplemented
501
     */
502
    @Override
503
    public InputStream get(Session session, Identifier pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented, InvalidRequest {
504

    
505
        return super.get(session, pid);
506

    
507
    }
508

    
509
    /**
510
     * Returns a Checksum for the specified object using an accepted hashing algorithm
511
     * 
512
     * @param session - the Session object containing the credentials for the Subject
513
     * @param pid - the object identifier for the given object
514
     * @param algorithm -  the name of an algorithm that will be used to compute 
515
     *                     a checksum of the bytes of the object
516
     * 
517
     * @return checksum - the checksum of the given object
518
     * 
519
     * @throws InvalidToken
520
     * @throws ServiceFailure
521
     * @throws NotAuthorized
522
     * @throws NotFound
523
     * @throws InvalidRequest
524
     * @throws NotImplemented
525
     */
526
    @Override
527
    public Checksum getChecksum(Session session, Identifier pid, String algorithm) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
528
            InvalidRequest, NotImplemented {
529

    
530
        Checksum checksum = null;
531

    
532
        InputStream inputStream = get(session, pid);
533

    
534
        try {
535
            checksum = ChecksumUtil.checksum(inputStream, algorithm);
536

    
537
        } catch (NoSuchAlgorithmException e) {
538
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned due to an internal error: "
539
                    + e.getMessage());
540
        } catch (IOException e) {
541
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned due to an internal error: "
542
                    + e.getMessage());
543
        }
544

    
545
        if (checksum == null) {
546
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned.");
547
        }
548

    
549
        return checksum;
550
    }
551

    
552
    /**
553
     * Return the system metadata for a given object
554
     * 
555
     * @param session - the Session object containing the credentials for the Subject
556
     * @param pid - the object identifier for the given object
557
     * 
558
     * @return inputStream - the input stream of the given system metadata object
559
     * 
560
     * @throws InvalidToken
561
     * @throws ServiceFailure
562
     * @throws NotAuthorized
563
     * @throws NotFound
564
     * @throws InvalidRequest
565
     * @throws NotImplemented
566
     */
567
    @Override
568
    public SystemMetadata getSystemMetadata(Session session, Identifier pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, InvalidRequest,
569
            NotImplemented {
570

    
571
        return super.getSystemMetadata(session, pid);
572
    }
573

    
574
    /**
575
     * Retrieve the list of objects present on the MN that match the calling parameters
576
     * 
577
     * @param session - the Session object containing the credentials for the Subject
578
     * @param startTime - Specifies the beginning of the time range from which 
579
     *                    to return object (>=)
580
     * @param endTime - Specifies the beginning of the time range from which 
581
     *                  to return object (>=)
582
     * @param objectFormat - Restrict results to the specified object format
583
     * @param replicaStatus - Indicates if replicated objects should be returned in the list
584
     * @param start - The zero-based index of the first value, relative to the 
585
     *                first record of the resultset that matches the parameters.
586
     * @param count - The maximum number of entries that should be returned in 
587
     *                the response. The Member Node may return less entries 
588
     *                than specified in this value.
589
     * 
590
     * @return objectList - the list of objects matching the criteria
591
     * 
592
     * @throws InvalidToken
593
     * @throws ServiceFailure
594
     * @throws NotAuthorized
595
     * @throws InvalidRequest
596
     * @throws NotImplemented
597
     */
598
    @Override
599
    public ObjectList listObjects(Session session, Date startTime, Date endTime, ObjectFormatIdentifier objectFormatId, Boolean replicaStatus, Integer start,
600
            Integer count) throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken {
601

    
602
        ObjectList objectList = null;
603

    
604
        try {
605
            objectList = IdentifierManager.getInstance().querySystemMetadata(startTime, endTime, objectFormatId, replicaStatus, start, count);
606
        } catch (Exception e) {
607
            throw new ServiceFailure("1580", "Error querying system metadata: " + e.getMessage());
608
        }
609

    
610
        return objectList;
611
    }
612

    
613
    /**
614
     * Return a description of the node's capabilities and services.
615
     * 
616
     * @return node - the technical capabilities of the Member Node
617
     * 
618
     * @throws ServiceFailure
619
     * @throws NotAuthorized
620
     * @throws InvalidRequest
621
     * @throws NotImplemented
622
     */
623
    @Override
624
    public Node getCapabilities() throws NotImplemented, NotAuthorized, ServiceFailure, InvalidRequest {
625

    
626
        String nodeName = null;
627
        String nodeId = null;
628
        String subject = null;
629
        String nodeDesc = null;
630
        String nodeTypeString = null;
631
        NodeType nodeType = null;
632
        String mnCoreServiceVersion = null;
633
        String mnReadServiceVersion = null;
634
        String mnAuthorizationServiceVersion = null;
635
        String mnStorageServiceVersion = null;
636
        String mnReplicationServiceVersion = null;
637

    
638
        boolean nodeSynchronize = false;
639
        boolean nodeReplicate = false;
640
        boolean mnCoreServiceAvailable = false;
641
        boolean mnReadServiceAvailable = false;
642
        boolean mnAuthorizationServiceAvailable = false;
643
        boolean mnStorageServiceAvailable = false;
644
        boolean mnReplicationServiceAvailable = false;
645

    
646
        try {
647
            // get the properties of the node based on configuration information
648
            nodeName = PropertyService.getProperty("dataone.nodeName");
649
            nodeId = PropertyService.getProperty("dataone.memberNodeId");
650
            subject = PropertyService.getProperty("dataone.subject");
651
            nodeDesc = PropertyService.getProperty("dataone.nodeDescription");
652
            nodeTypeString = PropertyService.getProperty("dataone.nodeType");
653
            nodeType = NodeType.convert(nodeTypeString);
654
            nodeSynchronize = new Boolean(PropertyService.getProperty("dataone.nodeSynchronize")).booleanValue();
655
            nodeReplicate = new Boolean(PropertyService.getProperty("dataone.nodeReplicate")).booleanValue();
656

    
657
            mnCoreServiceVersion = PropertyService.getProperty("dataone.mnCore.serviceVersion");
658
            mnReadServiceVersion = PropertyService.getProperty("dataone.mnRead.serviceVersion");
659
            mnAuthorizationServiceVersion = PropertyService.getProperty("dataone.mnAuthorization.serviceVersion");
660
            mnStorageServiceVersion = PropertyService.getProperty("dataone.mnStorage.serviceVersion");
661
            mnReplicationServiceVersion = PropertyService.getProperty("dataone.mnReplication.serviceVersion");
662

    
663
            mnCoreServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnCore.serviceAvailable")).booleanValue();
664
            mnReadServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnRead.serviceAvailable")).booleanValue();
665
            mnAuthorizationServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnAuthorization.serviceAvailable")).booleanValue();
666
            mnStorageServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnStorage.serviceAvailable")).booleanValue();
667
            mnReplicationServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnReplication.serviceAvailable")).booleanValue();
668

    
669
            // Set the properties of the node based on configuration information and
670
            // calls to current status methods
671
            Node node = new Node();
672
            node.setBaseURL(metacatUrl + "/" + nodeTypeString);
673
            node.setDescription(nodeDesc);
674

    
675
            // set the node's health information
676
            node.setState(NodeState.UP);
677
            
678
            // set the ping response to the current value
679
            Ping canPing = new Ping();
680
            canPing.setSuccess(false);
681
            try {
682
                canPing.setSuccess(ping());
683
            } catch (InsufficientResources e) {
684
                e.printStackTrace();
685
            } catch (UnsupportedType e) {
686
                e.printStackTrace();
687
            }
688
            node.setPing(canPing);
689

    
690
            NodeReference identifier = new NodeReference();
691
            identifier.setValue(nodeId);
692
            node.setIdentifier(identifier);
693
            Subject s = new Subject();
694
            s.setValue(subject);
695
            node.addSubject(s);
696
            node.setName(nodeName);
697
            node.setReplicate(nodeReplicate);
698
            node.setSynchronize(nodeSynchronize);
699

    
700
            // services: MNAuthorization, MNCore, MNRead, MNReplication, MNStorage
701
            Services services = new Services();
702

    
703
            Service sMNCore = new Service();
704
            sMNCore.setName("MNCore");
705
            sMNCore.setVersion(mnCoreServiceVersion);
706
            sMNCore.setAvailable(mnCoreServiceAvailable);
707

    
708
            Service sMNRead = new Service();
709
            sMNRead.setName("MNRead");
710
            sMNRead.setVersion(mnReadServiceVersion);
711
            sMNRead.setAvailable(mnReadServiceAvailable);
712

    
713
            Service sMNAuthorization = new Service();
714
            sMNAuthorization.setName("MNAuthorization");
715
            sMNAuthorization.setVersion(mnAuthorizationServiceVersion);
716
            sMNAuthorization.setAvailable(mnAuthorizationServiceAvailable);
717

    
718
            Service sMNStorage = new Service();
719
            sMNStorage.setName("MNStorage");
720
            sMNStorage.setVersion(mnStorageServiceVersion);
721
            sMNStorage.setAvailable(mnStorageServiceAvailable);
722

    
723
            Service sMNReplication = new Service();
724
            sMNReplication.setName("MNReplication");
725
            sMNReplication.setVersion(mnReplicationServiceVersion);
726
            sMNReplication.setAvailable(mnReplicationServiceAvailable);
727

    
728
            services.addService(sMNRead);
729
            services.addService(sMNCore);
730
            services.addService(sMNAuthorization);
731
            services.addService(sMNStorage);
732
            services.addService(sMNReplication);
733
            node.setServices(services);
734

    
735
            // TODO: Allow the metacat admin to determine the schedule
736
            // Set the schedule for synchronization
737
            Synchronization synchronization = new Synchronization();
738
            Schedule schedule = new Schedule();
739
            Date now = new Date();
740
            schedule.setYear("*");
741
            schedule.setMon("*");
742
            schedule.setMday("*");
743
            schedule.setWday("?");
744
            schedule.setHour("*");
745
            schedule.setMin("0/3");
746
            schedule.setSec("10");
747
            synchronization.setSchedule(schedule);
748
            synchronization.setLastHarvested(now);
749
            synchronization.setLastCompleteHarvest(now);
750
            node.setSynchronization(synchronization);
751

    
752
            node.setType(nodeType);
753
            return node;
754

    
755
        } catch (PropertyNotFoundException pnfe) {
756
            String msg = "MNodeService.getCapabilities(): " + "property not found: " + pnfe.getMessage();
757
            logMetacat.error(msg);
758
            throw new ServiceFailure("2162", msg);
759
        }
760
    }
761

    
762
    /**
763
     * Returns the number of operations that have been serviced by the node 
764
     * over time periods of one and 24 hours.
765
     * 
766
     * @param session - the Session object containing the credentials for the Subject
767
     * @param period - An ISO8601 compatible DateTime range specifying the time 
768
     *                 range for which to return operation statistics.
769
     * @param requestor - Limit to operations performed by given requestor identity.
770
     * @param event -  Enumerated value indicating the type of event being examined
771
     * @param format - Limit to events involving objects of the specified format
772
     * 
773
     * @return the desired log records
774
     * 
775
     * @throws InvalidToken
776
     * @throws ServiceFailure
777
     * @throws NotAuthorized
778
     * @throws InvalidRequest
779
     * @throws NotImplemented
780
     */
781
    @Override
782
    public MonitorList getOperationStatistics(Session session, Date startTime, Date endTime, Subject requestor, Event event, ObjectFormatIdentifier formatId)
783
            throws NotImplemented, ServiceFailure, NotAuthorized, InvalidRequest, InsufficientResources, UnsupportedType {
784

    
785
        MonitorList monitorList = new MonitorList();
786

    
787
        try {
788

    
789
            // get log records first
790
            Log logs = getLogRecords(session, startTime, endTime, event, 0, null);
791

    
792
            // TODO: aggregate by day or hour -- needs clarification
793
            int count = 1;
794
            for (LogEntry logEntry : logs.getLogEntryList()) {
795
                Identifier pid = logEntry.getIdentifier();
796
                Date logDate = logEntry.getDateLogged();
797
                // if we are filtering by format
798
                if (formatId != null) {
799
                    SystemMetadata sysmeta = IdentifierManager.getInstance().getSystemMetadata(pid.getValue());
800
                    if (!sysmeta.getFmtid().getValue().equals(formatId.getValue())) {
801
                        // does not match
802
                        continue;
803
                    }
804
                }
805
                MonitorInfo item = new MonitorInfo();
806
                item.setCount(count);
807
                item.setDate(new java.sql.Date(logDate.getTime()));
808
                monitorList.addMonitorInfo(item);
809

    
810
            }
811
        } catch (Exception e) {
812
            e.printStackTrace();
813
            throw new ServiceFailure("2081", "Could not retrieve statistics: " + e.getMessage());
814
        }
815

    
816
        return monitorList;
817

    
818
    }
819

    
820
    /**
821
     * Low level “are you alive” operation. A valid ping response is 
822
     * indicated by a HTTP status of 200.
823
     * 
824
     * @return true if the service is alive
825
     * 
826
     * @throws InvalidToken
827
     * @throws ServiceFailure
828
     * @throws NotAuthorized
829
     * @throws InvalidRequest
830
     * @throws NotImplemented
831
     */
832
    @Override
833
    public boolean ping() throws NotImplemented, ServiceFailure, NotAuthorized, InvalidRequest, InsufficientResources, UnsupportedType {
834

    
835
        // test if we can get a database connection
836
        boolean alive = false;
837
        int serialNumber = -1;
838
        DBConnection dbConn = null;
839
        try {
840
            dbConn = DBConnectionPool.getDBConnection("MNodeService.ping");
841
            serialNumber = dbConn.getCheckOutSerialNumber();
842
            alive = true;
843
        } catch (SQLException e) {
844
            return alive;
845
        } finally {
846
            // Return the database connection
847
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
848
        }
849

    
850
        return alive;
851
    }
852

    
853
    /**
854
     * A callback method used by a CN to indicate to a MN that it cannot 
855
     * complete synchronization of the science metadata identified by pid.  Log
856
     * the event in the metacat event log.
857
     * 
858
     * @param session
859
     * @param syncFailed
860
     * 
861
     * @throws ServiceFailure
862
     * @throws NotAuthorized
863
     * @throws InvalidRequest
864
     * @throws NotImplemented
865
     */
866
    @Override
867
    public void synchronizationFailed(Session session, SynchronizationFailed syncFailed) throws NotImplemented, ServiceFailure, NotAuthorized, InvalidRequest {
868

    
869
        String localId;
870

    
871
        try {
872
            localId = IdentifierManager.getInstance().getLocalId(syncFailed.getPid());
873
        } catch (McdbDocNotFoundException e) {
874
            throw new InvalidRequest("2163", "The identifier specified by " + syncFailed.getPid() + " was not found on this node.");
875

    
876
        }
877
        // TODO: update the CN URL below when the CNRead.SynchronizationFailed
878
        // method is changed to include the URL as a parameter
879
        logMetacat.debug("Synchronization for the object identified by " + syncFailed.getPid() + " failed from " + syncFailed.getNodeId()
880
                + " Logging the event to the Metacat EventLog as a 'syncFailed' event.");
881
        // TODO: use the event type enum when the SYNCHRONIZATION_FAILED event is added
882
        String principal = Constants.SUBJECT_PUBLIC;
883
        if (session != null && session.getSubject() != null) {
884
        	principal = session.getSubject().getValue();
885
        }
886
        try {
887
        	EventLog.getInstance().log(syncFailed.getNodeId(), principal, localId, "synchronization_failed");
888
        } catch (Exception e) {
889
            throw new ServiceFailure("2161", "Could not log the error for: " + syncFailed.getPid());
890
		}
891
        //EventLog.getInstance().log("CN URL WILL GO HERE", 
892
        //  session.getSubject().getValue(), localId, Event.SYNCHRONIZATION_FAILED);
893

    
894
    }
895

    
896
    /**
897
     * Essentially a get() but with different logging behavior
898
     */
899
    @Override
900
    public InputStream getReplica(Session session, Identifier pid) 
901
        throws InvalidRequest, InvalidToken, NotAuthorized, NotImplemented, 
902
        ServiceFailure, NotFound {
903

    
904
        logMetacat.info("MNodeService.getReplica() called.");
905

    
906
        InputStream inputStream = null; // bytes to be returned
907
        handler = new MetacatHandler(new Timer());
908
        boolean allowed = false;
909
        String localId; // the metacat docid for the pid
910

    
911
        // get the local docid from Metacat
912
        try {
913
            localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
914
        } catch (McdbDocNotFoundException e) {
915
            throw new NotFound("1020", "The object specified by " + pid.getValue() + " does not exist at this node.");
916
        }
917

    
918
        Node node = this.getCapabilities();
919
        Subject targetNodeSubject = node.getSubject(0);
920

    
921
        // check for authorization to replicate
922
        allowed = D1Client.getCN().isNodeAuthorized(session, targetNodeSubject, pid, Permission.REPLICATE);
923

    
924
        logMetacat.info("Called D1Client.isNodeAuthorized(). Allowed = " + allowed +
925
            " for identifier " + pid.getValue());
926

    
927
        // if the person is authorized, perform the read
928
        if (allowed) {
929
            try {
930
                inputStream = handler.read(localId);
931
            } catch (Exception e) {
932
                throw new ServiceFailure("1020", "The object specified by " + pid.getValue() + "could not be returned due to error: " + e.getMessage());
933
            }
934
        }
935

    
936
        // if we fail to set the input stream
937
        if (inputStream == null) {
938
            throw new NotFound("1020", "The object specified by " + pid.getValue() + "does not exist at this node.");
939
        }
940

    
941
        // log the replica event
942
        String principal = null;
943
        if (session.getSubject() != null) {
944
            principal = session.getSubject().getValue();
945
        }
946
        EventLog.getInstance().log(null, principal, localId, "getreplica");
947

    
948
        return inputStream;
949
    }
950

    
951
}
(3-3/6)