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 submitter to match the certificate
272
        sysmeta.setSubmitter(subject);
273

    
274
        // does the subject have WRITE ( == update) priveleges on the pid?
275
        allowed = isAuthorized(session, pid, Permission.WRITE);
276

    
277
        if (allowed) {
278

    
279
            // get the existing system metadata for the object
280
            SystemMetadata existingSysMeta = getSystemMetadata(session, pid);
281

    
282
            // add the newPid to the obsoletedBy list for the existing sysmeta
283
            existingSysMeta.setObsoletedBy(newPid);
284

    
285
            // then update the existing system metadata
286
            updateSystemMetadata(existingSysMeta);
287

    
288
            // prep the new system metadata, add pid to the affected lists
289
            sysmeta.setObsoletes(pid);
290
            //sysmeta.addDerivedFrom(pid);
291

    
292
            isScienceMetadata = isScienceMetadata(sysmeta);
293

    
294
            // do we have XML metadata or a data object?
295
            if (isScienceMetadata) {
296

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

    
308
                    }
309

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

    
315
                }
316

    
317
            } else {
318

    
319
                // update the data object
320
                localId = insertDataObject(object, newPid, session);
321

    
322
            }
323

    
324
            // and insert the new system metadata
325
            insertSystemMetadata(sysmeta);
326

    
327
            // log the update event
328
            EventLog.getInstance().log(metacatUrl, subject.getValue(), localId, "update");
329

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

    
335
        return newPid;
336
    }
337

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

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

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

    
375
        boolean result = false;
376

    
377
        // TODO: check credentials
378

    
379
        // get the referenced object
380
        Identifier pid = sysmeta.getIdentifier();
381

    
382
        // get from the membernode
383
        // TODO: switch credentials for the server retrieval?
384
        MNode mn = D1Client.getMN(sourceNode);
385
        InputStream object = null;
386

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

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

    
413
        return result;
414

    
415
    }
416

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

    
439
    	// get system metadata and construct the describe response
440
        SystemMetadata sysmeta = getSystemMetadata(session, pid);
441
        DescribeResponse describeResponse = new DescribeResponse(sysmeta.getFmtid(), sysmeta.getSize(), sysmeta.getDateSysMetadataModified(),
442
                sysmeta.getChecksum());
443

    
444
        return describeResponse;
445

    
446
    }
447

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

    
465
        return super.get(session, pid);
466

    
467
    }
468

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

    
490
        Checksum checksum = null;
491

    
492
        InputStream inputStream = get(session, pid);
493

    
494
        try {
495
            checksum = ChecksumUtil.checksum(inputStream, algorithm);
496

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

    
505
        if (checksum == null) {
506
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned.");
507
        }
508

    
509
        return checksum;
510
    }
511

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

    
531
        return super.getSystemMetadata(session, pid);
532
    }
533

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

    
562
        ObjectList objectList = null;
563

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

    
570
        return objectList;
571
    }
572

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

    
586
        String nodeName = null;
587
        String nodeId = null;
588
        String subject = null;
589
        String nodeDesc = null;
590
        String nodeTypeString = null;
591
        NodeType nodeType = null;
592
        String mnCoreServiceVersion = null;
593
        String mnReadServiceVersion = null;
594
        String mnAuthorizationServiceVersion = null;
595
        String mnStorageServiceVersion = null;
596
        String mnReplicationServiceVersion = null;
597

    
598
        boolean nodeSynchronize = false;
599
        boolean nodeReplicate = false;
600
        boolean mnCoreServiceAvailable = false;
601
        boolean mnReadServiceAvailable = false;
602
        boolean mnAuthorizationServiceAvailable = false;
603
        boolean mnStorageServiceAvailable = false;
604
        boolean mnReplicationServiceAvailable = false;
605

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

    
617
            mnCoreServiceVersion = PropertyService.getProperty("dataone.mnCore.serviceVersion");
618
            mnReadServiceVersion = PropertyService.getProperty("dataone.mnRead.serviceVersion");
619
            mnAuthorizationServiceVersion = PropertyService.getProperty("dataone.mnAuthorization.serviceVersion");
620
            mnStorageServiceVersion = PropertyService.getProperty("dataone.mnStorage.serviceVersion");
621
            mnReplicationServiceVersion = PropertyService.getProperty("dataone.mnReplication.serviceVersion");
622

    
623
            mnCoreServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnCore.serviceAvailable")).booleanValue();
624
            mnReadServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnRead.serviceAvailable")).booleanValue();
625
            mnAuthorizationServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnAuthorization.serviceAvailable")).booleanValue();
626
            mnStorageServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnStorage.serviceAvailable")).booleanValue();
627
            mnReplicationServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnReplication.serviceAvailable")).booleanValue();
628

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

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

    
650
            NodeReference identifier = new NodeReference();
651
            identifier.setValue(nodeId);
652
            node.setIdentifier(identifier);
653
            Subject s = new Subject();
654
            s.setValue(subject);
655
            node.addSubject(s);
656
            node.setName(nodeName);
657
            node.setReplicate(nodeReplicate);
658
            node.setSynchronize(nodeSynchronize);
659

    
660
            // services: MNAuthorization, MNCore, MNRead, MNReplication, MNStorage
661
            Services services = new Services();
662

    
663
            Service sMNCore = new Service();
664
            sMNCore.setName("MNCore");
665
            sMNCore.setVersion(mnCoreServiceVersion);
666
            sMNCore.setAvailable(mnCoreServiceAvailable);
667

    
668
            Service sMNRead = new Service();
669
            sMNRead.setName("MNRead");
670
            sMNRead.setVersion(mnReadServiceVersion);
671
            sMNRead.setAvailable(mnReadServiceAvailable);
672

    
673
            Service sMNAuthorization = new Service();
674
            sMNAuthorization.setName("MNAuthorization");
675
            sMNAuthorization.setVersion(mnAuthorizationServiceVersion);
676
            sMNAuthorization.setAvailable(mnAuthorizationServiceAvailable);
677

    
678
            Service sMNStorage = new Service();
679
            sMNStorage.setName("MNStorage");
680
            sMNStorage.setVersion(mnStorageServiceVersion);
681
            sMNStorage.setAvailable(mnStorageServiceAvailable);
682

    
683
            Service sMNReplication = new Service();
684
            sMNReplication.setName("MNReplication");
685
            sMNReplication.setVersion(mnReplicationServiceVersion);
686
            sMNReplication.setAvailable(mnReplicationServiceAvailable);
687

    
688
            services.addService(sMNRead);
689
            services.addService(sMNCore);
690
            services.addService(sMNAuthorization);
691
            services.addService(sMNStorage);
692
            services.addService(sMNReplication);
693
            node.setServices(services);
694

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

    
712
            node.setType(nodeType);
713
            return node;
714

    
715
        } catch (PropertyNotFoundException pnfe) {
716
            String msg = "MNodeService.getCapabilities(): " + "property not found: " + pnfe.getMessage();
717
            logMetacat.error(msg);
718
            throw new ServiceFailure("2162", msg);
719
        }
720
    }
721

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

    
745
        MonitorList monitorList = new MonitorList();
746

    
747
        try {
748

    
749
            // get log records first
750
            Log logs = getLogRecords(session, startTime, endTime, event, 0, null);
751

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

    
770
            }
771
        } catch (Exception e) {
772
            e.printStackTrace();
773
            throw new ServiceFailure("2081", "Could not retrieve statistics: " + e.getMessage());
774
        }
775

    
776
        return monitorList;
777

    
778
    }
779

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

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

    
810
        return alive;
811
    }
812

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

    
829
        String localId;
830

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

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

    
854
    }
855

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

    
862
        InputStream inputStream = null; // bytes to be returned
863
        handler = new MetacatHandler(new Timer());
864
        boolean allowed = false;
865
        String localId; // the metacat docid for the pid
866

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

    
874
        Node node = this.getCapabilities();
875
        Subject targetNodeSubject = node.getSubject(0);
876

    
877
        // check for authorization to replicate
878
        allowed = D1Client.getCN().isNodeAuthorized(session, targetNodeSubject, pid, Permission.REPLICATE);
879

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

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

    
894
        // log the replica event
895
        String principal = null;
896
        if (session.getSubject() != null) {
897
            principal = session.getSubject().getValue();
898
        }
899
        EventLog.getInstance().log(null, principal, localId, "getreplica");
900

    
901
        return inputStream;
902
    }
903

    
904
}
(3-3/6)