Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *  Copyright: 2000-2011 Regents of the University of California and the
4
 *              National Center for Ecological Analysis and Synthesis
5
 *
6
 *   '$Author: leinfelder $'
7
 *     '$Date: 2012-03-13 12:19:07 -0700 (Tue, 13 Mar 2012) $'
8
 *
9
 * This program is free software; you can redistribute it and/or modify
10
 * it under the terms of the GNU General Public License as published by
11
 * the Free Software Foundation; either version 2 of the License, or
12
 * (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program; if not, write to the Free Software
21
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22
 */
23

    
24
package edu.ucsb.nceas.metacat.dataone;
25

    
26
import java.io.File;
27
import java.io.FileNotFoundException;
28
import java.io.FileOutputStream;
29
import java.io.IOException;
30
import java.io.InputStream;
31
import java.io.OutputStream;
32
import java.sql.SQLException;
33
import java.util.ArrayList;
34
import java.util.Calendar;
35
import java.util.Date;
36
import java.util.Hashtable;
37
import java.util.List;
38
import java.util.Timer;
39
import java.util.Vector;
40

    
41
import javax.servlet.http.HttpServletRequest;
42

    
43

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

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

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

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

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

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

    
147
      return describeResponse;
148

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

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

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

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

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

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

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

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

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

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

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

    
373

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

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

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

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

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

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

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

    
426
      LogEntry le = new LogEntry();
427

    
428
      // handle Metacat -> DataONE event conversion
429
      if (eventS.equalsIgnoreCase("insert")) {
430
    	  eventS = Event.CREATE.xmlValue();
431
      }
432
      Event e = Event.convert(eventS);
433
      if (e == null) { // skip any events that are not Dataone Crud events
434
          logMetacat.warn("skipping unknown event type: '" + eventS + "'");
435
          continue;
436
      }
437
      le.setEvent(e);
438
      le.setEntryId(entryId);
439
      Identifier identifier = new Identifier();
440
      try {
441
        logMetacat.debug("converting docid '" + docid + "' to a pid.");
442
        if (docid == null || docid.trim().equals("") || docid.trim().equals("null")) {
443
          continue;
444
        }
445
        String docidNoRev = DocumentUtil.getSmartDocId(docid);
446
        //docid = docid.substring(0, docid.lastIndexOf("."));
447
        int rev = DocumentUtil.getRevisionFromAccessionNumber(docid);
448
        //int rev = im.getLatestRevForLocalId(docid);
449
        String guid = im.getGUID(docidNoRev, rev);
450
        identifier.setValue(guid);
451
      } catch (Exception ex) { 
452
        // try to get the pid, if that doesn't
453
        // work, just use the local id
454
        // throw new ServiceFailure("1030",
455
        // "Error getting pid for localId " +
456
        // docid + ": " + ex.getMessage());\
457

    
458
          logMetacat.warn("could not find pid for docid '" + docid + "'");
459

    
460
        // skip it if the pid can't be found
461
        continue;
462
      }
463

    
464
      // skip if we are not allowed to read the document in question
465
      // https://redmine.dataone.org/issues/2444
466
      boolean allowed = false;
467
      try {
468
    	  allowed = isAuthorized(session, identifier, Permission.READ);
469
      } catch (NotAuthorized ignore) {}
470
      catch (NotFound nf) {
471
    	  logMetacat.warn("Could not check authorization for pid: " + identifier.getValue(), nf);
472
      }
473
      if (!allowed) {
474
    	  logMetacat.debug(Permission.READ + " not allowed on document: " + identifier.getValue());
475
    	  continue;
476
      }
477
      
478
      le.setIdentifier(identifier);
479
      le.setIpAddress(ipAddress);
480
      Date logDate = DateTimeMarshaller.deserializeDateToUTC(dateLogged);
481
      le.setDateLogged(logDate);
482
      NodeReference memberNode = new NodeReference();
483
      String nodeId = "localhost";
484
      try {
485
          nodeId = PropertyService.getProperty("dataone.nodeId");
486
      } catch (PropertyNotFoundException e1) {
487
          // TODO Auto-generated catch block
488
          e1.printStackTrace();
489
      }
490
      memberNode.setValue(nodeId);
491
      le.setNodeIdentifier(memberNode);
492
      Subject princ = new Subject();
493
      princ.setValue(principal);
494
      le.setSubject(princ);
495
      le.setUserAgent(userAgent);
496

    
497
      // event filtering?
498
      if (event == null) {
499
    	  logs.add(le);
500
      } else if (le.getEvent().equals(event)) {
501
    	  logs.add(le);
502
      }
503
    }
504
    
505
    // d1 paging
506
    int total = logs.size();
507
    if (start != null && count != null) {
508
    	int toIndex = start + count;
509
    	// do not exceed total
510
    	toIndex = Math.min(toIndex, total);
511
    	// do not start greater than total
512
    	start = Math.min(start, total);
513
    	// sub set of the list
514
    	logs = new ArrayList<LogEntry>(logs.subList(start, toIndex));
515
    }
516

    
517
    log.setLogEntryList(logs);
518
    log.setStart(start);
519
    log.setCount(logs.size());
520
    log.setTotal(total);
521
    logMetacat.info("getLogRecords");
522
    return log;
523
  }
524
    
525
  /**
526
   * Return the object identified by the given object identifier
527
   * 
528
   * @param session - the Session object containing the credentials for the Subject
529
   * @param pid - the object identifier for the given object
530
   * 
531
   * TODO: The D1 Authorization API doesn't provide information on which 
532
   * authentication system the Subject belongs to, and so it's not possible to
533
   * discern which Person or Group is a valid KNB LDAP DN.  Fix this.
534
   * 
535
   * @return inputStream - the input stream of the given object
536
   * 
537
   * @throws InvalidToken
538
   * @throws ServiceFailure
539
   * @throws NotAuthorized
540
   * @throws InvalidRequest
541
   * @throws NotImplemented
542
   */
543
  public InputStream get(Session session, Identifier pid) 
544
    throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
545
    NotImplemented {
546
    
547
    InputStream inputStream = null; // bytes to be returned
548
    handler = new MetacatHandler(new Timer());
549
    boolean allowed = false;
550
    String localId; // the metacat docid for the pid
551
    
552
    // get the local docid from Metacat
553
    try {
554
      localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
555
    
556
    } catch (McdbDocNotFoundException e) {
557
      throw new NotFound("1020", "The object specified by " + 
558
                         pid.getValue() +
559
                         " does not exist at this node.");
560
    }
561
    
562
    // check for authorization
563
    try {
564
		allowed = isAuthorized(session, pid, Permission.READ);
565
	} catch (InvalidRequest e) {
566
		throw new ServiceFailure("1030", e.getDescription());
567
	}
568
    
569
    // if the person is authorized, perform the read
570
    if (allowed) {
571
      try {
572
        inputStream = handler.read(localId);
573
      } catch (Exception e) {
574
        throw new ServiceFailure("1020", "The object specified by " + 
575
            pid.getValue() +
576
            "could not be returned due to error: " +
577
            e.getMessage());
578
      }
579
    }
580

    
581
    // if we fail to set the input stream
582
    if ( inputStream == null ) {
583
      throw new NotFound("1020", "The object specified by " + 
584
                         pid.getValue() +
585
                         "does not exist at this node.");
586
    }
587
    
588
	// log the read event
589
    String principal = Constants.SUBJECT_PUBLIC;
590
    if (session != null && session.getSubject() != null) {
591
    	principal = session.getSubject().getValue();
592
    }
593
    EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), principal, localId, "read");
594
    
595
    return inputStream;
596
  }
597

    
598
  /**
599
   * Return the system metadata for a given object
600
   * 
601
   * @param session - the Session object containing the credentials for the Subject
602
   * @param pid - the object identifier for the given object
603
   * 
604
   * @return inputStream - the input stream of the given system metadata object
605
   * 
606
   * @throws InvalidToken
607
   * @throws ServiceFailure
608
   * @throws NotAuthorized
609
   * @throws NotFound
610
   * @throws InvalidRequest
611
   * @throws NotImplemented
612
   */
613
  public SystemMetadata getSystemMetadata(Session session, Identifier pid)
614
      throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
615
      NotImplemented {
616
      
617
	  boolean isAuthorized = false;
618
	  try {
619
		isAuthorized = isAuthorized(session, pid, Permission.READ);
620
	  } catch (InvalidRequest e) {
621
		throw new ServiceFailure("1090", e.getDescription());
622
	  }
623
	  
624
      if (!isAuthorized) {
625
        throw new NotAuthorized("1400", Permission.READ + " not allowed on " + pid.getValue());  
626
      }
627
      SystemMetadata systemMetadata = null;
628
      try {
629
        systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
630
        
631
      } catch (Exception e) {
632
        // convert hazelcast RuntimeException to NotFound
633
        throw new NotFound("1420", "No record found for: " + pid.getValue());
634
        
635
      }
636
    
637
    return systemMetadata;
638
  }
639
     
640
  /**
641
   * Test if the user identified by the provided token has administrative authorization 
642
   * for the operation on the specified object.
643
   * 
644
   * @param session - the Session object containing the credentials for the Subject
645
   * @param pid - The identifer of the resource for which access is being checked
646
   * @param operation - The type of operation which is being requested for the given pid
647
   * 
648
   * @return true if the operation is allowed
649
   * 
650
   * @throws ServiceFailure
651
   * @throws InvalidToken
652
   * @throws NotFound
653
   * @throws NotAuthorized
654
   * @throws NotImplemented
655
   */
656
  protected boolean isAdminAuthorized(Session session, Identifier pid,
657
      Permission permission) 
658
      throws ServiceFailure, InvalidToken, NotFound, NotAuthorized,
659
      NotImplemented {
660

    
661
      boolean allowed = false;
662
      // are we allowed to do this? only CNs and target MNs are allowed
663
      CNode cn = D1Client.getCN();
664
      List<Node> nodes = cn.listNodes().getNodeList();
665
      
666
      if ( nodes == null ) {
667
          throw new ServiceFailure("4852", "Couldn't get node list.");
668
  
669
      }
670
      
671
      // find the node in the node list
672
      for ( Node node : nodes ) {
673
          
674
          NodeReference nodeReference = node.getIdentifier();
675
          logMetacat.debug("In isAdminAuthorized(), Node reference is: " + nodeReference.getValue());
676
          
677
          Subject subject = session.getSubject();
678
          
679
          if (node.getType() == NodeType.CN) {
680
              List<Subject> nodeSubjects = node.getSubjectList();
681
              
682
              // check if the session subject is in the node subject list
683
              for (Subject nodeSubject : nodeSubjects) {
684
                  if ( nodeSubject.equals(subject) ) {
685
                      allowed = true; // subject of session == target node subject
686
                      break;
687
                      
688
                  }
689
              }              
690
          }
691
      }
692

    
693
      
694
      return allowed;
695
  }
696
  
697
  /**
698
   * Test if the user identified by the provided token has authorization 
699
   * for the operation on the specified object.
700
   * 
701
   * @param session - the Session object containing the credentials for the Subject
702
   * @param pid - The identifer of the resource for which access is being checked
703
   * @param operation - The type of operation which is being requested for the given pid
704
   *
705
   * @return true if the operation is allowed
706
   * 
707
   * @throws ServiceFailure
708
   * @throws InvalidToken
709
   * @throws NotFound
710
   * @throws NotAuthorized
711
   * @throws NotImplemented
712
   * @throws InvalidRequest
713
   */
714
  public boolean isAuthorized(Session session, Identifier pid, Permission permission)
715
    throws ServiceFailure, InvalidToken, NotFound, NotAuthorized,
716
    NotImplemented, InvalidRequest {
717

    
718
    boolean allowed = false;
719
    
720
    if (permission == null) {
721
    	throw new InvalidRequest("1761", "Permission was not provided or is invalid");
722
    }
723
    
724
    // permissions are hierarchical
725
    List<Permission> expandedPermissions = null;
726
    
727
    // for the "Verified" symbolic user
728
    Subject verifiedSubject = new Subject();
729
	verifiedSubject.setValue(Constants.SUBJECT_VERIFIED_USER);
730
    
731
    // get the subject[s] from the session
732
	List<Subject> subjects = new ArrayList<Subject>();
733
	if (session != null) {
734
		// primary subject
735
		Subject subject = session.getSubject();
736
		if (subject != null) {
737
			subjects.add(subject);
738
		}
739
		// details about the subject
740
		SubjectInfo subjectInfo = session.getSubjectInfo();
741
		if (subjectInfo != null) {
742
			// find subjectInfo for the primary subject
743
			List<Person> personList = subjectInfo.getPersonList();
744
			List<Group> groupList = subjectInfo.getGroupList();
745
			if (personList != null) {
746
				for (Person p : personList) {
747
					  // for every person listed (isVerified is transitive)
748
						logMetacat.debug("checking person");
749
						logMetacat.debug("p.getVerified(): " + p.getVerified());
750
						if (p.getVerified() != null && p.getVerified()) {
751
							// add the verified symbolic user
752
							if (!subjects.contains(verifiedSubject)) {
753
								subjects.add(verifiedSubject);
754
							}
755
						}
756
						// add the equivalent identities
757
						List<Subject> equivList = p.getEquivalentIdentityList();
758
						if (equivList != null) {
759
							for (Subject equivSubject : equivList) {
760
								subjects.add(equivSubject);
761
								// find that entry
762
								for (Person equivPerson: personList) {
763
									if (equivSubject.equals(equivPerson.getSubject())) {
764
										// transitive group membership
765
										if (equivPerson.getIsMemberOfList() != null) {
766
											for (Subject equivGroup: equivPerson.getIsMemberOfList()) {
767
												subjects.add(equivGroup);
768
											}
769
										}
770
										// TODO: is verified transitive?
771
										if (equivPerson.getVerified() != null && equivPerson.getVerified()) {
772
											// add the verified symbolic user
773
											if (!subjects.contains(verifiedSubject)) {
774
												subjects.add(verifiedSubject);
775
											}
776
										}
777
									}
778
								}
779
							}
780
						}
781
						// add the groups they are a member of
782
						List<Subject> memberOfList = p.getIsMemberOfList();
783
						if (memberOfList != null) {
784
							for (Subject g : memberOfList) {
785
								subjects.add(g);
786
							}
787
						}
788
						// look at all the Groups to see if this person has membership defined there
789
						if (groupList != null) {
790
							for (Group group: groupList) {
791
								if (group.getHasMemberList() != null) {
792
									for (Subject member: group.getHasMemberList()) {
793
										// is the person a member?
794
										if (member.equals(p.getSubject())) {
795
											// add this group as a subject to check if it is not already there
796
											if (!subjects.contains(group.getSubject())) {
797
												subjects.add(group.getSubject());
798
											}
799
										}
800
									}
801
								}
802
							}
803
						}
804
						break;
805
				}
806
			}
807
		}
808

    
809
		// add the authenticated symbolic since we have a session
810
		Subject authenticatedSubject = new Subject();
811
		authenticatedSubject.setValue(Constants.SUBJECT_AUTHENTICATED_USER);
812
		subjects.add(authenticatedSubject);
813
	}
814

    
815
    // add public subject for everyone
816
    Subject publicSubject = new Subject();
817
    publicSubject.setValue(Constants.SUBJECT_PUBLIC);
818
    subjects.add(publicSubject);
819
    
820
    // get the system metadata
821
    String pidStr = pid.getValue();
822
    SystemMetadata systemMetadata = null;
823
    try {
824
        systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
825

    
826
    } catch (Exception e) {
827
        // convert Hazelcast RuntimeException to NotFound
828
        logMetacat.error("An error occurred while getting system metadata for identifier " +
829
            pid.getValue() + ". The error message was: " + e.getMessage());
830
        throw new NotFound("1800", "No record found for " + pidStr);
831
        
832
    } 
833
    
834
    // throw not found if it was not found
835
    if (systemMetadata == null) {
836
    	throw new NotFound("1800", "No system metadata could be found for given PID: " + pidStr);
837
    }
838
	    
839
    // do we own it?
840
    for (Subject s: subjects) {
841
      logMetacat.debug("Comparing \t" + 
842
                       systemMetadata.getRightsHolder().getValue() +
843
                       " \tagainst \t" + s.getValue());
844
    	allowed = systemMetadata.getRightsHolder().equals(s);
845
    	if (allowed) {
846
    		return allowed;
847
    	}
848
    }    
849
    
850
    // otherwise check the access rules
851
    try {
852
	    List<AccessRule> allows = systemMetadata.getAccessPolicy().getAllowList();
853
	    search: // label break
854
	    for (AccessRule accessRule: allows) {
855
	      for (Subject s: subjects) {
856
	        logMetacat.debug("Checking allow access rule for subject: " + s.getValue());
857
	        if (accessRule.getSubjectList().contains(s)) {
858
	        	logMetacat.debug("Access rule contains subject: " + s.getValue());
859
	        	for (Permission p: accessRule.getPermissionList()) {
860
		        	logMetacat.debug("Checking permission: " + p.xmlValue());
861
	        		expandedPermissions = expandPermissions(p);
862
	        		allowed = expandedPermissions.contains(permission);
863
	        		if (allowed) {
864
			        	logMetacat.info("Permission granted: " + p.xmlValue() + " to " + s.getValue());
865
	        			break search; //label break
866
	        		}
867
	        	}
868
        		
869
	        }
870
	      }
871
	    }
872
    } catch (Exception e) {
873
    	// catch all for errors - safe side should be to deny the access
874
    	logMetacat.error("Problem checking authorization - defaulting to deny", e);
875
		allowed = false;
876
	  
877
    }
878
    
879
    // throw or return?
880
    if (!allowed) {
881
      throw new NotAuthorized("1820", permission + " not allowed on " + pidStr);
882
    }
883
    
884
    return allowed;
885
    
886
  }
887
  
888
  /*
889
   * parse a logEntry and get the relevant field from it
890
   * 
891
   * @param fieldname
892
   * @param entry
893
   * @return
894
   */
895
  private String getLogEntryField(String fieldname, String entry) {
896
    String begin = "<" + fieldname + ">";
897
    String end = "</" + fieldname + ">";
898
    // logMetacat.debug("looking for " + begin + " and " + end +
899
    // " in entry " + entry);
900
    String s = entry.substring(entry.indexOf(begin) + begin.length(), entry
901
        .indexOf(end));
902
    logMetacat.debug("entry " + fieldname + " : " + s);
903
    return s;
904
  }
905

    
906
  /** 
907
   * Determine if a given object should be treated as an XML science metadata
908
   * object. 
909
   * 
910
   * @param sysmeta - the SystemMetadata describing the object
911
   * @return true if the object should be treated as science metadata
912
   */
913
  public static boolean isScienceMetadata(SystemMetadata sysmeta) {
914
    
915
    ObjectFormat objectFormat = null;
916
    boolean isScienceMetadata = false;
917
    
918
    try {
919
      objectFormat = ObjectFormatCache.getInstance().getFormat(sysmeta.getFormatId());
920
      if ( objectFormat.getFormatType().equals("METADATA") ) {
921
      	isScienceMetadata = true;
922
      	
923
      }
924
      
925
       
926
    } catch (ServiceFailure e) {
927
      logMetacat.debug("There was a problem determining if the object identified by" + 
928
          sysmeta.getIdentifier().getValue() + 
929
          " is science metadata: " + e.getMessage());
930
    
931
    } catch (NotFound e) {
932
      logMetacat.debug("There was a problem determining if the object identified by" + 
933
          sysmeta.getIdentifier().getValue() + 
934
          " is science metadata: " + e.getMessage());
935
    
936
    }
937
    
938
    return isScienceMetadata;
939

    
940
  }
941
  
942
  /**
943
   * Insert or update an XML document into Metacat
944
   * 
945
   * @param xml - the XML document to insert or update
946
   * @param pid - the identifier to be used for the resulting object
947
   * 
948
   * @return localId - the resulting docid of the document created or updated
949
   * 
950
   */
951
  public String insertOrUpdateDocument(String xml, Identifier pid, 
952
    Session session, String insertOrUpdate) 
953
    throws ServiceFailure {
954
    
955
  	logMetacat.debug("Starting to insert xml document...");
956
    IdentifierManager im = IdentifierManager.getInstance();
957

    
958
    // generate pid/localId pair for sysmeta
959
    String localId = null;
960
    
961
    if(insertOrUpdate.equals("insert")) {
962
      localId = im.generateLocalId(pid.getValue(), 1);
963
      
964
    } else {
965
      //localid should already exist in the identifier table, so just find it
966
      try {
967
        logMetacat.debug("Updating pid " + pid.getValue());
968
        logMetacat.debug("looking in identifier table for pid " + pid.getValue());
969
        
970
        localId = im.getLocalId(pid.getValue());
971
        
972
        logMetacat.debug("localId: " + localId);
973
        //increment the revision
974
        String docid = localId.substring(0, localId.lastIndexOf("."));
975
        String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
976
        int rev = new Integer(revS).intValue();
977
        rev++;
978
        docid = docid + "." + rev;
979
        localId = docid;
980
        logMetacat.debug("incremented localId: " + localId);
981
      
982
      } catch(McdbDocNotFoundException e) {
983
        throw new ServiceFailure("1030", "D1NodeService.insertOrUpdateDocument(): " +
984
            "pid " + pid.getValue() + 
985
            " should have been in the identifier table, but it wasn't: " + 
986
            e.getMessage());
987
      
988
      }
989
      
990
    }
991

    
992
    params = new Hashtable<String, String[]>();
993
    String[] action = new String[1];
994
    action[0] = insertOrUpdate;
995
    params.put("action", action);
996
    String[] docid = new String[1];
997
    docid[0] = localId;
998
    params.put("docid", docid);
999
    String[] doctext = new String[1];
1000
    doctext[0] = xml;
1001
    params.put("doctext", doctext);
1002
    
1003
    String username = Constants.SUBJECT_PUBLIC;
1004
    String[] groupnames = null;
1005
    if (session != null ) {
1006
    	username = session.getSubject().getValue();
1007
    	if (session.getSubjectInfo() != null) {
1008
    		List<Group> groupList = session.getSubjectInfo().getGroupList();
1009
    		if (groupList != null) {
1010
    			groupnames = new String[groupList.size()];
1011
    			for (int i = 0; i > groupList.size(); i++ ) {
1012
    				groupnames[i] = groupList.get(i).getGroupName();
1013
    			}
1014
    		}
1015
    	}
1016
    }
1017
    
1018
    // do the insert or update action
1019
    handler = new MetacatHandler(new Timer());
1020
    String result = handler.handleInsertOrUpdateAction(request.getRemoteAddr(), request.getHeader("User-Agent"), null, 
1021
                        null, params, username, groupnames, false);
1022
    
1023
    if(result.indexOf("<error>") != -1) {
1024
    	String detailCode = "";
1025
    	if ( insertOrUpdate.equals("insert") ) {
1026
    		// make sure to remove the mapping so that subsequent attempts do not fail with IdentifierNotUnique
1027
    		im.removeMapping(pid.getValue(), localId);
1028
    		detailCode = "1190";
1029
    		
1030
    	} else if ( insertOrUpdate.equals("update") ) {
1031
    		detailCode = "1310";
1032
    		
1033
    	}
1034
        throw new ServiceFailure(detailCode, 
1035
          "Error inserting or updating document: " + result);
1036
    }
1037
    logMetacat.debug("Finsished inserting xml document with id " + localId);
1038
    
1039
    return localId;
1040
  }
1041
  
1042
  /**
1043
   * Insert a data document
1044
   * 
1045
   * @param object
1046
   * @param pid
1047
   * @param sessionData
1048
   * @throws ServiceFailure
1049
   * @returns localId of the data object inserted
1050
   */
1051
  public String insertDataObject(InputStream object, Identifier pid, 
1052
          Session session) throws ServiceFailure {
1053
      
1054
    String username = Constants.SUBJECT_PUBLIC;
1055
    String[] groupnames = null;
1056
    if (session != null ) {
1057
    	username = session.getSubject().getValue();
1058
    	if (session.getSubjectInfo() != null) {
1059
    		List<Group> groupList = session.getSubjectInfo().getGroupList();
1060
    		if (groupList != null) {
1061
    			groupnames = new String[groupList.size()];
1062
    			for (int i = 0; i > groupList.size(); i++ ) {
1063
    				groupnames[i] = groupList.get(i).getGroupName();
1064
    			}
1065
    		}
1066
    	}
1067
    }
1068
  
1069
    // generate pid/localId pair for object
1070
    logMetacat.debug("Generating a pid/localId mapping");
1071
    IdentifierManager im = IdentifierManager.getInstance();
1072
    String localId = im.generateLocalId(pid.getValue(), 1);
1073
  
1074
    // Save the data file to disk using "localId" as the name
1075
    String datafilepath = null;
1076
	try {
1077
		datafilepath = PropertyService.getProperty("application.datafilepath");
1078
	} catch (PropertyNotFoundException e) {
1079
		ServiceFailure sf = new ServiceFailure("1190", "Lookup data file path" + e.getMessage());
1080
		sf.initCause(e);
1081
		throw sf;
1082
	}
1083
    boolean locked = false;
1084
	try {
1085
		locked = DocumentImpl.getDataFileLockGrant(localId);
1086
	} catch (Exception e) {
1087
		ServiceFailure sf = new ServiceFailure("1190", "Could not lock file for writing:" + e.getMessage());
1088
		sf.initCause(e);
1089
		throw sf;
1090
	}
1091

    
1092
    logMetacat.debug("Case DATA: starting to write to disk.");
1093
	if (locked) {
1094

    
1095
          File dataDirectory = new File(datafilepath);
1096
          dataDirectory.mkdirs();
1097
  
1098
          File newFile = writeStreamToFile(dataDirectory, localId, object);
1099
  
1100
          // TODO: Check that the file size matches SystemMetadata
1101
          // long size = newFile.length();
1102
          // if (size == 0) {
1103
          //     throw new IOException("Uploaded file is 0 bytes!");
1104
          // }
1105
  
1106
          // Register the file in the database (which generates an exception
1107
          // if the localId is not acceptable or other untoward things happen
1108
          try {
1109
            logMetacat.debug("Registering document...");
1110
            DocumentImpl.registerDocument(localId, "BIN", localId,
1111
                    username, groupnames);
1112
            logMetacat.debug("Registration step completed.");
1113
            
1114
          } catch (SQLException e) {
1115
            //newFile.delete();
1116
            logMetacat.debug("SQLE: " + e.getMessage());
1117
            e.printStackTrace(System.out);
1118
            throw new ServiceFailure("1190", "Registration failed: " + 
1119
            		e.getMessage());
1120
            
1121
          } catch (AccessionNumberException e) {
1122
            //newFile.delete();
1123
            logMetacat.debug("ANE: " + e.getMessage());
1124
            e.printStackTrace(System.out);
1125
            throw new ServiceFailure("1190", "Registration failed: " + 
1126
            	e.getMessage());
1127
            
1128
          } catch (Exception e) {
1129
            //newFile.delete();
1130
            logMetacat.debug("Exception: " + e.getMessage());
1131
            e.printStackTrace(System.out);
1132
            throw new ServiceFailure("1190", "Registration failed: " + 
1133
            	e.getMessage());
1134
          }
1135
  
1136
          logMetacat.debug("Logging the creation event.");
1137
          EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, "create");
1138
  
1139
          // Schedule replication for this data file
1140
          logMetacat.debug("Scheduling replication.");
1141
          ForceReplicationHandler frh = new ForceReplicationHandler(
1142
            localId, "create", false, null);
1143
      }
1144
      
1145
      return localId;
1146
    
1147
  }
1148

    
1149
  /**
1150
   * Insert a systemMetadata document and return its localId
1151
   */
1152
  public void insertSystemMetadata(SystemMetadata sysmeta) 
1153
      throws ServiceFailure {
1154
      
1155
  	  logMetacat.debug("Starting to insert SystemMetadata...");
1156
      sysmeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
1157
      logMetacat.debug("Inserting new system metadata with modified date " + 
1158
          sysmeta.getDateSysMetadataModified());
1159
      
1160
      //insert the system metadata
1161
      try {
1162
        // note: the calling subclass handles the map hazelcast lock/unlock
1163
      	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
1164
      	
1165
      } catch (Exception e) {
1166
          throw new ServiceFailure("1190", e.getMessage());
1167
          
1168
	    }  
1169
  }
1170

    
1171
  /**
1172
   * Update a systemMetadata document
1173
   * 
1174
   * @param sysMeta - the system metadata object in the system to update
1175
   */
1176
    protected void updateSystemMetadata(SystemMetadata sysMeta)
1177
        throws ServiceFailure {
1178

    
1179
        logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
1180
        sysMeta.setDateSysMetadataModified(new Date());
1181
        try {
1182
            HazelcastService.getInstance().getSystemMetadataMap().lock(sysMeta.getIdentifier());
1183
            HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
1184

    
1185
        } catch (Exception e) {
1186
            throw new ServiceFailure("4862", e.getMessage());
1187

    
1188
        } finally {
1189
            HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
1190

    
1191
        }
1192

    
1193
    }
1194
  
1195
  /**
1196
   * Given a Permission, returns a list of all permissions that it encompasses
1197
   * Permissions are hierarchical so that WRITE also allows READ.
1198
   * @param permission
1199
   * @return list of included Permissions for the given permission
1200
   */
1201
  protected List<Permission> expandPermissions(Permission permission) {
1202
	  	List<Permission> expandedPermissions = new ArrayList<Permission>();
1203
	    if (permission.equals(Permission.READ)) {
1204
	    	expandedPermissions.add(Permission.READ);
1205
	    }
1206
	    if (permission.equals(Permission.WRITE)) {
1207
	    	expandedPermissions.add(Permission.READ);
1208
	    	expandedPermissions.add(Permission.WRITE);
1209
	    }
1210
	    if (permission.equals(Permission.CHANGE_PERMISSION)) {
1211
	    	expandedPermissions.add(Permission.READ);
1212
	    	expandedPermissions.add(Permission.WRITE);
1213
	    	expandedPermissions.add(Permission.CHANGE_PERMISSION);
1214
	    }
1215
	    return expandedPermissions;
1216
  }
1217

    
1218
  /*
1219
   * Write a stream to a file
1220
   * 
1221
   * @param dir - the directory to write to
1222
   * @param fileName - the file name to write to
1223
   * @param data - the object bytes as an input stream
1224
   * 
1225
   * @return newFile - the new file created
1226
   * 
1227
   * @throws ServiceFailure
1228
   */
1229
  private File writeStreamToFile(File dir, String fileName, InputStream data) 
1230
    throws ServiceFailure {
1231
    
1232
    File newFile = new File(dir, fileName);
1233
    logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1234

    
1235
    try {
1236
        if (newFile.createNewFile()) {
1237
          // write data stream to desired file
1238
          OutputStream os = new FileOutputStream(newFile);
1239
          long length = IOUtils.copyLarge(data, os);
1240
          os.flush();
1241
          os.close();
1242
        } else {
1243
          logMetacat.debug("File creation failed, or file already exists.");
1244
          throw new ServiceFailure("1190", "File already exists: " + fileName);
1245
        }
1246
    } catch (FileNotFoundException e) {
1247
      logMetacat.debug("FNF: " + e.getMessage());
1248
      throw new ServiceFailure("1190", "File not found: " + fileName + " " 
1249
                + e.getMessage());
1250
    } catch (IOException e) {
1251
      logMetacat.debug("IOE: " + e.getMessage());
1252
      throw new ServiceFailure("1190", "File was not written: " + fileName 
1253
                + " " + e.getMessage());
1254
    }
1255

    
1256
    return newFile;
1257
  }
1258
  
1259
}
(2-2/5)