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-26 12:07:45 -0700 (Mon, 26 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 == null || subject.getValue() == null || 
153
        subject.getValue().toLowerCase().equals(Constants.PUBLIC_SUBJECT) ) {
154
      throw new NotAuthorized("1100", "The provided identity does not have " +
155
        "permission to WRITE to the 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.reserveIdentifier() to reserve one.");
180
    	
181
    }
182
    
183
    // check that we are not attempting to subvert versioning
184
    if (sysmeta.getObsoletes() != null && sysmeta.getObsoletes().getValue() != null) {
185
    	throw new InvalidSystemMetadata("1180", 
186
    			"The supplied system metadata is invalid. " +
187
    			"The obsoletes field cannot have a value when creating entries.");
188
    }
189
    if (sysmeta.getObsoletedBy() != null && sysmeta.getObsoletedBy().getValue() != null) {
190
    	throw new InvalidSystemMetadata("1180", 
191
    			"The supplied system metadata is invalid. " +
192
    			"The obsoletedBy field cannot have a value when creating entries.");
193
	}
194
    
195
    // check for permission
196
    try {
197
      allowed = isAuthorized(session, pid, Permission.WRITE);
198
            
199
    } catch (NotFound e) {
200
      // The identifier doesn't exist, writing should be fine.
201
      allowed = true;
202
      
203
    }
204
    
205
    // verify checksum, only if we can reset the inputstream
206
    if (object.markSupported()) {
207
	    String checksumAlgorithm = sysmeta.getChecksum().getAlgorithm();
208
	    String checksumValue = sysmeta.getChecksum().getValue();
209
	    try {
210
			String computedChecksumValue = ChecksumUtil.checksum(object, checksumAlgorithm).getValue();
211
			// it's very important that we don't consume the stream
212
			object.reset();
213
			if (!computedChecksumValue.equals(checksumValue)) {
214
				throw new InvalidSystemMetadata("4896", "Checksum given does not match that of the object");
215
			}
216
		} catch (Exception e) {
217
			String msg = "Error verifying checksum values";
218
	      	logMetacat.error(msg, e);
219
	        throw new ServiceFailure("1190", msg + ": " + e.getMessage());
220
		}
221
    } else {
222
    	logMetacat.warn("mark is not supported on the object's input stream - cannot verify checksum without consuming stream");
223
    }
224
    	
225
    // we have the go ahead
226
    if ( allowed ) {
227
      
228
      // Science metadata (XML) or science data object?
229
      // TODO: there are cases where certain object formats are science metadata
230
      // but are not XML (netCDF ...).  Handle this.
231
      if ( isScienceMetadata(sysmeta) ) {
232
        
233
        // CASE METADATA:
234
      	String objectAsXML = "";
235
        try {
236
	        objectAsXML = IOUtils.toString(object, "UTF-8");
237
	        localId = insertOrUpdateDocument(objectAsXML, pid, session, "insert");
238
	        //localId = im.getLocalId(pid.getValue());
239

    
240
        } catch (IOException e) {
241
        	String msg = "The Node is unable to create the object. " +
242
          "There was a problem converting the object to XML";
243
        	logMetacat.info(msg);
244
          throw new ServiceFailure("1190", msg + ": " + e.getMessage());
245

    
246
        }
247
                    
248
      } else {
249
	        
250
	      // DEFAULT CASE: DATA (needs to be checked and completed)
251
	      localId = insertDataObject(object, pid, session);
252
      }   
253
    
254
    }
255

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

    
269
    resultPid = pid;
270
    
271
    return resultPid;
272
  }
273

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

    
300

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

    
314
    if ( start == null ) {
315
    	start = 0;
316
    	
317
    }
318
    
319
    if ( count == null ) {
320
    	count = 1000;
321
    	
322
    }
323

    
324
    logMetacat.debug("fromDate: " + fromDate);
325
    logMetacat.debug("toDate: " + toDate);
326

    
327
    String report = el.getReport(null, null, null, null,
328
        new java.sql.Timestamp(fromDate.getTime()),
329
        new java.sql.Timestamp(toDate.getTime()), false);
330

    
331
    logMetacat.debug("report: " + report);
332

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

    
345
      String entryId = getLogEntryField("entryid", entry);
346
      String ipAddress = getLogEntryField("ipAddress", entry);
347
      String principal = getLogEntryField("principal", entry);
348
      String docid = getLogEntryField("docid", entry);
349
      String eventS = getLogEntryField("event", entry);
350
      String dateLogged = getLogEntryField("dateLogged", entry);
351

    
352
      LogEntry le = new LogEntry();
353

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

    
377
        // skip it if the pid can't be found
378
        continue;
379
      }
380

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

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

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

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

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

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

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

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

    
705
  /** 
706
   * Determine if a given object should be treated as an XML science metadata
707
   * object. 
708
   * 
709
   * @param sysmeta - the SystemMetadata describing the object
710
   * @return true if the object should be treated as science metadata
711
   */
712
  public static boolean isScienceMetadata(SystemMetadata sysmeta) {
713
    
714
    ObjectFormat objectFormat = null;
715
    boolean isScienceMetadata = false;
716
    
717
    try {
718
      objectFormat = ObjectFormatCache.getInstance().getFormat(sysmeta.getFmtid());
719
      if ( objectFormat.getFormatType().equals("METADATA") ) {
720
      	isScienceMetadata = true;
721
      	
722
      }
723
      
724
    } catch (InvalidRequest e) {
725
       logMetacat.debug("There was a problem determining if the object identified by" + 
726
         sysmeta.getIdentifier().getValue() + 
727
         " is science metadata: " + e.getMessage());
728
       
729
    } catch (ServiceFailure 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 (NotFound 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 (InsufficientResources 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 (NotImplemented 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
    }
750
    
751
    return isScienceMetadata;
752

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

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

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

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

    
967
    //insert the system metadata
968
    try {
969
    	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
970
    } catch (Exception e) {
971
        throw new ServiceFailure("1190", e.getMessage());
972
	}  
973
  }
974

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

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

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

    
1035
    return newFile;
1036
  }
1037
  
1038
}
(2-2/6)