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, Identifier newPid, SystemMetadata sysmeta) throws InvalidToken,
257
            ServiceFailure, NotAuthorized, IdentifierNotUnique, UnsupportedType, InsufficientResources, NotFound, InvalidSystemMetadata, NotImplemented,
258
            InvalidRequest {
259

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

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

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

    
288
        // does the subject have WRITE ( == update) priveleges on the pid?
289
        allowed = isAuthorized(session, pid, Permission.WRITE);
290

    
291
        if (allowed) {
292

    
293
            // get the existing system metadata for the object
294
            SystemMetadata existingSysMeta = getSystemMetadata(session, pid);
295

    
296
            // add the newPid to the obsoletedBy list for the existing sysmeta
297
            existingSysMeta.setObsoletedBy(newPid);
298

    
299
            // then update the existing system metadata
300
            updateSystemMetadata(existingSysMeta);
301

    
302
            // prep the new system metadata, add pid to the affected lists
303
            sysmeta.setObsoletes(pid);
304
            //sysmeta.addDerivedFrom(pid);
305

    
306
            isScienceMetadata = isScienceMetadata(sysmeta);
307

    
308
            // do we have XML metadata or a data object?
309
            if (isScienceMetadata) {
310

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

    
322
                    }
323

    
324
                } catch (IOException e) {
325
                    String msg = "The Node is unable to create the object. " + "There was a problem converting the object to XML";
326
                    logMetacat.info(msg);
327
                    throw new ServiceFailure("1310", msg + ": " + e.getMessage());
328

    
329
                }
330

    
331
            } else {
332

    
333
                // update the data object
334
                localId = insertDataObject(object, newPid, session);
335

    
336
            }
337

    
338
            // and insert the new system metadata
339
            insertSystemMetadata(sysmeta);
340

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

    
344
        } else {
345
            throw new NotAuthorized("1200", "The provided identity does not have " + "permission to UPDATE the object identified by " + pid.getValue()
346
                    + " on the Member Node.");
347
        }
348

    
349
        return newPid;
350
    }
351

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

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

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

    
398
        logMetacat.info("MNodeService.replicate() called with parameters: \n" +
399
            "\tSession.Subject      = " + session.getSubject().getValue() + "\n" +
400
            "\tSystemMetadata       = " + sysmeta.toString()              + "\n" +
401
            "\tSource NodeReference ="  + sourceNode.getValue());
402
        
403
        boolean result = false;
404

    
405
        // TODO: check credentials
406

    
407
        // get the referenced object
408
        Identifier pid = sysmeta.getIdentifier();
409

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

    
422
        } catch (InvalidToken e) {
423
            e.printStackTrace();
424
            throw new ServiceFailure("2151", "Could not retrieve object to replicate (InvalidToken): " + e.getMessage());
425
        } catch (NotFound e) {
426
            e.printStackTrace();
427
            throw new ServiceFailure("2151", "Could not retrieve object to replicate (NotFound): " + e.getMessage());
428
        }
429

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

    
447
        try {
448
        	// call the CN as the MN to set the replication status
449
            cn.setReplicationStatus(null, pid, sourceNode, ReplicationStatus.COMPLETED);
450
            
451
        } catch (InvalidToken e) {
452
            // TODO Auto-generated catch block
453
            e.printStackTrace();
454
        } catch (NotFound e) {
455
            // TODO Auto-generated catch block
456
            e.printStackTrace();
457
        }
458
        return result;
459

    
460
    }
461

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

    
484
    	// get system metadata and construct the describe response
485
        SystemMetadata sysmeta = getSystemMetadata(session, pid);
486
        DescribeResponse describeResponse = new DescribeResponse(sysmeta.getFormatId(), sysmeta.getSize(), sysmeta.getDateSysMetadataModified(),
487
                sysmeta.getChecksum());
488

    
489
        return describeResponse;
490

    
491
    }
492

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

    
510
        return super.get(session, pid);
511

    
512
    }
513

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

    
535
        Checksum checksum = null;
536

    
537
        InputStream inputStream = get(session, pid);
538

    
539
        try {
540
            checksum = ChecksumUtil.checksum(inputStream, algorithm);
541

    
542
        } catch (NoSuchAlgorithmException e) {
543
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned due to an internal error: "
544
                    + e.getMessage());
545
        } catch (IOException e) {
546
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned due to an internal error: "
547
                    + e.getMessage());
548
        }
549

    
550
        if (checksum == null) {
551
            throw new ServiceFailure("1410", "The checksum for the object specified by " + pid.getValue() + "could not be returned.");
552
        }
553

    
554
        return checksum;
555
    }
556

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

    
576
        return super.getSystemMetadata(session, pid);
577
    }
578

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

    
607
        ObjectList objectList = null;
608

    
609
        try {
610
            objectList = IdentifierManager.getInstance().querySystemMetadata(startTime, endTime, objectFormatId, replicaStatus, start, count);
611
        } catch (Exception e) {
612
            throw new ServiceFailure("1580", "Error querying system metadata: " + e.getMessage());
613
        }
614

    
615
        return objectList;
616
    }
617

    
618
    /**
619
     * Return a description of the node's capabilities and services.
620
     * 
621
     * @return node - the technical capabilities of the Member Node
622
     * 
623
     * @throws ServiceFailure
624
     * @throws NotAuthorized
625
     * @throws InvalidRequest
626
     * @throws NotImplemented
627
     */
628
    @Override
629
    public Node getCapabilities() throws NotImplemented, NotAuthorized, ServiceFailure, InvalidRequest {
630

    
631
        String nodeName = null;
632
        String nodeId = null;
633
        String subject = null;
634
        String nodeDesc = null;
635
        String nodeTypeString = null;
636
        NodeType nodeType = null;
637
        String mnCoreServiceVersion = null;
638
        String mnReadServiceVersion = null;
639
        String mnAuthorizationServiceVersion = null;
640
        String mnStorageServiceVersion = null;
641
        String mnReplicationServiceVersion = null;
642

    
643
        boolean nodeSynchronize = false;
644
        boolean nodeReplicate = false;
645
        boolean mnCoreServiceAvailable = false;
646
        boolean mnReadServiceAvailable = false;
647
        boolean mnAuthorizationServiceAvailable = false;
648
        boolean mnStorageServiceAvailable = false;
649
        boolean mnReplicationServiceAvailable = false;
650

    
651
        try {
652
            // get the properties of the node based on configuration information
653
            nodeName = PropertyService.getProperty("dataone.nodeName");
654
            nodeId = PropertyService.getProperty("dataone.memberNodeId");
655
            subject = PropertyService.getProperty("dataone.subject");
656
            nodeDesc = PropertyService.getProperty("dataone.nodeDescription");
657
            nodeTypeString = PropertyService.getProperty("dataone.nodeType");
658
            nodeType = NodeType.convert(nodeTypeString);
659
            nodeSynchronize = new Boolean(PropertyService.getProperty("dataone.nodeSynchronize")).booleanValue();
660
            nodeReplicate = new Boolean(PropertyService.getProperty("dataone.nodeReplicate")).booleanValue();
661

    
662
            mnCoreServiceVersion = PropertyService.getProperty("dataone.mnCore.serviceVersion");
663
            mnReadServiceVersion = PropertyService.getProperty("dataone.mnRead.serviceVersion");
664
            mnAuthorizationServiceVersion = PropertyService.getProperty("dataone.mnAuthorization.serviceVersion");
665
            mnStorageServiceVersion = PropertyService.getProperty("dataone.mnStorage.serviceVersion");
666
            mnReplicationServiceVersion = PropertyService.getProperty("dataone.mnReplication.serviceVersion");
667

    
668
            mnCoreServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnCore.serviceAvailable")).booleanValue();
669
            mnReadServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnRead.serviceAvailable")).booleanValue();
670
            mnAuthorizationServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnAuthorization.serviceAvailable")).booleanValue();
671
            mnStorageServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnStorage.serviceAvailable")).booleanValue();
672
            mnReplicationServiceAvailable = new Boolean(PropertyService.getProperty("dataone.mnReplication.serviceAvailable")).booleanValue();
673

    
674
            // Set the properties of the node based on configuration information and
675
            // calls to current status methods
676
            String serviceName = SystemUtil.getContextURL() + "/" + PropertyService.getProperty("dataone.serviceName");
677
            Node node = new Node();
678
            node.setBaseURL(serviceName + "/" + nodeTypeString);
679
            node.setDescription(nodeDesc);
680

    
681
            // set the node's health information
682
            node.setState(NodeState.UP);
683
            
684
            // set the ping response to the current value
685
            Ping canPing = new Ping();
686
            canPing.setSuccess(false);
687
            try {
688
                canPing.setSuccess(ping());
689
            } catch (InsufficientResources e) {
690
                e.printStackTrace();
691
            } catch (UnsupportedType e) {
692
                e.printStackTrace();
693
            }
694
            node.setPing(canPing);
695

    
696
            NodeReference identifier = new NodeReference();
697
            identifier.setValue(nodeId);
698
            node.setIdentifier(identifier);
699
            Subject s = new Subject();
700
            s.setValue(subject);
701
            node.addSubject(s);
702
            node.setName(nodeName);
703
            node.setReplicate(nodeReplicate);
704
            node.setSynchronize(nodeSynchronize);
705

    
706
            // services: MNAuthorization, MNCore, MNRead, MNReplication, MNStorage
707
            Services services = new Services();
708

    
709
            Service sMNCore = new Service();
710
            sMNCore.setName("MNCore");
711
            sMNCore.setVersion(mnCoreServiceVersion);
712
            sMNCore.setAvailable(mnCoreServiceAvailable);
713

    
714
            Service sMNRead = new Service();
715
            sMNRead.setName("MNRead");
716
            sMNRead.setVersion(mnReadServiceVersion);
717
            sMNRead.setAvailable(mnReadServiceAvailable);
718

    
719
            Service sMNAuthorization = new Service();
720
            sMNAuthorization.setName("MNAuthorization");
721
            sMNAuthorization.setVersion(mnAuthorizationServiceVersion);
722
            sMNAuthorization.setAvailable(mnAuthorizationServiceAvailable);
723

    
724
            Service sMNStorage = new Service();
725
            sMNStorage.setName("MNStorage");
726
            sMNStorage.setVersion(mnStorageServiceVersion);
727
            sMNStorage.setAvailable(mnStorageServiceAvailable);
728

    
729
            Service sMNReplication = new Service();
730
            sMNReplication.setName("MNReplication");
731
            sMNReplication.setVersion(mnReplicationServiceVersion);
732
            sMNReplication.setAvailable(mnReplicationServiceAvailable);
733

    
734
            services.addService(sMNRead);
735
            services.addService(sMNCore);
736
            services.addService(sMNAuthorization);
737
            services.addService(sMNStorage);
738
            services.addService(sMNReplication);
739
            node.setServices(services);
740

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

    
758
            node.setType(nodeType);
759
            return node;
760

    
761
        } catch (PropertyNotFoundException pnfe) {
762
            String msg = "MNodeService.getCapabilities(): " + "property not found: " + pnfe.getMessage();
763
            logMetacat.error(msg);
764
            throw new ServiceFailure("2162", msg);
765
        }
766
    }
767

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

    
791
        MonitorList monitorList = new MonitorList();
792

    
793
        try {
794

    
795
            // get log records first
796
            Log logs = getLogRecords(session, startTime, endTime, event, 0, null);
797

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

    
816
            }
817
        } catch (Exception e) {
818
            e.printStackTrace();
819
            throw new ServiceFailure("2081", "Could not retrieve statistics: " + e.getMessage());
820
        }
821

    
822
        return monitorList;
823

    
824
    }
825

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

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

    
856
        return alive;
857
    }
858

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

    
875
        String localId;
876

    
877
        try {
878
            localId = IdentifierManager.getInstance().getLocalId(syncFailed.getPid());
879
        } catch (McdbDocNotFoundException e) {
880
            throw new InvalidRequest("2163", "The identifier specified by " + syncFailed.getPid() + " was not found on this node.");
881

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

    
900
    }
901

    
902
    /**
903
     * Essentially a get() but with different logging behavior
904
     */
905
    @Override
906
    public InputStream getReplica(Session session, Identifier pid) 
907
        throws InvalidRequest, InvalidToken, NotAuthorized, NotImplemented, 
908
        ServiceFailure, NotFound {
909

    
910
        logMetacat.info("MNodeService.getReplica() called.");
911

    
912
        InputStream inputStream = null; // bytes to be returned
913
        handler = new MetacatHandler(new Timer());
914
        boolean allowed = false;
915
        String localId; // the metacat docid for the pid
916

    
917
        // get the local docid from Metacat
918
        try {
919
            localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
920
        } catch (McdbDocNotFoundException e) {
921
            throw new NotFound("1020", "The object specified by " + pid.getValue() + " does not exist at this node.");
922
        }
923

    
924
        Subject targetNodeSubject = session.getSubject();
925

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

    
929
        logMetacat.info("Called D1Client.isNodeAuthorized(). Allowed = " + allowed +
930
            " for identifier " + pid.getValue());
931

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

    
941
        // if we fail to set the input stream
942
        if (inputStream == null) {
943
            throw new NotFound("1020", "The object specified by " + pid.getValue() + "does not exist at this node.");
944
        }
945

    
946
        // log the replica event
947
        String principal = null;
948
        if (session.getSubject() != null) {
949
            principal = session.getSubject().getValue();
950
        }
951
        EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), principal, localId, "getreplica");
952

    
953
        return inputStream;
954
    }
955

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

    
970
}
(3-3/4)