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: 2011-12-22 09:24:28 -0800 (Thu, 22 Dec 2011) $'
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.ObjectFormatCache;
47
import org.dataone.service.util.Constants;
48
import org.dataone.service.exceptions.IdentifierNotUnique;
49
import org.dataone.service.exceptions.InsufficientResources;
50
import org.dataone.service.exceptions.InvalidRequest;
51
import org.dataone.service.exceptions.InvalidSystemMetadata;
52
import org.dataone.service.exceptions.InvalidToken;
53
import org.dataone.service.exceptions.NotAuthorized;
54
import org.dataone.service.exceptions.NotFound;
55
import org.dataone.service.exceptions.NotImplemented;
56
import org.dataone.service.exceptions.ServiceFailure;
57
import org.dataone.service.exceptions.UnsupportedType;
58
import org.dataone.service.types.v1.AccessPolicy;
59
import org.dataone.service.types.v1.AccessRule;
60
import org.dataone.service.types.v1.DescribeResponse;
61
import org.dataone.service.types.v1.Event;
62
import org.dataone.service.types.v1.Identifier;
63
import org.dataone.service.types.v1.Group;
64
import org.dataone.service.types.v1.Log;
65
import org.dataone.service.types.v1.LogEntry;
66
import org.dataone.service.types.v1.NodeReference;
67
import org.dataone.service.types.v1.ObjectFormat;
68
import org.dataone.service.types.v1.Permission;
69
import org.dataone.service.types.v1.Person;
70
import org.dataone.service.types.v1.Session;
71
import org.dataone.service.types.v1.Subject;
72
import org.dataone.service.types.v1.SubjectInfo;
73
import org.dataone.service.types.v1.SubjectList;
74
import org.dataone.service.types.v1.SystemMetadata;
75
import org.dataone.service.types.v1.util.ChecksumUtil;
76

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

    
91
public abstract class D1NodeService {
92
  
93
  private static Logger logMetacat = Logger.getLogger(D1NodeService.class);
94

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

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

    
134
    // get system metadata and construct the describe response
135
      SystemMetadata sysmeta = getSystemMetadata(session, pid);
136
      DescribeResponse describeResponse = 
137
      	new DescribeResponse(sysmeta.getFormatId(), sysmeta.getSize(), 
138
      			sysmeta.getDateSysMetadataModified(),
139
      			sysmeta.getChecksum(), sysmeta.getSerialVersion());
140

    
141
      return describeResponse;
142

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

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

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

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

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

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

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

    
311
        }
312
                    
313
      } else {
314
	        
315
	      // DEFAULT CASE: DATA (needs to be checked and completed)
316
	      localId = insertDataObject(object, pid, session);
317
      }   
318
    
319
    }
320

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

    
336
    resultPid = pid;
337
    
338
    return resultPid;
339
  }
340

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

    
367

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

    
381
    if ( start == null ) {
382
    	start = 0;
383
    	
384
    }
385
    
386
    if ( count == null ) {
387
    	count = 1000;
388
    	
389
    }
390

    
391
    logMetacat.debug("fromDate: " + fromDate);
392
    logMetacat.debug("toDate: " + toDate);
393

    
394
    String report = el.getReport(null, null, null, null,
395
        new java.sql.Timestamp(fromDate.getTime()),
396
        new java.sql.Timestamp(toDate.getTime()), false);
397

    
398
    logMetacat.debug("report: " + report);
399

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

    
412
      String entryId = getLogEntryField("entryid", entry);
413
      String ipAddress = getLogEntryField("ipAddress", entry);
414
      String principal = getLogEntryField("principal", entry);
415
      String userAgent = getLogEntryField("userAgent", entry);
416
      String docid = getLogEntryField("docid", entry);
417
      String eventS = getLogEntryField("event", entry);
418
      String dateLogged = getLogEntryField("dateLogged", entry);
419

    
420
      LogEntry le = new LogEntry();
421

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

    
443
        // skip it if the pid can't be found
444
        continue;
445
      }
446

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

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

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

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

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

    
618
    boolean allowed = false;
619
    
620
    // permissions are hierarchical
621
    List<Permission> expandedPermissions = expandPermissions(permission);
622
    
623
    // for the "Verified" symbolic user
624
    Subject verifiedSubject = new Subject();
625
	verifiedSubject.setValue(Constants.SUBJECT_VERIFIED_USER);
626
    
627
    // get the subjects from the session
628
    List<Subject> subjects = new ArrayList<Subject>();
629
    if (session != null) {
630
	    Subject subject = session.getSubject();
631
	    if (subject != null) {
632
	    	subjects.add(subject);
633
	    }
634
	    SubjectInfo subjectInfo = session.getSubjectInfo();
635
	    if (subjectInfo != null) {
636
	    	// add the equivalent identities
637
	    	List<Person> personList = subjectInfo.getPersonList();
638
	    	if (personList != null) {
639
			    for (Person p: personList) {
640
			      subjects.add(p.getSubject());
641
			      if (p.getVerified()) {
642
			    	  // add the verified symbolic user
643
			    	  if (!subjects.contains(verifiedSubject)) {
644
			    		  subjects.add(verifiedSubject);
645
			    	  }
646
			      }
647
			    }
648
	    	}
649
	    	// add the groups
650
	    	List<Group> groupList = subjectInfo.getGroupList();
651
	    	if (groupList != null) {
652
			    for (Group g: groupList) {
653
			      subjects.add(g.getSubject());
654
			    }
655
	    	}
656
	    }
657
	    // add the authenticated symbolic as a check
658
	    Subject authenticatedSubject = new Subject();
659
	    authenticatedSubject.setValue(Constants.SUBJECT_AUTHENTICATED_USER);
660
	    subjects.add(authenticatedSubject);
661
	    
662
    }
663
    
664
    // add public subject
665
    Subject publicSubject = new Subject();
666
    publicSubject.setValue(Constants.SUBJECT_PUBLIC);
667
    subjects.add(publicSubject);
668
    
669
    // get the system metadata
670
    String pidStr = pid.getValue();
671
    SystemMetadata systemMetadata = null;
672
    try {
673
        HazelcastService.getInstance().getSystemMetadataMap().lock(pid);
674
        systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
675
        HazelcastService.getInstance().getSystemMetadataMap().unlock(pid);
676

    
677
    } catch (Exception e) {
678
        // convert Hazelcast RuntimeException to NotFound
679
        logMetacat.error("An error occurred while getting system metadata for identifier " +
680
            pid.getValue() + ". The error message was: " + e.getMessage());
681
        throw new NotFound("1800", "No record found for " + pidStr);
682
        
683
    } finally {
684
        HazelcastService.getInstance().getSystemMetadataMap().unlock(pid);
685
        
686
    }
687
    
688
    // throw not found if it was not found
689
    if (systemMetadata == null) {
690
    	throw new NotFound("1800", "No system metadata could be found for given PID: " + pidStr);
691
    }
692
	    
693
    // do we own it?
694
    for (Subject s: subjects) {
695
    	allowed = systemMetadata.getRightsHolder().equals(s);
696
    	if (allowed) {
697
    		return allowed;
698
    	}
699
    }    
700
    
701
    // otherwise check the access rules
702
    try {
703
	    List<AccessRule> allows = systemMetadata.getAccessPolicy().getAllowList();
704
	    search: // label break
705
	    for (AccessRule accessRule: allows) {
706
	      for (Subject s: subjects) {
707
	        if (accessRule.getSubjectList().contains(s)) {
708
	        	for (Permission p: expandedPermissions) {
709
		          allowed = accessRule.getPermissionList().contains(p);
710
		          if (allowed) {
711
		        	  break search; //label break
712
		          }
713
	        	}
714
        		
715
	        }
716
	      }
717
	    }
718
    } catch (Exception e) {
719
    	// catch all for errors - safe side should be to deny the access
720
    	logMetacat.error("Problem checking authorization - defaulting to deny", e);
721
		allowed = false;
722
	}
723
    
724
    // throw or return?
725
    if (!allowed) {
726
      throw new NotAuthorized("1820", permission + " not allowed on " + pidStr);
727
    }
728
    
729
    return allowed;
730
    
731
  }
732
  
733
  /*
734
   * parse a logEntry and get the relevant field from it
735
   * 
736
   * @param fieldname
737
   * @param entry
738
   * @return
739
   */
740
  private String getLogEntryField(String fieldname, String entry) {
741
    String begin = "<" + fieldname + ">";
742
    String end = "</" + fieldname + ">";
743
    // logMetacat.debug("looking for " + begin + " and " + end +
744
    // " in entry " + entry);
745
    String s = entry.substring(entry.indexOf(begin) + begin.length(), entry
746
        .indexOf(end));
747
    logMetacat.debug("entry " + fieldname + " : " + s);
748
    return s;
749
  }
750

    
751
  /** 
752
   * Determine if a given object should be treated as an XML science metadata
753
   * object. 
754
   * 
755
   * @param sysmeta - the SystemMetadata describing the object
756
   * @return true if the object should be treated as science metadata
757
   */
758
  public static boolean isScienceMetadata(SystemMetadata sysmeta) {
759
    
760
    ObjectFormat objectFormat = null;
761
    boolean isScienceMetadata = false;
762
    
763
    try {
764
      objectFormat = ObjectFormatCache.getInstance().getFormat(sysmeta.getFormatId());
765
      if ( objectFormat.getFormatType().equals("METADATA") ) {
766
      	isScienceMetadata = true;
767
      	
768
      }
769
      
770
    } catch (InvalidRequest e) {
771
       logMetacat.debug("There was a problem determining if the object identified by" + 
772
         sysmeta.getIdentifier().getValue() + 
773
         " is science metadata: " + e.getMessage());
774
       
775
    } catch (ServiceFailure e) {
776
      logMetacat.debug("There was a problem determining if the object identified by" + 
777
          sysmeta.getIdentifier().getValue() + 
778
          " is science metadata: " + e.getMessage());
779
    
780
    } catch (NotFound e) {
781
      logMetacat.debug("There was a problem determining if the object identified by" + 
782
          sysmeta.getIdentifier().getValue() + 
783
          " is science metadata: " + e.getMessage());
784
    
785
    } catch (InsufficientResources e) {
786
      logMetacat.debug("There was a problem determining if the object identified by" + 
787
          sysmeta.getIdentifier().getValue() + 
788
          " is science metadata: " + e.getMessage());
789
    
790
    } catch (NotImplemented e) {
791
      logMetacat.debug("There was a problem determining if the object identified by" + 
792
          sysmeta.getIdentifier().getValue() + 
793
          " is science metadata: " + e.getMessage());
794
    
795
    }
796
    
797
    return isScienceMetadata;
798

    
799
  }
800
  
801
  /**
802
   * Insert or update an XML document into Metacat
803
   * 
804
   * @param xml - the XML document to insert or update
805
   * @param pid - the identifier to be used for the resulting object
806
   * 
807
   * @return localId - the resulting docid of the document created or updated
808
   * 
809
   */
810
  public String insertOrUpdateDocument(String xml, Identifier pid, 
811
    Session session, String insertOrUpdate) 
812
    throws ServiceFailure {
813
    
814
  	logMetacat.debug("Starting to insert xml document...");
815
    IdentifierManager im = IdentifierManager.getInstance();
816

    
817
    // generate pid/localId pair for sysmeta
818
    String localId = null;
819
    
820
    if(insertOrUpdate.equals("insert")) {
821
      localId = im.generateLocalId(pid.getValue(), 1);
822
      
823
    } else {
824
      //localid should already exist in the identifier table, so just find it
825
      try {
826
        logMetacat.debug("Updating pid " + pid.getValue());
827
        logMetacat.debug("looking in identifier table for pid " + pid.getValue());
828
        
829
        localId = im.getLocalId(pid.getValue());
830
        
831
        logMetacat.debug("localId: " + localId);
832
        //increment the revision
833
        String docid = localId.substring(0, localId.lastIndexOf("."));
834
        String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
835
        int rev = new Integer(revS).intValue();
836
        rev++;
837
        docid = docid + "." + rev;
838
        localId = docid;
839
        logMetacat.debug("incremented localId: " + localId);
840
      
841
      } catch(McdbDocNotFoundException e) {
842
        throw new ServiceFailure("1030", "D1NodeService.insertOrUpdateDocument(): " +
843
            "pid " + pid.getValue() + 
844
            " should have been in the identifier table, but it wasn't: " + 
845
            e.getMessage());
846
      
847
      }
848
      
849
    }
850

    
851
    params = new Hashtable<String, String[]>();
852
    String[] action = new String[1];
853
    action[0] = insertOrUpdate;
854
    params.put("action", action);
855
    String[] docid = new String[1];
856
    docid[0] = localId;
857
    params.put("docid", docid);
858
    String[] doctext = new String[1];
859
    doctext[0] = xml;
860
    params.put("doctext", doctext);
861
    
862
    String username = Constants.SUBJECT_PUBLIC;
863
    String[] groupnames = null;
864
    if (session != null ) {
865
    	username = session.getSubject().getValue();
866
    	if (session.getSubjectInfo() != null) {
867
    		List<Group> groupList = session.getSubjectInfo().getGroupList();
868
    		if (groupList != null) {
869
    			groupnames = new String[groupList.size()];
870
    			for (int i = 0; i > groupList.size(); i++ ) {
871
    				groupnames[i] = groupList.get(i).getGroupName();
872
    			}
873
    		}
874
    	}
875
    }
876
    
877
    // do the insert or update action
878
    handler = new MetacatHandler(new Timer());
879
    String result = handler.handleInsertOrUpdateAction(request.getRemoteAddr(), request.getHeader("User-Agent"), null, 
880
                        null, params, username, groupnames);
881
    
882
    if(result.indexOf("<error>") != -1) {
883
    	String detailCode = "";
884
    	if ( insertOrUpdate.equals("insert") ) {
885
    		detailCode = "1190";
886
    		
887
    	} else if ( insertOrUpdate.equals("update") ) {
888
    		detailCode = "1310";
889
    		
890
    	}
891
        throw new ServiceFailure(detailCode, 
892
          "Error inserting or updating document: " + result);
893
    }
894
    logMetacat.debug("Finsished inserting xml document with id " + localId);
895
    
896
    return localId;
897
  }
898
  
899
  /**
900
   * Insert a data document
901
   * 
902
   * @param object
903
   * @param pid
904
   * @param sessionData
905
   * @throws ServiceFailure
906
   * @returns localId of the data object inserted
907
   */
908
  public String insertDataObject(InputStream object, Identifier pid, 
909
          Session session) throws ServiceFailure {
910
      
911
    String username = Constants.SUBJECT_PUBLIC;
912
    String[] groupnames = null;
913
    if (session != null ) {
914
    	username = session.getSubject().getValue();
915
    	if (session.getSubjectInfo() != null) {
916
    		List<Group> groupList = session.getSubjectInfo().getGroupList();
917
    		if (groupList != null) {
918
    			groupnames = new String[groupList.size()];
919
    			for (int i = 0; i > groupList.size(); i++ ) {
920
    				groupnames[i] = groupList.get(i).getGroupName();
921
    			}
922
    		}
923
    	}
924
    }
925
  
926
    // generate pid/localId pair for object
927
    logMetacat.debug("Generating a pid/localId mapping");
928
    IdentifierManager im = IdentifierManager.getInstance();
929
    String localId = im.generateLocalId(pid.getValue(), 1);
930
  
931
    // Save the data file to disk using "localId" as the name
932
    String datafilepath = null;
933
	try {
934
		datafilepath = PropertyService.getProperty("application.datafilepath");
935
	} catch (PropertyNotFoundException e) {
936
		ServiceFailure sf = new ServiceFailure("1190", "Lookup data file path" + e.getMessage());
937
		sf.initCause(e);
938
		throw sf;
939
	}
940
    boolean locked = false;
941
	try {
942
		locked = DocumentImpl.getDataFileLockGrant(localId);
943
	} catch (Exception e) {
944
		ServiceFailure sf = new ServiceFailure("1190", "Could not lock file for writing:" + e.getMessage());
945
		sf.initCause(e);
946
		throw sf;
947
	}
948

    
949
    logMetacat.debug("Case DATA: starting to write to disk.");
950
	if (locked) {
951

    
952
          File dataDirectory = new File(datafilepath);
953
          dataDirectory.mkdirs();
954
  
955
          File newFile = writeStreamToFile(dataDirectory, localId, object);
956
  
957
          // TODO: Check that the file size matches SystemMetadata
958
          // long size = newFile.length();
959
          // if (size == 0) {
960
          //     throw new IOException("Uploaded file is 0 bytes!");
961
          // }
962
  
963
          // Register the file in the database (which generates an exception
964
          // if the localId is not acceptable or other untoward things happen
965
          try {
966
            logMetacat.debug("Registering document...");
967
            DocumentImpl.registerDocument(localId, "BIN", localId,
968
                    username, groupnames);
969
            logMetacat.debug("Registration step completed.");
970
            
971
          } catch (SQLException e) {
972
            //newFile.delete();
973
            logMetacat.debug("SQLE: " + e.getMessage());
974
            e.printStackTrace(System.out);
975
            throw new ServiceFailure("1190", "Registration failed: " + 
976
            		e.getMessage());
977
            
978
          } catch (AccessionNumberException e) {
979
            //newFile.delete();
980
            logMetacat.debug("ANE: " + e.getMessage());
981
            e.printStackTrace(System.out);
982
            throw new ServiceFailure("1190", "Registration failed: " + 
983
            	e.getMessage());
984
            
985
          } catch (Exception e) {
986
            //newFile.delete();
987
            logMetacat.debug("Exception: " + e.getMessage());
988
            e.printStackTrace(System.out);
989
            throw new ServiceFailure("1190", "Registration failed: " + 
990
            	e.getMessage());
991
          }
992
  
993
          logMetacat.debug("Logging the creation event.");
994
          EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, "create");
995
  
996
          // Schedule replication for this data file
997
          logMetacat.debug("Scheduling replication.");
998
          ForceReplicationHandler frh = new ForceReplicationHandler(
999
            localId, "create", false, null);
1000
      }
1001
      
1002
      return localId;
1003
    
1004
  }
1005

    
1006
  /**
1007
   * Insert a systemMetadata document and return its localId
1008
   */
1009
  public void insertSystemMetadata(SystemMetadata sysmeta) 
1010
      throws ServiceFailure {
1011
      
1012
  	  logMetacat.debug("Starting to insert SystemMetadata...");
1013
      sysmeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
1014
      logMetacat.debug("Inserting new system metadata with modified date " + 
1015
          sysmeta.getDateSysMetadataModified());
1016
      
1017
      //insert the system metadata
1018
      try {
1019
        // note: the calling subclass handles the map hazelcast lock/unlock
1020
      	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
1021
      	
1022
      } catch (Exception e) {
1023
          throw new ServiceFailure("1190", e.getMessage());
1024
          
1025
	    }  
1026
  }
1027

    
1028
  /**
1029
   * Update a systemMetadata document
1030
   * 
1031
   * @param sysMeta - the system metadata object in the system to update
1032
   */
1033
  protected void updateSystemMetadata(SystemMetadata sysMeta)
1034
    throws ServiceFailure {
1035
      
1036
    logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
1037
    sysMeta.setDateSysMetadataModified(new Date());
1038
    try {
1039
    	HazelcastService.getInstance().getSystemMetadataMap().lock(sysMeta.getIdentifier());
1040
    	HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
1041
    	HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
1042
	} catch (Exception e) {
1043
		throw new ServiceFailure("4862", e.getMessage());
1044
	} finally {
1045
		HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
1046
	}
1047
      
1048
  }
1049
  
1050
  /**
1051
   * Given a Permission, returns a list of all permissions that it encompasses
1052
   * Permissions are hierarchical so that WRITE also allows READ.
1053
   * @param permission
1054
   * @return list of included Permissions for the given permission
1055
   */
1056
  protected List<Permission> expandPermissions(Permission permission) {
1057
	  	List<Permission> expandedPermissions = new ArrayList<Permission>();
1058
	    if (permission.equals(Permission.READ)) {
1059
	    	expandedPermissions.add(Permission.READ);
1060
	    }
1061
	    if (permission.equals(Permission.WRITE)) {
1062
	    	expandedPermissions.add(Permission.READ);
1063
	    	expandedPermissions.add(Permission.WRITE);
1064
	    }
1065
	    if (permission.equals(Permission.CHANGE_PERMISSION)) {
1066
	    	expandedPermissions.add(Permission.READ);
1067
	    	expandedPermissions.add(Permission.WRITE);
1068
	    	expandedPermissions.add(Permission.CHANGE_PERMISSION);
1069
	    }
1070
	    return expandedPermissions;
1071
  }
1072

    
1073
  /*
1074
   * Write a stream to a file
1075
   * 
1076
   * @param dir - the directory to write to
1077
   * @param fileName - the file name to write to
1078
   * @param data - the object bytes as an input stream
1079
   * 
1080
   * @return newFile - the new file created
1081
   * 
1082
   * @throws ServiceFailure
1083
   */
1084
  private File writeStreamToFile(File dir, String fileName, InputStream data) 
1085
    throws ServiceFailure {
1086
    
1087
    File newFile = new File(dir, fileName);
1088
    logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1089

    
1090
    try {
1091
        if (newFile.createNewFile()) {
1092
          // write data stream to desired file
1093
          OutputStream os = new FileOutputStream(newFile);
1094
          long length = IOUtils.copyLarge(data, os);
1095
          os.flush();
1096
          os.close();
1097
        } else {
1098
          logMetacat.debug("File creation failed, or file already exists.");
1099
          throw new ServiceFailure("1190", "File already exists: " + fileName);
1100
        }
1101
    } catch (FileNotFoundException e) {
1102
      logMetacat.debug("FNF: " + e.getMessage());
1103
      throw new ServiceFailure("1190", "File not found: " + fileName + " " 
1104
                + e.getMessage());
1105
    } catch (IOException e) {
1106
      logMetacat.debug("IOE: " + e.getMessage());
1107
      throw new ServiceFailure("1190", "File was not written: " + fileName 
1108
                + " " + e.getMessage());
1109
    }
1110

    
1111
    return newFile;
1112
  }
1113
  
1114
}
(2-2/5)