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.Date;
31
import java.util.List;
32
import java.util.Timer;
33

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

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

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

    
122
    /* the instance of the MNodeService object */
123
    private static MNodeService instance = null;
124

    
125
    /* the logger instance */
126
    private Logger logMetacat = null;
127

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

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

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

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

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

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

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

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

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

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

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

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

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

    
223
        return pid;
224
    }
225

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

    
255
        // check if the pid has been reserved
256
        try {
257
            boolean hasReservation = D1Client.getCN().hasReservation(session, pid);
258
            if (!hasReservation) {
259
                throw new NotAuthorized("", "No reservation for pid: " + pid.getValue());
260
            }
261
        } catch (NotFound e) {
262
            // okay to continue
263
        }
264

    
265
        String localId = null;
266
        boolean allowed = false;
267
        boolean isScienceMetadata = false;
268
        Subject subject = session.getSubject();
269

    
270
        // do we have a valid pid?
271
        if (pid == null || pid.getValue().trim().equals("")) {
272
            throw new InvalidRequest("1202", "The provided identifier was invalid.");
273
        }
274

    
275
        // check for the existing identifier
276
        try {
277
            localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
278
        } catch (McdbDocNotFoundException e) {
279
            throw new InvalidRequest("1202", "The object with the provided " + "identifier was not found.");
280
        }
281

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

    
285
        if (allowed) {
286

    
287
            // get the existing system metadata for the object
288
            SystemMetadata existingSysMeta = getSystemMetadata(session, pid);
289

    
290
            // add the newPid to the obsoletedBy list for the existing sysmeta
291
            existingSysMeta.setObsoletedBy(newPid);
292

    
293
            // then update the existing system metadata
294
            updateSystemMetadata(existingSysMeta);
295

    
296
            // prep the new system metadata, add pid to the affected lists
297
            sysmeta.setObsoletes(pid);
298
            //sysmeta.addDerivedFrom(pid);
299

    
300
            isScienceMetadata = isScienceMetadata(sysmeta);
301

    
302
            // do we have XML metadata or a data object?
303
            if (isScienceMetadata) {
304

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

    
316
                    }
317

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

    
323
                }
324

    
325
            } else {
326

    
327
                // update the data object
328
                localId = insertDataObject(object, newPid, session);
329

    
330
            }
331

    
332
            // and insert the new system metadata
333
            insertSystemMetadata(sysmeta);
334

    
335
            // log the update event
336
            EventLog.getInstance().log(metacatUrl, subject.getValue(), localId, "update");
337

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

    
343
        return newPid;
344
    }
345

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

    
349
        // check if the pid has been reserved
350
        try {
351
            boolean hasReservation = D1Client.getCN().hasReservation(session, pid);
352
            if (!hasReservation) {
353
                throw new NotAuthorized("", "No reservation for pid: " + pid.getValue());
354
            }
355
        } catch (NotFound e) {
356
            // okay to continue
357
        }
358

    
359
        return super.create(session, pid, object, sysmeta);
360
    }
361

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

    
387
        boolean result = false;
388

    
389
        // TODO: check credentials
390

    
391
        // get the referenced object
392
        Identifier pid = sysmeta.getIdentifier();
393

    
394
        // get from the membernode
395
        // TODO: switch credentials for the server retrieval?
396
        MNode mn = D1Client.getMN(sourceNode);
397
        InputStream object = null;
398

    
399
        try {
400
            object = mn.get(session, pid);
401
        } catch (InvalidToken e) {
402
            e.printStackTrace();
403
            throw new ServiceFailure("2151", "Could not retrieve object to replicate (InvalidToken): " + e.getMessage());
404
        } catch (NotFound e) {
405
            e.printStackTrace();
406
            throw new ServiceFailure("2151", "Could not retrieve object to replicate (NotFound): " + e.getMessage());
407
        }
408

    
409
        // add it to local store
410
        Identifier retPid;
411
        try {
412
            retPid = create(session, pid, object, sysmeta);
413
            result = (retPid.getValue().equals(pid.getValue()));
414
        } catch (InvalidToken e) {
415
            e.printStackTrace();
416
            throw new ServiceFailure("2151", "Could not save object to local store (InvalidToken): " + e.getMessage());
417
        } catch (IdentifierNotUnique e) {
418
            e.printStackTrace();
419
            throw new ServiceFailure("2151", "Could not save object to local store (IdentifierNotUnique): " + e.getMessage());
420
        } catch (InvalidSystemMetadata e) {
421
            e.printStackTrace();
422
            throw new ServiceFailure("2151", "Could not save object to local store (InvalidSystemMetadata): " + e.getMessage());
423
        }
424

    
425
        return result;
426

    
427
    }
428

    
429
    /**
430
     * This method provides a lighter weight mechanism than 
431
     * MN_read.getSystemMetadata() for a client to determine basic 
432
     * properties of the referenced object.
433
     * 
434
     * @param session - the Session object containing the credentials for the Subject
435
     * @param pid - the identifier of the object to be described
436
     * 
437
     * @return describeResponse - A set of values providing a basic description 
438
     *                            of the object.
439
     * 
440
     * @throws InvalidToken
441
     * @throws ServiceFailure
442
     * @throws NotAuthorized
443
     * @throws NotFound
444
     * @throws NotImplemented
445
     * @throws InvalidRequest
446
     */
447
    @Override
448
    public DescribeResponse describe(Session session, Identifier pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented,
449
            InvalidRequest {
450

    
451
        if (session == null) {
452
            throw new InvalidToken("1370", "The session object is null");
453
        }
454

    
455
        if (pid == null || pid.getValue().trim().equals("")) {
456
            throw new InvalidRequest("1362", "The object identifier is null. " + "A valid identifier is required.");
457
        }
458

    
459
        SystemMetadata sysmeta = getSystemMetadata(session, pid);
460
        DescribeResponse describeResponse = new DescribeResponse(sysmeta.getFmtid(), sysmeta.getSize(), sysmeta.getDateSysMetadataModified(),
461
                sysmeta.getChecksum());
462

    
463
        return describeResponse;
464

    
465
    }
466

    
467
    /**
468
     * Return the object identified by the given object identifier
469
     * 
470
     * @param session - the Session object containing the credentials for the Subject
471
     * @param pid - the object identifier for the given object
472
     * 
473
     * @return inputStream - the input stream of the given object
474
     * 
475
     * @throws InvalidToken
476
     * @throws ServiceFailure
477
     * @throws NotAuthorized
478
     * @throws InvalidRequest
479
     * @throws NotImplemented
480
     */
481
    @Override
482
    public InputStream get(Session session, Identifier pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented, InvalidRequest {
483

    
484
        return super.get(session, pid);
485

    
486
    }
487

    
488
    /**
489
     * Returns a Checksum for the specified object using an accepted hashing algorithm
490
     * 
491
     * @param session - the Session object containing the credentials for the Subject
492
     * @param pid - the object identifier for the given object
493
     * @param algorithm -  the name of an algorithm that will be used to compute 
494
     *                     a checksum of the bytes of the object
495
     * 
496
     * @return checksum - the checksum of the given object
497
     * 
498
     * @throws InvalidToken
499
     * @throws ServiceFailure
500
     * @throws NotAuthorized
501
     * @throws NotFound
502
     * @throws InvalidRequest
503
     * @throws NotImplemented
504
     */
505
    @Override
506
    public Checksum getChecksum(Session session, Identifier pid, String algorithm) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
507
            InvalidRequest, NotImplemented {
508

    
509
        Checksum checksum = null;
510

    
511
        InputStream inputStream = get(session, pid);
512

    
513
        try {
514
            checksum = ChecksumUtil.checksum(inputStream, algorithm);
515

    
516
        } catch (NoSuchAlgorithmException e) {
517
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned due to an internal error: "
518
                    + e.getMessage());
519
        } catch (IOException e) {
520
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned due to an internal error: "
521
                    + e.getMessage());
522
        }
523

    
524
        if (checksum == null) {
525
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned.");
526
        }
527

    
528
        return checksum;
529
    }
530

    
531
    /**
532
     * Return the system metadata for a given object
533
     * 
534
     * @param session - the Session object containing the credentials for the Subject
535
     * @param pid - the object identifier for the given object
536
     * 
537
     * @return inputStream - the input stream of the given system metadata object
538
     * 
539
     * @throws InvalidToken
540
     * @throws ServiceFailure
541
     * @throws NotAuthorized
542
     * @throws NotFound
543
     * @throws InvalidRequest
544
     * @throws NotImplemented
545
     */
546
    @Override
547
    public SystemMetadata getSystemMetadata(Session session, Identifier pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, InvalidRequest,
548
            NotImplemented {
549

    
550
        return super.getSystemMetadata(session, pid);
551
    }
552

    
553
    /**
554
     * Retrieve the list of objects present on the MN that match the calling parameters
555
     * 
556
     * @param session - the Session object containing the credentials for the Subject
557
     * @param startTime - Specifies the beginning of the time range from which 
558
     *                    to return object (>=)
559
     * @param endTime - Specifies the beginning of the time range from which 
560
     *                  to return object (>=)
561
     * @param objectFormat - Restrict results to the specified object format
562
     * @param replicaStatus - Indicates if replicated objects should be returned in the list
563
     * @param start - The zero-based index of the first value, relative to the 
564
     *                first record of the resultset that matches the parameters.
565
     * @param count - The maximum number of entries that should be returned in 
566
     *                the response. The Member Node may return less entries 
567
     *                than specified in this value.
568
     * 
569
     * @return objectList - the list of objects matching the criteria
570
     * 
571
     * @throws InvalidToken
572
     * @throws ServiceFailure
573
     * @throws NotAuthorized
574
     * @throws InvalidRequest
575
     * @throws NotImplemented
576
     */
577
    @Override
578
    public ObjectList listObjects(Session session, Date startTime, Date endTime, ObjectFormatIdentifier objectFormatId, Boolean replicaStatus, Integer start,
579
            Integer count) throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken {
580

    
581
        ObjectList objectList = null;
582

    
583
        try {
584
            objectList = IdentifierManager.getInstance().querySystemMetadata(startTime, endTime, objectFormatId, replicaStatus, start, count);
585
        } catch (Exception e) {
586
            throw new ServiceFailure("1580", "Error querying system metadata: " + e.getMessage());
587
        }
588

    
589
        return objectList;
590
    }
591

    
592
    /**
593
     * Return a description of the node's capabilities and services.
594
     * 
595
     * @return node - the technical capabilities of the Member Node
596
     * 
597
     * @throws ServiceFailure
598
     * @throws NotAuthorized
599
     * @throws InvalidRequest
600
     * @throws NotImplemented
601
     */
602
    @Override
603
    public Node getCapabilities() throws NotImplemented, NotAuthorized, ServiceFailure, InvalidRequest {
604

    
605
        String nodeName = null;
606
        String nodeId = null;
607
        String subject = null;
608
        String nodeDesc = null;
609
        String nodeTypeString = null;
610
        NodeType nodeType = null;
611
        String mnCoreServiceVersion = null;
612
        String mnReadServiceVersion = null;
613
        String mnAuthorizationServiceVersion = null;
614
        String mnStorageServiceVersion = null;
615
        String mnReplicationServiceVersion = null;
616

    
617
        boolean nodeSynchronize = false;
618
        boolean nodeReplicate = false;
619
        boolean mnCoreServiceAvailable = false;
620
        boolean mnReadServiceAvailable = false;
621
        boolean mnAuthorizationServiceAvailable = false;
622
        boolean mnStorageServiceAvailable = false;
623
        boolean mnReplicationServiceAvailable = false;
624

    
625
        try {
626
            // get the properties of the node based on configuration information
627
            nodeName = PropertyService.getProperty("dataone.nodeName");
628
            nodeId = PropertyService.getProperty("dataone.memberNodeId");
629
            subject = PropertyService.getProperty("dataone.subject");
630
            nodeDesc = PropertyService.getProperty("dataone.nodeDescription");
631
            nodeTypeString = PropertyService.getProperty("dataone.nodeType");
632
            nodeType = NodeType.convert(nodeTypeString);
633
            nodeSynchronize = new Boolean(PropertyService.getProperty("dataone.nodeSynchronize")).booleanValue();
634
            nodeReplicate = new Boolean(PropertyService.getProperty("dataone.nodeReplicate")).booleanValue();
635

    
636
            mnCoreServiceVersion = PropertyService.getProperty("dataone.mnCore.serviceVersion");
637
            mnReadServiceVersion = PropertyService.getProperty("dataone.mnRead.serviceVersion");
638
            mnAuthorizationServiceVersion = PropertyService.getProperty("dataone.mnAuthorization.serviceVersion");
639
            mnStorageServiceVersion = PropertyService.getProperty("dataone.mnStorage.serviceVersion");
640
            mnReplicationServiceVersion = PropertyService.getProperty("dataone.mnReplication.serviceVersion");
641

    
642
            mnCoreServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnCore.serviceAvailable")).booleanValue();
643
            mnReadServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnRead.serviceAvailable")).booleanValue();
644
            mnAuthorizationServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnAuthorization.serviceAvailable")).booleanValue();
645
            mnStorageServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnStorage.serviceAvailable")).booleanValue();
646
            mnReplicationServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnReplication.serviceAvailable")).booleanValue();
647

    
648
            // Set the properties of the node based on configuration information and
649
            // calls to current status methods
650
            Node node = new Node();
651
            node.setBaseURL(metacatUrl + "/" + nodeTypeString);
652
            node.setDescription(nodeDesc);
653

    
654
            // set the node's health information
655
            node.setState(NodeState.UP);
656
            
657
            // set the ping response to the current value
658
            Ping canPing = new Ping();
659
            canPing.setSuccess(false);
660
            try {
661
                canPing.setSuccess(ping());
662
            } catch (InsufficientResources e) {
663
                e.printStackTrace();
664
            } catch (UnsupportedType e) {
665
                e.printStackTrace();
666
            }
667
            node.setPing(canPing);
668

    
669
            NodeReference identifier = new NodeReference();
670
            identifier.setValue(nodeId);
671
            node.setIdentifier(identifier);
672
            Subject s = new Subject();
673
            s.setValue(subject);
674
            node.addSubject(s);
675
            node.setName(nodeName);
676
            node.setReplicate(nodeReplicate);
677
            node.setSynchronize(nodeSynchronize);
678

    
679
            // services: MNAuthorization, MNCore, MNRead, MNReplication, MNStorage
680
            Services services = new Services();
681

    
682
            Service sMNCore = new Service();
683
            sMNCore.setName("MNCore");
684
            sMNCore.setVersion(mnCoreServiceVersion);
685
            sMNCore.setAvailable(mnCoreServiceAvailable);
686

    
687
            Service sMNRead = new Service();
688
            sMNRead.setName("MNRead");
689
            sMNRead.setVersion(mnReadServiceVersion);
690
            sMNRead.setAvailable(mnReadServiceAvailable);
691

    
692
            Service sMNAuthorization = new Service();
693
            sMNAuthorization.setName("MNAuthorization");
694
            sMNAuthorization.setVersion(mnAuthorizationServiceVersion);
695
            sMNAuthorization.setAvailable(mnAuthorizationServiceAvailable);
696

    
697
            Service sMNStorage = new Service();
698
            sMNStorage.setName("MNStorage");
699
            sMNStorage.setVersion(mnStorageServiceVersion);
700
            sMNStorage.setAvailable(mnStorageServiceAvailable);
701

    
702
            Service sMNReplication = new Service();
703
            sMNReplication.setName("MNReplication");
704
            sMNReplication.setVersion(mnReplicationServiceVersion);
705
            sMNReplication.setAvailable(mnReplicationServiceAvailable);
706

    
707
            services.addService(sMNRead);
708
            services.addService(sMNCore);
709
            services.addService(sMNAuthorization);
710
            services.addService(sMNStorage);
711
            services.addService(sMNReplication);
712
            node.setServices(services);
713

    
714
            // TODO: Allow the metacat admin to determine the schedule
715
            // Set the schedule for synchronization
716
            Synchronization synchronization = new Synchronization();
717
            Schedule schedule = new Schedule();
718
            Date now = new Date();
719
            schedule.setYear("*");
720
            schedule.setMon("*");
721
            schedule.setMday("*");
722
            schedule.setWday("*");
723
            schedule.setHour("*");
724
            schedule.setMin("0,5,10,15,20,25,30,35,40,45,50,55");
725
            schedule.setSec("*");
726
            synchronization.setSchedule(schedule);
727
            synchronization.setLastHarvested(now);
728
            synchronization.setLastCompleteHarvest(now);
729
            node.setSynchronization(synchronization);
730

    
731
            node.setType(nodeType);
732
            return node;
733

    
734
        } catch (PropertyNotFoundException pnfe) {
735
            String msg = "MNodeService.getCapabilities(): " + "property not found: " + pnfe.getMessage();
736
            logMetacat.error(msg);
737
            throw new ServiceFailure("2162", msg);
738
        }
739
    }
740

    
741
    /**
742
     * Returns the number of operations that have been serviced by the node 
743
     * over time periods of one and 24 hours.
744
     * 
745
     * @param session - the Session object containing the credentials for the Subject
746
     * @param period - An ISO8601 compatible DateTime range specifying the time 
747
     *                 range for which to return operation statistics.
748
     * @param requestor - Limit to operations performed by given requestor identity.
749
     * @param event -  Enumerated value indicating the type of event being examined
750
     * @param format - Limit to events involving objects of the specified format
751
     * 
752
     * @return the desired log records
753
     * 
754
     * @throws InvalidToken
755
     * @throws ServiceFailure
756
     * @throws NotAuthorized
757
     * @throws InvalidRequest
758
     * @throws NotImplemented
759
     */
760
    @Override
761
    public MonitorList getOperationStatistics(Session session, Date startTime, Date endTime, Subject requestor, Event event, ObjectFormatIdentifier formatId)
762
            throws NotImplemented, ServiceFailure, NotAuthorized, InvalidRequest, InsufficientResources, UnsupportedType {
763

    
764
        MonitorList monitorList = new MonitorList();
765

    
766
        try {
767

    
768
            // get log records first
769
            Log logs = getLogRecords(session, startTime, endTime, event, 0, null);
770

    
771
            // TODO: aggregate by day or hour -- needs clarification
772
            int count = 1;
773
            for (LogEntry logEntry : logs.getLogEntryList()) {
774
                Identifier pid = logEntry.getIdentifier();
775
                Date logDate = logEntry.getDateLogged();
776
                // if we are filtering by format
777
                if (formatId != null) {
778
                    SystemMetadata sysmeta = IdentifierManager.getInstance().getSystemMetadata(pid.getValue());
779
                    if (!sysmeta.getFmtid().getValue().equals(formatId.getValue())) {
780
                        // does not match
781
                        continue;
782
                    }
783
                }
784
                MonitorInfo item = new MonitorInfo();
785
                item.setCount(count);
786
                item.setDate(new java.sql.Date(logDate.getTime()));
787
                monitorList.addMonitorInfo(item);
788

    
789
            }
790
        } catch (Exception e) {
791
            e.printStackTrace();
792
            throw new ServiceFailure("2081", "Could not retrieve statistics: " + e.getMessage());
793
        }
794

    
795
        return monitorList;
796

    
797
    }
798

    
799
    /**
800
     * Low level “are you alive” operation. A valid ping response is 
801
     * indicated by a HTTP status of 200.
802
     * 
803
     * @return true if the service is alive
804
     * 
805
     * @throws InvalidToken
806
     * @throws ServiceFailure
807
     * @throws NotAuthorized
808
     * @throws InvalidRequest
809
     * @throws NotImplemented
810
     */
811
    @Override
812
    public boolean ping() throws NotImplemented, ServiceFailure, NotAuthorized, InvalidRequest, InsufficientResources, UnsupportedType {
813

    
814
        // test if we can get a database connection
815
        boolean alive = false;
816
        int serialNumber = -1;
817
        DBConnection dbConn = null;
818
        try {
819
            dbConn = DBConnectionPool.getDBConnection("MNodeService.ping");
820
            serialNumber = dbConn.getCheckOutSerialNumber();
821
            alive = true;
822
        } catch (SQLException e) {
823
            return alive;
824
        } finally {
825
            // Return the database connection
826
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
827
        }
828

    
829
        return alive;
830
    }
831

    
832
    /**
833
     * A callback method used by a CN to indicate to a MN that it cannot 
834
     * complete synchronization of the science metadata identified by pid.  Log
835
     * the event in the metacat event log.
836
     * 
837
     * @param session
838
     * @param syncFailed
839
     * 
840
     * @throws ServiceFailure
841
     * @throws NotAuthorized
842
     * @throws InvalidRequest
843
     * @throws NotImplemented
844
     */
845
    @Override
846
    public void synchronizationFailed(Session session, SynchronizationFailed syncFailed) throws NotImplemented, ServiceFailure, NotAuthorized, InvalidRequest {
847

    
848
        String localId;
849

    
850
        try {
851
            localId = IdentifierManager.getInstance().getLocalId(syncFailed.getPid());
852
        } catch (McdbDocNotFoundException e) {
853
            throw new InvalidRequest("2163", "The identifier specified by " + syncFailed.getPid() + " was not found on this node.");
854

    
855
        }
856
        // TODO: update the CN URL below when the CNRead.SynchronizationFailed
857
        // method is changed to include the URL as a parameter
858
        logMetacat.debug("Synchronization for the object identified by " + syncFailed.getPid() + " failed from " + syncFailed.getNodeId()
859
                + " Logging the event to the Metacat EventLog as a 'syncFailed' event.");
860
        // TODO: use the event type enum when the SYNCHRONIZATION_FAILED event is added
861
        EventLog.getInstance().log(syncFailed.getNodeId(), session.getSubject().getValue(), localId, "synchronization_failed");
862
        //EventLog.getInstance().log("CN URL WILL GO HERE", 
863
        //  session.getSubject().getValue(), localId, Event.SYNCHRONIZATION_FAILED);
864

    
865
    }
866

    
867
    /**
868
     * Essentially a get() but with different logging behavior
869
     */
870
    @Override
871
    public InputStream getReplica(Session session, Identifier pid) throws InvalidRequest, InvalidToken, NotAuthorized, NotImplemented, ServiceFailure, NotFound {
872

    
873
        InputStream inputStream = null; // bytes to be returned
874
        handler = new MetacatHandler(new Timer());
875
        boolean allowed = false;
876
        String localId; // the metacat docid for the pid
877

    
878
        // get the local docid from Metacat
879
        try {
880
            localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
881
        } catch (McdbDocNotFoundException e) {
882
            throw new NotFound("1020", "The object specified by " + pid.getValue() + " does not exist at this node.");
883
        }
884

    
885
        Node node = this.getCapabilities();
886
        Subject targetNodeSubject = node.getSubject(0);
887

    
888
        // check for authorization to replicate
889
        allowed = D1Client.getCN().isNodeAuthorized(session, targetNodeSubject, pid, Permission.REPLICATE);
890

    
891
        // if the person is authorized, perform the read
892
        if (allowed) {
893
            try {
894
                inputStream = handler.read(localId);
895
            } catch (Exception e) {
896
                throw new ServiceFailure("1020", "The object specified by " + pid.getValue() + "could not be returned due to error: " + e.getMessage());
897
            }
898
        }
899

    
900
        // if we fail to set the input stream
901
        if (inputStream == null) {
902
            throw new NotFound("1020", "The object specified by " + pid.getValue() + "does not exist at this node.");
903
        }
904

    
905
        // log the replica event
906
        String principal = null;
907
        if (session.getSubject() != null) {
908
            principal = session.getSubject().getValue();
909
        }
910
        EventLog.getInstance().log(null, principal, localId, "getreplica");
911

    
912
        return inputStream;
913
    }
914

    
915
}
(3-3/6)