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-11-23 10:19:39 -0800 (Wed, 23 Nov 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.Event;
61
import org.dataone.service.types.v1.Identifier;
62
import org.dataone.service.types.v1.Group;
63
import org.dataone.service.types.v1.Log;
64
import org.dataone.service.types.v1.LogEntry;
65
import org.dataone.service.types.v1.NodeReference;
66
import org.dataone.service.types.v1.ObjectFormat;
67
import org.dataone.service.types.v1.Permission;
68
import org.dataone.service.types.v1.Person;
69
import org.dataone.service.types.v1.Session;
70
import org.dataone.service.types.v1.Subject;
71
import org.dataone.service.types.v1.SubjectInfo;
72
import org.dataone.service.types.v1.SubjectList;
73
import org.dataone.service.types.v1.SystemMetadata;
74
import org.dataone.service.types.v1.util.ChecksumUtil;
75

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

    
88
public abstract class D1NodeService {
89
  
90
  private static Logger logMetacat = Logger.getLogger(D1NodeService.class);
91

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

    
101
  /**
102
   * Constructor - used to set the metacatUrl from a subclass extending D1NodeService
103
   * 
104
   * @param metacatUrl - the URL of the metacat service, including the ending /d1
105
   */
106
  public D1NodeService(HttpServletRequest request) {
107
		this.request = request;
108
	}
109
  
110
  /**
111
   * Adds a new object to the Node, where the object is either a data 
112
   * object or a science metadata object. This method is called by clients 
113
   * to create new data objects on Member Nodes or internally for Coordinating
114
   * Nodes
115
   * 
116
   * @param session - the Session object containing the credentials for the Subject
117
   * @param pid - The object identifier to be created
118
   * @param object - the object bytes
119
   * @param sysmeta - the system metadata that describes the object  
120
   * 
121
   * @return pid - the object identifier created
122
   * 
123
   * @throws InvalidToken
124
   * @throws ServiceFailure
125
   * @throws NotAuthorized
126
   * @throws IdentifierNotUnique
127
   * @throws UnsupportedType
128
   * @throws InsufficientResources
129
   * @throws InvalidSystemMetadata
130
   * @throws NotImplemented
131
   * @throws InvalidRequest
132
   */
133
  public Identifier create(Session session, Identifier pid, InputStream object,
134
    SystemMetadata sysmeta) 
135
    throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, 
136
    UnsupportedType, InsufficientResources, InvalidSystemMetadata, 
137
    NotImplemented, InvalidRequest {
138

    
139
    Identifier resultPid = null;
140
    String localId = null;
141
    boolean allowed = false;
142
    
143
    // check for null session
144
    if (session == null) {
145
    	throw new InvalidToken("4894", "Session is required to WRITE to the Node.");
146
    }
147
    Subject subject = session.getSubject();
148

    
149
    Subject publicSubject = new Subject();
150
    publicSubject.setValue(Constants.SUBJECT_PUBLIC);
151
	// be sure the user is authenticated for create()
152
    if (subject == null || subject.getValue() == null || 
153
        subject.equals(publicSubject) ) {
154
      throw new NotAuthorized("1100", "The provided identity does not have " +
155
        "permission to WRITE to the Node.");
156
      
157
    }
158
    
159
    // verify that pid == SystemMetadata.getIdentifier()
160
    logMetacat.debug("Comparing pid|sysmeta_pid: " + 
161
      pid.getValue() + "|" + sysmeta.getIdentifier().getValue());
162
    if (!pid.getValue().equals(sysmeta.getIdentifier().getValue())) {
163
        throw new InvalidSystemMetadata("1180", 
164
            "The supplied system metadata is invalid. " +
165
            "The identifier " + pid.getValue() + " does not match identifier" +
166
            "in the system metadata identified by " +
167
            sysmeta.getIdentifier().getValue() + ".");
168
        
169
    }
170

    
171
    logMetacat.debug("Checking if identifier exists...");
172
    // Check that the identifier does not already exist
173
    if (IdentifierManager.getInstance().identifierExists(pid.getValue())) {
174
	    	throw new IdentifierNotUnique("1120", 
175
			          "The requested identifier " + pid.getValue() +
176
			          " is already used by another object and" +
177
			          "therefore can not be used for this object. Clients should choose" +
178
			          "a new identifier that is unique and retry the operation or " +
179
			          "use CN.reserveIdentifier() to reserve one.");
180
    	
181
    }
182
    
183
    // check that we are not attempting to subvert versioning
184
    if (sysmeta.getObsoletes() != null && sysmeta.getObsoletes().getValue() != null) {
185
    	throw new InvalidSystemMetadata("1180", 
186
    			"The supplied system metadata is invalid. " +
187
    			"The obsoletes field cannot have a value when creating entries.");
188
    }
189
    if (sysmeta.getObsoletedBy() != null && sysmeta.getObsoletedBy().getValue() != null) {
190
    	throw new InvalidSystemMetadata("1180", 
191
    			"The supplied system metadata is invalid. " +
192
    			"The obsoletedBy field cannot have a value when creating entries.");
193
	}
194
    
195
    // TODO: this probably needs to be refined more
196
    try {
197
      allowed = isAuthorized(session, pid, Permission.WRITE);
198
            
199
    } catch (NotFound e) {
200
      // The identifier doesn't exist, writing should be fine.
201
      allowed = true;
202
    }
203
    
204
    // verify checksum, only if we can reset the inputstream
205
    if (object.markSupported()) {
206
	    String checksumAlgorithm = sysmeta.getChecksum().getAlgorithm();
207
	    String checksumValue = sysmeta.getChecksum().getValue();
208
	    try {
209
			String computedChecksumValue = ChecksumUtil.checksum(object, checksumAlgorithm).getValue();
210
			// it's very important that we don't consume the stream
211
			object.reset();
212
			if (!computedChecksumValue.equals(checksumValue)) {
213
				throw new InvalidSystemMetadata("4896", "Checksum given does not match that of the object");
214
			}
215
		} catch (Exception e) {
216
			String msg = "Error verifying checksum values";
217
	      	logMetacat.error(msg, e);
218
	        throw new ServiceFailure("1190", msg + ": " + e.getMessage());
219
		}
220
    } else {
221
    	logMetacat.warn("mark is not supported on the object's input stream - cannot verify checksum without consuming stream");
222
    }
223
    	
224
    // we have the go ahead
225
    if ( allowed ) {
226
      
227
      // Science metadata (XML) or science data object?
228
      // TODO: there are cases where certain object formats are science metadata
229
      // but are not XML (netCDF ...).  Handle this.
230
      if ( isScienceMetadata(sysmeta) ) {
231
        
232
        // CASE METADATA:
233
      	String objectAsXML = "";
234
        try {
235
	        objectAsXML = IOUtils.toString(object, "UTF-8");
236
	        localId = insertOrUpdateDocument(objectAsXML, pid, session, "insert");
237
	        //localId = im.getLocalId(pid.getValue());
238

    
239
        } catch (IOException e) {
240
        	String msg = "The Node is unable to create the object. " +
241
          "There was a problem converting the object to XML";
242
        	logMetacat.info(msg);
243
          throw new ServiceFailure("1190", msg + ": " + e.getMessage());
244

    
245
        }
246
                    
247
      } else {
248
	        
249
	      // DEFAULT CASE: DATA (needs to be checked and completed)
250
	      localId = insertDataObject(object, pid, session);
251
      }   
252
    
253
    }
254

    
255
    // save the sysmeta
256
    try {
257
      // lock and unlock of the pid happens in the subclass
258
    	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
259
    	
260
    } catch (Exception e) {
261
    	logMetacat.error("Problem creating system metadata: " + pid.getValue(), e);
262
        throw new ServiceFailure("1190", e.getMessage());
263
	}
264
    
265
    // setting the resulting identifier failed
266
    if (localId == null ) {
267
      throw new ServiceFailure("1190", "The Node is unable to create the object. ");
268
    }
269

    
270
    resultPid = pid;
271
    
272
    return resultPid;
273
  }
274

    
275
  /**
276
   * Return the log records associated with a given event between the start and 
277
   * end dates listed given a particular Subject listed in the Session
278
   * 
279
   * @param session - the Session object containing the credentials for the Subject
280
   * @param fromDate - the start date of the desired log records
281
   * @param toDate - the end date of the desired log records
282
   * @param event - restrict log records of a specific event type
283
   * @param start - zero based offset from the first record in the 
284
   *                set of matching log records. Used to assist with 
285
   *                paging the response.
286
   * @param count - maximum number of log records to return in the response. 
287
   *                Used to assist with paging the response.
288
   * 
289
   * @return the desired log records
290
   * 
291
   * @throws InvalidToken
292
   * @throws ServiceFailure
293
   * @throws NotAuthorized
294
   * @throws InvalidRequest
295
   * @throws NotImplemented
296
   */
297
  public Log getLogRecords(Session session, Date fromDate, Date toDate, 
298
      Event event, Integer start, Integer count) throws InvalidToken, ServiceFailure,
299
      NotAuthorized, InvalidRequest, NotImplemented {
300

    
301

    
302
    Log log = new Log();
303
    List<LogEntry> logs = new Vector<LogEntry>();
304
    IdentifierManager im = IdentifierManager.getInstance();
305
    EventLog el = EventLog.getInstance();
306
    if ( fromDate == null ) {
307
      logMetacat.debug("setting fromdate from null");
308
      fromDate = new Date(1);
309
    }
310
    if ( toDate == null ) {
311
      logMetacat.debug("setting todate from null");
312
      toDate = new Date();
313
    }
314

    
315
    if ( start == null ) {
316
    	start = 0;
317
    	
318
    }
319
    
320
    if ( count == null ) {
321
    	count = 1000;
322
    	
323
    }
324

    
325
    logMetacat.debug("fromDate: " + fromDate);
326
    logMetacat.debug("toDate: " + toDate);
327

    
328
    String report = el.getReport(null, null, null, null,
329
        new java.sql.Timestamp(fromDate.getTime()),
330
        new java.sql.Timestamp(toDate.getTime()), false);
331

    
332
    logMetacat.debug("report: " + report);
333

    
334
    String logEntry = "<logEntry>";
335
    String endLogEntry = "</logEntry>";
336
    int startIndex = 0;
337
    int foundIndex = report.indexOf(logEntry, startIndex);
338
    while (foundIndex != -1) {
339
      // parse out each entry
340
      int endEntryIndex = report.indexOf(endLogEntry, foundIndex);
341
      String entry = report.substring(foundIndex, endEntryIndex);
342
      logMetacat.debug("entry: " + entry);
343
      startIndex = endEntryIndex + endLogEntry.length();
344
      foundIndex = report.indexOf(logEntry, startIndex);
345

    
346
      String entryId = getLogEntryField("entryid", entry);
347
      String ipAddress = getLogEntryField("ipAddress", entry);
348
      String principal = getLogEntryField("principal", entry);
349
      String userAgent = getLogEntryField("userAgent", entry);
350
      String docid = getLogEntryField("docid", entry);
351
      String eventS = getLogEntryField("event", entry);
352
      String dateLogged = getLogEntryField("dateLogged", entry);
353

    
354
      LogEntry le = new LogEntry();
355

    
356
      Event e = Event.convert(eventS);
357
      if (e == null) { // skip any events that are not Dataone Crud events
358
        continue;
359
      }
360
      le.setEvent(e);
361
      Identifier entryid = new Identifier();
362
      entryid.setValue(entryId);
363
      le.setEntryId(entryid);
364
      Identifier identifier = new Identifier();
365
      try {
366
        logMetacat.debug("converting docid '" + docid + "' to a pid.");
367
        if (docid == null || docid.trim().equals("") || docid.trim().equals("null")) {
368
          continue;
369
        }
370
        docid = docid.substring(0, docid.lastIndexOf("."));
371
        identifier.setValue(im.getGUID(docid, im.getLatestRevForLocalId(docid)));
372
      } catch (Exception ex) { 
373
        // try to get the pid, if that doesn't
374
        // work, just use the local id
375
        // throw new ServiceFailure("1030",
376
        // "Error getting pid for localId " +
377
        // docid + ": " + ex.getMessage());\
378

    
379
        // skip it if the pid can't be found
380
        continue;
381
      }
382

    
383
      le.setIdentifier(identifier);
384
      le.setIpAddress(ipAddress);
385
      Calendar c = Calendar.getInstance();
386
      String year = dateLogged.substring(0, 4);
387
      String month = dateLogged.substring(5, 7);
388
      String date = dateLogged.substring(8, 10);
389
      logMetacat.debug("year: " + year + " month: " + month + " day: " + date);
390
      c.set(new Integer(year).intValue(), new Integer(month).intValue(),
391
          new Integer(date).intValue());
392
      Date logDate = c.getTime();
393
      le.setDateLogged(logDate);
394
      NodeReference memberNode = new NodeReference();
395
      memberNode.setValue(ipAddress);
396
      le.setMemberNode(memberNode);
397
      Subject princ = new Subject();
398
      princ.setValue(principal);
399
      le.setSubject(princ);
400
      le.setUserAgent(userAgent);
401

    
402
      // event filtering?
403
      if (event == null) {
404
    	  logs.add(le);
405
      } else if (le.getEvent().equals(event)) {
406
    	  logs.add(le);
407
      }
408
    }
409
    
410
    // d1 paging
411
    int total = logs.size();
412
    if (start != null && count != null) {
413
    	int toIndex = start + count;
414
    	if (toIndex <= total) {
415
    		logs = new ArrayList<LogEntry>(logs.subList(start, toIndex));
416
    	}
417
    }
418

    
419
    log.setLogEntryList(logs);
420
    log.setStart(start);
421
    log.setCount(logs.size());
422
    log.setTotal(total);
423
    logMetacat.info("getLogRecords");
424
    return log;
425
  }
426
    
427
  /**
428
   * Return the object identified by the given object identifier
429
   * 
430
   * @param session - the Session object containing the credentials for the Subject
431
   * @param pid - the object identifier for the given object
432
   * 
433
   * TODO: The D1 Authorization API doesn't provide information on which 
434
   * authentication system the Subject belongs to, and so it's not possible to
435
   * discern which Person or Group is a valid KNB LDAP DN.  Fix this.
436
   * 
437
   * @return inputStream - the input stream of the given object
438
   * 
439
   * @throws InvalidToken
440
   * @throws ServiceFailure
441
   * @throws NotAuthorized
442
   * @throws InvalidRequest
443
   * @throws NotImplemented
444
   */
445
  public InputStream get(Session session, Identifier pid) 
446
    throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
447
    NotImplemented {
448
    
449
    InputStream inputStream = null; // bytes to be returned
450
    handler = new MetacatHandler(new Timer());
451
    boolean allowed = false;
452
    String localId; // the metacat docid for the pid
453
    
454
    // get the local docid from Metacat
455
    try {
456
      localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
457
    
458
    } catch (McdbDocNotFoundException e) {
459
      throw new NotFound("1020", "The object specified by " + 
460
                         pid.getValue() +
461
                         " does not exist at this node.");
462
    }
463
    
464
    // check for authorization
465
    allowed = isAuthorized(session, pid, Permission.READ);
466
    
467
    // if the person is authorized, perform the read
468
    if (allowed) {
469
      try {
470
        inputStream = handler.read(localId);
471
      } catch (Exception e) {
472
        throw new ServiceFailure("1020", "The object specified by " + 
473
            pid.getValue() +
474
            "could not be returned due to error: " +
475
            e.getMessage());
476
      }
477
    }
478

    
479
    // if we fail to set the input stream
480
    if ( inputStream == null ) {
481
      throw new NotFound("1020", "The object specified by " + 
482
                         pid.getValue() +
483
                         "does not exist at this node.");
484
    }
485
    
486
	// log the read event
487
    String principal = Constants.SUBJECT_PUBLIC;
488
    if (session != null && session.getSubject() != null) {
489
    	principal = session.getSubject().getValue();
490
    }
491
    EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), principal, localId, "read");
492
    
493
    return inputStream;
494
  }
495

    
496
  /**
497
   * Return the system metadata for a given object
498
   * 
499
   * @param session - the Session object containing the credentials for the Subject
500
   * @param pid - the object identifier for the given object
501
   * 
502
   * @return inputStream - the input stream of the given system metadata object
503
   * 
504
   * @throws InvalidToken
505
   * @throws ServiceFailure
506
   * @throws NotAuthorized
507
   * @throws NotFound
508
   * @throws InvalidRequest
509
   * @throws NotImplemented
510
   */
511
  public SystemMetadata getSystemMetadata(Session session, Identifier pid)
512
      throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
513
      NotImplemented {
514
      
515
      if (!isAuthorized(session, pid, Permission.READ)) {
516
        throw new NotAuthorized("1400", Permission.READ + " not allowed on " + pid.getValue());  
517
      }
518
      SystemMetadata systemMetadata = null;
519
      try {
520
        HazelcastService.getInstance().getSystemMetadataMap().lock(pid);
521
        systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
522
        HazelcastService.getInstance().getSystemMetadataMap().unlock(pid);
523
        
524
      } catch (Exception e) {
525
        // convert hazelcast RuntimeException to NotFound
526
        throw new NotFound("1420", "No record found for: " + pid.getValue());
527
        
528
      }
529
    
530
    return systemMetadata;
531
  }
532
     
533
  /**
534
   * Test if the user identified by the provided token has authorization 
535
   * for operation on the specified object.
536
   * 
537
   * @param session - the Session object containing the credentials for the Subject
538
   * @param pid - The identifer of the resource for which access is being checked
539
   * @param operation - The type of operation which is being requested for the given pid
540
   *
541
   * @return true if the operation is allowed
542
   * 
543
   * @throws ServiceFailure
544
   * @throws InvalidToken
545
   * @throws NotFound
546
   * @throws NotAuthorized
547
   * @throws NotImplemented
548
   * @throws InvalidRequest
549
   */
550
  public boolean isAuthorized(Session session, Identifier pid, Permission permission)
551
    throws ServiceFailure, InvalidToken, NotFound, NotAuthorized,
552
    NotImplemented {
553

    
554
    boolean allowed = false;
555
    
556
    // get the subjects from the session
557
    List<Subject> subjects = new ArrayList<Subject>();
558
    if (session != null) {
559
	    Subject subject = session.getSubject();
560
	    if (subject != null) {
561
	    	subjects.add(subject);
562
	    }
563
	    SubjectInfo subjectInfo = session.getSubjectInfo();
564
	    if (subjectInfo != null) {
565
	    	List<Person> personList = subjectInfo.getPersonList();
566
	    	if (personList != null) {
567
			    for (Person p: personList) {
568
			      subjects.add(p.getSubject());
569
			      if (p.getVerified()) {
570
			    	  // add the verified symbolic user
571
			    	  Subject verifiedSubject = new Subject();
572
			    	  verifiedSubject.setValue(Constants.SUBJECT_VERIFIED_USER);
573
			    	  if (!subjects.contains(verifiedSubject)) {
574
			    		  subjects.add(verifiedSubject);
575
			    	  }
576
			      }
577
			    }
578
	    	}
579
	    	List<Group> groupList = subjectInfo.getGroupList();
580
	    	if (groupList != null) {
581
			    for (Group g: groupList) {
582
			      subjects.add(g.getSubject());
583
			    }
584
	    	}
585
	    }
586
	    // add the authenticated symbolic as a check
587
	    Subject authenticatedSubject = new Subject();
588
	    authenticatedSubject.setValue(Constants.SUBJECT_AUTHENTICATED_USER);
589
	    subjects.add(authenticatedSubject);
590
	    
591
    }
592
    
593
    // add public subject
594
    Subject publicSubject = new Subject();
595
    publicSubject.setValue(Constants.SUBJECT_PUBLIC);
596
    subjects.add(publicSubject);
597
    
598
    // get the system metadata
599
    String pidStr = pid.getValue();
600
    SystemMetadata systemMetadata = null;
601
    try {
602
        HazelcastService.getInstance().getSystemMetadataMap().lock(pid);
603
        systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
604
        HazelcastService.getInstance().getSystemMetadataMap().unlock(pid);
605

    
606
    } catch (Exception e) {
607
        // convert Hazelcast RuntimeException to NotFound
608
        logMetacat.error("An error occurred while getting system metadata for identifier " +
609
            pid.getValue() + ". The error message was: " + e.getMessage());
610
        throw new NotFound("1800", "No record found for " + pidStr);
611
        
612
    } finally {
613
        HazelcastService.getInstance().getSystemMetadataMap().unlock(pid);
614
        
615
    }
616
    
617
    // throw not found if it was not found
618
    if (systemMetadata == null) {
619
    	throw new NotFound("1800", "No system metadata could be found for given PID: " + pidStr);
620
    }
621
	    
622
    // do we own it?
623
    for (Subject s: subjects) {
624
    	allowed = systemMetadata.getRightsHolder().equals(s);
625
    	if (allowed) {
626
    		return allowed;
627
    	}
628
    }    
629
    
630
    // otherwise check the access rules
631
    try {
632
	    List<AccessRule> allows = systemMetadata.getAccessPolicy().getAllowList();
633
	    search: // label break
634
	    for (AccessRule accessRule: allows) {
635
	      for (Subject s: subjects) {
636
	        //if (accessRule.getSubjectList().contains(s)) {
637
        	for (Subject ruleSubject: accessRule.getSubjectList()) {
638
        		if (ruleSubject.equals(s)) {
639
		          allowed = accessRule.getPermissionList().contains(permission);
640
		          if (allowed) {
641
		        	  break search; //label break
642
		          }
643
        		}
644
	        }
645
	      }
646
	    }
647
    } catch (Exception e) {
648
    	// catch all for errors - safe side should be to deny the access
649
    	logMetacat.error("Problem checking authorization - defaulting to deny", e);
650
		allowed = false;
651
	}
652
    
653
    // throw or return?
654
    if (!allowed) {
655
      throw new NotAuthorized("1820", permission + " not allowed on " + pidStr);
656
    }
657
    
658
    return allowed;
659
    
660
  }
661
  
662
  /*
663
   * parse a logEntry and get the relevant field from it
664
   * 
665
   * @param fieldname
666
   * @param entry
667
   * @return
668
   */
669
  private String getLogEntryField(String fieldname, String entry) {
670
    String begin = "<" + fieldname + ">";
671
    String end = "</" + fieldname + ">";
672
    // logMetacat.debug("looking for " + begin + " and " + end +
673
    // " in entry " + entry);
674
    String s = entry.substring(entry.indexOf(begin) + begin.length(), entry
675
        .indexOf(end));
676
    logMetacat.debug("entry " + fieldname + " : " + s);
677
    return s;
678
  }
679

    
680
  /** 
681
   * Determine if a given object should be treated as an XML science metadata
682
   * object. 
683
   * 
684
   * @param sysmeta - the SystemMetadata describing the object
685
   * @return true if the object should be treated as science metadata
686
   */
687
  public static boolean isScienceMetadata(SystemMetadata sysmeta) {
688
    
689
    ObjectFormat objectFormat = null;
690
    boolean isScienceMetadata = false;
691
    
692
    try {
693
      objectFormat = ObjectFormatCache.getInstance().getFormat(sysmeta.getFormatId());
694
      if ( objectFormat.getFormatType().equals("METADATA") ) {
695
      	isScienceMetadata = true;
696
      	
697
      }
698
      
699
    } catch (InvalidRequest e) {
700
       logMetacat.debug("There was a problem determining if the object identified by" + 
701
         sysmeta.getIdentifier().getValue() + 
702
         " is science metadata: " + e.getMessage());
703
       
704
    } catch (ServiceFailure e) {
705
      logMetacat.debug("There was a problem determining if the object identified by" + 
706
          sysmeta.getIdentifier().getValue() + 
707
          " is science metadata: " + e.getMessage());
708
    
709
    } catch (NotFound e) {
710
      logMetacat.debug("There was a problem determining if the object identified by" + 
711
          sysmeta.getIdentifier().getValue() + 
712
          " is science metadata: " + e.getMessage());
713
    
714
    } catch (InsufficientResources e) {
715
      logMetacat.debug("There was a problem determining if the object identified by" + 
716
          sysmeta.getIdentifier().getValue() + 
717
          " is science metadata: " + e.getMessage());
718
    
719
    } catch (NotImplemented e) {
720
      logMetacat.debug("There was a problem determining if the object identified by" + 
721
          sysmeta.getIdentifier().getValue() + 
722
          " is science metadata: " + e.getMessage());
723
    
724
    }
725
    
726
    return isScienceMetadata;
727

    
728
  }
729
  
730
  /**
731
   * Insert or update an XML document into Metacat
732
   * 
733
   * @param xml - the XML document to insert or update
734
   * @param pid - the identifier to be used for the resulting object
735
   * 
736
   * @return localId - the resulting docid of the document created or updated
737
   * 
738
   */
739
  protected String insertOrUpdateDocument(String xml, Identifier pid, 
740
    Session session, String insertOrUpdate) 
741
    throws ServiceFailure {
742
    
743
  	logMetacat.debug("Starting to insert xml document...");
744
    IdentifierManager im = IdentifierManager.getInstance();
745

    
746
    // generate pid/localId pair for sysmeta
747
    String localId = null;
748
    
749
    if(insertOrUpdate.equals("insert")) {
750
      localId = im.generateLocalId(pid.getValue(), 1);
751
      
752
    } else {
753
      //localid should already exist in the identifier table, so just find it
754
      try {
755
        logMetacat.debug("Updating pid " + pid.getValue());
756
        logMetacat.debug("looking in identifier table for pid " + pid.getValue());
757
        
758
        localId = im.getLocalId(pid.getValue());
759
        
760
        logMetacat.debug("localId: " + localId);
761
        //increment the revision
762
        String docid = localId.substring(0, localId.lastIndexOf("."));
763
        String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
764
        int rev = new Integer(revS).intValue();
765
        rev++;
766
        docid = docid + "." + rev;
767
        localId = docid;
768
        logMetacat.debug("incremented localId: " + localId);
769
      
770
      } catch(McdbDocNotFoundException e) {
771
        throw new ServiceFailure("1030", "D1NodeService.insertOrUpdateDocument(): " +
772
            "pid " + pid.getValue() + 
773
            " should have been in the identifier table, but it wasn't: " + 
774
            e.getMessage());
775
      
776
      }
777
      
778
    }
779

    
780
    params = new Hashtable<String, String[]>();
781
    String[] action = new String[1];
782
    action[0] = insertOrUpdate;
783
    params.put("action", action);
784
    String[] docid = new String[1];
785
    docid[0] = localId;
786
    params.put("docid", docid);
787
    String[] doctext = new String[1];
788
    doctext[0] = xml;
789
    params.put("doctext", doctext);
790
    
791
    String username = Constants.SUBJECT_PUBLIC;
792
    String[] groupnames = null;
793
    if (session != null ) {
794
    	username = session.getSubject().getValue();
795
    	if (session.getSubjectInfo() != null) {
796
    		List<Group> groupList = session.getSubjectInfo().getGroupList();
797
    		if (groupList != null) {
798
    			groupnames = new String[groupList.size()];
799
    			for (int i = 0; i > groupList.size(); i++ ) {
800
    				groupnames[i] = groupList.get(i).getGroupName();
801
    			}
802
    		}
803
    	}
804
    }
805
    
806
    // do the insert or update action
807
    handler = new MetacatHandler(new Timer());
808
    String result = handler.handleInsertOrUpdateAction(request.getRemoteAddr(), request.getHeader("User-Agent"), null, 
809
                        null, params, username, groupnames);
810
    
811
    if(result.indexOf("<error>") != -1) {
812
    	String detailCode = "";
813
    	if ( insertOrUpdate.equals("insert") ) {
814
    		detailCode = "1190";
815
    		
816
    	} else if ( insertOrUpdate.equals("update") ) {
817
    		detailCode = "1310";
818
    		
819
    	}
820
        throw new ServiceFailure(detailCode, 
821
          "Error inserting or updating document: " + result);
822
    }
823
    logMetacat.debug("Finsished inserting xml document with id " + localId);
824
    
825
    return localId;
826
  }
827
  
828
  /**
829
   * Insert a data document
830
   * 
831
   * @param object
832
   * @param pid
833
   * @param sessionData
834
   * @throws ServiceFailure
835
   * @returns localId of the data object inserted
836
   */
837
  protected String insertDataObject(InputStream object, Identifier pid, 
838
          Session session) throws ServiceFailure {
839
      
840
    String username = Constants.SUBJECT_PUBLIC;
841
    String[] groupnames = null;
842
    if (session != null ) {
843
    	username = session.getSubject().getValue();
844
    	if (session.getSubjectInfo() != null) {
845
    		List<Group> groupList = session.getSubjectInfo().getGroupList();
846
    		if (groupList != null) {
847
    			groupnames = new String[groupList.size()];
848
    			for (int i = 0; i > groupList.size(); i++ ) {
849
    				groupnames[i] = groupList.get(i).getGroupName();
850
    			}
851
    		}
852
    	}
853
    }
854
  
855
    // generate pid/localId pair for object
856
    logMetacat.debug("Generating a pid/localId mapping");
857
    IdentifierManager im = IdentifierManager.getInstance();
858
    String localId = im.generateLocalId(pid.getValue(), 1);
859
  
860
    try {
861
      logMetacat.debug("Case DATA: starting to write to disk.");
862
      if (DocumentImpl.getDataFileLockGrant(localId)) {
863
  
864
        // Save the data file to disk using "localId" as the name
865
        try {
866
          String datafilepath = PropertyService.getProperty("application.datafilepath");
867
  
868
          File dataDirectory = new File(datafilepath);
869
          dataDirectory.mkdirs();
870
  
871
          File newFile = writeStreamToFile(dataDirectory, localId, object);
872
  
873
          // TODO: Check that the file size matches SystemMetadata
874
          // long size = newFile.length();
875
          // if (size == 0) {
876
          //     throw new IOException("Uploaded file is 0 bytes!");
877
          // }
878
  
879
          // Register the file in the database (which generates an exception
880
          // if the localId is not acceptable or other untoward things happen
881
          try {
882
            logMetacat.debug("Registering document...");
883
            DocumentImpl.registerDocument(localId, "BIN", localId,
884
                    username, groupnames);
885
            logMetacat.debug("Registration step completed.");
886
            
887
          } catch (SQLException e) {
888
            //newFile.delete();
889
            logMetacat.debug("SQLE: " + e.getMessage());
890
            e.printStackTrace(System.out);
891
            throw new ServiceFailure("1190", "Registration failed: " + 
892
            		e.getMessage());
893
            
894
          } catch (AccessionNumberException e) {
895
            //newFile.delete();
896
            logMetacat.debug("ANE: " + e.getMessage());
897
            e.printStackTrace(System.out);
898
            throw new ServiceFailure("1190", "Registration failed: " + 
899
            	e.getMessage());
900
            
901
          } catch (Exception e) {
902
            //newFile.delete();
903
            logMetacat.debug("Exception: " + e.getMessage());
904
            e.printStackTrace(System.out);
905
            throw new ServiceFailure("1190", "Registration failed: " + 
906
            	e.getMessage());
907
          }
908
  
909
          logMetacat.debug("Logging the creation event.");
910
          EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, "create");
911
  
912
          // Schedule replication for this data file
913
          logMetacat.debug("Scheduling replication.");
914
          ForceReplicationHandler frh = new ForceReplicationHandler(
915
            localId, "create", false, null);
916
  
917
        } catch (PropertyNotFoundException e) {
918
          throw new ServiceFailure("1190", "Could not lock file for writing:" + 
919
          	e.getMessage());
920
          
921
        }
922
      }
923
      return localId;
924
    } catch (Exception e) {
925
        // Could not get a lock on the document, so we can not update the file now
926
        throw new ServiceFailure("1190", "Failed to lock file: " + e.getMessage());
927
    }
928
    
929
  }
930

    
931
  /**
932
   * Insert a systemMetadata document and return its localId
933
   */
934
  protected void insertSystemMetadata(SystemMetadata sysmeta) 
935
      throws ServiceFailure {
936
      
937
  	  logMetacat.debug("Starting to insert SystemMetadata...");
938
      sysmeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
939
      logMetacat.debug("Inserting new system metadata with modified date " + 
940
          sysmeta.getDateSysMetadataModified());
941
      
942
      //insert the system metadata
943
      try {
944
        // note: the calling subclass handles the map hazelcast lock/unlock
945
      	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
946
      	
947
      } catch (Exception e) {
948
          throw new ServiceFailure("1190", e.getMessage());
949
          
950
	    }  
951
  }
952

    
953
  /**
954
   * Update a systemMetadata document
955
   * 
956
   * @param sysMeta - the system metadata object in the system to update
957
   */
958
  protected void updateSystemMetadata(SystemMetadata sysMeta)
959
    throws ServiceFailure {
960
      
961
    logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
962
    sysMeta.setDateSysMetadataModified(new Date());
963
    try {
964
    	HazelcastService.getInstance().getSystemMetadataMap().lock(sysMeta.getIdentifier());
965
    	HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
966
    	HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
967
	} catch (Exception e) {
968
		throw new ServiceFailure("4862", e.getMessage());
969
	} finally {
970
		HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
971
	}
972
      
973
  }
974

    
975
  /*
976
   * Write a stream to a file
977
   * 
978
   * @param dir - the directory to write to
979
   * @param fileName - the file name to write to
980
   * @param data - the object bytes as an input stream
981
   * 
982
   * @return newFile - the new file created
983
   * 
984
   * @throws ServiceFailure
985
   */
986
  private File writeStreamToFile(File dir, String fileName, InputStream data) 
987
    throws ServiceFailure {
988
    
989
    File newFile = new File(dir, fileName);
990
    logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
991

    
992
    try {
993
        if (newFile.createNewFile()) {
994
          // write data stream to desired file
995
          OutputStream os = new FileOutputStream(newFile);
996
          long length = IOUtils.copyLarge(data, os);
997
          os.flush();
998
          os.close();
999
        } else {
1000
          logMetacat.debug("File creation failed, or file already exists.");
1001
          throw new ServiceFailure("1190", "File already exists: " + fileName);
1002
        }
1003
    } catch (FileNotFoundException e) {
1004
      logMetacat.debug("FNF: " + e.getMessage());
1005
      throw new ServiceFailure("1190", "File not found: " + fileName + " " 
1006
                + e.getMessage());
1007
    } catch (IOException e) {
1008
      logMetacat.debug("IOE: " + e.getMessage());
1009
      throw new ServiceFailure("1190", "File was not written: " + fileName 
1010
                + " " + e.getMessage());
1011
    }
1012

    
1013
    return newFile;
1014
  }
1015
  
1016
}
(2-2/5)