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-10-12 11:17:30 -0700 (Wed, 12 Oct 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.SubjectInfo;
70
import org.dataone.service.types.v1.SubjectList;
71
import org.dataone.service.types.v1.SystemMetadata;
72
import org.dataone.service.types.v1.util.ChecksumUtil;
73

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

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

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

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

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

    
147
    Identifier resultPid = null;
148
    String localId = null;
149
    boolean allowed = false;
150
    
151
    // check for null session
152
    if (session == null) {
153
    	throw new InvalidToken("4894", "Session is required to WRITE to the Node.");
154
    }
155
    Subject subject = session.getSubject();
156

    
157
    // be sure the user is authenticated for create()
158
    if (subject == null || subject.getValue() == null || 
159
        subject.getValue().toLowerCase().equals(Constants.SUBJECT_PUBLIC) ) {
160
      throw new NotAuthorized("1100", "The provided identity does not have " +
161
        "permission to WRITE to the Node.");
162
      
163
    }
164
    
165
    // verify that pid == SystemMetadata.getIdentifier()
166
    logMetacat.debug("Comparing pid|sysmeta_pid: " + 
167
      pid.getValue() + "|" + sysmeta.getIdentifier().getValue());
168
    if (!pid.getValue().equals(sysmeta.getIdentifier().getValue())) {
169
        throw new InvalidSystemMetadata("1180", 
170
            "The supplied system metadata is invalid. " +
171
            "The identifier " + pid.getValue() + " does not match identifier" +
172
            "in the system metadata identified by " +
173
            sysmeta.getIdentifier().getValue() + ".");
174
        
175
    }
176

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

    
246
        } catch (IOException e) {
247
        	String msg = "The Node is unable to create the object. " +
248
          "There was a problem converting the object to XML";
249
        	logMetacat.info(msg);
250
          throw new ServiceFailure("1190", msg + ": " + e.getMessage());
251

    
252
        }
253
                    
254
      } else {
255
	        
256
	      // DEFAULT CASE: DATA (needs to be checked and completed)
257
	      localId = insertDataObject(object, pid, session);
258
      }   
259
    
260
    }
261

    
262
    // save the sysmeta
263
    try {
264
    	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
265
    } catch (Exception e) {
266
    	logMetacat.error("Problem creating system metadata: " + pid.getValue(), e);
267
        throw new ServiceFailure("1190", e.getMessage());
268
	}
269
    
270
    // setting the resulting identifier failed
271
    if (localId == null ) {
272
      throw new ServiceFailure("1190", "The Node is unable to create the object. ");
273
    }
274

    
275
    resultPid = pid;
276
    
277
    return resultPid;
278
  }
279

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

    
306

    
307
    Log log = new Log();
308
    List<LogEntry> logs = new Vector<LogEntry>();
309
    IdentifierManager im = IdentifierManager.getInstance();
310
    EventLog el = EventLog.getInstance();
311
    if ( fromDate == null ) {
312
      logMetacat.debug("setting fromdate from null");
313
      fromDate = new Date(1);
314
    }
315
    if ( toDate == null ) {
316
      logMetacat.debug("setting todate from null");
317
      toDate = new Date();
318
    }
319

    
320
    if ( start == null ) {
321
    	start = 0;
322
    	
323
    }
324
    
325
    if ( count == null ) {
326
    	count = 1000;
327
    	
328
    }
329

    
330
    logMetacat.debug("fromDate: " + fromDate);
331
    logMetacat.debug("toDate: " + toDate);
332

    
333
    String report = el.getReport(null, null, null, null,
334
        new java.sql.Timestamp(fromDate.getTime()),
335
        new java.sql.Timestamp(toDate.getTime()), false);
336

    
337
    logMetacat.debug("report: " + report);
338

    
339
    String logEntry = "<logEntry>";
340
    String endLogEntry = "</logEntry>";
341
    int startIndex = 0;
342
    int foundIndex = report.indexOf(logEntry, startIndex);
343
    while (foundIndex != -1) {
344
      // parse out each entry
345
      int endEntryIndex = report.indexOf(endLogEntry, foundIndex);
346
      String entry = report.substring(foundIndex, endEntryIndex);
347
      logMetacat.debug("entry: " + entry);
348
      startIndex = endEntryIndex + endLogEntry.length();
349
      foundIndex = report.indexOf(logEntry, startIndex);
350

    
351
      String entryId = getLogEntryField("entryid", entry);
352
      String ipAddress = getLogEntryField("ipAddress", entry);
353
      String principal = getLogEntryField("principal", entry);
354
      String docid = getLogEntryField("docid", entry);
355
      String eventS = getLogEntryField("event", entry);
356
      String dateLogged = getLogEntryField("dateLogged", entry);
357

    
358
      LogEntry le = new LogEntry();
359

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

    
383
        // skip it if the pid can't be found
384
        continue;
385
      }
386

    
387
      le.setIdentifier(identifier);
388
      le.setIpAddress(ipAddress);
389
      Calendar c = Calendar.getInstance();
390
      String year = dateLogged.substring(0, 4);
391
      String month = dateLogged.substring(5, 7);
392
      String date = dateLogged.substring(8, 10);
393
      logMetacat.debug("year: " + year + " month: " + month + " day: " + date);
394
      c.set(new Integer(year).intValue(), new Integer(month).intValue(),
395
          new Integer(date).intValue());
396
      Date logDate = c.getTime();
397
      le.setDateLogged(logDate);
398
      NodeReference memberNode = new NodeReference();
399
      memberNode.setValue(ipAddress);
400
      le.setMemberNode(memberNode);
401
      Subject princ = new Subject();
402
      princ.setValue(principal);
403
      le.setSubject(princ);
404
      le.setUserAgent("metacat/RESTService");
405

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

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

    
483
    // if we fail to set the input stream
484
    if ( inputStream == null ) {
485
      throw new NotFound("1020", "The object specified by " + 
486
                         pid.getValue() +
487
                         "does not exist at this node.");
488
    }
489
    
490
	// log the read event
491
    String principal = Constants.SUBJECT_PUBLIC;
492
    if (session != null && session.getSubject() != null) {
493
    	principal = session.getSubject().getValue();
494
    }
495
    EventLog.getInstance().log(null, principal, localId, "read");
496
    
497
    return inputStream;
498
  }
499

    
500
  /**
501
   * Return the system metadata for a given object
502
   * 
503
   * @param session - the Session object containing the credentials for the Subject
504
   * @param pid - the object identifier for the given object
505
   * 
506
   * @return inputStream - the input stream of the given system metadata object
507
   * 
508
   * @throws InvalidToken
509
   * @throws ServiceFailure
510
   * @throws NotAuthorized
511
   * @throws NotFound
512
   * @throws InvalidRequest
513
   * @throws NotImplemented
514
   */
515
  public SystemMetadata getSystemMetadata(Session session, Identifier pid)
516
    throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
517
    InvalidRequest, NotImplemented {
518

    
519
    if (!isAuthorized(session, pid, Permission.READ)) {
520
      throw new NotAuthorized("1400", Permission.READ + " not allowed on " + pid.getValue());  
521
    }
522
    SystemMetadata systemMetadata = null;
523
    try {
524
      systemMetadata = IdentifierManager.getInstance().getSystemMetadata(pid.getValue());
525
    } catch (McdbDocNotFoundException e) {
526
      throw new NotFound("1420", "No record found for: " + pid.getValue());
527
    }
528
    
529
    return systemMetadata;
530
  }
531
   
532
  /**
533
   * Set access for a given object using the object identifier and a Subject
534
   * under a given Session.
535
   * 
536
   * @param session - the Session object containing the credentials for the Subject
537
   * @param pid - the object identifier for the given object to apply the policy
538
   * @param policy - the access policy to be applied
539
   * 
540
   * @return true if the application of the policy succeeds
541
   * @throws InvalidToken
542
   * @throws ServiceFailure
543
   * @throws NotFound
544
   * @throws NotAuthorized
545
   * @throws NotImplemented
546
   * @throws InvalidRequest
547
   */
548
  public boolean setAccessPolicy(Session session, Identifier pid, 
549
    AccessPolicy accessPolicy) 
550
    throws InvalidToken, ServiceFailure, NotFound, NotAuthorized, 
551
    NotImplemented, InvalidRequest {
552

    
553
    boolean success = false;
554
    
555
    // get the subject
556
    Subject subject = session.getSubject();
557
    // get the system metadata
558
    String pidStr = pid.getValue();
559
    
560
    // are we allowed to do this?
561
    if (!isAuthorized(session, pid, Permission.CHANGE_PERMISSION)) {
562
      throw new NotAuthorized("4420", "not allowed by " + subject.getValue() + " on " + pidStr);  
563
    }
564
    
565
    SystemMetadata systemMetadata = null;
566
    try {
567
      systemMetadata = IdentifierManager.getInstance().getSystemMetadata(pidStr);
568
    } catch (McdbDocNotFoundException e) {
569
      throw new NotFound("4400", "No record found for: " + pid);
570
    }
571
        
572
    // set the access policy
573
    systemMetadata.setAccessPolicy(accessPolicy);
574
    
575
    // update the metadata
576
    try {
577
    	HazelcastService.getInstance().getSystemMetadataMap().lock(systemMetadata.getIdentifier());
578
    	HazelcastService.getInstance().getSystemMetadataMap().put(systemMetadata.getIdentifier(), systemMetadata);
579
    	HazelcastService.getInstance().getSystemMetadataMap().unlock(systemMetadata.getIdentifier());
580
	} catch (Exception e) {
581
		throw new ServiceFailure("4430", e.getMessage());
582
	} finally {
583
		HazelcastService.getInstance().getSystemMetadataMap().unlock(systemMetadata.getIdentifier());
584
	}
585
    
586
    // TODO: how do we know if the map was persisted?
587
    success = true;
588
    
589
    return success;
590
  }
591
  
592
  /**
593
   * Test if the user identified by the provided token has authorization 
594
   * for operation on the specified object.
595
   * 
596
   * @param session - the Session object containing the credentials for the Subject
597
   * @param pid - The identifer of the resource for which access is being checked
598
   * @param operation - The type of operation which is being requested for the given pid
599
   *
600
   * @return true if the operation is allowed
601
   * 
602
   * @throws ServiceFailure
603
   * @throws InvalidToken
604
   * @throws NotFound
605
   * @throws NotAuthorized
606
   * @throws NotImplemented
607
   * @throws InvalidRequest
608
   */
609
  public boolean isAuthorized(Session session, Identifier pid, Permission permission)
610
    throws ServiceFailure, InvalidToken, NotFound, NotAuthorized,
611
    NotImplemented, InvalidRequest {
612

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

    
711
  /** 
712
   * Determine if a given object should be treated as an XML science metadata
713
   * object. 
714
   * 
715
   * @param sysmeta - the SystemMetadata describing the object
716
   * @return true if the object should be treated as science metadata
717
   */
718
  public static boolean isScienceMetadata(SystemMetadata sysmeta) {
719
    
720
    ObjectFormat objectFormat = null;
721
    boolean isScienceMetadata = false;
722
    
723
    try {
724
      objectFormat = ObjectFormatCache.getInstance().getFormat(sysmeta.getFmtid());
725
      if ( objectFormat.getFormatType().equals("METADATA") ) {
726
      	isScienceMetadata = true;
727
      	
728
      }
729
      
730
    } catch (InvalidRequest e) {
731
       logMetacat.debug("There was a problem determining if the object identified by" + 
732
         sysmeta.getIdentifier().getValue() + 
733
         " is science metadata: " + e.getMessage());
734
       
735
    } catch (ServiceFailure e) {
736
      logMetacat.debug("There was a problem determining if the object identified by" + 
737
          sysmeta.getIdentifier().getValue() + 
738
          " is science metadata: " + e.getMessage());
739
    
740
    } catch (NotFound e) {
741
      logMetacat.debug("There was a problem determining if the object identified by" + 
742
          sysmeta.getIdentifier().getValue() + 
743
          " is science metadata: " + e.getMessage());
744
    
745
    } catch (InsufficientResources e) {
746
      logMetacat.debug("There was a problem determining if the object identified by" + 
747
          sysmeta.getIdentifier().getValue() + 
748
          " is science metadata: " + e.getMessage());
749
    
750
    } catch (NotImplemented e) {
751
      logMetacat.debug("There was a problem determining if the object identified by" + 
752
          sysmeta.getIdentifier().getValue() + 
753
          " is science metadata: " + e.getMessage());
754
    
755
    }
756
    
757
    return isScienceMetadata;
758

    
759
  }
760
  
761
  /**
762
   * Insert or update an XML document into Metacat
763
   * 
764
   * @param xml - the XML document to insert or update
765
   * @param pid - the identifier to be used for the resulting object
766
   * 
767
   * @return localId - the resulting docid of the document created or updated
768
   * 
769
   */
770
  protected String insertOrUpdateDocument(String xml, Identifier pid, 
771
    Session session, String insertOrUpdate) 
772
    throws ServiceFailure {
773
    
774
  	logMetacat.debug("Starting to insert xml document...");
775
    IdentifierManager im = IdentifierManager.getInstance();
776

    
777
    // generate pid/localId pair for sysmeta
778
    String localId = null;
779
    
780
    if(insertOrUpdate.equals("insert")) {
781
      localId = im.generateLocalId(pid.getValue(), 1);
782
      
783
    } else {
784
      //localid should already exist in the identifier table, so just find it
785
      try {
786
        logMetacat.debug("Updating pid " + pid.getValue());
787
        logMetacat.debug("looking in identifier table for pid " + pid.getValue());
788
        
789
        localId = im.getLocalId(pid.getValue());
790
        
791
        logMetacat.debug("localId: " + localId);
792
        //increment the revision
793
        String docid = localId.substring(0, localId.lastIndexOf("."));
794
        String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
795
        int rev = new Integer(revS).intValue();
796
        rev++;
797
        docid = docid + "." + rev;
798
        localId = docid;
799
        logMetacat.debug("incremented localId: " + localId);
800
      
801
      } catch(McdbDocNotFoundException e) {
802
        throw new ServiceFailure("1030", "D1NodeService.insertOrUpdateDocument(): " +
803
            "pid " + pid.getValue() + 
804
            " should have been in the identifier table, but it wasn't: " + 
805
            e.getMessage());
806
      
807
      }
808
      
809
    }
810

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

    
962
  /**
963
   * Insert a systemMetadata document and return its localId
964
   */
965
  protected void insertSystemMetadata(SystemMetadata sysmeta) 
966
    throws ServiceFailure {
967
    
968
  	logMetacat.debug("Starting to insert SystemMetadata...");
969
    sysmeta.setDateSysMetadataModified(new Date());
970
    logMetacat.debug("Inserting new system metadata with modified date " + 
971
        sysmeta.getDateSysMetadataModified());
972

    
973
    //insert the system metadata
974
    try {
975
    	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
976
    } catch (Exception e) {
977
        throw new ServiceFailure("1190", e.getMessage());
978
	}  
979
  }
980

    
981
  /**
982
   * Update a systemMetadata document
983
   * 
984
   * @param sysMeta - the system metadata object in the system to update
985
   */
986
  protected void updateSystemMetadata(SystemMetadata sysMeta)
987
    throws ServiceFailure {
988
      
989
    logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
990
    sysMeta.setDateSysMetadataModified(new Date());
991
    try {
992
    	HazelcastService.getInstance().getSystemMetadataMap().lock(sysMeta.getIdentifier());
993
    	HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
994
    	HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
995
	} catch (Exception e) {
996
		throw new ServiceFailure("4862", e.getMessage());
997
	} finally {
998
		HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
999
	}
1000
      
1001
  }
1002

    
1003
  /*
1004
   * Write a stream to a file
1005
   * 
1006
   * @param dir - the directory to write to
1007
   * @param fileName - the file name to write to
1008
   * @param data - the object bytes as an input stream
1009
   * 
1010
   * @return newFile - the new file created
1011
   * 
1012
   * @throws ServiceFailure
1013
   */
1014
  private File writeStreamToFile(File dir, String fileName, InputStream data) 
1015
    throws ServiceFailure {
1016
    
1017
    File newFile = new File(dir, fileName);
1018
    logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1019

    
1020
    try {
1021
        if (newFile.createNewFile()) {
1022
          // write data stream to desired file
1023
          OutputStream os = new FileOutputStream(newFile);
1024
          long length = IOUtils.copyLarge(data, os);
1025
          os.flush();
1026
          os.close();
1027
        } else {
1028
          logMetacat.debug("File creation failed, or file already exists.");
1029
          throw new ServiceFailure("1190", "File already exists: " + fileName);
1030
        }
1031
    } catch (FileNotFoundException e) {
1032
      logMetacat.debug("FNF: " + e.getMessage());
1033
      throw new ServiceFailure("1190", "File not found: " + fileName + " " 
1034
                + e.getMessage());
1035
    } catch (IOException e) {
1036
      logMetacat.debug("IOE: " + e.getMessage());
1037
      throw new ServiceFailure("1190", "File was not written: " + fileName 
1038
                + " " + e.getMessage());
1039
    }
1040

    
1041
    return newFile;
1042
  }
1043
  
1044
}
(2-2/6)