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.client.auth.CertificateManager;
43
import org.dataone.configuration.Settings;
44
import org.dataone.service.exceptions.IdentifierNotUnique;
45
import org.dataone.service.exceptions.InsufficientResources;
46
import org.dataone.service.exceptions.InvalidRequest;
47
import org.dataone.service.exceptions.InvalidSystemMetadata;
48
import org.dataone.service.exceptions.InvalidToken;
49
import org.dataone.service.exceptions.NotAuthorized;
50
import org.dataone.service.exceptions.NotFound;
51
import org.dataone.service.exceptions.NotImplemented;
52
import org.dataone.service.exceptions.ServiceFailure;
53
import org.dataone.service.exceptions.SynchronizationFailed;
54
import org.dataone.service.exceptions.UnsupportedType;
55
import org.dataone.service.mn.tier1.v1.MNCore;
56
import org.dataone.service.mn.tier1.v1.MNRead;
57
import org.dataone.service.mn.tier2.v1.MNAuthorization;
58
import org.dataone.service.mn.tier3.v1.MNStorage;
59
import org.dataone.service.mn.tier4.v1.MNReplication;
60
import org.dataone.service.types.v1.AccessPolicy;
61
import org.dataone.service.types.v1.Checksum;
62
import org.dataone.service.types.v1.DescribeResponse;
63
import org.dataone.service.types.v1.Event;
64
import org.dataone.service.types.v1.Group;
65
import org.dataone.service.types.v1.Identifier;
66
import org.dataone.service.types.v1.Log;
67
import org.dataone.service.types.v1.LogEntry;
68
import org.dataone.service.types.v1.MonitorInfo;
69
import org.dataone.service.types.v1.MonitorList;
70
import org.dataone.service.types.v1.Node;
71
import org.dataone.service.types.v1.NodeReference;
72
import org.dataone.service.types.v1.NodeState;
73
import org.dataone.service.types.v1.NodeType;
74
import org.dataone.service.types.v1.ObjectFormatIdentifier;
75
import org.dataone.service.types.v1.ObjectList;
76
import org.dataone.service.types.v1.Permission;
77
import org.dataone.service.types.v1.Ping;
78
import org.dataone.service.types.v1.ReplicationStatus;
79
import org.dataone.service.types.v1.Schedule;
80
import org.dataone.service.types.v1.Service;
81
import org.dataone.service.types.v1.Services;
82
import org.dataone.service.types.v1.Session;
83
import org.dataone.service.types.v1.Subject;
84
import org.dataone.service.types.v1.Synchronization;
85
import org.dataone.service.types.v1.SystemMetadata;
86
import org.dataone.service.types.v1.util.ChecksumUtil;
87
import org.dataone.service.util.Constants;
88

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

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

    
130
    /* the logger instance */
131
    private Logger logMetacat = null;
132

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

    
142
    /**
143
     * Constructor, private for singleton access
144
     */
145
    private MNodeService(HttpServletRequest request) {
146
        super(request);
147
        logMetacat = Logger.getLogger(MNodeService.class);
148
        
149
        // set the Member Node certificate file location
150
        CertificateManager.getInstance().setCertificateLocation(Settings.getConfiguration().getString("D1Client.certificate.file"));
151
    }
152

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

    
173
        String localId = null;
174
        boolean allowed = false;
175
        String username = Constants.SUBJECT_PUBLIC;
176
        String[] groupnames = null;
177
        if (session != null) {
178
            username = session.getSubject().getValue();
179
            if (session.getSubjectInfo() != null) {
180
                List<Group> groupList = session.getSubjectInfo().getGroupList();
181
                if (groupList != null) {
182
                    groupnames = new String[groupList.size()];
183
                    for (int i = 0; i > groupList.size(); i++) {
184
                        groupnames[i] = groupList.get(i).getGroupName();
185
                    }
186
                }
187
            }
188
        }
189

    
190
        // do we have a valid pid?
191
        if (pid == null || pid.getValue().trim().equals("")) {
192
            throw new InvalidRequest("1322", "The provided identifier was invalid.");
193
        }
194

    
195
        // check for the existing identifier
196
        try {
197
            localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
198
        } catch (McdbDocNotFoundException e) {
199
            throw new InvalidRequest("1322", "The object with the provided " + "identifier was not found.");
200
        }
201

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

    
205
        if (allowed) {
206
            try {
207
                // delete the document
208
                DocumentImpl.delete(localId, username, groupnames, null);
209
                EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, Event.DELETE.xmlValue());
210

    
211
            } catch (McdbDocNotFoundException e) {
212
                throw new InvalidRequest("1322", "The provided identifier was invalid.");
213

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

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

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

    
224
        } else {
225
            throw new NotAuthorized("1320", "The provided identity does not have " + "permission to DELETE objects on the Member Node.");
226
        }
227

    
228
        return pid;
229
    }
230

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

    
262
        String localId = null;
263
        boolean allowed = false;
264
        boolean isScienceMetadata = false;
265
        Subject subject = session.getSubject();
266

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

    
273
        // check for the existing identifier
274
        try {
275
            localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
276
            
277
        } catch (McdbDocNotFoundException e) {
278
            throw new InvalidRequest("1202", "The object with the provided " + 
279
                "identifier was not found.");
280
            
281
        }
282
        
283
        // set the originating node
284
        NodeReference originMemberNode = this.getCapabilities().getIdentifier();
285
        sysmeta.setOriginMemberNode(originMemberNode);
286
        
287
        // set the submitter to match the certificate
288
        sysmeta.setSubmitter(subject);
289
        // set the dates
290
        Date now = Calendar.getInstance().getTime();
291
        sysmeta.setDateSysMetadataModified(now);
292
        sysmeta.setDateUploaded(now);
293

    
294
        // does the subject have WRITE ( == update) priveleges on the pid?
295
        allowed = isAuthorized(session, pid, Permission.WRITE);
296

    
297
        if (allowed) {
298

    
299
            // get the existing system metadata for the object
300
            SystemMetadata existingSysMeta = getSystemMetadata(session, pid);
301

    
302
            // add the newPid to the obsoletedBy list for the existing sysmeta
303
            existingSysMeta.setObsoletedBy(newPid);
304

    
305
            // then update the existing system metadata
306
            updateSystemMetadata(existingSysMeta);
307

    
308
            // prep the new system metadata, add pid to the affected lists
309
            sysmeta.setObsoletes(pid);
310
            //sysmeta.addDerivedFrom(pid);
311

    
312
            isScienceMetadata = isScienceMetadata(sysmeta);
313

    
314
            // do we have XML metadata or a data object?
315
            if (isScienceMetadata) {
316

    
317
                // update the science metadata XML document
318
                // TODO: handle non-XML metadata/data documents (like netCDF)
319
                // TODO: don't put objects into memory using stream to string
320
                String objectAsXML = "";
321
                try {
322
                    objectAsXML = IOUtils.toString(object, "UTF-8");
323
                    localId = insertOrUpdateDocument(objectAsXML, newPid, session, "update");
324
                    // register the newPid and the generated localId
325
                    if (newPid != null) {
326
                        IdentifierManager.getInstance().createMapping(newPid.getValue(), localId);
327

    
328
                    }
329

    
330
                } catch (IOException e) {
331
                    String msg = "The Node is unable to create the object. " + "There was a problem converting the object to XML";
332
                    logMetacat.info(msg);
333
                    throw new ServiceFailure("1310", msg + ": " + e.getMessage());
334

    
335
                }
336

    
337
            } else {
338

    
339
                // update the data object
340
                localId = insertDataObject(object, newPid, session);
341

    
342
            }
343

    
344
            // and insert the new system metadata
345
            insertSystemMetadata(sysmeta);
346

    
347
            // log the update event
348
            EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), subject.getValue(), localId, Event.UPDATE.toString());
349

    
350
        } else {
351
            throw new NotAuthorized("1200", "The provided identity does not have " + "permission to UPDATE the object identified by " + pid.getValue()
352
                    + " on the Member Node.");
353
        }
354

    
355
        return newPid;
356
    }
357

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

    
361
      // check for null session
362
        if (session == null) {
363
          throw new InvalidToken("1110", "Session is required to WRITE to the Node.");
364
        }
365
        // set the submitter to match the certificate
366
        sysmeta.setSubmitter(session.getSubject());
367
        // set the originating node
368
        NodeReference originMemberNode = this.getCapabilities().getIdentifier();
369
        sysmeta.setOriginMemberNode(originMemberNode);
370
        // set the dates
371
        Date now = Calendar.getInstance().getTime();
372
    sysmeta.setDateSysMetadataModified(now);
373
    sysmeta.setDateUploaded(now);
374
        // call the shared impl
375
        return super.create(session, pid, object, sysmeta);
376
    }
377

    
378
    /**
379
     * Called by a Coordinating Node to request that the Member Node create a 
380
     * copy of the specified object by retrieving it from another Member 
381
     * Node and storing it locally so that it can be made accessible to 
382
     * the DataONE system.
383
     * 
384
     * @param session - the Session object containing the credentials for the Subject
385
     * @param sysmeta - Copy of the CN held system metadata for the object
386
     * @param sourceNode - A reference to node from which the content should be 
387
     *                     retrieved. The reference should be resolved by 
388
     *                     checking the CN node registry.
389
     * 
390
     * @return true if the replication succeeds
391
     * 
392
     * @throws ServiceFailure
393
     * @throws NotAuthorized
394
     * @throws NotImplemented
395
     * @throws UnsupportedType
396
     * @throws InsufficientResources
397
     * @throws InvalidRequest
398
     */
399
    @Override
400
    public boolean replicate(Session session, SystemMetadata sysmeta, NodeReference sourceNode) 
401
        throws NotImplemented, ServiceFailure, NotAuthorized, InvalidRequest, 
402
        InsufficientResources, UnsupportedType {
403

    
404
        logMetacat.info("MNodeService.replicate() called with parameters: \n" +
405
            "\tSession.Subject      = " + session.getSubject().getValue() + "\n" +
406
            "\tSystemMetadata       = " + sysmeta.toString()              + "\n" +
407
            "\tSource NodeReference ="  + sourceNode.getValue());
408
        
409
        boolean result = false;
410

    
411
        // TODO: check credentials
412

    
413
        // get the referenced object
414
        Identifier pid = sysmeta.getIdentifier();
415

    
416
        // get from the membernode
417
        // TODO: switch credentials for the server retrieval?
418
        MNode mn = D1Client.getMN(sourceNode);
419
        CNode cn = D1Client.getCN();
420
        
421
        InputStream object = null;
422
        
423
        try {
424
          // session should be null to use the default certificate location set in the Certificate manager
425
            object = mn.getReplica(null, pid);
426
            logMetacat.info("MNodeService.replicate() called for identifier " + pid.getValue());
427

    
428
        } catch (InvalidToken e) {
429
            e.printStackTrace();
430
            throw new ServiceFailure("2151", "Could not retrieve object to replicate (InvalidToken): " + e.getMessage());
431
        } catch (NotFound e) {
432
            e.printStackTrace();
433
            throw new ServiceFailure("2151", "Could not retrieve object to replicate (NotFound): " + e.getMessage());
434
        }
435

    
436
        // add it to local store
437
        Identifier retPid;
438
        try {
439
          // skip the MN.create -- this mutates the system metadata and we dont want it to
440
            retPid = super.create(session, pid, object, sysmeta);
441
            result = (retPid.getValue().equals(pid.getValue()));
442
        } catch (InvalidToken e) {
443
            e.printStackTrace();
444
            throw new ServiceFailure("2151", "Could not save object to local store (InvalidToken): " + e.getMessage());
445
        } catch (IdentifierNotUnique e) {
446
            e.printStackTrace();
447
            throw new ServiceFailure("2151", "Could not save object to local store (IdentifierNotUnique): " + e.getMessage());
448
        } catch (InvalidSystemMetadata e) {
449
            e.printStackTrace();
450
            throw new ServiceFailure("2151", "Could not save object to local store (InvalidSystemMetadata): " + e.getMessage());
451
        }
452

    
453
        try {
454
          // call the CN as the MN to set the replication status
455
            cn.setReplicationStatus(null, pid, sourceNode, ReplicationStatus.COMPLETED);
456
            
457
        } catch (InvalidToken e) {
458
            // TODO Auto-generated catch block
459
            e.printStackTrace();
460
        } catch (NotFound e) {
461
            // TODO Auto-generated catch block
462
            e.printStackTrace();
463
        }
464
        return result;
465

    
466
    }
467

    
468
    /**
469
     * This method provides a lighter weight mechanism than 
470
     * MN_read.getSystemMetadata() for a client to determine basic 
471
     * properties of the referenced object.
472
     * 
473
     * @param session - the Session object containing the credentials for the Subject
474
     * @param pid - the identifier of the object to be described
475
     * 
476
     * @return describeResponse - A set of values providing a basic description 
477
     *                            of the object.
478
     * 
479
     * @throws InvalidToken
480
     * @throws ServiceFailure
481
     * @throws NotAuthorized
482
     * @throws NotFound
483
     * @throws NotImplemented
484
     * @throws InvalidRequest
485
     */
486
    @Override
487
    public DescribeResponse describe(Session session, Identifier pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented,
488
            InvalidRequest {
489

    
490
      // get system metadata and construct the describe response
491
        SystemMetadata sysmeta = getSystemMetadata(session, pid);
492
        DescribeResponse describeResponse = new DescribeResponse(sysmeta.getFormatId(), sysmeta.getSize(), sysmeta.getDateSysMetadataModified(),
493
                sysmeta.getChecksum());
494

    
495
        return describeResponse;
496

    
497
    }
498

    
499
    /**
500
     * Return the object identified by the given object identifier
501
     * 
502
     * @param session - the Session object containing the credentials for the Subject
503
     * @param pid - the object identifier for the given object
504
     * 
505
     * @return inputStream - the input stream of the given object
506
     * 
507
     * @throws InvalidToken
508
     * @throws ServiceFailure
509
     * @throws NotAuthorized
510
     * @throws InvalidRequest
511
     * @throws NotImplemented
512
     */
513
    @Override
514
    public InputStream get(Session session, Identifier pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented, InvalidRequest {
515

    
516
        return super.get(session, pid);
517

    
518
    }
519

    
520
    /**
521
     * Returns a Checksum for the specified object using an accepted hashing algorithm
522
     * 
523
     * @param session - the Session object containing the credentials for the Subject
524
     * @param pid - the object identifier for the given object
525
     * @param algorithm -  the name of an algorithm that will be used to compute 
526
     *                     a checksum of the bytes of the object
527
     * 
528
     * @return checksum - the checksum of the given object
529
     * 
530
     * @throws InvalidToken
531
     * @throws ServiceFailure
532
     * @throws NotAuthorized
533
     * @throws NotFound
534
     * @throws InvalidRequest
535
     * @throws NotImplemented
536
     */
537
    @Override
538
    public Checksum getChecksum(Session session, Identifier pid, String algorithm) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
539
            InvalidRequest, NotImplemented {
540

    
541
        Checksum checksum = null;
542

    
543
        InputStream inputStream = get(session, pid);
544

    
545
        try {
546
            checksum = ChecksumUtil.checksum(inputStream, algorithm);
547

    
548
        } catch (NoSuchAlgorithmException e) {
549
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned due to an internal error: "
550
                    + e.getMessage());
551
        } catch (IOException e) {
552
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned due to an internal error: "
553
                    + e.getMessage());
554
        }
555

    
556
        if (checksum == null) {
557
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned.");
558
        }
559

    
560
        return checksum;
561
    }
562

    
563
    /**
564
     * Return the system metadata for a given object
565
     * 
566
     * @param session - the Session object containing the credentials for the Subject
567
     * @param pid - the object identifier for the given object
568
     * 
569
     * @return inputStream - the input stream of the given system metadata object
570
     * 
571
     * @throws InvalidToken
572
     * @throws ServiceFailure
573
     * @throws NotAuthorized
574
     * @throws NotFound
575
     * @throws InvalidRequest
576
     * @throws NotImplemented
577
     */
578
    @Override
579
    public SystemMetadata getSystemMetadata(Session session, Identifier pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, InvalidRequest,
580
            NotImplemented {
581

    
582
        return super.getSystemMetadata(session, pid);
583
    }
584

    
585
    /**
586
     * Retrieve the list of objects present on the MN that match the calling parameters
587
     * 
588
     * @param session - the Session object containing the credentials for the Subject
589
     * @param startTime - Specifies the beginning of the time range from which 
590
     *                    to return object (>=)
591
     * @param endTime - Specifies the beginning of the time range from which 
592
     *                  to return object (>=)
593
     * @param objectFormat - Restrict results to the specified object format
594
     * @param replicaStatus - Indicates if replicated objects should be returned in the list
595
     * @param start - The zero-based index of the first value, relative to the 
596
     *                first record of the resultset that matches the parameters.
597
     * @param count - The maximum number of entries that should be returned in 
598
     *                the response. The Member Node may return less entries 
599
     *                than specified in this value.
600
     * 
601
     * @return objectList - the list of objects matching the criteria
602
     * 
603
     * @throws InvalidToken
604
     * @throws ServiceFailure
605
     * @throws NotAuthorized
606
     * @throws InvalidRequest
607
     * @throws NotImplemented
608
     */
609
    @Override
610
    public ObjectList listObjects(Session session, Date startTime, Date endTime, ObjectFormatIdentifier objectFormatId, Boolean replicaStatus, Integer start,
611
            Integer count) throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken {
612

    
613
        ObjectList objectList = null;
614

    
615
        try {
616
            objectList = IdentifierManager.getInstance().querySystemMetadata(startTime, endTime, objectFormatId, replicaStatus, start, count);
617
        } catch (Exception e) {
618
            throw new ServiceFailure("1580", "Error querying system metadata: " + e.getMessage());
619
        }
620

    
621
        return objectList;
622
    }
623

    
624
    /**
625
     * Return a description of the node's capabilities and services.
626
     * 
627
     * @return node - the technical capabilities of the Member Node
628
     * 
629
     * @throws ServiceFailure
630
     * @throws NotAuthorized
631
     * @throws InvalidRequest
632
     * @throws NotImplemented
633
     */
634
    @Override
635
    public Node getCapabilities() throws NotImplemented, NotAuthorized, ServiceFailure, InvalidRequest {
636

    
637
        String nodeName = null;
638
        String nodeId = null;
639
        String subject = null;
640
        String nodeDesc = null;
641
        String nodeTypeString = null;
642
        NodeType nodeType = null;
643
        String mnCoreServiceVersion = null;
644
        String mnReadServiceVersion = null;
645
        String mnAuthorizationServiceVersion = null;
646
        String mnStorageServiceVersion = null;
647
        String mnReplicationServiceVersion = null;
648

    
649
        boolean nodeSynchronize = false;
650
        boolean nodeReplicate = false;
651
        boolean mnCoreServiceAvailable = false;
652
        boolean mnReadServiceAvailable = false;
653
        boolean mnAuthorizationServiceAvailable = false;
654
        boolean mnStorageServiceAvailable = false;
655
        boolean mnReplicationServiceAvailable = false;
656

    
657
        try {
658
            // get the properties of the node based on configuration information
659
            nodeName = PropertyService.getProperty("dataone.nodeName");
660
            nodeId = PropertyService.getProperty("dataone.memberNodeId");
661
            subject = PropertyService.getProperty("dataone.subject");
662
            nodeDesc = PropertyService.getProperty("dataone.nodeDescription");
663
            nodeTypeString = PropertyService.getProperty("dataone.nodeType");
664
            nodeType = NodeType.convert(nodeTypeString);
665
            nodeSynchronize = new Boolean(PropertyService.getProperty("dataone.nodeSynchronize")).booleanValue();
666
            nodeReplicate = new Boolean(PropertyService.getProperty("dataone.nodeReplicate")).booleanValue();
667

    
668
            mnCoreServiceVersion = PropertyService.getProperty("dataone.mnCore.serviceVersion");
669
            mnReadServiceVersion = PropertyService.getProperty("dataone.mnRead.serviceVersion");
670
            mnAuthorizationServiceVersion = PropertyService.getProperty("dataone.mnAuthorization.serviceVersion");
671
            mnStorageServiceVersion = PropertyService.getProperty("dataone.mnStorage.serviceVersion");
672
            mnReplicationServiceVersion = PropertyService.getProperty("dataone.mnReplication.serviceVersion");
673

    
674
            mnCoreServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnCore.serviceAvailable")).booleanValue();
675
            mnReadServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnRead.serviceAvailable")).booleanValue();
676
            mnAuthorizationServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnAuthorization.serviceAvailable")).booleanValue();
677
            mnStorageServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnStorage.serviceAvailable")).booleanValue();
678
            mnReplicationServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnReplication.serviceAvailable")).booleanValue();
679

    
680
            // Set the properties of the node based on configuration information and
681
            // calls to current status methods
682
            String serviceName = SystemUtil.getContextURL() + "/" + PropertyService.getProperty("dataone.serviceName");
683
            Node node = new Node();
684
            node.setBaseURL(serviceName + "/" + nodeTypeString);
685
            node.setDescription(nodeDesc);
686

    
687
            // set the node's health information
688
            node.setState(NodeState.UP);
689
            
690
            // set the ping response to the current value
691
            Ping canPing = new Ping();
692
            canPing.setSuccess(false);
693
            try {
694
                canPing.setSuccess(ping());
695
            } catch (InsufficientResources e) {
696
                e.printStackTrace();
697
            } catch (UnsupportedType e) {
698
                e.printStackTrace();
699
            }
700
            node.setPing(canPing);
701

    
702
            NodeReference identifier = new NodeReference();
703
            identifier.setValue(nodeId);
704
            node.setIdentifier(identifier);
705
            Subject s = new Subject();
706
            s.setValue(subject);
707
            node.addSubject(s);
708
            node.setName(nodeName);
709
            node.setReplicate(nodeReplicate);
710
            node.setSynchronize(nodeSynchronize);
711

    
712
            // services: MNAuthorization, MNCore, MNRead, MNReplication, MNStorage
713
            Services services = new Services();
714

    
715
            Service sMNCore = new Service();
716
            sMNCore.setName("MNCore");
717
            sMNCore.setVersion(mnCoreServiceVersion);
718
            sMNCore.setAvailable(mnCoreServiceAvailable);
719

    
720
            Service sMNRead = new Service();
721
            sMNRead.setName("MNRead");
722
            sMNRead.setVersion(mnReadServiceVersion);
723
            sMNRead.setAvailable(mnReadServiceAvailable);
724

    
725
            Service sMNAuthorization = new Service();
726
            sMNAuthorization.setName("MNAuthorization");
727
            sMNAuthorization.setVersion(mnAuthorizationServiceVersion);
728
            sMNAuthorization.setAvailable(mnAuthorizationServiceAvailable);
729

    
730
            Service sMNStorage = new Service();
731
            sMNStorage.setName("MNStorage");
732
            sMNStorage.setVersion(mnStorageServiceVersion);
733
            sMNStorage.setAvailable(mnStorageServiceAvailable);
734

    
735
            Service sMNReplication = new Service();
736
            sMNReplication.setName("MNReplication");
737
            sMNReplication.setVersion(mnReplicationServiceVersion);
738
            sMNReplication.setAvailable(mnReplicationServiceAvailable);
739

    
740
            services.addService(sMNRead);
741
            services.addService(sMNCore);
742
            services.addService(sMNAuthorization);
743
            services.addService(sMNStorage);
744
            services.addService(sMNReplication);
745
            node.setServices(services);
746

    
747
            // TODO: Allow the metacat admin to determine the schedule
748
            // Set the schedule for synchronization
749
            Synchronization synchronization = new Synchronization();
750
            Schedule schedule = new Schedule();
751
            Date now = new Date();
752
            schedule.setYear("*");
753
            schedule.setMon("*");
754
            schedule.setMday("*");
755
            schedule.setWday("?");
756
            schedule.setHour("*");
757
            schedule.setMin("0/3");
758
            schedule.setSec("10");
759
            synchronization.setSchedule(schedule);
760
            synchronization.setLastHarvested(now);
761
            synchronization.setLastCompleteHarvest(now);
762
            node.setSynchronization(synchronization);
763

    
764
            node.setType(nodeType);
765
            return node;
766

    
767
        } catch (PropertyNotFoundException pnfe) {
768
            String msg = "MNodeService.getCapabilities(): " + "property not found: " + pnfe.getMessage();
769
            logMetacat.error(msg);
770
            throw new ServiceFailure("2162", msg);
771
        }
772
    }
773

    
774
    /**
775
     * Returns the number of operations that have been serviced by the node 
776
     * over time periods of one and 24 hours.
777
     * 
778
     * @param session - the Session object containing the credentials for the Subject
779
     * @param period - An ISO8601 compatible DateTime range specifying the time 
780
     *                 range for which to return operation statistics.
781
     * @param requestor - Limit to operations performed by given requestor identity.
782
     * @param event -  Enumerated value indicating the type of event being examined
783
     * @param format - Limit to events involving objects of the specified format
784
     * 
785
     * @return the desired log records
786
     * 
787
     * @throws InvalidToken
788
     * @throws ServiceFailure
789
     * @throws NotAuthorized
790
     * @throws InvalidRequest
791
     * @throws NotImplemented
792
     */
793
    @Override
794
    public MonitorList getOperationStatistics(Session session, Date startTime, Date endTime, Subject requestor, Event event, ObjectFormatIdentifier formatId)
795
            throws NotImplemented, ServiceFailure, NotAuthorized, InvalidRequest, InsufficientResources, UnsupportedType {
796

    
797
        MonitorList monitorList = new MonitorList();
798

    
799
        try {
800

    
801
            // get log records first
802
            Log logs = getLogRecords(session, startTime, endTime, event, 0, null);
803

    
804
            // TODO: aggregate by day or hour -- needs clarification
805
            int count = 1;
806
            for (LogEntry logEntry : logs.getLogEntryList()) {
807
                Identifier pid = logEntry.getIdentifier();
808
                Date logDate = logEntry.getDateLogged();
809
                // if we are filtering by format
810
                if (formatId != null) {
811
                    SystemMetadata sysmeta = IdentifierManager.getInstance().getSystemMetadata(pid.getValue());
812
                    if (!sysmeta.getFormatId().getValue().equals(formatId.getValue())) {
813
                        // does not match
814
                        continue;
815
                    }
816
                }
817
                MonitorInfo item = new MonitorInfo();
818
                item.setCount(count);
819
                item.setDate(new java.sql.Date(logDate.getTime()));
820
                monitorList.addMonitorInfo(item);
821

    
822
            }
823
        } catch (Exception e) {
824
            e.printStackTrace();
825
            throw new ServiceFailure("2081", "Could not retrieve statistics: " + e.getMessage());
826
        }
827

    
828
        return monitorList;
829

    
830
    }
831

    
832
    /**
833
     * Low level “are you alive” operation. A valid ping response is 
834
     * indicated by a HTTP status of 200.
835
     * 
836
     * @return true if the service is alive
837
     * 
838
     * @throws InvalidToken
839
     * @throws ServiceFailure
840
     * @throws NotAuthorized
841
     * @throws InvalidRequest
842
     * @throws NotImplemented
843
     */
844
    @Override
845
    public boolean ping() throws NotImplemented, ServiceFailure, NotAuthorized, InvalidRequest, InsufficientResources, UnsupportedType {
846

    
847
        // test if we can get a database connection
848
        boolean alive = false;
849
        int serialNumber = -1;
850
        DBConnection dbConn = null;
851
        try {
852
            dbConn = DBConnectionPool.getDBConnection("MNodeService.ping");
853
            serialNumber = dbConn.getCheckOutSerialNumber();
854
            alive = true;
855
        } catch (SQLException e) {
856
            return alive;
857
        } finally {
858
            // Return the database connection
859
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
860
        }
861

    
862
        return alive;
863
    }
864

    
865
    /**
866
     * A callback method used by a CN to indicate to a MN that it cannot 
867
     * complete synchronization of the science metadata identified by pid.  Log
868
     * the event in the metacat event log.
869
     * 
870
     * @param session
871
     * @param syncFailed
872
     * 
873
     * @throws ServiceFailure
874
     * @throws NotAuthorized
875
     * @throws InvalidRequest
876
     * @throws NotImplemented
877
     */
878
    @Override
879
    public void synchronizationFailed(Session session, SynchronizationFailed syncFailed) throws NotImplemented, ServiceFailure, NotAuthorized, InvalidRequest {
880

    
881
        String localId;
882

    
883
        try {
884
            localId = IdentifierManager.getInstance().getLocalId(syncFailed.getPid());
885
        } catch (McdbDocNotFoundException e) {
886
            throw new InvalidRequest("2163", "The identifier specified by " + syncFailed.getPid() + " was not found on this node.");
887

    
888
        }
889
        // TODO: update the CN URL below when the CNRead.SynchronizationFailed
890
        // method is changed to include the URL as a parameter
891
        logMetacat.debug("Synchronization for the object identified by " + syncFailed.getPid() + " failed from " + syncFailed.getNodeId()
892
                + " Logging the event to the Metacat EventLog as a 'syncFailed' event.");
893
        // TODO: use the event type enum when the SYNCHRONIZATION_FAILED event is added
894
        String principal = Constants.SUBJECT_PUBLIC;
895
        if (session != null && session.getSubject() != null) {
896
          principal = session.getSubject().getValue();
897
        }
898
        try {
899
          EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), principal, localId, "synchronization_failed");
900
        } catch (Exception e) {
901
            throw new ServiceFailure("2161", "Could not log the error for: " + syncFailed.getPid());
902
    }
903
        //EventLog.getInstance().log("CN URL WILL GO HERE", 
904
        //  session.getSubject().getValue(), localId, Event.SYNCHRONIZATION_FAILED);
905

    
906
    }
907

    
908
    /**
909
     * Essentially a get() but with different logging behavior
910
     */
911
    @Override
912
    public InputStream getReplica(Session session, Identifier pid) 
913
        throws InvalidRequest, InvalidToken, NotAuthorized, NotImplemented, 
914
        ServiceFailure, NotFound {
915

    
916
        logMetacat.info("MNodeService.getReplica() called.");
917

    
918
        InputStream inputStream = null; // bytes to be returned
919
        handler = new MetacatHandler(new Timer());
920
        boolean allowed = false;
921
        String localId; // the metacat docid for the pid
922

    
923
        // get the local docid from Metacat
924
        try {
925
            localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
926
        } catch (McdbDocNotFoundException e) {
927
            throw new NotFound("1020", "The object specified by " + pid.getValue() + " does not exist at this node.");
928
        }
929

    
930
        Subject targetNodeSubject = session.getSubject();
931

    
932
        // check for authorization to replicate, null session to act as this source MN
933
        allowed = D1Client.getCN().isNodeAuthorized(null, targetNodeSubject, pid, Permission.REPLICATE);
934

    
935
        logMetacat.info("Called D1Client.isNodeAuthorized(). Allowed = " + allowed +
936
            " for identifier " + pid.getValue());
937

    
938
        // if the person is authorized, perform the read
939
        if (allowed) {
940
            try {
941
                inputStream = handler.read(localId);
942
            } catch (Exception e) {
943
                throw new ServiceFailure("1020", "The object specified by " + pid.getValue() + "could not be returned due to error: " + e.getMessage());
944
            }
945
        }
946

    
947
        // if we fail to set the input stream
948
        if (inputStream == null) {
949
            throw new NotFound("1020", "The object specified by " + pid.getValue() + "does not exist at this node.");
950
        }
951

    
952
        // log the replica event
953
        String principal = null;
954
        if (session.getSubject() != null) {
955
            principal = session.getSubject().getValue();
956
        }
957
        EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), principal, localId, "getreplica");
958

    
959
        return inputStream;
960
    }
961

    
962
    /**
963
     * Set the access policy
964
     */
965
    @Deprecated
966
    @Override
967
    public boolean setAccessPolicy(Session session, Identifier pid,
968
        AccessPolicy policy) 
969
        throws InvalidToken, ServiceFailure, NotFound, NotAuthorized, 
970
        NotImplemented, InvalidRequest {
971
        
972
        throw new NotImplemented("4401", "This method is deprecated for Member Nodes.");
973
        
974
    }
975

    
976
}
(3-3/4)