Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *  Copyright: 2000-2011 Regents of the University of California and the
4
 *              National Center for Ecological Analysis and Synthesis
5
 *
6
 *   '$Author:  $'
7
 *     '$Date:  $'
8
 *
9
 * This program is free software; you can redistribute it and/or modify
10
 * it under the terms of the GNU General Public License as published by
11
 * the Free Software Foundation; either version 2 of the License, or
12
 * (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program; if not, write to the Free Software
21
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22
 */
23

    
24
package edu.ucsb.nceas.metacat.dataone;
25

    
26
import java.io.IOException;
27
import java.io.InputStream;
28
import java.security.NoSuchAlgorithmException;
29
import java.sql.SQLException;
30
import java.util.Calendar;
31
import java.util.Date;
32
import java.util.List;
33
import java.util.Timer;
34

    
35
import javax.servlet.http.HttpServletRequest;
36

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

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

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

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

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

    
139
    /**
140
     * Constructor, private for singleton access
141
     */
142
    private MNodeService(HttpServletRequest request) {
143
        super(request);
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.SUBJECT_PUBLIC;
170
        String[] groupnames = null;
171
        if (session != null) {
172
            username = session.getSubject().getValue();
173
            if (session.getSubjectInfo() != null) {
174
                List<Group> groupList = session.getSubjectInfo().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(request.getRemoteAddr(), request.getHeader("User-Agent"), 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
        // set the dates
278
        Date now = Calendar.getInstance().getTime();
279
		sysmeta.setDateSysMetadataModified(now);
280
		sysmeta.setDateUploaded(now);
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(request.getRemoteAddr(), request.getHeader("User-Agent"), subject.getValue(), localId, Event.UPDATE.toString());
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 for null session
350
        if (session == null) {
351
        	throw new InvalidToken("1110", "Session is required to WRITE to the Node.");
352
        }
353
        // set the submitter to match the certificate
354
        sysmeta.setSubmitter(session.getSubject());
355
        // set the originating node
356
        NodeReference originMemberNode = this.getCapabilities().getIdentifier();
357
        sysmeta.setOriginMemberNode(originMemberNode);
358
        // set the dates
359
        Date now = Calendar.getInstance().getTime();
360
		sysmeta.setDateSysMetadataModified(now);
361
		sysmeta.setDateUploaded(now);
362
        // call the shared impl
363
        return super.create(session, pid, object, sysmeta);
364
    }
365

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

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

    
399
        // TODO: check credentials
400

    
401
        // get the referenced object
402
        Identifier pid = sysmeta.getIdentifier();
403

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

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

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

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

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

    
452
    }
453

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

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

    
481
        return describeResponse;
482

    
483
    }
484

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

    
502
        return super.get(session, pid);
503

    
504
    }
505

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

    
527
        Checksum checksum = null;
528

    
529
        InputStream inputStream = get(session, pid);
530

    
531
        try {
532
            checksum = ChecksumUtil.checksum(inputStream, algorithm);
533

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

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

    
546
        return checksum;
547
    }
548

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

    
568
        return super.getSystemMetadata(session, pid);
569
    }
570

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

    
599
        ObjectList objectList = null;
600

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

    
607
        return objectList;
608
    }
609

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

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

    
635
        boolean nodeSynchronize = false;
636
        boolean nodeReplicate = false;
637
        boolean mnCoreServiceAvailable = false;
638
        boolean mnReadServiceAvailable = false;
639
        boolean mnAuthorizationServiceAvailable = false;
640
        boolean mnStorageServiceAvailable = false;
641
        boolean mnReplicationServiceAvailable = false;
642

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

    
654
            mnCoreServiceVersion = PropertyService.getProperty("dataone.mnCore.serviceVersion");
655
            mnReadServiceVersion = PropertyService.getProperty("dataone.mnRead.serviceVersion");
656
            mnAuthorizationServiceVersion = PropertyService.getProperty("dataone.mnAuthorization.serviceVersion");
657
            mnStorageServiceVersion = PropertyService.getProperty("dataone.mnStorage.serviceVersion");
658
            mnReplicationServiceVersion = PropertyService.getProperty("dataone.mnReplication.serviceVersion");
659

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

    
666
            // Set the properties of the node based on configuration information and
667
            // calls to current status methods
668
            String serviceName = SystemUtil.getContextURL() + "/" + PropertyService.getProperty("dataone.serviceName");
669
            Node node = new Node();
670
            node.setBaseURL(serviceName + "/" + nodeTypeString);
671
            node.setDescription(nodeDesc);
672

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

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

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

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

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

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

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

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

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

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

    
750
            node.setType(nodeType);
751
            return node;
752

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

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

    
783
        MonitorList monitorList = new MonitorList();
784

    
785
        try {
786

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

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

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

    
814
        return monitorList;
815

    
816
    }
817

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

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

    
848
        return alive;
849
    }
850

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

    
867
        String localId;
868

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

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

    
892
    }
893

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

    
902
        logMetacat.info("MNodeService.getReplica() called.");
903

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

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

    
916
        Node node = this.getCapabilities();
917
        Subject targetNodeSubject = node.getSubject(0);
918

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

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

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

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

    
939
        // log the replica event
940
        String principal = null;
941
        if (session.getSubject() != null) {
942
            principal = session.getSubject().getValue();
943
        }
944
        EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), principal, localId, "getreplica");
945

    
946
        return inputStream;
947
    }
948

    
949
}
(3-3/6)