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 10:43:01 -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
			if (personList != null) {
745
				for (Person p : personList) {
746
					  // for every person listed (isVerified is transitive)
747
						logMetacat.debug("checking person");
748
						logMetacat.debug("p.getVerified(): " + p.getVerified());
749
						if (p.getVerified() != null && p.getVerified()) {
750
							// add the verified symbolic user
751
							if (!subjects.contains(verifiedSubject)) {
752
								subjects.add(verifiedSubject);
753
							}
754
						}
755
						// add the equivalent identities
756
						List<Subject> equivList = p
757
								.getEquivalentIdentityList();
758
						if (equivList != null) {
759
							for (Subject equiv : equivList) {
760
								subjects.add(equiv);
761
							}
762
						}
763
						// add the groups
764
						List<Subject> groupList = p.getIsMemberOfList();
765
						if (groupList != null) {
766
							for (Subject g : groupList) {
767
								subjects.add(g);
768
							}
769
						}
770
						break;
771
				}
772
			}
773
		}
774

    
775
		// add the authenticated symbolic since we have a session
776
		Subject authenticatedSubject = new Subject();
777
		authenticatedSubject.setValue(Constants.SUBJECT_AUTHENTICATED_USER);
778
		subjects.add(authenticatedSubject);
779
	}
780

    
781
    // add public subject for everyone
782
    Subject publicSubject = new Subject();
783
    publicSubject.setValue(Constants.SUBJECT_PUBLIC);
784
    subjects.add(publicSubject);
785
    
786
    // get the system metadata
787
    String pidStr = pid.getValue();
788
    SystemMetadata systemMetadata = null;
789
    try {
790
        systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
791

    
792
    } catch (Exception e) {
793
        // convert Hazelcast RuntimeException to NotFound
794
        logMetacat.error("An error occurred while getting system metadata for identifier " +
795
            pid.getValue() + ". The error message was: " + e.getMessage());
796
        throw new NotFound("1800", "No record found for " + pidStr);
797
        
798
    } 
799
    
800
    // throw not found if it was not found
801
    if (systemMetadata == null) {
802
    	throw new NotFound("1800", "No system metadata could be found for given PID: " + pidStr);
803
    }
804
	    
805
    // do we own it?
806
    for (Subject s: subjects) {
807
      logMetacat.debug("Comparing \t" + 
808
                       systemMetadata.getRightsHolder().getValue() +
809
                       " \tagainst \t" + s.getValue());
810
    	allowed = systemMetadata.getRightsHolder().equals(s);
811
    	if (allowed) {
812
    		return allowed;
813
    	}
814
    }    
815
    
816
    // otherwise check the access rules
817
    try {
818
	    List<AccessRule> allows = systemMetadata.getAccessPolicy().getAllowList();
819
	    search: // label break
820
	    for (AccessRule accessRule: allows) {
821
	      for (Subject s: subjects) {
822
	        logMetacat.debug("Checking allow access rule for subject: " + s.getValue());
823
	        if (accessRule.getSubjectList().contains(s)) {
824
	        	logMetacat.debug("Access rule contains subject: " + s.getValue());
825
	        	for (Permission p: accessRule.getPermissionList()) {
826
		        	logMetacat.debug("Checking permission: " + p.xmlValue());
827
	        		expandedPermissions = expandPermissions(p);
828
	        		allowed = expandedPermissions.contains(permission);
829
	        		if (allowed) {
830
			        	logMetacat.info("Permission granted: " + p.xmlValue() + " to " + s.getValue());
831
	        			break search; //label break
832
	        		}
833
	        	}
834
        		
835
	        }
836
	      }
837
	    }
838
    } catch (Exception e) {
839
    	// catch all for errors - safe side should be to deny the access
840
    	logMetacat.error("Problem checking authorization - defaulting to deny", e);
841
		allowed = false;
842
	  
843
    }
844
    
845
    // throw or return?
846
    if (!allowed) {
847
      throw new NotAuthorized("1820", permission + " not allowed on " + pidStr);
848
    }
849
    
850
    return allowed;
851
    
852
  }
853
  
854
  /*
855
   * parse a logEntry and get the relevant field from it
856
   * 
857
   * @param fieldname
858
   * @param entry
859
   * @return
860
   */
861
  private String getLogEntryField(String fieldname, String entry) {
862
    String begin = "<" + fieldname + ">";
863
    String end = "</" + fieldname + ">";
864
    // logMetacat.debug("looking for " + begin + " and " + end +
865
    // " in entry " + entry);
866
    String s = entry.substring(entry.indexOf(begin) + begin.length(), entry
867
        .indexOf(end));
868
    logMetacat.debug("entry " + fieldname + " : " + s);
869
    return s;
870
  }
871

    
872
  /** 
873
   * Determine if a given object should be treated as an XML science metadata
874
   * object. 
875
   * 
876
   * @param sysmeta - the SystemMetadata describing the object
877
   * @return true if the object should be treated as science metadata
878
   */
879
  public static boolean isScienceMetadata(SystemMetadata sysmeta) {
880
    
881
    ObjectFormat objectFormat = null;
882
    boolean isScienceMetadata = false;
883
    
884
    try {
885
      objectFormat = ObjectFormatCache.getInstance().getFormat(sysmeta.getFormatId());
886
      if ( objectFormat.getFormatType().equals("METADATA") ) {
887
      	isScienceMetadata = true;
888
      	
889
      }
890
      
891
       
892
    } catch (ServiceFailure e) {
893
      logMetacat.debug("There was a problem determining if the object identified by" + 
894
          sysmeta.getIdentifier().getValue() + 
895
          " is science metadata: " + e.getMessage());
896
    
897
    } catch (NotFound e) {
898
      logMetacat.debug("There was a problem determining if the object identified by" + 
899
          sysmeta.getIdentifier().getValue() + 
900
          " is science metadata: " + e.getMessage());
901
    
902
    }
903
    
904
    return isScienceMetadata;
905

    
906
  }
907
  
908
  /**
909
   * Insert or update an XML document into Metacat
910
   * 
911
   * @param xml - the XML document to insert or update
912
   * @param pid - the identifier to be used for the resulting object
913
   * 
914
   * @return localId - the resulting docid of the document created or updated
915
   * 
916
   */
917
  public String insertOrUpdateDocument(String xml, Identifier pid, 
918
    Session session, String insertOrUpdate) 
919
    throws ServiceFailure {
920
    
921
  	logMetacat.debug("Starting to insert xml document...");
922
    IdentifierManager im = IdentifierManager.getInstance();
923

    
924
    // generate pid/localId pair for sysmeta
925
    String localId = null;
926
    
927
    if(insertOrUpdate.equals("insert")) {
928
      localId = im.generateLocalId(pid.getValue(), 1);
929
      
930
    } else {
931
      //localid should already exist in the identifier table, so just find it
932
      try {
933
        logMetacat.debug("Updating pid " + pid.getValue());
934
        logMetacat.debug("looking in identifier table for pid " + pid.getValue());
935
        
936
        localId = im.getLocalId(pid.getValue());
937
        
938
        logMetacat.debug("localId: " + localId);
939
        //increment the revision
940
        String docid = localId.substring(0, localId.lastIndexOf("."));
941
        String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
942
        int rev = new Integer(revS).intValue();
943
        rev++;
944
        docid = docid + "." + rev;
945
        localId = docid;
946
        logMetacat.debug("incremented localId: " + localId);
947
      
948
      } catch(McdbDocNotFoundException e) {
949
        throw new ServiceFailure("1030", "D1NodeService.insertOrUpdateDocument(): " +
950
            "pid " + pid.getValue() + 
951
            " should have been in the identifier table, but it wasn't: " + 
952
            e.getMessage());
953
      
954
      }
955
      
956
    }
957

    
958
    params = new Hashtable<String, String[]>();
959
    String[] action = new String[1];
960
    action[0] = insertOrUpdate;
961
    params.put("action", action);
962
    String[] docid = new String[1];
963
    docid[0] = localId;
964
    params.put("docid", docid);
965
    String[] doctext = new String[1];
966
    doctext[0] = xml;
967
    params.put("doctext", doctext);
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
    // do the insert or update action
985
    handler = new MetacatHandler(new Timer());
986
    String result = handler.handleInsertOrUpdateAction(request.getRemoteAddr(), request.getHeader("User-Agent"), null, 
987
                        null, params, username, groupnames, false);
988
    
989
    if(result.indexOf("<error>") != -1) {
990
    	String detailCode = "";
991
    	if ( insertOrUpdate.equals("insert") ) {
992
    		// make sure to remove the mapping so that subsequent attempts do not fail with IdentifierNotUnique
993
    		im.removeMapping(pid.getValue(), localId);
994
    		detailCode = "1190";
995
    		
996
    	} else if ( insertOrUpdate.equals("update") ) {
997
    		detailCode = "1310";
998
    		
999
    	}
1000
        throw new ServiceFailure(detailCode, 
1001
          "Error inserting or updating document: " + result);
1002
    }
1003
    logMetacat.debug("Finsished inserting xml document with id " + localId);
1004
    
1005
    return localId;
1006
  }
1007
  
1008
  /**
1009
   * Insert a data document
1010
   * 
1011
   * @param object
1012
   * @param pid
1013
   * @param sessionData
1014
   * @throws ServiceFailure
1015
   * @returns localId of the data object inserted
1016
   */
1017
  public String insertDataObject(InputStream object, Identifier pid, 
1018
          Session session) throws ServiceFailure {
1019
      
1020
    String username = Constants.SUBJECT_PUBLIC;
1021
    String[] groupnames = null;
1022
    if (session != null ) {
1023
    	username = session.getSubject().getValue();
1024
    	if (session.getSubjectInfo() != null) {
1025
    		List<Group> groupList = session.getSubjectInfo().getGroupList();
1026
    		if (groupList != null) {
1027
    			groupnames = new String[groupList.size()];
1028
    			for (int i = 0; i > groupList.size(); i++ ) {
1029
    				groupnames[i] = groupList.get(i).getGroupName();
1030
    			}
1031
    		}
1032
    	}
1033
    }
1034
  
1035
    // generate pid/localId pair for object
1036
    logMetacat.debug("Generating a pid/localId mapping");
1037
    IdentifierManager im = IdentifierManager.getInstance();
1038
    String localId = im.generateLocalId(pid.getValue(), 1);
1039
  
1040
    // Save the data file to disk using "localId" as the name
1041
    String datafilepath = null;
1042
	try {
1043
		datafilepath = PropertyService.getProperty("application.datafilepath");
1044
	} catch (PropertyNotFoundException e) {
1045
		ServiceFailure sf = new ServiceFailure("1190", "Lookup data file path" + e.getMessage());
1046
		sf.initCause(e);
1047
		throw sf;
1048
	}
1049
    boolean locked = false;
1050
	try {
1051
		locked = DocumentImpl.getDataFileLockGrant(localId);
1052
	} catch (Exception e) {
1053
		ServiceFailure sf = new ServiceFailure("1190", "Could not lock file for writing:" + e.getMessage());
1054
		sf.initCause(e);
1055
		throw sf;
1056
	}
1057

    
1058
    logMetacat.debug("Case DATA: starting to write to disk.");
1059
	if (locked) {
1060

    
1061
          File dataDirectory = new File(datafilepath);
1062
          dataDirectory.mkdirs();
1063
  
1064
          File newFile = writeStreamToFile(dataDirectory, localId, object);
1065
  
1066
          // TODO: Check that the file size matches SystemMetadata
1067
          // long size = newFile.length();
1068
          // if (size == 0) {
1069
          //     throw new IOException("Uploaded file is 0 bytes!");
1070
          // }
1071
  
1072
          // Register the file in the database (which generates an exception
1073
          // if the localId is not acceptable or other untoward things happen
1074
          try {
1075
            logMetacat.debug("Registering document...");
1076
            DocumentImpl.registerDocument(localId, "BIN", localId,
1077
                    username, groupnames);
1078
            logMetacat.debug("Registration step completed.");
1079
            
1080
          } catch (SQLException e) {
1081
            //newFile.delete();
1082
            logMetacat.debug("SQLE: " + e.getMessage());
1083
            e.printStackTrace(System.out);
1084
            throw new ServiceFailure("1190", "Registration failed: " + 
1085
            		e.getMessage());
1086
            
1087
          } catch (AccessionNumberException e) {
1088
            //newFile.delete();
1089
            logMetacat.debug("ANE: " + e.getMessage());
1090
            e.printStackTrace(System.out);
1091
            throw new ServiceFailure("1190", "Registration failed: " + 
1092
            	e.getMessage());
1093
            
1094
          } catch (Exception e) {
1095
            //newFile.delete();
1096
            logMetacat.debug("Exception: " + e.getMessage());
1097
            e.printStackTrace(System.out);
1098
            throw new ServiceFailure("1190", "Registration failed: " + 
1099
            	e.getMessage());
1100
          }
1101
  
1102
          logMetacat.debug("Logging the creation event.");
1103
          EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, "create");
1104
  
1105
          // Schedule replication for this data file
1106
          logMetacat.debug("Scheduling replication.");
1107
          ForceReplicationHandler frh = new ForceReplicationHandler(
1108
            localId, "create", false, null);
1109
      }
1110
      
1111
      return localId;
1112
    
1113
  }
1114

    
1115
  /**
1116
   * Insert a systemMetadata document and return its localId
1117
   */
1118
  public void insertSystemMetadata(SystemMetadata sysmeta) 
1119
      throws ServiceFailure {
1120
      
1121
  	  logMetacat.debug("Starting to insert SystemMetadata...");
1122
      sysmeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
1123
      logMetacat.debug("Inserting new system metadata with modified date " + 
1124
          sysmeta.getDateSysMetadataModified());
1125
      
1126
      //insert the system metadata
1127
      try {
1128
        // note: the calling subclass handles the map hazelcast lock/unlock
1129
      	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
1130
      	
1131
      } catch (Exception e) {
1132
          throw new ServiceFailure("1190", e.getMessage());
1133
          
1134
	    }  
1135
  }
1136

    
1137
  /**
1138
   * Update a systemMetadata document
1139
   * 
1140
   * @param sysMeta - the system metadata object in the system to update
1141
   */
1142
    protected void updateSystemMetadata(SystemMetadata sysMeta)
1143
        throws ServiceFailure {
1144

    
1145
        logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
1146
        sysMeta.setDateSysMetadataModified(new Date());
1147
        try {
1148
            HazelcastService.getInstance().getSystemMetadataMap().lock(sysMeta.getIdentifier());
1149
            HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
1150

    
1151
        } catch (Exception e) {
1152
            throw new ServiceFailure("4862", e.getMessage());
1153

    
1154
        } finally {
1155
            HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
1156

    
1157
        }
1158

    
1159
    }
1160
  
1161
  /**
1162
   * Given a Permission, returns a list of all permissions that it encompasses
1163
   * Permissions are hierarchical so that WRITE also allows READ.
1164
   * @param permission
1165
   * @return list of included Permissions for the given permission
1166
   */
1167
  protected List<Permission> expandPermissions(Permission permission) {
1168
	  	List<Permission> expandedPermissions = new ArrayList<Permission>();
1169
	    if (permission.equals(Permission.READ)) {
1170
	    	expandedPermissions.add(Permission.READ);
1171
	    }
1172
	    if (permission.equals(Permission.WRITE)) {
1173
	    	expandedPermissions.add(Permission.READ);
1174
	    	expandedPermissions.add(Permission.WRITE);
1175
	    }
1176
	    if (permission.equals(Permission.CHANGE_PERMISSION)) {
1177
	    	expandedPermissions.add(Permission.READ);
1178
	    	expandedPermissions.add(Permission.WRITE);
1179
	    	expandedPermissions.add(Permission.CHANGE_PERMISSION);
1180
	    }
1181
	    return expandedPermissions;
1182
  }
1183

    
1184
  /*
1185
   * Write a stream to a file
1186
   * 
1187
   * @param dir - the directory to write to
1188
   * @param fileName - the file name to write to
1189
   * @param data - the object bytes as an input stream
1190
   * 
1191
   * @return newFile - the new file created
1192
   * 
1193
   * @throws ServiceFailure
1194
   */
1195
  private File writeStreamToFile(File dir, String fileName, InputStream data) 
1196
    throws ServiceFailure {
1197
    
1198
    File newFile = new File(dir, fileName);
1199
    logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1200

    
1201
    try {
1202
        if (newFile.createNewFile()) {
1203
          // write data stream to desired file
1204
          OutputStream os = new FileOutputStream(newFile);
1205
          long length = IOUtils.copyLarge(data, os);
1206
          os.flush();
1207
          os.close();
1208
        } else {
1209
          logMetacat.debug("File creation failed, or file already exists.");
1210
          throw new ServiceFailure("1190", "File already exists: " + fileName);
1211
        }
1212
    } catch (FileNotFoundException e) {
1213
      logMetacat.debug("FNF: " + e.getMessage());
1214
      throw new ServiceFailure("1190", "File not found: " + fileName + " " 
1215
                + e.getMessage());
1216
    } catch (IOException e) {
1217
      logMetacat.debug("IOE: " + e.getMessage());
1218
      throw new ServiceFailure("1190", "File was not written: " + fileName 
1219
                + " " + e.getMessage());
1220
    }
1221

    
1222
    return newFile;
1223
  }
1224
  
1225
}
(2-2/5)