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 15:07: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
    try {
555
      IdentifierManager.getInstance().updateSystemMetadata(systemMetadata);
556
      success = true;
557
    } catch (McdbDocNotFoundException e) {
558
      throw new ServiceFailure("4430", e.getMessage());
559
    }
560

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

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

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

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

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

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

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

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

    
950
  /**
951
   * Update a systemMetadata document
952
   * 
953
   * @param sysMeta - the system metadata object in the system to update
954
   */
955
  protected void updateSystemMetadata(SystemMetadata sysMeta)
956
    throws ServiceFailure {
957
      
958
    logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
959
    sysMeta.setDateSysMetadataModified(new Date());
960
    try {
961
	    IdentifierManager.getInstance().updateSystemMetadata(sysMeta);
962
	    
963
    } catch (McdbDocNotFoundException e) {
964
    	
965
      throw new ServiceFailure("1030", "Error updating system metadata: " + 
966
        e.getClass() + ": " + e.getMessage());
967
      
968
    }
969
      
970
  }
971

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

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

    
1010
    return newFile;
1011
  }
1012
  
1013
}
(3-3/7)