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

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

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

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

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

    
268
    resultPid = pid;
269
    
270
    return resultPid;
271
  }
272

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

    
299

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

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

    
323
    logMetacat.debug("fromDate: " + fromDate);
324
    logMetacat.debug("toDate: " + toDate);
325

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

    
330
    logMetacat.debug("report: " + report);
331

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

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

    
352
      LogEntry le = new LogEntry();
353

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1011
    return newFile;
1012
  }
1013
  
1014
}
(2-2/4)