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 10:00:08 -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.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
    boolean allowed = false;
149
    
150
    // check for null session
151
    if (session == null) {
152
    	throw new InvalidToken("4894", "Session is required to WRITE to the Node.");
153
    }
154
    Subject subject = session.getSubject();
155

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

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

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

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

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

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

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

    
305

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

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

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

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

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

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

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

    
357
      LogEntry le = new LogEntry();
358

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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