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: leinfelder $'
7
 *     '$Date: 2012-01-24 10:35:22 -0800 (Tue, 24 Jan 2012) $'
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.File;
27
import java.io.FileNotFoundException;
28
import java.io.FileOutputStream;
29
import java.io.IOException;
30
import java.io.InputStream;
31
import java.io.OutputStream;
32
import java.sql.SQLException;
33
import java.util.ArrayList;
34
import java.util.Calendar;
35
import java.util.Date;
36
import java.util.Hashtable;
37
import java.util.List;
38
import java.util.Timer;
39
import java.util.Vector;
40

    
41
import javax.servlet.http.HttpServletRequest;
42

    
43

    
44
import org.apache.commons.io.IOUtils;
45
import org.apache.log4j.Logger;
46
import org.dataone.client.CNode;
47
import org.dataone.client.D1Client;
48
import org.dataone.client.ObjectFormatCache;
49
import org.dataone.service.util.Constants;
50
import org.dataone.service.util.DateTimeMarshaller;
51
import org.dataone.service.exceptions.IdentifierNotUnique;
52
import org.dataone.service.exceptions.InsufficientResources;
53
import org.dataone.service.exceptions.InvalidRequest;
54
import org.dataone.service.exceptions.InvalidSystemMetadata;
55
import org.dataone.service.exceptions.InvalidToken;
56
import org.dataone.service.exceptions.NotAuthorized;
57
import org.dataone.service.exceptions.NotFound;
58
import org.dataone.service.exceptions.NotImplemented;
59
import org.dataone.service.exceptions.ServiceFailure;
60
import org.dataone.service.exceptions.UnsupportedType;
61
import org.dataone.service.types.v1.AccessPolicy;
62
import org.dataone.service.types.v1.AccessRule;
63
import org.dataone.service.types.v1.DescribeResponse;
64
import org.dataone.service.types.v1.Event;
65
import org.dataone.service.types.v1.Identifier;
66
import org.dataone.service.types.v1.Group;
67
import org.dataone.service.types.v1.Log;
68
import org.dataone.service.types.v1.LogEntry;
69
import org.dataone.service.types.v1.Node;
70
import org.dataone.service.types.v1.NodeReference;
71
import org.dataone.service.types.v1.NodeType;
72
import org.dataone.service.types.v1.ObjectFormat;
73
import org.dataone.service.types.v1.Permission;
74
import org.dataone.service.types.v1.Person;
75
import org.dataone.service.types.v1.Session;
76
import org.dataone.service.types.v1.Subject;
77
import org.dataone.service.types.v1.SubjectInfo;
78
import org.dataone.service.types.v1.SubjectList;
79
import org.dataone.service.types.v1.SystemMetadata;
80
import org.dataone.service.types.v1.util.ChecksumUtil;
81

    
82
import edu.ucsb.nceas.metacat.AccessionNumberException;
83
import edu.ucsb.nceas.metacat.DocumentImpl;
84
import edu.ucsb.nceas.metacat.EventLog;
85
import edu.ucsb.nceas.metacat.IdentifierManager;
86
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
87
import edu.ucsb.nceas.metacat.MetacatHandler;
88
import edu.ucsb.nceas.metacat.database.DBConnection;
89
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
90
import edu.ucsb.nceas.metacat.dataone.hazelcast.HazelcastService;
91
import edu.ucsb.nceas.metacat.properties.PropertyService;
92
import edu.ucsb.nceas.metacat.replication.ForceReplicationHandler;
93
import edu.ucsb.nceas.metacat.util.SystemUtil;
94
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
95

    
96
public abstract class D1NodeService {
97
  
98
  private static Logger logMetacat = Logger.getLogger(D1NodeService.class);
99

    
100
  /** For logging the operations */
101
  protected HttpServletRequest request;
102
  
103
  /* reference to the metacat handler */
104
  protected MetacatHandler handler;
105
  
106
  /* parameters set in the incoming request */
107
  private Hashtable<String, String[]> params;
108

    
109
  /**
110
   * Constructor - used to set the metacatUrl from a subclass extending D1NodeService
111
   * 
112
   * @param metacatUrl - the URL of the metacat service, including the ending /d1
113
   */
114
  public D1NodeService(HttpServletRequest request) {
115
		this.request = request;
116
	}
117
  
118
  /**
119
   * This method provides a lighter weight mechanism than 
120
   * getSystemMetadata() for a client to determine basic 
121
   * properties of the referenced object.
122
   * 
123
   * @param session - the Session object containing the credentials for the Subject
124
   * @param pid - the identifier of the object to be described
125
   * 
126
   * @return describeResponse - A set of values providing a basic description 
127
   *                            of the object.
128
   * 
129
   * @throws InvalidToken
130
   * @throws ServiceFailure
131
   * @throws NotAuthorized
132
   * @throws NotFound
133
   * @throws NotImplemented
134
   * @throws InvalidRequest
135
   */
136
  public DescribeResponse describe(Session session, Identifier pid) 
137
      throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
138

    
139
    // get system metadata and construct the describe response
140
      SystemMetadata sysmeta = getSystemMetadata(session, pid);
141
      DescribeResponse describeResponse = 
142
      	new DescribeResponse(sysmeta.getFormatId(), sysmeta.getSize(), 
143
      			sysmeta.getDateSysMetadataModified(),
144
      			sysmeta.getChecksum(), sysmeta.getSerialVersion());
145

    
146
      return describeResponse;
147

    
148
  }
149
  
150
  /**
151
   * Low level, "are you alive" operation. A valid ping response is 
152
   * indicated by a HTTP status of 200.
153
   * 
154
   * @return true if the service is alive
155
   * 
156
   * @throws NotImplemented
157
   * @throws ServiceFailure
158
   * @throws InsufficientResources
159
   */
160
  public Date ping() 
161
      throws NotImplemented, ServiceFailure, InsufficientResources {
162

    
163
      // test if we can get a database connection
164
      int serialNumber = -1;
165
      DBConnection dbConn = null;
166
      try {
167
          dbConn = DBConnectionPool.getDBConnection("MNodeService.ping");
168
          serialNumber = dbConn.getCheckOutSerialNumber();
169
      } catch (SQLException e) {
170
      	ServiceFailure sf = new ServiceFailure("", e.getMessage());
171
      	sf.initCause(e);
172
          throw sf;
173
      } finally {
174
          // Return the database connection
175
          DBConnectionPool.returnDBConnection(dbConn, serialNumber);
176
      }
177

    
178
      return Calendar.getInstance().getTime();
179
  }
180
  
181
  /**
182
   * Adds a new object to the Node, where the object is either a data 
183
   * object or a science metadata object. This method is called by clients 
184
   * to create new data objects on Member Nodes or internally for Coordinating
185
   * Nodes
186
   * 
187
   * @param session - the Session object containing the credentials for the Subject
188
   * @param pid - The object identifier to be created
189
   * @param object - the object bytes
190
   * @param sysmeta - the system metadata that describes the object  
191
   * 
192
   * @return pid - the object identifier created
193
   * 
194
   * @throws InvalidToken
195
   * @throws ServiceFailure
196
   * @throws NotAuthorized
197
   * @throws IdentifierNotUnique
198
   * @throws UnsupportedType
199
   * @throws InsufficientResources
200
   * @throws InvalidSystemMetadata
201
   * @throws NotImplemented
202
   * @throws InvalidRequest
203
   */
204
  public Identifier create(Session session, Identifier pid, InputStream object,
205
    SystemMetadata sysmeta) 
206
    throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, 
207
    UnsupportedType, InsufficientResources, InvalidSystemMetadata, 
208
    NotImplemented, InvalidRequest {
209

    
210
    Identifier resultPid = null;
211
    String localId = null;
212
    boolean allowed = false;
213
    
214
    // check for null session
215
    if (session == null) {
216
    	throw new InvalidToken("4894", "Session is required to WRITE to the Node.");
217
    }
218
    Subject subject = session.getSubject();
219

    
220
    Subject publicSubject = new Subject();
221
    publicSubject.setValue(Constants.SUBJECT_PUBLIC);
222
	// be sure the user is authenticated for create()
223
    if (subject == null || subject.getValue() == null || 
224
        subject.equals(publicSubject) ) {
225
      throw new NotAuthorized("1100", "The provided identity does not have " +
226
        "permission to WRITE to the Node.");
227
      
228
    }
229
    
230
    // verify that pid == SystemMetadata.getIdentifier()
231
    logMetacat.debug("Comparing pid|sysmeta_pid: " + 
232
      pid.getValue() + "|" + sysmeta.getIdentifier().getValue());
233
    if (!pid.getValue().equals(sysmeta.getIdentifier().getValue())) {
234
        throw new InvalidSystemMetadata("1180", 
235
            "The supplied system metadata is invalid. " +
236
            "The identifier " + pid.getValue() + " does not match identifier" +
237
            "in the system metadata identified by " +
238
            sysmeta.getIdentifier().getValue() + ".");
239
        
240
    }
241

    
242
    logMetacat.debug("Checking if identifier exists...");
243
    // Check that the identifier does not already exist
244
    if (IdentifierManager.getInstance().identifierExists(pid.getValue())) {
245
	    	throw new IdentifierNotUnique("1120", 
246
			          "The requested identifier " + pid.getValue() +
247
			          " is already used by another object and" +
248
			          "therefore can not be used for this object. Clients should choose" +
249
			          "a new identifier that is unique and retry the operation or " +
250
			          "use CN.reserveIdentifier() to reserve one.");
251
    	
252
    }
253
    
254
    // check that we are not attempting to subvert versioning
255
    if (sysmeta.getObsoletes() != null && sysmeta.getObsoletes().getValue() != null) {
256
    	throw new InvalidSystemMetadata("1180", 
257
    			"The supplied system metadata is invalid. " +
258
    			"The obsoletes field cannot have a value when creating entries.");
259
    }
260
    if (sysmeta.getObsoletedBy() != null && sysmeta.getObsoletedBy().getValue() != null) {
261
    	throw new InvalidSystemMetadata("1180", 
262
    			"The supplied system metadata is invalid. " +
263
    			"The obsoletedBy field cannot have a value when creating entries.");
264
	}
265
    
266
    // TODO: this probably needs to be refined more
267
    try {
268
      allowed = isAuthorized(session, pid, Permission.WRITE);
269
            
270
    } catch (NotFound e) {
271
      // The identifier doesn't exist, writing should be fine.
272
      allowed = true;
273
    }
274
    
275
    // verify checksum, only if we can reset the inputstream
276
    if (object.markSupported()) {
277
	    String checksumAlgorithm = sysmeta.getChecksum().getAlgorithm();
278
	    String checksumValue = sysmeta.getChecksum().getValue();
279
	    try {
280
			String computedChecksumValue = ChecksumUtil.checksum(object, checksumAlgorithm).getValue();
281
			// it's very important that we don't consume the stream
282
			object.reset();
283
			if (!computedChecksumValue.equals(checksumValue)) {
284
				throw new InvalidSystemMetadata("4896", "Checksum given does not match that of the object");
285
			}
286
		} catch (Exception e) {
287
			String msg = "Error verifying checksum values";
288
	      	logMetacat.error(msg, e);
289
	        throw new ServiceFailure("1190", msg + ": " + e.getMessage());
290
		}
291
    } else {
292
    	logMetacat.warn("mark is not supported on the object's input stream - cannot verify checksum without consuming stream");
293
    }
294
    	
295
    // we have the go ahead
296
    if ( allowed ) {
297
      
298
      // Science metadata (XML) or science data object?
299
      // TODO: there are cases where certain object formats are science metadata
300
      // but are not XML (netCDF ...).  Handle this.
301
      if ( isScienceMetadata(sysmeta) ) {
302
        
303
        // CASE METADATA:
304
      	String objectAsXML = "";
305
        try {
306
	        objectAsXML = IOUtils.toString(object, "UTF-8");
307
	        localId = insertOrUpdateDocument(objectAsXML, pid, session, "insert");
308
	        //localId = im.getLocalId(pid.getValue());
309

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

    
316
        }
317
                    
318
      } else {
319
	        
320
	      // DEFAULT CASE: DATA (needs to be checked and completed)
321
	      localId = insertDataObject(object, pid, session);
322
      }   
323
    
324
    }
325

    
326
    // save the sysmeta
327
    try {
328
      // lock and unlock of the pid happens in the subclass
329
    	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
330
    	
331
    } catch (Exception e) {
332
    	logMetacat.error("Problem creating system metadata: " + pid.getValue(), e);
333
        throw new ServiceFailure("1190", e.getMessage());
334
	}
335
    
336
    // setting the resulting identifier failed
337
    if (localId == null ) {
338
      throw new ServiceFailure("1190", "The Node is unable to create the object. ");
339
    }
340

    
341
    resultPid = pid;
342
    
343
    return resultPid;
344
  }
345

    
346
  /**
347
   * Return the log records associated with a given event between the start and 
348
   * end dates listed given a particular Subject listed in the Session
349
   * 
350
   * @param session - the Session object containing the credentials for the Subject
351
   * @param fromDate - the start date of the desired log records
352
   * @param toDate - the end date of the desired log records
353
   * @param event - restrict log records of a specific event type
354
   * @param start - zero based offset from the first record in the 
355
   *                set of matching log records. Used to assist with 
356
   *                paging the response.
357
   * @param count - maximum number of log records to return in the response. 
358
   *                Used to assist with paging the response.
359
   * 
360
   * @return the desired log records
361
   * 
362
   * @throws InvalidToken
363
   * @throws ServiceFailure
364
   * @throws NotAuthorized
365
   * @throws InvalidRequest
366
   * @throws NotImplemented
367
   */
368
  public Log getLogRecords(Session session, Date fromDate, Date toDate, 
369
      Event event, Integer start, Integer count) throws InvalidToken, ServiceFailure,
370
      NotAuthorized, InvalidRequest, NotImplemented {
371

    
372

    
373
    Log log = new Log();
374
    List<LogEntry> logs = new Vector<LogEntry>();
375
    IdentifierManager im = IdentifierManager.getInstance();
376
    EventLog el = EventLog.getInstance();
377
    if ( fromDate == null ) {
378
      logMetacat.debug("setting fromdate from null");
379
      fromDate = new Date(1);
380
    }
381
    if ( toDate == null ) {
382
      logMetacat.debug("setting todate from null");
383
      toDate = new Date();
384
    }
385

    
386
    if ( start == null ) {
387
    	start = 0;
388
    	
389
    }
390
    
391
    if ( count == null ) {
392
    	count = 1000;
393
    	
394
    }
395

    
396
    logMetacat.debug("fromDate: " + fromDate);
397
    logMetacat.debug("toDate: " + toDate);
398

    
399
    String report = el.getReport(null, null, null, null,
400
        new java.sql.Timestamp(fromDate.getTime()),
401
        new java.sql.Timestamp(toDate.getTime()), false);
402

    
403
    logMetacat.debug("report: " + report);
404

    
405
    String logEntry = "<logEntry>";
406
    String endLogEntry = "</logEntry>";
407
    int startIndex = 0;
408
    int foundIndex = report.indexOf(logEntry, startIndex);
409
    while (foundIndex != -1) {
410
      // parse out each entry
411
      int endEntryIndex = report.indexOf(endLogEntry, foundIndex);
412
      String entry = report.substring(foundIndex, endEntryIndex);
413
      logMetacat.debug("entry: " + entry);
414
      startIndex = endEntryIndex + endLogEntry.length();
415
      foundIndex = report.indexOf(logEntry, startIndex);
416

    
417
      String entryId = getLogEntryField("entryid", entry);
418
      String ipAddress = getLogEntryField("ipAddress", entry);
419
      String principal = getLogEntryField("principal", entry);
420
      String userAgent = getLogEntryField("userAgent", entry);
421
      String docid = getLogEntryField("docid", entry);
422
      String eventS = getLogEntryField("event", entry);
423
      String dateLogged = getLogEntryField("dateLogged", entry);
424

    
425
      LogEntry le = new LogEntry();
426

    
427
      Event e = Event.convert(eventS);
428
      if (e == null) { // skip any events that are not Dataone Crud events
429
        continue;
430
      }
431
      le.setEvent(e);
432
      le.setEntryId(entryId);
433
      Identifier identifier = new Identifier();
434
      try {
435
        logMetacat.debug("converting docid '" + docid + "' to a pid.");
436
        if (docid == null || docid.trim().equals("") || docid.trim().equals("null")) {
437
          continue;
438
        }
439
        docid = docid.substring(0, docid.lastIndexOf("."));
440
        identifier.setValue(im.getGUID(docid, im.getLatestRevForLocalId(docid)));
441
      } catch (Exception ex) { 
442
        // try to get the pid, if that doesn't
443
        // work, just use the local id
444
        // throw new ServiceFailure("1030",
445
        // "Error getting pid for localId " +
446
        // docid + ": " + ex.getMessage());\
447

    
448
        // skip it if the pid can't be found
449
        continue;
450
      }
451

    
452
      le.setIdentifier(identifier);
453
      le.setIpAddress(ipAddress);
454
      Date logDate = DateTimeMarshaller.deserializeDateToUTC(dateLogged);
455
      le.setDateLogged(logDate);
456
      NodeReference memberNode = new NodeReference();
457
      memberNode.setValue(ipAddress);
458
      le.setNodeIdentifier(memberNode);
459
      Subject princ = new Subject();
460
      princ.setValue(principal);
461
      le.setSubject(princ);
462
      le.setUserAgent(userAgent);
463

    
464
      // event filtering?
465
      if (event == null) {
466
    	  logs.add(le);
467
      } else if (le.getEvent().equals(event)) {
468
    	  logs.add(le);
469
      }
470
    }
471
    
472
    // d1 paging
473
    int total = logs.size();
474
    if (start != null && count != null) {
475
    	int toIndex = start + count;
476
    	if (toIndex <= total) {
477
    		logs = new ArrayList<LogEntry>(logs.subList(start, toIndex));
478
    	}
479
    }
480

    
481
    log.setLogEntryList(logs);
482
    log.setStart(start);
483
    log.setCount(logs.size());
484
    log.setTotal(total);
485
    logMetacat.info("getLogRecords");
486
    return log;
487
  }
488
    
489
  /**
490
   * Return the object identified by the given object identifier
491
   * 
492
   * @param session - the Session object containing the credentials for the Subject
493
   * @param pid - the object identifier for the given object
494
   * 
495
   * TODO: The D1 Authorization API doesn't provide information on which 
496
   * authentication system the Subject belongs to, and so it's not possible to
497
   * discern which Person or Group is a valid KNB LDAP DN.  Fix this.
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
  public InputStream get(Session session, Identifier pid) 
508
    throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
509
    NotImplemented {
510
    
511
    InputStream inputStream = null; // bytes to be returned
512
    handler = new MetacatHandler(new Timer());
513
    boolean allowed = false;
514
    String localId; // the metacat docid for the pid
515
    
516
    // get the local docid from Metacat
517
    try {
518
      localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
519
    
520
    } catch (McdbDocNotFoundException e) {
521
      throw new NotFound("1020", "The object specified by " + 
522
                         pid.getValue() +
523
                         " does not exist at this node.");
524
    }
525
    
526
    // check for authorization
527
    allowed = isAuthorized(session, pid, Permission.READ);
528
    
529
    // if the person is authorized, perform the read
530
    if (allowed) {
531
      try {
532
        inputStream = handler.read(localId);
533
      } catch (Exception e) {
534
        throw new ServiceFailure("1020", "The object specified by " + 
535
            pid.getValue() +
536
            "could not be returned due to error: " +
537
            e.getMessage());
538
      }
539
    }
540

    
541
    // if we fail to set the input stream
542
    if ( inputStream == null ) {
543
      throw new NotFound("1020", "The object specified by " + 
544
                         pid.getValue() +
545
                         "does not exist at this node.");
546
    }
547
    
548
	// log the read event
549
    String principal = Constants.SUBJECT_PUBLIC;
550
    if (session != null && session.getSubject() != null) {
551
    	principal = session.getSubject().getValue();
552
    }
553
    EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), principal, localId, "read");
554
    
555
    return inputStream;
556
  }
557

    
558
  /**
559
   * Return the system metadata for a given object
560
   * 
561
   * @param session - the Session object containing the credentials for the Subject
562
   * @param pid - the object identifier for the given object
563
   * 
564
   * @return inputStream - the input stream of the given system metadata object
565
   * 
566
   * @throws InvalidToken
567
   * @throws ServiceFailure
568
   * @throws NotAuthorized
569
   * @throws NotFound
570
   * @throws InvalidRequest
571
   * @throws NotImplemented
572
   */
573
  public SystemMetadata getSystemMetadata(Session session, Identifier pid)
574
      throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
575
      NotImplemented {
576
      
577
      if (!isAuthorized(session, pid, Permission.READ)) {
578
        throw new NotAuthorized("1400", Permission.READ + " not allowed on " + pid.getValue());  
579
      }
580
      SystemMetadata systemMetadata = null;
581
      try {
582
        systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
583
        
584
      } catch (Exception e) {
585
        // convert hazelcast RuntimeException to NotFound
586
        throw new NotFound("1420", "No record found for: " + pid.getValue());
587
        
588
      }
589
    
590
    return systemMetadata;
591
  }
592
     
593
  /**
594
   * Test if the user identified by the provided token has administrative authorization 
595
   * for the operation on the specified object.
596
   * 
597
   * @param session - the Session object containing the credentials for the Subject
598
   * @param pid - The identifer of the resource for which access is being checked
599
   * @param operation - The type of operation which is being requested for the given pid
600
   * 
601
   * @return true if the operation is allowed
602
   * 
603
   * @throws ServiceFailure
604
   * @throws InvalidToken
605
   * @throws NotFound
606
   * @throws NotAuthorized
607
   * @throws NotImplemented
608
   */
609
  protected boolean isAdminAuthorized(Session session, Identifier pid,
610
      Permission permission) 
611
      throws ServiceFailure, InvalidToken, NotFound, NotAuthorized,
612
      NotImplemented {
613

    
614
      boolean allowed = false;
615
      // are we allowed to do this? only CNs and target MNs are allowed
616
      CNode cn = D1Client.getCN();
617
      List<Node> nodes = cn.listNodes().getNodeList();
618
      
619
      if ( nodes == null ) {
620
          throw new ServiceFailure("4852", "Couldn't get node list.");
621
  
622
      }
623
      
624
      // find the node in the node list
625
      for ( Node node : nodes ) {
626
          
627
          NodeReference nodeReference = node.getIdentifier();
628
          logMetacat.debug("In isAdminAuthorized(), Node reference is: " + nodeReference.getValue());
629
          
630
          Subject subject = session.getSubject();
631
          
632
          if (node.getType() == NodeType.CN) {
633
              List<Subject> nodeSubjects = node.getSubjectList();
634
              
635
              // check if the session subject is in the node subject list
636
              for (Subject nodeSubject : nodeSubjects) {
637
                  if ( nodeSubject.equals(subject) ) {
638
                      allowed = true; // subject of session == target node subject
639
                      break;
640
                      
641
                  }
642
              }              
643
          }
644
      }
645

    
646
      
647
      return allowed;
648
  }
649
  
650
  /**
651
   * Test if the user identified by the provided token has authorization 
652
   * for the operation on the specified object.
653
   * 
654
   * @param session - the Session object containing the credentials for the Subject
655
   * @param pid - The identifer of the resource for which access is being checked
656
   * @param operation - The type of operation which is being requested for the given pid
657
   *
658
   * @return true if the operation is allowed
659
   * 
660
   * @throws ServiceFailure
661
   * @throws InvalidToken
662
   * @throws NotFound
663
   * @throws NotAuthorized
664
   * @throws NotImplemented
665
   * @throws InvalidRequest
666
   */
667
  public boolean isAuthorized(Session session, Identifier pid, Permission permission)
668
    throws ServiceFailure, InvalidToken, NotFound, NotAuthorized,
669
    NotImplemented {
670

    
671
    boolean allowed = false;
672
    
673
    // permissions are hierarchical
674
    List<Permission> expandedPermissions = null;
675
    
676
    // for the "Verified" symbolic user
677
    Subject verifiedSubject = new Subject();
678
	verifiedSubject.setValue(Constants.SUBJECT_VERIFIED_USER);
679
    
680
    // get the subjects from the session
681
    List<Subject> subjects = new ArrayList<Subject>();
682
    if (session != null) {
683
	    Subject subject = session.getSubject();
684
	    if (subject != null) {
685
	    	subjects.add(subject);
686
	    }
687
	    SubjectInfo subjectInfo = session.getSubjectInfo();
688
	    if (subjectInfo != null) {
689
	    	// add the equivalent identities
690
	    	List<Person> personList = subjectInfo.getPersonList();
691
	    	if (personList != null) {
692
			    for (Person p: personList) {
693
			      subjects.add(p.getSubject());
694
			      if (p.getVerified()) {
695
			    	  // add the verified symbolic user
696
			    	  if (!subjects.contains(verifiedSubject)) {
697
			    		  subjects.add(verifiedSubject);
698
			    	  }
699
			      }
700
			    }
701
	    	}
702
	    	// add the groups
703
	    	List<Group> groupList = subjectInfo.getGroupList();
704
	    	if (groupList != null) {
705
			    for (Group g: groupList) {
706
			      subjects.add(g.getSubject());
707
			    }
708
	    	}
709
	    }
710
	    // add the authenticated symbolic as a check
711
	    Subject authenticatedSubject = new Subject();
712
	    authenticatedSubject.setValue(Constants.SUBJECT_AUTHENTICATED_USER);
713
	    subjects.add(authenticatedSubject);
714
	    
715
    }
716
    
717
    // add public subject
718
    Subject publicSubject = new Subject();
719
    publicSubject.setValue(Constants.SUBJECT_PUBLIC);
720
    subjects.add(publicSubject);
721
    
722
    // get the system metadata
723
    String pidStr = pid.getValue();
724
    SystemMetadata systemMetadata = null;
725
    try {
726
        systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
727

    
728
    } catch (Exception e) {
729
        // convert Hazelcast RuntimeException to NotFound
730
        logMetacat.error("An error occurred while getting system metadata for identifier " +
731
            pid.getValue() + ". The error message was: " + e.getMessage());
732
        throw new NotFound("1800", "No record found for " + pidStr);
733
        
734
    } 
735
    
736
    // throw not found if it was not found
737
    if (systemMetadata == null) {
738
    	throw new NotFound("1800", "No system metadata could be found for given PID: " + pidStr);
739
    }
740
	    
741
    // do we own it?
742
    for (Subject s: subjects) {
743
    	allowed = systemMetadata.getRightsHolder().equals(s);
744
    	if (allowed) {
745
    		return allowed;
746
    	}
747
    }    
748
    
749
    // otherwise check the access rules
750
    try {
751
	    List<AccessRule> allows = systemMetadata.getAccessPolicy().getAllowList();
752
	    search: // label break
753
	    for (AccessRule accessRule: allows) {
754
	      for (Subject s: subjects) {
755
	        if (accessRule.getSubjectList().contains(s)) {
756
	        	for (Permission p: accessRule.getPermissionList()) {
757
	        		expandedPermissions = expandPermissions(p);
758
	        		allowed = expandedPermissions.contains(permission);
759
	        		if (allowed) {
760
	        			break search; //label break
761
	        		}
762
	        	}
763
        		
764
	        }
765
	      }
766
	    }
767
    } catch (Exception e) {
768
    	// catch all for errors - safe side should be to deny the access
769
    	logMetacat.error("Problem checking authorization - defaulting to deny", e);
770
		allowed = false;
771
	}
772
    
773
    // throw or return?
774
    if (!allowed) {
775
      throw new NotAuthorized("1820", permission + " not allowed on " + pidStr);
776
    }
777
    
778
    return allowed;
779
    
780
  }
781
  
782
  /*
783
   * parse a logEntry and get the relevant field from it
784
   * 
785
   * @param fieldname
786
   * @param entry
787
   * @return
788
   */
789
  private String getLogEntryField(String fieldname, String entry) {
790
    String begin = "<" + fieldname + ">";
791
    String end = "</" + fieldname + ">";
792
    // logMetacat.debug("looking for " + begin + " and " + end +
793
    // " in entry " + entry);
794
    String s = entry.substring(entry.indexOf(begin) + begin.length(), entry
795
        .indexOf(end));
796
    logMetacat.debug("entry " + fieldname + " : " + s);
797
    return s;
798
  }
799

    
800
  /** 
801
   * Determine if a given object should be treated as an XML science metadata
802
   * object. 
803
   * 
804
   * @param sysmeta - the SystemMetadata describing the object
805
   * @return true if the object should be treated as science metadata
806
   */
807
  public static boolean isScienceMetadata(SystemMetadata sysmeta) {
808
    
809
    ObjectFormat objectFormat = null;
810
    boolean isScienceMetadata = false;
811
    
812
    try {
813
      objectFormat = ObjectFormatCache.getInstance().getFormat(sysmeta.getFormatId());
814
      if ( objectFormat.getFormatType().equals("METADATA") ) {
815
      	isScienceMetadata = true;
816
      	
817
      }
818
      
819
    } catch (InvalidRequest e) {
820
       logMetacat.debug("There was a problem determining if the object identified by" + 
821
         sysmeta.getIdentifier().getValue() + 
822
         " is science metadata: " + e.getMessage());
823
       
824
    } catch (ServiceFailure e) {
825
      logMetacat.debug("There was a problem determining if the object identified by" + 
826
          sysmeta.getIdentifier().getValue() + 
827
          " is science metadata: " + e.getMessage());
828
    
829
    } catch (NotFound e) {
830
      logMetacat.debug("There was a problem determining if the object identified by" + 
831
          sysmeta.getIdentifier().getValue() + 
832
          " is science metadata: " + e.getMessage());
833
    
834
    } catch (InsufficientResources e) {
835
      logMetacat.debug("There was a problem determining if the object identified by" + 
836
          sysmeta.getIdentifier().getValue() + 
837
          " is science metadata: " + e.getMessage());
838
    
839
    } catch (NotImplemented e) {
840
      logMetacat.debug("There was a problem determining if the object identified by" + 
841
          sysmeta.getIdentifier().getValue() + 
842
          " is science metadata: " + e.getMessage());
843
    
844
    }
845
    
846
    return isScienceMetadata;
847

    
848
  }
849
  
850
  /**
851
   * Insert or update an XML document into Metacat
852
   * 
853
   * @param xml - the XML document to insert or update
854
   * @param pid - the identifier to be used for the resulting object
855
   * 
856
   * @return localId - the resulting docid of the document created or updated
857
   * 
858
   */
859
  public String insertOrUpdateDocument(String xml, Identifier pid, 
860
    Session session, String insertOrUpdate) 
861
    throws ServiceFailure {
862
    
863
  	logMetacat.debug("Starting to insert xml document...");
864
    IdentifierManager im = IdentifierManager.getInstance();
865

    
866
    // generate pid/localId pair for sysmeta
867
    String localId = null;
868
    
869
    if(insertOrUpdate.equals("insert")) {
870
      localId = im.generateLocalId(pid.getValue(), 1);
871
      
872
    } else {
873
      //localid should already exist in the identifier table, so just find it
874
      try {
875
        logMetacat.debug("Updating pid " + pid.getValue());
876
        logMetacat.debug("looking in identifier table for pid " + pid.getValue());
877
        
878
        localId = im.getLocalId(pid.getValue());
879
        
880
        logMetacat.debug("localId: " + localId);
881
        //increment the revision
882
        String docid = localId.substring(0, localId.lastIndexOf("."));
883
        String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
884
        int rev = new Integer(revS).intValue();
885
        rev++;
886
        docid = docid + "." + rev;
887
        localId = docid;
888
        logMetacat.debug("incremented localId: " + localId);
889
      
890
      } catch(McdbDocNotFoundException e) {
891
        throw new ServiceFailure("1030", "D1NodeService.insertOrUpdateDocument(): " +
892
            "pid " + pid.getValue() + 
893
            " should have been in the identifier table, but it wasn't: " + 
894
            e.getMessage());
895
      
896
      }
897
      
898
    }
899

    
900
    params = new Hashtable<String, String[]>();
901
    String[] action = new String[1];
902
    action[0] = insertOrUpdate;
903
    params.put("action", action);
904
    String[] docid = new String[1];
905
    docid[0] = localId;
906
    params.put("docid", docid);
907
    String[] doctext = new String[1];
908
    doctext[0] = xml;
909
    params.put("doctext", doctext);
910
    
911
    String username = Constants.SUBJECT_PUBLIC;
912
    String[] groupnames = null;
913
    if (session != null ) {
914
    	username = session.getSubject().getValue();
915
    	if (session.getSubjectInfo() != null) {
916
    		List<Group> groupList = session.getSubjectInfo().getGroupList();
917
    		if (groupList != null) {
918
    			groupnames = new String[groupList.size()];
919
    			for (int i = 0; i > groupList.size(); i++ ) {
920
    				groupnames[i] = groupList.get(i).getGroupName();
921
    			}
922
    		}
923
    	}
924
    }
925
    
926
    // do the insert or update action
927
    handler = new MetacatHandler(new Timer());
928
    String result = handler.handleInsertOrUpdateAction(request.getRemoteAddr(), request.getHeader("User-Agent"), null, 
929
                        null, params, username, groupnames);
930
    
931
    if(result.indexOf("<error>") != -1) {
932
    	String detailCode = "";
933
    	if ( insertOrUpdate.equals("insert") ) {
934
    		detailCode = "1190";
935
    		
936
    	} else if ( insertOrUpdate.equals("update") ) {
937
    		detailCode = "1310";
938
    		
939
    	}
940
        throw new ServiceFailure(detailCode, 
941
          "Error inserting or updating document: " + result);
942
    }
943
    logMetacat.debug("Finsished inserting xml document with id " + localId);
944
    
945
    return localId;
946
  }
947
  
948
  /**
949
   * Insert a data document
950
   * 
951
   * @param object
952
   * @param pid
953
   * @param sessionData
954
   * @throws ServiceFailure
955
   * @returns localId of the data object inserted
956
   */
957
  public String insertDataObject(InputStream object, Identifier pid, 
958
          Session session) throws ServiceFailure {
959
      
960
    String username = Constants.SUBJECT_PUBLIC;
961
    String[] groupnames = null;
962
    if (session != null ) {
963
    	username = session.getSubject().getValue();
964
    	if (session.getSubjectInfo() != null) {
965
    		List<Group> groupList = session.getSubjectInfo().getGroupList();
966
    		if (groupList != null) {
967
    			groupnames = new String[groupList.size()];
968
    			for (int i = 0; i > groupList.size(); i++ ) {
969
    				groupnames[i] = groupList.get(i).getGroupName();
970
    			}
971
    		}
972
    	}
973
    }
974
  
975
    // generate pid/localId pair for object
976
    logMetacat.debug("Generating a pid/localId mapping");
977
    IdentifierManager im = IdentifierManager.getInstance();
978
    String localId = im.generateLocalId(pid.getValue(), 1);
979
  
980
    // Save the data file to disk using "localId" as the name
981
    String datafilepath = null;
982
	try {
983
		datafilepath = PropertyService.getProperty("application.datafilepath");
984
	} catch (PropertyNotFoundException e) {
985
		ServiceFailure sf = new ServiceFailure("1190", "Lookup data file path" + e.getMessage());
986
		sf.initCause(e);
987
		throw sf;
988
	}
989
    boolean locked = false;
990
	try {
991
		locked = DocumentImpl.getDataFileLockGrant(localId);
992
	} catch (Exception e) {
993
		ServiceFailure sf = new ServiceFailure("1190", "Could not lock file for writing:" + e.getMessage());
994
		sf.initCause(e);
995
		throw sf;
996
	}
997

    
998
    logMetacat.debug("Case DATA: starting to write to disk.");
999
	if (locked) {
1000

    
1001
          File dataDirectory = new File(datafilepath);
1002
          dataDirectory.mkdirs();
1003
  
1004
          File newFile = writeStreamToFile(dataDirectory, localId, object);
1005
  
1006
          // TODO: Check that the file size matches SystemMetadata
1007
          // long size = newFile.length();
1008
          // if (size == 0) {
1009
          //     throw new IOException("Uploaded file is 0 bytes!");
1010
          // }
1011
  
1012
          // Register the file in the database (which generates an exception
1013
          // if the localId is not acceptable or other untoward things happen
1014
          try {
1015
            logMetacat.debug("Registering document...");
1016
            DocumentImpl.registerDocument(localId, "BIN", localId,
1017
                    username, groupnames);
1018
            logMetacat.debug("Registration step completed.");
1019
            
1020
          } catch (SQLException e) {
1021
            //newFile.delete();
1022
            logMetacat.debug("SQLE: " + e.getMessage());
1023
            e.printStackTrace(System.out);
1024
            throw new ServiceFailure("1190", "Registration failed: " + 
1025
            		e.getMessage());
1026
            
1027
          } catch (AccessionNumberException e) {
1028
            //newFile.delete();
1029
            logMetacat.debug("ANE: " + e.getMessage());
1030
            e.printStackTrace(System.out);
1031
            throw new ServiceFailure("1190", "Registration failed: " + 
1032
            	e.getMessage());
1033
            
1034
          } catch (Exception e) {
1035
            //newFile.delete();
1036
            logMetacat.debug("Exception: " + e.getMessage());
1037
            e.printStackTrace(System.out);
1038
            throw new ServiceFailure("1190", "Registration failed: " + 
1039
            	e.getMessage());
1040
          }
1041
  
1042
          logMetacat.debug("Logging the creation event.");
1043
          EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, "create");
1044
  
1045
          // Schedule replication for this data file
1046
          logMetacat.debug("Scheduling replication.");
1047
          ForceReplicationHandler frh = new ForceReplicationHandler(
1048
            localId, "create", false, null);
1049
      }
1050
      
1051
      return localId;
1052
    
1053
  }
1054

    
1055
  /**
1056
   * Insert a systemMetadata document and return its localId
1057
   */
1058
  public void insertSystemMetadata(SystemMetadata sysmeta) 
1059
      throws ServiceFailure {
1060
      
1061
  	  logMetacat.debug("Starting to insert SystemMetadata...");
1062
      sysmeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
1063
      logMetacat.debug("Inserting new system metadata with modified date " + 
1064
          sysmeta.getDateSysMetadataModified());
1065
      
1066
      //insert the system metadata
1067
      try {
1068
        // note: the calling subclass handles the map hazelcast lock/unlock
1069
      	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
1070
      	
1071
      } catch (Exception e) {
1072
          throw new ServiceFailure("1190", e.getMessage());
1073
          
1074
	    }  
1075
  }
1076

    
1077
  /**
1078
   * Update a systemMetadata document
1079
   * 
1080
   * @param sysMeta - the system metadata object in the system to update
1081
   */
1082
    protected void updateSystemMetadata(SystemMetadata sysMeta)
1083
        throws ServiceFailure {
1084

    
1085
        logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
1086
        sysMeta.setDateSysMetadataModified(new Date());
1087
        try {
1088
            HazelcastService.getInstance().getSystemMetadataMap().lock(sysMeta.getIdentifier());
1089
            HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
1090

    
1091
        } catch (Exception e) {
1092
            throw new ServiceFailure("4862", e.getMessage());
1093

    
1094
        } finally {
1095
            HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
1096

    
1097
        }
1098

    
1099
    }
1100
  
1101
  /**
1102
   * Given a Permission, returns a list of all permissions that it encompasses
1103
   * Permissions are hierarchical so that WRITE also allows READ.
1104
   * @param permission
1105
   * @return list of included Permissions for the given permission
1106
   */
1107
  protected List<Permission> expandPermissions(Permission permission) {
1108
	  	List<Permission> expandedPermissions = new ArrayList<Permission>();
1109
	    if (permission.equals(Permission.READ)) {
1110
	    	expandedPermissions.add(Permission.READ);
1111
	    }
1112
	    if (permission.equals(Permission.WRITE)) {
1113
	    	expandedPermissions.add(Permission.READ);
1114
	    	expandedPermissions.add(Permission.WRITE);
1115
	    }
1116
	    if (permission.equals(Permission.CHANGE_PERMISSION)) {
1117
	    	expandedPermissions.add(Permission.READ);
1118
	    	expandedPermissions.add(Permission.WRITE);
1119
	    	expandedPermissions.add(Permission.CHANGE_PERMISSION);
1120
	    }
1121
	    return expandedPermissions;
1122
  }
1123

    
1124
  /*
1125
   * Write a stream to a file
1126
   * 
1127
   * @param dir - the directory to write to
1128
   * @param fileName - the file name to write to
1129
   * @param data - the object bytes as an input stream
1130
   * 
1131
   * @return newFile - the new file created
1132
   * 
1133
   * @throws ServiceFailure
1134
   */
1135
  private File writeStreamToFile(File dir, String fileName, InputStream data) 
1136
    throws ServiceFailure {
1137
    
1138
    File newFile = new File(dir, fileName);
1139
    logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1140

    
1141
    try {
1142
        if (newFile.createNewFile()) {
1143
          // write data stream to desired file
1144
          OutputStream os = new FileOutputStream(newFile);
1145
          long length = IOUtils.copyLarge(data, os);
1146
          os.flush();
1147
          os.close();
1148
        } else {
1149
          logMetacat.debug("File creation failed, or file already exists.");
1150
          throw new ServiceFailure("1190", "File already exists: " + fileName);
1151
        }
1152
    } catch (FileNotFoundException e) {
1153
      logMetacat.debug("FNF: " + e.getMessage());
1154
      throw new ServiceFailure("1190", "File not found: " + fileName + " " 
1155
                + e.getMessage());
1156
    } catch (IOException e) {
1157
      logMetacat.debug("IOE: " + e.getMessage());
1158
      throw new ServiceFailure("1190", "File was not written: " + fileName 
1159
                + " " + e.getMessage());
1160
    }
1161

    
1162
    return newFile;
1163
  }
1164
  
1165
}
(2-2/5)