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 17:04:24 -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.dataone.hazelcast.HazelcastService;
80
import edu.ucsb.nceas.metacat.properties.PropertyService;
81
import edu.ucsb.nceas.metacat.replication.ForceReplicationHandler;
82
import edu.ucsb.nceas.metacat.util.SystemUtil;
83
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
84

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

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

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

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

    
146
    Identifier resultPid = null;
147
    String localId = null;
148
    Subject subject = session.getSubject();
149
    boolean allowed = false;
150
    
151
    // be sure the user is authenticated for create()
152
    if (subject.getValue() == null || 
153
        subject.getValue().toLowerCase().equals("public") ) {
154
      throw new NotAuthorized("1100", "The provided identity does not have " +
155
        "permission to WRITE to the Member 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_crud.reserveIdentifier() to reserve one.");
180
    	
181
    }
182

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

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

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

    
244
    // save the sysmeta
245
    HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
246
    
247
    // setting the resulting identifier failed
248
    if (localId == null ) {
249
      throw new ServiceFailure("1190", "The Node is unable to create the object. ");
250
    }
251

    
252
    
253
    resultPid = pid;
254
    
255
    return resultPid;
256
  }
257

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

    
284

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

    
298
    if ( start == null ) {
299
    	start = 0;
300
    	
301
    }
302
    
303
    if ( count == null ) {
304
    	count = 1000;
305
    	
306
    }
307

    
308
    logMetacat.debug("fromDate: " + fromDate);
309
    logMetacat.debug("toDate: " + toDate);
310

    
311
    String report = el.getReport(null, null, null, null,
312
        new java.sql.Timestamp(fromDate.getTime()),
313
        new java.sql.Timestamp(toDate.getTime()), false);
314

    
315
    logMetacat.debug("report: " + report);
316

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

    
329
      String entryId = getLogEntryField("entryid", entry);
330
      String ipAddress = getLogEntryField("ipAddress", entry);
331
      String principal = getLogEntryField("principal", entry);
332
      String docid = getLogEntryField("docid", entry);
333
      String eventS = getLogEntryField("event", entry);
334
      String dateLogged = getLogEntryField("dateLogged", entry);
335

    
336
      LogEntry le = new LogEntry();
337

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

    
361
        // skip it if the pid can't be found
362
        continue;
363
      }
364

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

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

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

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

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

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

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

    
556
    // TODO: how do we know if the map was persisted?
557
    success = true;
558
    
559
    return success;
560
  }
561
  
562
  /**
563
   * Test if the user identified by the provided token has authorization 
564
   * for operation on the specified object.
565
   * 
566
   * @param session - the Session object containing the credentials for the Subject
567
   * @param pid - The identifer of the resource for which access is being checked
568
   * @param operation - The type of operation which is being requested for the given pid
569
   *
570
   * @return true if the operation is allowed
571
   * 
572
   * @throws ServiceFailure
573
   * @throws InvalidToken
574
   * @throws NotFound
575
   * @throws NotAuthorized
576
   * @throws NotImplemented
577
   * @throws InvalidRequest
578
   */
579
  public boolean isAuthorized(Session session, Identifier pid, Permission permission)
580
    throws ServiceFailure, InvalidToken, NotFound, NotAuthorized,
581
    NotImplemented, InvalidRequest {
582

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

    
681
  /** 
682
   * Determine if a given object should be treated as an XML science metadata
683
   * object. 
684
   * 
685
   * @param sysmeta - the SystemMetadata describing the object
686
   * @return true if the object should be treated as science metadata
687
   */
688
  public static boolean isScienceMetadata(SystemMetadata sysmeta) {
689
    
690
    ObjectFormat objectFormat = null;
691
    boolean isScienceMetadata = false;
692
    
693
    try {
694
      objectFormat = ObjectFormatCache.getInstance().getFormat(sysmeta.getFmtid());
695
      if ( objectFormat.getFormatType().equals("METADATA") ) {
696
      	isScienceMetadata = true;
697
      	
698
      }
699
      
700
    } catch (InvalidRequest e) {
701
       logMetacat.debug("There was a problem determining if the object identified by" + 
702
         sysmeta.getIdentifier().getValue() + 
703
         " is science metadata: " + e.getMessage());
704
       
705
    } catch (ServiceFailure 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 (NotFound 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 (InsufficientResources 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 (NotImplemented 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
    }
726
    
727
    return isScienceMetadata;
728

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

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

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

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

    
943
    //insert the system metadata
944
    HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
945
      
946
  }
947

    
948
  /**
949
   * Update a systemMetadata document
950
   * 
951
   * @param sysMeta - the system metadata object in the system to update
952
   */
953
  protected void updateSystemMetadata(SystemMetadata sysMeta)
954
    throws ServiceFailure {
955
      
956
    logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
957
    sysMeta.setDateSysMetadataModified(new Date());
958
    HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
959
      
960
  }
961

    
962
  /*
963
   * Write a stream to a file
964
   * 
965
   * @param dir - the directory to write to
966
   * @param fileName - the file name to write to
967
   * @param data - the object bytes as an input stream
968
   * 
969
   * @return newFile - the new file created
970
   * 
971
   * @throws ServiceFailure
972
   */
973
  private File writeStreamToFile(File dir, String fileName, InputStream data) 
974
    throws ServiceFailure {
975
    
976
    File newFile = new File(dir, fileName);
977
    logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
978

    
979
    try {
980
        if (newFile.createNewFile()) {
981
          // write data stream to desired file
982
          OutputStream os = new FileOutputStream(newFile);
983
          long length = IOUtils.copyLarge(data, os);
984
          os.flush();
985
          os.close();
986
        } else {
987
          logMetacat.debug("File creation failed, or file already exists.");
988
          throw new ServiceFailure("1190", "File already exists: " + fileName);
989
        }
990
    } catch (FileNotFoundException e) {
991
      logMetacat.debug("FNF: " + e.getMessage());
992
      throw new ServiceFailure("1190", "File not found: " + fileName + " " 
993
                + e.getMessage());
994
    } catch (IOException e) {
995
      logMetacat.debug("IOE: " + e.getMessage());
996
      throw new ServiceFailure("1190", "File was not written: " + fileName 
997
                + " " + e.getMessage());
998
    }
999

    
1000
    return newFile;
1001
  }
1002
  
1003
}
(2-2/6)