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
    	// get system metadata and construct the describe response
452
        SystemMetadata sysmeta = getSystemMetadata(session, pid);
453
        DescribeResponse describeResponse = new DescribeResponse(sysmeta.getFmtid(), sysmeta.getSize(), sysmeta.getDateSysMetadataModified(),
454
                sysmeta.getChecksum());
455

    
456
        return describeResponse;
457

    
458
    }
459

    
460
    /**
461
     * Return the object identified by the given object identifier
462
     * 
463
     * @param session - the Session object containing the credentials for the Subject
464
     * @param pid - the object identifier for the given object
465
     * 
466
     * @return inputStream - the input stream of the given object
467
     * 
468
     * @throws InvalidToken
469
     * @throws ServiceFailure
470
     * @throws NotAuthorized
471
     * @throws InvalidRequest
472
     * @throws NotImplemented
473
     */
474
    @Override
475
    public InputStream get(Session session, Identifier pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented, InvalidRequest {
476

    
477
        return super.get(session, pid);
478

    
479
    }
480

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

    
502
        Checksum checksum = null;
503

    
504
        InputStream inputStream = get(session, pid);
505

    
506
        try {
507
            checksum = ChecksumUtil.checksum(inputStream, algorithm);
508

    
509
        } catch (NoSuchAlgorithmException e) {
510
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned due to an internal error: "
511
                    + e.getMessage());
512
        } catch (IOException e) {
513
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned due to an internal error: "
514
                    + e.getMessage());
515
        }
516

    
517
        if (checksum == null) {
518
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned.");
519
        }
520

    
521
        return checksum;
522
    }
523

    
524
    /**
525
     * Return the system metadata for a given object
526
     * 
527
     * @param session - the Session object containing the credentials for the Subject
528
     * @param pid - the object identifier for the given object
529
     * 
530
     * @return inputStream - the input stream of the given system metadata object
531
     * 
532
     * @throws InvalidToken
533
     * @throws ServiceFailure
534
     * @throws NotAuthorized
535
     * @throws NotFound
536
     * @throws InvalidRequest
537
     * @throws NotImplemented
538
     */
539
    @Override
540
    public SystemMetadata getSystemMetadata(Session session, Identifier pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, InvalidRequest,
541
            NotImplemented {
542

    
543
        return super.getSystemMetadata(session, pid);
544
    }
545

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

    
574
        ObjectList objectList = null;
575

    
576
        try {
577
            objectList = IdentifierManager.getInstance().querySystemMetadata(startTime, endTime, objectFormatId, replicaStatus, start, count);
578
        } catch (Exception e) {
579
            throw new ServiceFailure("1580", "Error querying system metadata: " + e.getMessage());
580
        }
581

    
582
        return objectList;
583
    }
584

    
585
    /**
586
     * Return a description of the node's capabilities and services.
587
     * 
588
     * @return node - the technical capabilities of the Member Node
589
     * 
590
     * @throws ServiceFailure
591
     * @throws NotAuthorized
592
     * @throws InvalidRequest
593
     * @throws NotImplemented
594
     */
595
    @Override
596
    public Node getCapabilities() throws NotImplemented, NotAuthorized, ServiceFailure, InvalidRequest {
597

    
598
        String nodeName = null;
599
        String nodeId = null;
600
        String subject = null;
601
        String nodeDesc = null;
602
        String nodeTypeString = null;
603
        NodeType nodeType = null;
604
        String mnCoreServiceVersion = null;
605
        String mnReadServiceVersion = null;
606
        String mnAuthorizationServiceVersion = null;
607
        String mnStorageServiceVersion = null;
608
        String mnReplicationServiceVersion = null;
609

    
610
        boolean nodeSynchronize = false;
611
        boolean nodeReplicate = false;
612
        boolean mnCoreServiceAvailable = false;
613
        boolean mnReadServiceAvailable = false;
614
        boolean mnAuthorizationServiceAvailable = false;
615
        boolean mnStorageServiceAvailable = false;
616
        boolean mnReplicationServiceAvailable = false;
617

    
618
        try {
619
            // get the properties of the node based on configuration information
620
            nodeName = PropertyService.getProperty("dataone.nodeName");
621
            nodeId = PropertyService.getProperty("dataone.memberNodeId");
622
            subject = PropertyService.getProperty("dataone.subject");
623
            nodeDesc = PropertyService.getProperty("dataone.nodeDescription");
624
            nodeTypeString = PropertyService.getProperty("dataone.nodeType");
625
            nodeType = NodeType.convert(nodeTypeString);
626
            nodeSynchronize = new Boolean(PropertyService.getProperty("dataone.nodeSynchronize")).booleanValue();
627
            nodeReplicate = new Boolean(PropertyService.getProperty("dataone.nodeReplicate")).booleanValue();
628

    
629
            mnCoreServiceVersion = PropertyService.getProperty("dataone.mnCore.serviceVersion");
630
            mnReadServiceVersion = PropertyService.getProperty("dataone.mnRead.serviceVersion");
631
            mnAuthorizationServiceVersion = PropertyService.getProperty("dataone.mnAuthorization.serviceVersion");
632
            mnStorageServiceVersion = PropertyService.getProperty("dataone.mnStorage.serviceVersion");
633
            mnReplicationServiceVersion = PropertyService.getProperty("dataone.mnReplication.serviceVersion");
634

    
635
            mnCoreServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnCore.serviceAvailable")).booleanValue();
636
            mnReadServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnRead.serviceAvailable")).booleanValue();
637
            mnAuthorizationServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnAuthorization.serviceAvailable")).booleanValue();
638
            mnStorageServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnStorage.serviceAvailable")).booleanValue();
639
            mnReplicationServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnReplication.serviceAvailable")).booleanValue();
640

    
641
            // Set the properties of the node based on configuration information and
642
            // calls to current status methods
643
            Node node = new Node();
644
            node.setBaseURL(metacatUrl + "/" + nodeTypeString);
645
            node.setDescription(nodeDesc);
646

    
647
            // set the node's health information
648
            node.setState(NodeState.UP);
649
            
650
            // set the ping response to the current value
651
            Ping canPing = new Ping();
652
            canPing.setSuccess(false);
653
            try {
654
                canPing.setSuccess(ping());
655
            } catch (InsufficientResources e) {
656
                e.printStackTrace();
657
            } catch (UnsupportedType e) {
658
                e.printStackTrace();
659
            }
660
            node.setPing(canPing);
661

    
662
            NodeReference identifier = new NodeReference();
663
            identifier.setValue(nodeId);
664
            node.setIdentifier(identifier);
665
            Subject s = new Subject();
666
            s.setValue(subject);
667
            node.addSubject(s);
668
            node.setName(nodeName);
669
            node.setReplicate(nodeReplicate);
670
            node.setSynchronize(nodeSynchronize);
671

    
672
            // services: MNAuthorization, MNCore, MNRead, MNReplication, MNStorage
673
            Services services = new Services();
674

    
675
            Service sMNCore = new Service();
676
            sMNCore.setName("MNCore");
677
            sMNCore.setVersion(mnCoreServiceVersion);
678
            sMNCore.setAvailable(mnCoreServiceAvailable);
679

    
680
            Service sMNRead = new Service();
681
            sMNRead.setName("MNRead");
682
            sMNRead.setVersion(mnReadServiceVersion);
683
            sMNRead.setAvailable(mnReadServiceAvailable);
684

    
685
            Service sMNAuthorization = new Service();
686
            sMNAuthorization.setName("MNAuthorization");
687
            sMNAuthorization.setVersion(mnAuthorizationServiceVersion);
688
            sMNAuthorization.setAvailable(mnAuthorizationServiceAvailable);
689

    
690
            Service sMNStorage = new Service();
691
            sMNStorage.setName("MNStorage");
692
            sMNStorage.setVersion(mnStorageServiceVersion);
693
            sMNStorage.setAvailable(mnStorageServiceAvailable);
694

    
695
            Service sMNReplication = new Service();
696
            sMNReplication.setName("MNReplication");
697
            sMNReplication.setVersion(mnReplicationServiceVersion);
698
            sMNReplication.setAvailable(mnReplicationServiceAvailable);
699

    
700
            services.addService(sMNRead);
701
            services.addService(sMNCore);
702
            services.addService(sMNAuthorization);
703
            services.addService(sMNStorage);
704
            services.addService(sMNReplication);
705
            node.setServices(services);
706

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

    
724
            node.setType(nodeType);
725
            return node;
726

    
727
        } catch (PropertyNotFoundException pnfe) {
728
            String msg = "MNodeService.getCapabilities(): " + "property not found: " + pnfe.getMessage();
729
            logMetacat.error(msg);
730
            throw new ServiceFailure("2162", msg);
731
        }
732
    }
733

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

    
757
        MonitorList monitorList = new MonitorList();
758

    
759
        try {
760

    
761
            // get log records first
762
            Log logs = getLogRecords(session, startTime, endTime, event, 0, null);
763

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

    
782
            }
783
        } catch (Exception e) {
784
            e.printStackTrace();
785
            throw new ServiceFailure("2081", "Could not retrieve statistics: " + e.getMessage());
786
        }
787

    
788
        return monitorList;
789

    
790
    }
791

    
792
    /**
793
     * Low level “are you alive” operation. A valid ping response is 
794
     * indicated by a HTTP status of 200.
795
     * 
796
     * @return true if the service is alive
797
     * 
798
     * @throws InvalidToken
799
     * @throws ServiceFailure
800
     * @throws NotAuthorized
801
     * @throws InvalidRequest
802
     * @throws NotImplemented
803
     */
804
    @Override
805
    public boolean ping() throws NotImplemented, ServiceFailure, NotAuthorized, InvalidRequest, InsufficientResources, UnsupportedType {
806

    
807
        // test if we can get a database connection
808
        boolean alive = false;
809
        int serialNumber = -1;
810
        DBConnection dbConn = null;
811
        try {
812
            dbConn = DBConnectionPool.getDBConnection("MNodeService.ping");
813
            serialNumber = dbConn.getCheckOutSerialNumber();
814
            alive = true;
815
        } catch (SQLException e) {
816
            return alive;
817
        } finally {
818
            // Return the database connection
819
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
820
        }
821

    
822
        return alive;
823
    }
824

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

    
841
        String localId;
842

    
843
        try {
844
            localId = IdentifierManager.getInstance().getLocalId(syncFailed.getPid());
845
        } catch (McdbDocNotFoundException e) {
846
            throw new InvalidRequest("2163", "The identifier specified by " + syncFailed.getPid() + " was not found on this node.");
847

    
848
        }
849
        // TODO: update the CN URL below when the CNRead.SynchronizationFailed
850
        // method is changed to include the URL as a parameter
851
        logMetacat.debug("Synchronization for the object identified by " + syncFailed.getPid() + " failed from " + syncFailed.getNodeId()
852
                + " Logging the event to the Metacat EventLog as a 'syncFailed' event.");
853
        // TODO: use the event type enum when the SYNCHRONIZATION_FAILED event is added
854
        String principal = Constants.PUBLIC_SUBJECT;
855
        if (session != null && session.getSubject() != null) {
856
        	principal = session.getSubject().getValue();
857
        }
858
        try {
859
        	EventLog.getInstance().log(syncFailed.getNodeId(), principal, localId, "synchronization_failed");
860
        } catch (Exception e) {
861
            throw new ServiceFailure("2161", "Could not log the error for: " + syncFailed.getPid());
862
		}
863
        //EventLog.getInstance().log("CN URL WILL GO HERE", 
864
        //  session.getSubject().getValue(), localId, Event.SYNCHRONIZATION_FAILED);
865

    
866
    }
867

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

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

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

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

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

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

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

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

    
913
        return inputStream;
914
    }
915

    
916
}
(3-3/6)