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.Synchronization;
77
import org.dataone.service.types.v1.SystemMetadata;
78
import org.dataone.service.types.v1.util.ChecksumUtil;
79
import org.dataone.service.util.Constants;
80

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
222
        return pid;
223
    }
224

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

    
254
        String localId = null;
255
        boolean allowed = false;
256
        boolean isScienceMetadata = false;
257
        Subject subject = session.getSubject();
258

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

    
264
        // check for the existing identifier
265
        try {
266
            localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
267
        } catch (McdbDocNotFoundException e) {
268
            throw new InvalidRequest("1202", "The object with the provided " + "identifier was not found.");
269
        }
270
        
271
        // set the originating node
272
        NodeReference originMemberNode = this.getCapabilities().getIdentifier();
273
        sysmeta.setOriginMemberNode(originMemberNode);
274
        
275
        // set the submitter to match the certificate
276
        sysmeta.setSubmitter(subject);
277

    
278
        // does the subject have WRITE ( == update) priveleges on the pid?
279
        allowed = isAuthorized(session, pid, Permission.WRITE);
280

    
281
        if (allowed) {
282

    
283
            // get the existing system metadata for the object
284
            SystemMetadata existingSysMeta = getSystemMetadata(session, pid);
285

    
286
            // add the newPid to the obsoletedBy list for the existing sysmeta
287
            existingSysMeta.setObsoletedBy(newPid);
288

    
289
            // then update the existing system metadata
290
            updateSystemMetadata(existingSysMeta);
291

    
292
            // prep the new system metadata, add pid to the affected lists
293
            sysmeta.setObsoletes(pid);
294
            //sysmeta.addDerivedFrom(pid);
295

    
296
            isScienceMetadata = isScienceMetadata(sysmeta);
297

    
298
            // do we have XML metadata or a data object?
299
            if (isScienceMetadata) {
300

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

    
312
                    }
313

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

    
319
                }
320

    
321
            } else {
322

    
323
                // update the data object
324
                localId = insertDataObject(object, newPid, session);
325

    
326
            }
327

    
328
            // and insert the new system metadata
329
            insertSystemMetadata(sysmeta);
330

    
331
            // log the update event
332
            EventLog.getInstance().log(metacatUrl, subject.getValue(), localId, "update");
333

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

    
339
        return newPid;
340
    }
341

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

    
345
        // set the submitter to match the certificate
346
        sysmeta.setSubmitter(session.getSubject());
347
        // set the originating node
348
        NodeReference originMemberNode = this.getCapabilities().getIdentifier();
349
        sysmeta.setOriginMemberNode(originMemberNode);
350
        // call the shared impl
351
        return super.create(session, pid, object, sysmeta);
352
    }
353

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

    
379
        boolean result = false;
380

    
381
        // TODO: check credentials
382

    
383
        // get the referenced object
384
        Identifier pid = sysmeta.getIdentifier();
385

    
386
        // get from the membernode
387
        // TODO: switch credentials for the server retrieval?
388
        MNode mn = D1Client.getMN(sourceNode);
389
        InputStream object = null;
390

    
391
        try {
392
            object = mn.get(session, pid);
393
        } catch (InvalidToken e) {
394
            e.printStackTrace();
395
            throw new ServiceFailure("2151", "Could not retrieve object to replicate (InvalidToken): " + e.getMessage());
396
        } catch (NotFound e) {
397
            e.printStackTrace();
398
            throw new ServiceFailure("2151", "Could not retrieve object to replicate (NotFound): " + e.getMessage());
399
        }
400

    
401
        // add it to local store
402
        Identifier retPid;
403
        try {
404
            retPid = create(session, pid, object, sysmeta);
405
            result = (retPid.getValue().equals(pid.getValue()));
406
        } catch (InvalidToken e) {
407
            e.printStackTrace();
408
            throw new ServiceFailure("2151", "Could not save object to local store (InvalidToken): " + e.getMessage());
409
        } catch (IdentifierNotUnique e) {
410
            e.printStackTrace();
411
            throw new ServiceFailure("2151", "Could not save object to local store (IdentifierNotUnique): " + e.getMessage());
412
        } catch (InvalidSystemMetadata e) {
413
            e.printStackTrace();
414
            throw new ServiceFailure("2151", "Could not save object to local store (InvalidSystemMetadata): " + e.getMessage());
415
        }
416

    
417
        return result;
418

    
419
    }
420

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

    
443
    	// get system metadata and construct the describe response
444
        SystemMetadata sysmeta = getSystemMetadata(session, pid);
445
        DescribeResponse describeResponse = new DescribeResponse(sysmeta.getFmtid(), sysmeta.getSize(), sysmeta.getDateSysMetadataModified(),
446
                sysmeta.getChecksum());
447

    
448
        return describeResponse;
449

    
450
    }
451

    
452
    /**
453
     * Return the object identified by the given object identifier
454
     * 
455
     * @param session - the Session object containing the credentials for the Subject
456
     * @param pid - the object identifier for the given object
457
     * 
458
     * @return inputStream - the input stream of the given object
459
     * 
460
     * @throws InvalidToken
461
     * @throws ServiceFailure
462
     * @throws NotAuthorized
463
     * @throws InvalidRequest
464
     * @throws NotImplemented
465
     */
466
    @Override
467
    public InputStream get(Session session, Identifier pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented, InvalidRequest {
468

    
469
        return super.get(session, pid);
470

    
471
    }
472

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

    
494
        Checksum checksum = null;
495

    
496
        InputStream inputStream = get(session, pid);
497

    
498
        try {
499
            checksum = ChecksumUtil.checksum(inputStream, algorithm);
500

    
501
        } catch (NoSuchAlgorithmException e) {
502
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned due to an internal error: "
503
                    + e.getMessage());
504
        } catch (IOException e) {
505
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned due to an internal error: "
506
                    + e.getMessage());
507
        }
508

    
509
        if (checksum == null) {
510
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned.");
511
        }
512

    
513
        return checksum;
514
    }
515

    
516
    /**
517
     * Return the system metadata for a given object
518
     * 
519
     * @param session - the Session object containing the credentials for the Subject
520
     * @param pid - the object identifier for the given object
521
     * 
522
     * @return inputStream - the input stream of the given system metadata object
523
     * 
524
     * @throws InvalidToken
525
     * @throws ServiceFailure
526
     * @throws NotAuthorized
527
     * @throws NotFound
528
     * @throws InvalidRequest
529
     * @throws NotImplemented
530
     */
531
    @Override
532
    public SystemMetadata getSystemMetadata(Session session, Identifier pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, InvalidRequest,
533
            NotImplemented {
534

    
535
        return super.getSystemMetadata(session, pid);
536
    }
537

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

    
566
        ObjectList objectList = null;
567

    
568
        try {
569
            objectList = IdentifierManager.getInstance().querySystemMetadata(startTime, endTime, objectFormatId, replicaStatus, start, count);
570
        } catch (Exception e) {
571
            throw new ServiceFailure("1580", "Error querying system metadata: " + e.getMessage());
572
        }
573

    
574
        return objectList;
575
    }
576

    
577
    /**
578
     * Return a description of the node's capabilities and services.
579
     * 
580
     * @return node - the technical capabilities of the Member Node
581
     * 
582
     * @throws ServiceFailure
583
     * @throws NotAuthorized
584
     * @throws InvalidRequest
585
     * @throws NotImplemented
586
     */
587
    @Override
588
    public Node getCapabilities() throws NotImplemented, NotAuthorized, ServiceFailure, InvalidRequest {
589

    
590
        String nodeName = null;
591
        String nodeId = null;
592
        String subject = null;
593
        String nodeDesc = null;
594
        String nodeTypeString = null;
595
        NodeType nodeType = null;
596
        String mnCoreServiceVersion = null;
597
        String mnReadServiceVersion = null;
598
        String mnAuthorizationServiceVersion = null;
599
        String mnStorageServiceVersion = null;
600
        String mnReplicationServiceVersion = null;
601

    
602
        boolean nodeSynchronize = false;
603
        boolean nodeReplicate = false;
604
        boolean mnCoreServiceAvailable = false;
605
        boolean mnReadServiceAvailable = false;
606
        boolean mnAuthorizationServiceAvailable = false;
607
        boolean mnStorageServiceAvailable = false;
608
        boolean mnReplicationServiceAvailable = false;
609

    
610
        try {
611
            // get the properties of the node based on configuration information
612
            nodeName = PropertyService.getProperty("dataone.nodeName");
613
            nodeId = PropertyService.getProperty("dataone.memberNodeId");
614
            subject = PropertyService.getProperty("dataone.subject");
615
            nodeDesc = PropertyService.getProperty("dataone.nodeDescription");
616
            nodeTypeString = PropertyService.getProperty("dataone.nodeType");
617
            nodeType = NodeType.convert(nodeTypeString);
618
            nodeSynchronize = new Boolean(PropertyService.getProperty("dataone.nodeSynchronize")).booleanValue();
619
            nodeReplicate = new Boolean(PropertyService.getProperty("dataone.nodeReplicate")).booleanValue();
620

    
621
            mnCoreServiceVersion = PropertyService.getProperty("dataone.mnCore.serviceVersion");
622
            mnReadServiceVersion = PropertyService.getProperty("dataone.mnRead.serviceVersion");
623
            mnAuthorizationServiceVersion = PropertyService.getProperty("dataone.mnAuthorization.serviceVersion");
624
            mnStorageServiceVersion = PropertyService.getProperty("dataone.mnStorage.serviceVersion");
625
            mnReplicationServiceVersion = PropertyService.getProperty("dataone.mnReplication.serviceVersion");
626

    
627
            mnCoreServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnCore.serviceAvailable")).booleanValue();
628
            mnReadServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnRead.serviceAvailable")).booleanValue();
629
            mnAuthorizationServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnAuthorization.serviceAvailable")).booleanValue();
630
            mnStorageServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnStorage.serviceAvailable")).booleanValue();
631
            mnReplicationServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnReplication.serviceAvailable")).booleanValue();
632

    
633
            // Set the properties of the node based on configuration information and
634
            // calls to current status methods
635
            Node node = new Node();
636
            node.setBaseURL(metacatUrl + "/" + nodeTypeString);
637
            node.setDescription(nodeDesc);
638

    
639
            // set the node's health information
640
            node.setState(NodeState.UP);
641
            
642
            // set the ping response to the current value
643
            Ping canPing = new Ping();
644
            canPing.setSuccess(false);
645
            try {
646
                canPing.setSuccess(ping());
647
            } catch (InsufficientResources e) {
648
                e.printStackTrace();
649
            } catch (UnsupportedType e) {
650
                e.printStackTrace();
651
            }
652
            node.setPing(canPing);
653

    
654
            NodeReference identifier = new NodeReference();
655
            identifier.setValue(nodeId);
656
            node.setIdentifier(identifier);
657
            Subject s = new Subject();
658
            s.setValue(subject);
659
            node.addSubject(s);
660
            node.setName(nodeName);
661
            node.setReplicate(nodeReplicate);
662
            node.setSynchronize(nodeSynchronize);
663

    
664
            // services: MNAuthorization, MNCore, MNRead, MNReplication, MNStorage
665
            Services services = new Services();
666

    
667
            Service sMNCore = new Service();
668
            sMNCore.setName("MNCore");
669
            sMNCore.setVersion(mnCoreServiceVersion);
670
            sMNCore.setAvailable(mnCoreServiceAvailable);
671

    
672
            Service sMNRead = new Service();
673
            sMNRead.setName("MNRead");
674
            sMNRead.setVersion(mnReadServiceVersion);
675
            sMNRead.setAvailable(mnReadServiceAvailable);
676

    
677
            Service sMNAuthorization = new Service();
678
            sMNAuthorization.setName("MNAuthorization");
679
            sMNAuthorization.setVersion(mnAuthorizationServiceVersion);
680
            sMNAuthorization.setAvailable(mnAuthorizationServiceAvailable);
681

    
682
            Service sMNStorage = new Service();
683
            sMNStorage.setName("MNStorage");
684
            sMNStorage.setVersion(mnStorageServiceVersion);
685
            sMNStorage.setAvailable(mnStorageServiceAvailable);
686

    
687
            Service sMNReplication = new Service();
688
            sMNReplication.setName("MNReplication");
689
            sMNReplication.setVersion(mnReplicationServiceVersion);
690
            sMNReplication.setAvailable(mnReplicationServiceAvailable);
691

    
692
            services.addService(sMNRead);
693
            services.addService(sMNCore);
694
            services.addService(sMNAuthorization);
695
            services.addService(sMNStorage);
696
            services.addService(sMNReplication);
697
            node.setServices(services);
698

    
699
            // TODO: Allow the metacat admin to determine the schedule
700
            // Set the schedule for synchronization
701
            Synchronization synchronization = new Synchronization();
702
            Schedule schedule = new Schedule();
703
            Date now = new Date();
704
            schedule.setYear("*");
705
            schedule.setMon("*");
706
            schedule.setMday("*");
707
            schedule.setWday("?");
708
            schedule.setHour("*");
709
            schedule.setMin("0/3");
710
            schedule.setSec("10");
711
            synchronization.setSchedule(schedule);
712
            synchronization.setLastHarvested(now);
713
            synchronization.setLastCompleteHarvest(now);
714
            node.setSynchronization(synchronization);
715

    
716
            node.setType(nodeType);
717
            return node;
718

    
719
        } catch (PropertyNotFoundException pnfe) {
720
            String msg = "MNodeService.getCapabilities(): " + "property not found: " + pnfe.getMessage();
721
            logMetacat.error(msg);
722
            throw new ServiceFailure("2162", msg);
723
        }
724
    }
725

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

    
749
        MonitorList monitorList = new MonitorList();
750

    
751
        try {
752

    
753
            // get log records first
754
            Log logs = getLogRecords(session, startTime, endTime, event, 0, null);
755

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

    
774
            }
775
        } catch (Exception e) {
776
            e.printStackTrace();
777
            throw new ServiceFailure("2081", "Could not retrieve statistics: " + e.getMessage());
778
        }
779

    
780
        return monitorList;
781

    
782
    }
783

    
784
    /**
785
     * Low level “are you alive” operation. A valid ping response is 
786
     * indicated by a HTTP status of 200.
787
     * 
788
     * @return true if the service is alive
789
     * 
790
     * @throws InvalidToken
791
     * @throws ServiceFailure
792
     * @throws NotAuthorized
793
     * @throws InvalidRequest
794
     * @throws NotImplemented
795
     */
796
    @Override
797
    public boolean ping() throws NotImplemented, ServiceFailure, NotAuthorized, InvalidRequest, InsufficientResources, UnsupportedType {
798

    
799
        // test if we can get a database connection
800
        boolean alive = false;
801
        int serialNumber = -1;
802
        DBConnection dbConn = null;
803
        try {
804
            dbConn = DBConnectionPool.getDBConnection("MNodeService.ping");
805
            serialNumber = dbConn.getCheckOutSerialNumber();
806
            alive = true;
807
        } catch (SQLException e) {
808
            return alive;
809
        } finally {
810
            // Return the database connection
811
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
812
        }
813

    
814
        return alive;
815
    }
816

    
817
    /**
818
     * A callback method used by a CN to indicate to a MN that it cannot 
819
     * complete synchronization of the science metadata identified by pid.  Log
820
     * the event in the metacat event log.
821
     * 
822
     * @param session
823
     * @param syncFailed
824
     * 
825
     * @throws ServiceFailure
826
     * @throws NotAuthorized
827
     * @throws InvalidRequest
828
     * @throws NotImplemented
829
     */
830
    @Override
831
    public void synchronizationFailed(Session session, SynchronizationFailed syncFailed) throws NotImplemented, ServiceFailure, NotAuthorized, InvalidRequest {
832

    
833
        String localId;
834

    
835
        try {
836
            localId = IdentifierManager.getInstance().getLocalId(syncFailed.getPid());
837
        } catch (McdbDocNotFoundException e) {
838
            throw new InvalidRequest("2163", "The identifier specified by " + syncFailed.getPid() + " was not found on this node.");
839

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

    
858
    }
859

    
860
    /**
861
     * Essentially a get() but with different logging behavior
862
     */
863
    @Override
864
    public InputStream getReplica(Session session, Identifier pid) throws InvalidRequest, InvalidToken, NotAuthorized, NotImplemented, ServiceFailure, NotFound {
865

    
866
        InputStream inputStream = null; // bytes to be returned
867
        handler = new MetacatHandler(new Timer());
868
        boolean allowed = false;
869
        String localId; // the metacat docid for the pid
870

    
871
        // get the local docid from Metacat
872
        try {
873
            localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
874
        } catch (McdbDocNotFoundException e) {
875
            throw new NotFound("1020", "The object specified by " + pid.getValue() + " does not exist at this node.");
876
        }
877

    
878
        Node node = this.getCapabilities();
879
        Subject targetNodeSubject = node.getSubject(0);
880

    
881
        // check for authorization to replicate
882
        allowed = D1Client.getCN().isNodeAuthorized(session, targetNodeSubject, pid, Permission.REPLICATE);
883

    
884
        // if the person is authorized, perform the read
885
        if (allowed) {
886
            try {
887
                inputStream = handler.read(localId);
888
            } catch (Exception e) {
889
                throw new ServiceFailure("1020", "The object specified by " + pid.getValue() + "could not be returned due to error: " + e.getMessage());
890
            }
891
        }
892

    
893
        // if we fail to set the input stream
894
        if (inputStream == null) {
895
            throw new NotFound("1020", "The object specified by " + pid.getValue() + "does not exist at this node.");
896
        }
897

    
898
        // log the replica event
899
        String principal = null;
900
        if (session.getSubject() != null) {
901
            principal = session.getSubject().getValue();
902
        }
903
        EventLog.getInstance().log(null, principal, localId, "getreplica");
904

    
905
        return inputStream;
906
    }
907

    
908
}
(3-3/6)