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-20 10:48:24 -0700 (Tue, 20 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
    try {
246
    	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
247
    } catch (Exception e) {
248
        throw new ServiceFailure("1190", e.getMessage());
249
	}
250
    
251
    // setting the resulting identifier failed
252
    if (localId == null ) {
253
      throw new ServiceFailure("1190", "The Node is unable to create the object. ");
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
    	HazelcastService.getInstance().getSystemMetadataMap().lock(systemMetadata.getIdentifier());
559
    	HazelcastService.getInstance().getSystemMetadataMap().put(systemMetadata.getIdentifier(), systemMetadata);
560
    	HazelcastService.getInstance().getSystemMetadataMap().unlock(systemMetadata.getIdentifier());
561
	} catch (Exception e) {
562
		throw new ServiceFailure("4430", e.getMessage());
563
	} finally {
564
		HazelcastService.getInstance().getSystemMetadataMap().unlock(systemMetadata.getIdentifier());
565
	}
566
    
567
    // TODO: how do we know if the map was persisted?
568
    success = true;
569
    
570
    return success;
571
  }
572
  
573
  /**
574
   * Test if the user identified by the provided token has authorization 
575
   * for operation on the specified object.
576
   * 
577
   * @param session - the Session object containing the credentials for the Subject
578
   * @param pid - The identifer of the resource for which access is being checked
579
   * @param operation - The type of operation which is being requested for the given pid
580
   *
581
   * @return true if the operation is allowed
582
   * 
583
   * @throws ServiceFailure
584
   * @throws InvalidToken
585
   * @throws NotFound
586
   * @throws NotAuthorized
587
   * @throws NotImplemented
588
   * @throws InvalidRequest
589
   */
590
  public boolean isAuthorized(Session session, Identifier pid, Permission permission)
591
    throws ServiceFailure, InvalidToken, NotFound, NotAuthorized,
592
    NotImplemented, InvalidRequest {
593

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

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

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

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

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

    
943
  /**
944
   * Insert a systemMetadata document and return its localId
945
   */
946
  protected void insertSystemMetadata(SystemMetadata sysmeta) 
947
    throws ServiceFailure {
948
    
949
  	logMetacat.debug("Starting to insert SystemMetadata...");
950
    sysmeta.setDateSysMetadataModified(new Date());
951
    logMetacat.debug("Inserting new system metadata with modified date " + 
952
        sysmeta.getDateSysMetadataModified());
953

    
954
    //insert the system metadata
955
    try {
956
    	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
957
    } catch (Exception e) {
958
        throw new ServiceFailure("1190", e.getMessage());
959
	}  
960
  }
961

    
962
  /**
963
   * Update a systemMetadata document
964
   * 
965
   * @param sysMeta - the system metadata object in the system to update
966
   */
967
  protected void updateSystemMetadata(SystemMetadata sysMeta)
968
    throws ServiceFailure {
969
      
970
    logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
971
    sysMeta.setDateSysMetadataModified(new Date());
972
    try {
973
    	HazelcastService.getInstance().getSystemMetadataMap().lock(sysMeta.getIdentifier());
974
    	HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
975
    	HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
976
	} catch (Exception e) {
977
		throw new ServiceFailure("4862", e.getMessage());
978
	} finally {
979
		HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
980
	}
981
      
982
  }
983

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

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

    
1022
    return newFile;
1023
  }
1024
  
1025
}
(2-2/6)