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-07 12:34:56 -0800 (Sat, 07 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
                  } else {
648
                      throw new NotAuthorized("4851", permission + 
649
                          " not allowed on " + pid.getValue());
650
                  }
651
              }                 
652
          }
653
      }
654

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

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

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

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

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

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

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

    
1007
    logMetacat.debug("Case DATA: starting to write to disk.");
1008
	if (locked) {
1009

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

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

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

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

    
1100
        } catch (Exception e) {
1101
            throw new ServiceFailure("4862", e.getMessage());
1102

    
1103
        } finally {
1104
            HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
1105

    
1106
        }
1107

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

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

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

    
1171
    return newFile;
1172
  }
1173
  
1174
}
(2-2/5)