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: cjones $'
7
 *     '$Date: 2012-01-10 17:01:54 -0800 (Tue, 10 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.exceptions.IdentifierNotUnique;
51
import org.dataone.service.exceptions.InsufficientResources;
52
import org.dataone.service.exceptions.InvalidRequest;
53
import org.dataone.service.exceptions.InvalidSystemMetadata;
54
import org.dataone.service.exceptions.InvalidToken;
55
import org.dataone.service.exceptions.NotAuthorized;
56
import org.dataone.service.exceptions.NotFound;
57
import org.dataone.service.exceptions.NotImplemented;
58
import org.dataone.service.exceptions.ServiceFailure;
59
import org.dataone.service.exceptions.UnsupportedType;
60
import org.dataone.service.types.v1.AccessPolicy;
61
import org.dataone.service.types.v1.AccessRule;
62
import org.dataone.service.types.v1.DescribeResponse;
63
import org.dataone.service.types.v1.Event;
64
import org.dataone.service.types.v1.Identifier;
65
import org.dataone.service.types.v1.Group;
66
import org.dataone.service.types.v1.Log;
67
import org.dataone.service.types.v1.LogEntry;
68
import org.dataone.service.types.v1.Node;
69
import org.dataone.service.types.v1.NodeReference;
70
import org.dataone.service.types.v1.NodeType;
71
import org.dataone.service.types.v1.ObjectFormat;
72
import org.dataone.service.types.v1.Permission;
73
import org.dataone.service.types.v1.Person;
74
import org.dataone.service.types.v1.Session;
75
import org.dataone.service.types.v1.Subject;
76
import org.dataone.service.types.v1.SubjectInfo;
77
import org.dataone.service.types.v1.SubjectList;
78
import org.dataone.service.types.v1.SystemMetadata;
79
import org.dataone.service.types.v1.util.ChecksumUtil;
80

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

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

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

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

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

    
145
      return describeResponse;
146

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

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

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

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

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

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

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

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

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

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

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

    
371

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

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

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

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

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

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

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

    
424
      LogEntry le = new LogEntry();
425

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

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

    
451
      le.setIdentifier(identifier);
452
      le.setIpAddress(ipAddress);
453
      Calendar c = Calendar.getInstance();
454
      String year = dateLogged.substring(0, 4);
455
      String month = dateLogged.substring(5, 7);
456
      String date = dateLogged.substring(8, 10);
457
      logMetacat.debug("year: " + year + " month: " + month + " day: " + date);
458
      c.set(new Integer(year).intValue(), new Integer(month).intValue(),
459
          new Integer(date).intValue());
460
      Date logDate = c.getTime();
461
      le.setDateLogged(logDate);
462
      NodeReference memberNode = new NodeReference();
463
      memberNode.setValue(ipAddress);
464
      le.setNodeIdentifier(memberNode);
465
      Subject princ = new Subject();
466
      princ.setValue(principal);
467
      le.setSubject(princ);
468
      le.setUserAgent(userAgent);
469

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

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

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

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

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

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

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

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

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

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

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

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

    
1004
    logMetacat.debug("Case DATA: starting to write to disk.");
1005
	if (locked) {
1006

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

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

    
1083
  /**
1084
   * Update a systemMetadata document
1085
   * 
1086
   * @param sysMeta - the system metadata object in the system to update
1087
   */
1088
    protected void updateSystemMetadata(SystemMetadata sysMeta)
1089
        throws ServiceFailure {
1090

    
1091
        logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
1092
        sysMeta.setDateSysMetadataModified(new Date());
1093
        try {
1094
            HazelcastService.getInstance().getSystemMetadataMap().lock(sysMeta.getIdentifier());
1095
            HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
1096

    
1097
        } catch (Exception e) {
1098
            throw new ServiceFailure("4862", e.getMessage());
1099

    
1100
        } finally {
1101
            HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
1102

    
1103
        }
1104

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

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

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

    
1168
    return newFile;
1169
  }
1170
  
1171
}
(2-2/5)