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-06 13:41:55 -0800 (Tue, 06 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
      Event e = Event.convert(eventS);
429
      if (e == null) { // skip any events that are not Dataone Crud events
430
        continue;
431
      }
432
      le.setEvent(e);
433
      le.setEntryId(entryId);
434
      Identifier identifier = new Identifier();
435
      try {
436
        logMetacat.debug("converting docid '" + docid + "' to a pid.");
437
        if (docid == null || docid.trim().equals("") || docid.trim().equals("null")) {
438
          continue;
439
        }
440
        String docidNoRev = DocumentUtil.getSmartDocId(docid);
441
        //docid = docid.substring(0, docid.lastIndexOf("."));
442
        int rev = DocumentUtil.getRevisionFromAccessionNumber(docid);
443
        //int rev = im.getLatestRevForLocalId(docid);
444
        String guid = im.getGUID(docidNoRev, rev);
445
        identifier.setValue(guid);
446
      } catch (Exception ex) { 
447
        // try to get the pid, if that doesn't
448
        // work, just use the local id
449
        // throw new ServiceFailure("1030",
450
        // "Error getting pid for localId " +
451
        // docid + ": " + ex.getMessage());\
452

    
453
        // skip it if the pid can't be found
454
        continue;
455
      }
456

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

    
487
      // event filtering?
488
      if (event == null) {
489
    	  logs.add(le);
490
      } else if (le.getEvent().equals(event)) {
491
    	  logs.add(le);
492
      }
493
    }
494
    
495
    // d1 paging
496
    int total = logs.size();
497
    if (start != null && count != null) {
498
    	int toIndex = start + count;
499
    	if (toIndex <= total) {
500
    		logs = new ArrayList<LogEntry>(logs.subList(start, toIndex));
501
    	}
502
    }
503

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

    
568
    // if we fail to set the input stream
569
    if ( inputStream == null ) {
570
      throw new NotFound("1020", "The object specified by " + 
571
                         pid.getValue() +
572
                         "does not exist at this node.");
573
    }
574
    
575
	// log the read event
576
    String principal = Constants.SUBJECT_PUBLIC;
577
    if (session != null && session.getSubject() != null) {
578
    	principal = session.getSubject().getValue();
579
    }
580
    EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), principal, localId, "read");
581
    
582
    return inputStream;
583
  }
584

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

    
648
      boolean allowed = false;
649
      // are we allowed to do this? only CNs and target MNs are allowed
650
      CNode cn = D1Client.getCN();
651
      List<Node> nodes = cn.listNodes().getNodeList();
652
      
653
      if ( nodes == null ) {
654
          throw new ServiceFailure("4852", "Couldn't get node list.");
655
  
656
      }
657
      
658
      // find the node in the node list
659
      for ( Node node : nodes ) {
660
          
661
          NodeReference nodeReference = node.getIdentifier();
662
          logMetacat.debug("In isAdminAuthorized(), Node reference is: " + nodeReference.getValue());
663
          
664
          Subject subject = session.getSubject();
665
          
666
          if (node.getType() == NodeType.CN) {
667
              List<Subject> nodeSubjects = node.getSubjectList();
668
              
669
              // check if the session subject is in the node subject list
670
              for (Subject nodeSubject : nodeSubjects) {
671
                  if ( nodeSubject.equals(subject) ) {
672
                      allowed = true; // subject of session == target node subject
673
                      break;
674
                      
675
                  }
676
              }              
677
          }
678
      }
679

    
680
      
681
      return allowed;
682
  }
683
  
684
  /**
685
   * Test if the user identified by the provided token has authorization 
686
   * for the operation on the specified object.
687
   * 
688
   * @param session - the Session object containing the credentials for the Subject
689
   * @param pid - The identifer of the resource for which access is being checked
690
   * @param operation - The type of operation which is being requested for the given pid
691
   *
692
   * @return true if the operation is allowed
693
   * 
694
   * @throws ServiceFailure
695
   * @throws InvalidToken
696
   * @throws NotFound
697
   * @throws NotAuthorized
698
   * @throws NotImplemented
699
   * @throws InvalidRequest
700
   */
701
  public boolean isAuthorized(Session session, Identifier pid, Permission permission)
702
    throws ServiceFailure, InvalidToken, NotFound, NotAuthorized,
703
    NotImplemented, InvalidRequest {
704

    
705
    boolean allowed = false;
706
    
707
    if (permission == null) {
708
    	throw new InvalidRequest("1761", "Permission was not provided or is invalid");
709
    }
710
    
711
    // permissions are hierarchical
712
    List<Permission> expandedPermissions = null;
713
    
714
    // for the "Verified" symbolic user
715
    Subject verifiedSubject = new Subject();
716
	verifiedSubject.setValue(Constants.SUBJECT_VERIFIED_USER);
717
    
718
    // get the subject[s] from the session
719
	List<Subject> subjects = new ArrayList<Subject>();
720
	if (session != null) {
721
		// primary subject
722
		Subject subject = session.getSubject();
723
		if (subject != null) {
724
			subjects.add(subject);
725
		}
726
		// details about the subject
727
		SubjectInfo subjectInfo = session.getSubjectInfo();
728
		if (subjectInfo != null) {
729
			// find subjectInfo for the primary subject
730
			List<Person> personList = subjectInfo.getPersonList();
731
			if (personList != null) {
732
				for (Person p : personList) {
733
					  // for every person listed (isVerified is transitive)
734
						logMetacat.debug("checking person");
735
						logMetacat.debug("p.getVerified(): " + p.getVerified());
736
						if (p.getVerified() != null && p.getVerified()) {
737
							// add the verified symbolic user
738
							if (!subjects.contains(verifiedSubject)) {
739
								subjects.add(verifiedSubject);
740
							}
741
						}
742
						// add the equivalent identities
743
						List<Subject> equivList = p
744
								.getEquivalentIdentityList();
745
						if (equivList != null) {
746
							for (Subject equiv : equivList) {
747
								subjects.add(equiv);
748
							}
749
						}
750
						// add the groups
751
						List<Subject> groupList = p.getIsMemberOfList();
752
						if (groupList != null) {
753
							for (Subject g : groupList) {
754
								subjects.add(g);
755
							}
756
						}
757
						break;
758
				}
759
			}
760
		}
761

    
762
		// add the authenticated symbolic since we have a session
763
		Subject authenticatedSubject = new Subject();
764
		authenticatedSubject.setValue(Constants.SUBJECT_AUTHENTICATED_USER);
765
		subjects.add(authenticatedSubject);
766
	}
767

    
768
    // add public subject for everyone
769
    Subject publicSubject = new Subject();
770
    publicSubject.setValue(Constants.SUBJECT_PUBLIC);
771
    subjects.add(publicSubject);
772
    
773
    // get the system metadata
774
    String pidStr = pid.getValue();
775
    SystemMetadata systemMetadata = null;
776
    try {
777
        systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
778

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

    
855
  /** 
856
   * Determine if a given object should be treated as an XML science metadata
857
   * object. 
858
   * 
859
   * @param sysmeta - the SystemMetadata describing the object
860
   * @return true if the object should be treated as science metadata
861
   */
862
  public static boolean isScienceMetadata(SystemMetadata sysmeta) {
863
    
864
    ObjectFormat objectFormat = null;
865
    boolean isScienceMetadata = false;
866
    
867
    try {
868
      objectFormat = ObjectFormatCache.getInstance().getFormat(sysmeta.getFormatId());
869
      if ( objectFormat.getFormatType().equals("METADATA") ) {
870
      	isScienceMetadata = true;
871
      	
872
      }
873
      
874
       
875
    } catch (ServiceFailure e) {
876
      logMetacat.debug("There was a problem determining if the object identified by" + 
877
          sysmeta.getIdentifier().getValue() + 
878
          " is science metadata: " + e.getMessage());
879
    
880
    } catch (NotFound e) {
881
      logMetacat.debug("There was a problem determining if the object identified by" + 
882
          sysmeta.getIdentifier().getValue() + 
883
          " is science metadata: " + e.getMessage());
884
    
885
    }
886
    
887
    return isScienceMetadata;
888

    
889
  }
890
  
891
  /**
892
   * Insert or update an XML document into Metacat
893
   * 
894
   * @param xml - the XML document to insert or update
895
   * @param pid - the identifier to be used for the resulting object
896
   * 
897
   * @return localId - the resulting docid of the document created or updated
898
   * 
899
   */
900
  public String insertOrUpdateDocument(String xml, Identifier pid, 
901
    Session session, String insertOrUpdate) 
902
    throws ServiceFailure {
903
    
904
  	logMetacat.debug("Starting to insert xml document...");
905
    IdentifierManager im = IdentifierManager.getInstance();
906

    
907
    // generate pid/localId pair for sysmeta
908
    String localId = null;
909
    
910
    if(insertOrUpdate.equals("insert")) {
911
      localId = im.generateLocalId(pid.getValue(), 1);
912
      
913
    } else {
914
      //localid should already exist in the identifier table, so just find it
915
      try {
916
        logMetacat.debug("Updating pid " + pid.getValue());
917
        logMetacat.debug("looking in identifier table for pid " + pid.getValue());
918
        
919
        localId = im.getLocalId(pid.getValue());
920
        
921
        logMetacat.debug("localId: " + localId);
922
        //increment the revision
923
        String docid = localId.substring(0, localId.lastIndexOf("."));
924
        String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
925
        int rev = new Integer(revS).intValue();
926
        rev++;
927
        docid = docid + "." + rev;
928
        localId = docid;
929
        logMetacat.debug("incremented localId: " + localId);
930
      
931
      } catch(McdbDocNotFoundException e) {
932
        throw new ServiceFailure("1030", "D1NodeService.insertOrUpdateDocument(): " +
933
            "pid " + pid.getValue() + 
934
            " should have been in the identifier table, but it wasn't: " + 
935
            e.getMessage());
936
      
937
      }
938
      
939
    }
940

    
941
    params = new Hashtable<String, String[]>();
942
    String[] action = new String[1];
943
    action[0] = insertOrUpdate;
944
    params.put("action", action);
945
    String[] docid = new String[1];
946
    docid[0] = localId;
947
    params.put("docid", docid);
948
    String[] doctext = new String[1];
949
    doctext[0] = xml;
950
    params.put("doctext", doctext);
951
    
952
    String username = Constants.SUBJECT_PUBLIC;
953
    String[] groupnames = null;
954
    if (session != null ) {
955
    	username = session.getSubject().getValue();
956
    	if (session.getSubjectInfo() != null) {
957
    		List<Group> groupList = session.getSubjectInfo().getGroupList();
958
    		if (groupList != null) {
959
    			groupnames = new String[groupList.size()];
960
    			for (int i = 0; i > groupList.size(); i++ ) {
961
    				groupnames[i] = groupList.get(i).getGroupName();
962
    			}
963
    		}
964
    	}
965
    }
966
    
967
    // do the insert or update action
968
    handler = new MetacatHandler(new Timer());
969
    String result = handler.handleInsertOrUpdateAction(request.getRemoteAddr(), request.getHeader("User-Agent"), null, 
970
                        null, params, username, groupnames, false);
971
    
972
    if(result.indexOf("<error>") != -1) {
973
    	String detailCode = "";
974
    	if ( insertOrUpdate.equals("insert") ) {
975
    		// make sure to remove the mapping so that subsequent attempts do not fail with IdentifierNotUnique
976
    		im.removeMapping(pid.getValue(), localId);
977
    		detailCode = "1190";
978
    		
979
    	} else if ( insertOrUpdate.equals("update") ) {
980
    		detailCode = "1310";
981
    		
982
    	}
983
        throw new ServiceFailure(detailCode, 
984
          "Error inserting or updating document: " + result);
985
    }
986
    logMetacat.debug("Finsished inserting xml document with id " + localId);
987
    
988
    return localId;
989
  }
990
  
991
  /**
992
   * Insert a data document
993
   * 
994
   * @param object
995
   * @param pid
996
   * @param sessionData
997
   * @throws ServiceFailure
998
   * @returns localId of the data object inserted
999
   */
1000
  public String insertDataObject(InputStream object, Identifier pid, 
1001
          Session session) throws ServiceFailure {
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
    // generate pid/localId pair for object
1019
    logMetacat.debug("Generating a pid/localId mapping");
1020
    IdentifierManager im = IdentifierManager.getInstance();
1021
    String localId = im.generateLocalId(pid.getValue(), 1);
1022
  
1023
    // Save the data file to disk using "localId" as the name
1024
    String datafilepath = null;
1025
	try {
1026
		datafilepath = PropertyService.getProperty("application.datafilepath");
1027
	} catch (PropertyNotFoundException e) {
1028
		ServiceFailure sf = new ServiceFailure("1190", "Lookup data file path" + e.getMessage());
1029
		sf.initCause(e);
1030
		throw sf;
1031
	}
1032
    boolean locked = false;
1033
	try {
1034
		locked = DocumentImpl.getDataFileLockGrant(localId);
1035
	} catch (Exception e) {
1036
		ServiceFailure sf = new ServiceFailure("1190", "Could not lock file for writing:" + e.getMessage());
1037
		sf.initCause(e);
1038
		throw sf;
1039
	}
1040

    
1041
    logMetacat.debug("Case DATA: starting to write to disk.");
1042
	if (locked) {
1043

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

    
1098
  /**
1099
   * Insert a systemMetadata document and return its localId
1100
   */
1101
  public void insertSystemMetadata(SystemMetadata sysmeta) 
1102
      throws ServiceFailure {
1103
      
1104
  	  logMetacat.debug("Starting to insert SystemMetadata...");
1105
      sysmeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
1106
      logMetacat.debug("Inserting new system metadata with modified date " + 
1107
          sysmeta.getDateSysMetadataModified());
1108
      
1109
      //insert the system metadata
1110
      try {
1111
        // note: the calling subclass handles the map hazelcast lock/unlock
1112
      	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
1113
      	
1114
      } catch (Exception e) {
1115
          throw new ServiceFailure("1190", e.getMessage());
1116
          
1117
	    }  
1118
  }
1119

    
1120
  /**
1121
   * Update a systemMetadata document
1122
   * 
1123
   * @param sysMeta - the system metadata object in the system to update
1124
   */
1125
    protected void updateSystemMetadata(SystemMetadata sysMeta)
1126
        throws ServiceFailure {
1127

    
1128
        logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
1129
        sysMeta.setDateSysMetadataModified(new Date());
1130
        try {
1131
            HazelcastService.getInstance().getSystemMetadataMap().lock(sysMeta.getIdentifier());
1132
            HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
1133

    
1134
        } catch (Exception e) {
1135
            throw new ServiceFailure("4862", e.getMessage());
1136

    
1137
        } finally {
1138
            HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
1139

    
1140
        }
1141

    
1142
    }
1143
  
1144
  /**
1145
   * Given a Permission, returns a list of all permissions that it encompasses
1146
   * Permissions are hierarchical so that WRITE also allows READ.
1147
   * @param permission
1148
   * @return list of included Permissions for the given permission
1149
   */
1150
  protected List<Permission> expandPermissions(Permission permission) {
1151
	  	List<Permission> expandedPermissions = new ArrayList<Permission>();
1152
	    if (permission.equals(Permission.READ)) {
1153
	    	expandedPermissions.add(Permission.READ);
1154
	    }
1155
	    if (permission.equals(Permission.WRITE)) {
1156
	    	expandedPermissions.add(Permission.READ);
1157
	    	expandedPermissions.add(Permission.WRITE);
1158
	    }
1159
	    if (permission.equals(Permission.CHANGE_PERMISSION)) {
1160
	    	expandedPermissions.add(Permission.READ);
1161
	    	expandedPermissions.add(Permission.WRITE);
1162
	    	expandedPermissions.add(Permission.CHANGE_PERMISSION);
1163
	    }
1164
	    return expandedPermissions;
1165
  }
1166

    
1167
  /*
1168
   * Write a stream to a file
1169
   * 
1170
   * @param dir - the directory to write to
1171
   * @param fileName - the file name to write to
1172
   * @param data - the object bytes as an input stream
1173
   * 
1174
   * @return newFile - the new file created
1175
   * 
1176
   * @throws ServiceFailure
1177
   */
1178
  private File writeStreamToFile(File dir, String fileName, InputStream data) 
1179
    throws ServiceFailure {
1180
    
1181
    File newFile = new File(dir, fileName);
1182
    logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1183

    
1184
    try {
1185
        if (newFile.createNewFile()) {
1186
          // write data stream to desired file
1187
          OutputStream os = new FileOutputStream(newFile);
1188
          long length = IOUtils.copyLarge(data, os);
1189
          os.flush();
1190
          os.close();
1191
        } else {
1192
          logMetacat.debug("File creation failed, or file already exists.");
1193
          throw new ServiceFailure("1190", "File already exists: " + fileName);
1194
        }
1195
    } catch (FileNotFoundException e) {
1196
      logMetacat.debug("FNF: " + e.getMessage());
1197
      throw new ServiceFailure("1190", "File not found: " + fileName + " " 
1198
                + e.getMessage());
1199
    } catch (IOException e) {
1200
      logMetacat.debug("IOE: " + e.getMessage());
1201
      throw new ServiceFailure("1190", "File was not written: " + fileName 
1202
                + " " + e.getMessage());
1203
    }
1204

    
1205
    return newFile;
1206
  }
1207
  
1208
}
(2-2/5)