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-09-16 13:13:42 -0700 (Fri, 16 Sep 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

    
42
import org.apache.commons.io.IOUtils;
43
import org.apache.log4j.Logger;
44
import org.dataone.client.ObjectFormatCache;
45
import org.dataone.service.util.Constants;
46
import org.dataone.service.exceptions.IdentifierNotUnique;
47
import org.dataone.service.exceptions.InsufficientResources;
48
import org.dataone.service.exceptions.InvalidRequest;
49
import org.dataone.service.exceptions.InvalidSystemMetadata;
50
import org.dataone.service.exceptions.InvalidToken;
51
import org.dataone.service.exceptions.NotAuthorized;
52
import org.dataone.service.exceptions.NotFound;
53
import org.dataone.service.exceptions.NotImplemented;
54
import org.dataone.service.exceptions.ServiceFailure;
55
import org.dataone.service.exceptions.UnsupportedType;
56
import org.dataone.service.types.v1.AccessPolicy;
57
import org.dataone.service.types.v1.AccessRule;
58
import org.dataone.service.types.v1.Event;
59
import org.dataone.service.types.v1.Identifier;
60
import org.dataone.service.types.v1.Group;
61
import org.dataone.service.types.v1.Log;
62
import org.dataone.service.types.v1.LogEntry;
63
import org.dataone.service.types.v1.NodeReference;
64
import org.dataone.service.types.v1.ObjectFormat;
65
import org.dataone.service.types.v1.Permission;
66
import org.dataone.service.types.v1.Person;
67
import org.dataone.service.types.v1.Session;
68
import org.dataone.service.types.v1.Subject;
69
import org.dataone.service.types.v1.SubjectList;
70
import org.dataone.service.types.v1.SystemMetadata;
71
import org.dataone.service.types.v1.util.ChecksumUtil;
72

    
73
import edu.ucsb.nceas.metacat.AccessionNumberException;
74
import edu.ucsb.nceas.metacat.DocumentImpl;
75
import edu.ucsb.nceas.metacat.EventLog;
76
import edu.ucsb.nceas.metacat.IdentifierManager;
77
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
78
import edu.ucsb.nceas.metacat.MetacatHandler;
79
import edu.ucsb.nceas.metacat.properties.PropertyService;
80
import edu.ucsb.nceas.metacat.replication.ForceReplicationHandler;
81
import edu.ucsb.nceas.metacat.util.SystemUtil;
82
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
83

    
84
public abstract class D1NodeService {
85
  
86
  private static Logger logMetacat = Logger.getLogger(D1NodeService.class);
87

    
88
  /* the metacat URL as a string (including ending /d1 service)*/
89
  protected String metacatUrl;
90
  
91
  /* reference to the metacat handler */
92
  protected MetacatHandler handler;
93
  
94
  /* parameters set in the incoming request */
95
  private Hashtable<String, String[]> params;
96

    
97
  /**
98
   * Constructor - used to set the metacatUrl from a subclass extending D1NodeService
99
   * 
100
   * @param metacatUrl - the URL of the metacat service, including the ending /d1
101
   */
102
  public D1NodeService() {
103
  	this.metacatUrl = "";
104
  	
105
    try {
106
	    this.metacatUrl = SystemUtil.getContextURL() + "/" +
107
	    PropertyService.getProperty("dataone.serviceName");
108
    } catch (PropertyNotFoundException e) {
109
      throw new RuntimeException("Error getting the servlet url in D1NodeService: " + 
110
        	e.getMessage());
111

    
112
    }
113
    
114
  }
115
  
116
  /**
117
   * Adds a new object to the Node, where the object is either a data 
118
   * object or a science metadata object. This method is called by clients 
119
   * to create new data objects on Member Nodes or internally for Coordinating
120
   * Nodes
121
   * 
122
   * @param session - the Session object containing the credentials for the Subject
123
   * @param pid - The object identifier to be created
124
   * @param object - the object bytes
125
   * @param sysmeta - the system metadata that describes the object  
126
   * 
127
   * @return pid - the object identifier created
128
   * 
129
   * @throws InvalidToken
130
   * @throws ServiceFailure
131
   * @throws NotAuthorized
132
   * @throws IdentifierNotUnique
133
   * @throws UnsupportedType
134
   * @throws InsufficientResources
135
   * @throws InvalidSystemMetadata
136
   * @throws NotImplemented
137
   * @throws InvalidRequest
138
   */
139
  public Identifier create(Session session, Identifier pid, InputStream object,
140
    SystemMetadata sysmeta) 
141
    throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, 
142
    UnsupportedType, InsufficientResources, InvalidSystemMetadata, 
143
    NotImplemented, InvalidRequest {
144

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

    
170
    logMetacat.debug("Checking if identifier exists...");
171
    // Check that the identifier does not already exist
172
    if (IdentifierManager.getInstance().identifierExists(pid.getValue())) {
173
	    	throw new IdentifierNotUnique("1120", 
174
			          "The requested identifier " + pid.getValue() +
175
			          " is already used by another object and" +
176
			          "therefore can not be used for this object. Clients should choose" +
177
			          "a new identifier that is unique and retry the operation or " +
178
			          "use CN_crud.reserveIdentifier() to reserve one.");
179
    	
180
    }
181

    
182
    // check for permission
183
    try {
184
      allowed = isAuthorized(session, pid, Permission.WRITE);
185
            
186
    } catch (NotFound e) {
187
      // The identifier doesn't exist, writing should be fine.
188
      allowed = true;
189
      
190
    }
191
    
192
    // verify checksum, only if we can reset the inputstream
193
    if (object.markSupported()) {
194
	    String checksumAlgorithm = sysmeta.getChecksum().getAlgorithm();
195
	    String checksumValue = sysmeta.getChecksum().getValue();
196
	    try {
197
			String computedChecksumValue = ChecksumUtil.checksum(object, checksumAlgorithm).getValue();
198
			// it's very important that we don't consume the stream
199
			object.reset();
200
			if (!computedChecksumValue.equals(checksumValue)) {
201
				throw new InvalidSystemMetadata("4896", "Checksum given does not match that of the object");
202
			}
203
		} catch (Exception e) {
204
			String msg = "Error verifying checksum values";
205
	      	logMetacat.error(msg, e);
206
	        throw new ServiceFailure("1190", msg + ": " + e.getMessage());
207
		}
208
    } else {
209
    	logMetacat.warn("mark is not supported on the object's input stream - cannot verify checksum without consuming stream");
210
    }
211
    	
212
    // we have the go ahead
213
    if ( allowed ) {
214
      
215
      // Science metadata (XML) or science data object?
216
      // TODO: there are cases where certain object formats are science metadata
217
      // but are not XML (netCDF ...).  Handle this.
218
      if ( isScienceMetadata(sysmeta) ) {
219
        
220
        // CASE METADATA:
221
      	String objectAsXML = "";
222
        try {
223
	        objectAsXML = IOUtils.toString(object, "UTF-8");
224
	        localId = insertOrUpdateDocument(objectAsXML, pid, session, "insert");
225
	        //localId = im.getLocalId(pid.getValue());
226

    
227
        } catch (IOException e) {
228
        	String msg = "The Node is unable to create the object. " +
229
          "There was a problem converting the object to XML";
230
        	logMetacat.info(msg);
231
          throw new ServiceFailure("1190", msg + ": " + e.getMessage());
232

    
233
        }
234
                    
235
      } else {
236
	        
237
	      // DEFAULT CASE: DATA (needs to be checked and completed)
238
	      localId = insertDataObject(object, pid, session);
239
      }   
240
    
241
    }
242

    
243
    // save the sysmeta
244
    try {
245
		IdentifierManager.getInstance().createSystemMetadata(sysmeta);
246
	} catch (McdbDocNotFoundException e) {
247
	    throw new ServiceFailure("1190", "Unable to save System Metadata for the object. ");
248
	}
249
    
250
    // setting the resulting identifier failed
251
    if (localId == null ) {
252
      throw new ServiceFailure("1190", "The Node is unable to create the object. ");
253
    }
254

    
255
    
256
    resultPid = pid;
257
    
258
    return resultPid;
259
  }
260

    
261
  /**
262
   * Return the log records associated with a given event between the start and 
263
   * end dates listed given a particular Subject listed in the Session
264
   * 
265
   * @param session - the Session object containing the credentials for the Subject
266
   * @param fromDate - the start date of the desired log records
267
   * @param toDate - the end date of the desired log records
268
   * @param event - restrict log records of a specific event type
269
   * @param start - zero based offset from the first record in the 
270
   *                set of matching log records. Used to assist with 
271
   *                paging the response.
272
   * @param count - maximum number of log records to return in the response. 
273
   *                Used to assist with paging the response.
274
   * 
275
   * @return the desired log records
276
   * 
277
   * @throws InvalidToken
278
   * @throws ServiceFailure
279
   * @throws NotAuthorized
280
   * @throws InvalidRequest
281
   * @throws NotImplemented
282
   */
283
  public Log getLogRecords(Session session, Date fromDate, Date toDate, 
284
      Event event, Integer start, Integer count) throws InvalidToken, ServiceFailure,
285
      NotAuthorized, InvalidRequest, NotImplemented {
286

    
287

    
288
    Log log = new Log();
289
    List<LogEntry> logs = new Vector<LogEntry>();
290
    IdentifierManager im = IdentifierManager.getInstance();
291
    EventLog el = EventLog.getInstance();
292
    if ( fromDate == null ) {
293
      logMetacat.debug("setting fromdate from null");
294
      fromDate = new Date(1);
295
    }
296
    if ( toDate == null ) {
297
      logMetacat.debug("setting todate from null");
298
      toDate = new Date();
299
    }
300

    
301
    if ( start == null ) {
302
    	start = 0;
303
    	
304
    }
305
    
306
    if ( count == null ) {
307
    	count = 1000;
308
    	
309
    }
310

    
311
    logMetacat.debug("fromDate: " + fromDate);
312
    logMetacat.debug("toDate: " + toDate);
313

    
314
    String report = el.getReport(null, null, null, null,
315
        new java.sql.Timestamp(fromDate.getTime()),
316
        new java.sql.Timestamp(toDate.getTime()), false);
317

    
318
    logMetacat.debug("report: " + report);
319

    
320
    String logEntry = "<logEntry>";
321
    String endLogEntry = "</logEntry>";
322
    int startIndex = 0;
323
    int foundIndex = report.indexOf(logEntry, startIndex);
324
    while (foundIndex != -1) {
325
      // parse out each entry
326
      int endEntryIndex = report.indexOf(endLogEntry, foundIndex);
327
      String entry = report.substring(foundIndex, endEntryIndex);
328
      logMetacat.debug("entry: " + entry);
329
      startIndex = endEntryIndex + endLogEntry.length();
330
      foundIndex = report.indexOf(logEntry, startIndex);
331

    
332
      String entryId = getLogEntryField("entryid", entry);
333
      String ipAddress = getLogEntryField("ipAddress", entry);
334
      String principal = getLogEntryField("principal", entry);
335
      String docid = getLogEntryField("docid", entry);
336
      String eventS = getLogEntryField("event", entry);
337
      String dateLogged = getLogEntryField("dateLogged", entry);
338

    
339
      LogEntry le = new LogEntry();
340

    
341
      Event e = Event.convert(eventS);
342
      if (e == null) { // skip any events that are not Dataone Crud events
343
        continue;
344
      }
345
      le.setEvent(e);
346
      Identifier entryid = new Identifier();
347
      entryid.setValue(entryId);
348
      le.setEntryId(entryid);
349
      Identifier identifier = new Identifier();
350
      try {
351
        logMetacat.debug("converting docid '" + docid + "' to a pid.");
352
        if (docid == null || docid.trim().equals("") || docid.trim().equals("null")) {
353
          continue;
354
        }
355
        docid = docid.substring(0, docid.lastIndexOf("."));
356
        identifier.setValue(im.getGUID(docid, im.getLatestRevForLocalId(docid)));
357
      } catch (Exception ex) { 
358
        // try to get the pid, if that doesn't
359
        // work, just use the local id
360
        // throw new ServiceFailure("1030",
361
        // "Error getting pid for localId " +
362
        // docid + ": " + ex.getMessage());\
363

    
364
        // skip it if the pid can't be found
365
        continue;
366
      }
367

    
368
      le.setIdentifier(identifier);
369
      le.setIpAddress(ipAddress);
370
      Calendar c = Calendar.getInstance();
371
      String year = dateLogged.substring(0, 4);
372
      String month = dateLogged.substring(5, 7);
373
      String date = dateLogged.substring(8, 10);
374
      logMetacat.debug("year: " + year + " month: " + month + " day: " + date);
375
      c.set(new Integer(year).intValue(), new Integer(month).intValue(),
376
          new Integer(date).intValue());
377
      Date logDate = c.getTime();
378
      le.setDateLogged(logDate);
379
      NodeReference memberNode = new NodeReference();
380
      memberNode.setValue(ipAddress);
381
      le.setMemberNode(memberNode);
382
      Subject princ = new Subject();
383
      princ.setValue(principal);
384
      le.setSubject(princ);
385
      le.setUserAgent("metacat/RESTService");
386

    
387
      // event filtering?
388
      if (event == null) {
389
    	  logs.add(le);
390
      } else if (le.getEvent().equals(event)) {
391
    	  logs.add(le);
392
      }
393
    }
394
    
395
    // d1 paging
396
    int total = logs.size();
397
    if (start != null && count != null) {
398
    	int toIndex = start + count;
399
    	if (toIndex <= total) {
400
    		logs = new ArrayList<LogEntry>(logs.subList(start, toIndex));
401
    	}
402
    }
403

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

    
464
    // if we fail to set the input stream
465
    if ( inputStream == null ) {
466
      throw new NotFound("1020", "The object specified by " + 
467
                         pid.getValue() +
468
                         "does not exist at this node.");
469
    }
470
    
471
	// log the read event
472
    String principal = Constants.PUBLIC_SUBJECT;
473
    if (session != null && session.getSubject() != null) {
474
    	principal = session.getSubject().getValue();
475
    }
476
    EventLog.getInstance().log(null, principal, localId, "read");
477
    
478
    return inputStream;
479
  }
480

    
481
  /**
482
   * Return the system metadata for a given object
483
   * 
484
   * @param session - the Session object containing the credentials for the Subject
485
   * @param pid - the object identifier for the given object
486
   * 
487
   * @return inputStream - the input stream of the given system metadata object
488
   * 
489
   * @throws InvalidToken
490
   * @throws ServiceFailure
491
   * @throws NotAuthorized
492
   * @throws NotFound
493
   * @throws InvalidRequest
494
   * @throws NotImplemented
495
   */
496
  public SystemMetadata getSystemMetadata(Session session, Identifier pid)
497
    throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
498
    InvalidRequest, NotImplemented {
499

    
500
    if (!isAuthorized(session, pid, Permission.READ)) {
501
      throw new NotAuthorized("1400", Permission.READ + " not allowed on " + pid.getValue());  
502
    }
503
    SystemMetadata systemMetadata = null;
504
    try {
505
      systemMetadata = IdentifierManager.getInstance().getSystemMetadata(pid.getValue());
506
    } catch (McdbDocNotFoundException e) {
507
      throw new NotFound("1420", "No record found for: " + pid.getValue());
508
    }
509
    
510
    return systemMetadata;
511
  }
512
   
513
  /**
514
   * Set access for a given object using the object identifier and a Subject
515
   * under a given Session.
516
   * 
517
   * @param session - the Session object containing the credentials for the Subject
518
   * @param pid - the object identifier for the given object to apply the policy
519
   * @param policy - the access policy to be applied
520
   * 
521
   * @return true if the application of the policy succeeds
522
   * @throws InvalidToken
523
   * @throws ServiceFailure
524
   * @throws NotFound
525
   * @throws NotAuthorized
526
   * @throws NotImplemented
527
   * @throws InvalidRequest
528
   */
529
  public boolean setAccessPolicy(Session session, Identifier pid, 
530
    AccessPolicy accessPolicy) 
531
    throws InvalidToken, ServiceFailure, NotFound, NotAuthorized, 
532
    NotImplemented, InvalidRequest {
533

    
534
    boolean success = false;
535
    
536
    // get the subject
537
    Subject subject = session.getSubject();
538
    // get the system metadata
539
    String pidStr = pid.getValue();
540
    
541
    // are we allowed to do this?
542
    if (!isAuthorized(session, pid, Permission.CHANGE_PERMISSION)) {
543
      throw new NotAuthorized("4420", "not allowed by " + subject.getValue() + " on " + pidStr);  
544
    }
545
    
546
    SystemMetadata systemMetadata = null;
547
    try {
548
      systemMetadata = IdentifierManager.getInstance().getSystemMetadata(pidStr);
549
    } catch (McdbDocNotFoundException e) {
550
      throw new NotFound("4400", "No record found for: " + pid);
551
    }
552
        
553
    // set the access policy
554
    systemMetadata.setAccessPolicy(accessPolicy);
555
    
556
    // update the metadata
557
    try {
558
      IdentifierManager.getInstance().updateSystemMetadata(systemMetadata);
559
      success = true;
560
    } catch (McdbDocNotFoundException e) {
561
      throw new ServiceFailure("4430", e.getMessage());
562
    }
563

    
564
    return success;
565
  }
566
  
567
  /**
568
   * Test if the user identified by the provided token has authorization 
569
   * for operation on the specified object.
570
   * 
571
   * @param session - the Session object containing the credentials for the Subject
572
   * @param pid - The identifer of the resource for which access is being checked
573
   * @param operation - The type of operation which is being requested for the given pid
574
   *
575
   * @return true if the operation is allowed
576
   * 
577
   * @throws ServiceFailure
578
   * @throws InvalidToken
579
   * @throws NotFound
580
   * @throws NotAuthorized
581
   * @throws NotImplemented
582
   * @throws InvalidRequest
583
   */
584
  public boolean isAuthorized(Session session, Identifier pid, Permission permission)
585
    throws ServiceFailure, InvalidToken, NotFound, NotAuthorized,
586
    NotImplemented, InvalidRequest {
587

    
588
    boolean allowed = false;
589
    
590
    // get the subjects from the session
591
    List<Subject> subjects = new ArrayList<Subject>();
592
    if (session != null) {
593
	    Subject subject = session.getSubject();
594
	    if (subject != null) {
595
	    	subjects.add(subject);
596
	    }
597
	    SubjectList subjectList = session.getSubjectList();
598
	    if (subjectList != null) {
599
	    	List<Person> personList = subjectList.getPersonList();
600
	    	if (personList != null) {
601
			    for (Person p: personList) {
602
			      subjects.add(p.getSubject());
603
			    }
604
	    	}
605
	    	List<Group> groupList = subjectList.getGroupList();
606
	    	if (groupList != null) {
607
			    for (Group g: groupList) {
608
			      subjects.add(g.getSubject());
609
			    }
610
	    	}
611
	    }
612
    }
613
    
614
    // add public subject
615
    Subject publicSubject = new Subject();
616
    publicSubject.setValue(Constants.PUBLIC_SUBJECT);
617
    subjects.add(publicSubject);
618
    
619
    // get the system metadata
620
    String pidStr = pid.getValue();
621
    SystemMetadata systemMetadata = null;
622
    try {
623
      systemMetadata = IdentifierManager.getInstance().getSystemMetadata(pidStr);
624
    } catch (McdbDocNotFoundException e) {
625
      throw new NotFound("1800", "No record found for " + pidStr);
626
    }
627
	    
628
    // do we own it?
629
    for (Subject s: subjects) {
630
    	allowed = systemMetadata.getRightsHolder().getValue().equals(s.getValue());
631
    	if (allowed) {
632
    		return allowed;
633
    	}
634
    }    
635
    
636
    // otherwise check the access rules
637
    try {
638
	    List<AccessRule> allows = systemMetadata.getAccessPolicy().getAllowList();
639
	    search: // label break
640
	    for (AccessRule accessRule: allows) {
641
	      for (Subject s: subjects) {
642
	        //if (accessRule.getSubjectList().contains(s)) {
643
        	for (Subject ruleSubject: accessRule.getSubjectList()) {
644
        		if (ruleSubject.getValue().equals(s.getValue())) {
645
		          allowed = accessRule.getPermissionList().contains(permission);
646
		          if (allowed) {
647
		        	  break search; //label break
648
		          }
649
        		}
650
	        }
651
	      }
652
	    }
653
    } catch (Exception e) {
654
    	// catch all for errors - safe side should be to deny the access
655
    	logMetacat.error("Problem checking authorization - defaulting to deny", e);
656
		allowed = false;
657
	}
658
    
659
    // throw or return?
660
    if (!allowed) {
661
      throw new NotAuthorized("1820", permission + " not allowed on " + pidStr);
662
    }
663
    
664
    return allowed;
665
    
666
  }
667
  
668
  /*
669
   * parse a logEntry and get the relevant field from it
670
   * 
671
   * @param fieldname
672
   * @param entry
673
   * @return
674
   */
675
  private String getLogEntryField(String fieldname, String entry) {
676
    String begin = "<" + fieldname + ">";
677
    String end = "</" + fieldname + ">";
678
    // logMetacat.debug("looking for " + begin + " and " + end +
679
    // " in entry " + entry);
680
    String s = entry.substring(entry.indexOf(begin) + begin.length(), entry
681
        .indexOf(end));
682
    logMetacat.debug("entry " + fieldname + " : " + s);
683
    return s;
684
  }
685

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

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

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

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

    
937
  /**
938
   * Insert a systemMetadata document and return its localId
939
   */
940
  protected void insertSystemMetadata(SystemMetadata sysmeta) 
941
    throws ServiceFailure {
942
    
943
  	logMetacat.debug("Starting to insert SystemMetadata...");
944
    sysmeta.setDateSysMetadataModified(new Date());
945
    logMetacat.debug("Inserting new system metadata with modified date " + 
946
        sysmeta.getDateSysMetadataModified());
947

    
948
    //insert the system metadata
949
	try {
950
		IdentifierManager.getInstance().createSystemMetadata(sysmeta);
951
	  
952
	} catch (McdbDocNotFoundException e) {
953
      throw new ServiceFailure("1030", "Error inserting system metadata: " + 
954
      	e.getClass() + ": " + e.getMessage());
955
      
956
    }
957
      
958
  }
959

    
960
  /**
961
   * Update a systemMetadata document
962
   * 
963
   * @param sysMeta - the system metadata object in the system to update
964
   */
965
  protected void updateSystemMetadata(SystemMetadata sysMeta)
966
    throws ServiceFailure {
967
      
968
    logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
969
    sysMeta.setDateSysMetadataModified(new Date());
970
    try {
971
	    IdentifierManager.getInstance().updateSystemMetadata(sysMeta);
972
	    
973
    } catch (McdbDocNotFoundException e) {
974
    	
975
      throw new ServiceFailure("1030", "Error updating system metadata: " + 
976
        e.getClass() + ": " + e.getMessage());
977
      
978
    }
979
      
980
  }
981

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

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

    
1020
    return newFile;
1021
  }
1022
  
1023
}
(3-3/7)