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: 2012-04-09 15:18:39 -0700 (Mon, 09 Apr 2012) $'
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
import javax.servlet.http.HttpServletRequest;
42

    
43

    
44
import org.apache.commons.io.IOUtils;
45
import org.apache.log4j.Logger;
46
import org.dataone.client.CNode;
47
import org.dataone.client.D1Client;
48
import org.dataone.client.ObjectFormatCache;
49
import org.dataone.service.util.Constants;
50
import org.dataone.service.util.DateTimeMarshaller;
51
import org.dataone.service.exceptions.IdentifierNotUnique;
52
import org.dataone.service.exceptions.InsufficientResources;
53
import org.dataone.service.exceptions.InvalidRequest;
54
import org.dataone.service.exceptions.InvalidSystemMetadata;
55
import org.dataone.service.exceptions.InvalidToken;
56
import org.dataone.service.exceptions.NotAuthorized;
57
import org.dataone.service.exceptions.NotFound;
58
import org.dataone.service.exceptions.NotImplemented;
59
import org.dataone.service.exceptions.ServiceFailure;
60
import org.dataone.service.exceptions.UnsupportedType;
61
import org.dataone.service.types.v1.AccessPolicy;
62
import org.dataone.service.types.v1.AccessRule;
63
import org.dataone.service.types.v1.DescribeResponse;
64
import org.dataone.service.types.v1.Event;
65
import org.dataone.service.types.v1.Identifier;
66
import org.dataone.service.types.v1.Group;
67
import org.dataone.service.types.v1.Log;
68
import org.dataone.service.types.v1.LogEntry;
69
import org.dataone.service.types.v1.Node;
70
import org.dataone.service.types.v1.NodeReference;
71
import org.dataone.service.types.v1.NodeType;
72
import org.dataone.service.types.v1.ObjectFormat;
73
import org.dataone.service.types.v1.Permission;
74
import org.dataone.service.types.v1.Person;
75
import org.dataone.service.types.v1.Session;
76
import org.dataone.service.types.v1.Subject;
77
import org.dataone.service.types.v1.SubjectInfo;
78
import org.dataone.service.types.v1.SubjectList;
79
import org.dataone.service.types.v1.SystemMetadata;
80
import org.dataone.service.types.v1.util.ChecksumUtil;
81

    
82
import edu.ucsb.nceas.metacat.AccessionNumberException;
83
import edu.ucsb.nceas.metacat.DocumentImpl;
84
import edu.ucsb.nceas.metacat.EventLog;
85
import edu.ucsb.nceas.metacat.IdentifierManager;
86
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
87
import edu.ucsb.nceas.metacat.MetacatHandler;
88
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
89
import edu.ucsb.nceas.metacat.database.DBConnection;
90
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
91
import edu.ucsb.nceas.metacat.dataone.hazelcast.HazelcastService;
92
import edu.ucsb.nceas.metacat.properties.PropertyService;
93
import edu.ucsb.nceas.metacat.replication.ForceReplicationHandler;
94
import edu.ucsb.nceas.metacat.util.DocumentUtil;
95
import edu.ucsb.nceas.metacat.util.SystemUtil;
96
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
97

    
98
public abstract class D1NodeService {
99
  
100
  private static Logger logMetacat = Logger.getLogger(D1NodeService.class);
101

    
102
  /** For logging the operations */
103
  protected HttpServletRequest request;
104
  
105
  /* reference to the metacat handler */
106
  protected MetacatHandler handler;
107
  
108
  /* parameters set in the incoming request */
109
  private Hashtable<String, String[]> params;
110

    
111
  /**
112
   * Constructor - used to set the metacatUrl from a subclass extending D1NodeService
113
   * 
114
   * @param metacatUrl - the URL of the metacat service, including the ending /d1
115
   */
116
  public D1NodeService(HttpServletRequest request) {
117
		this.request = request;
118
	}
119
  
120
  /**
121
   * This method provides a lighter weight mechanism than 
122
   * getSystemMetadata() for a client to determine basic 
123
   * properties of the referenced object.
124
   * 
125
   * @param session - the Session object containing the credentials for the Subject
126
   * @param pid - the identifier of the object to be described
127
   * 
128
   * @return describeResponse - A set of values providing a basic description 
129
   *                            of the object.
130
   * 
131
   * @throws InvalidToken
132
   * @throws ServiceFailure
133
   * @throws NotAuthorized
134
   * @throws NotFound
135
   * @throws NotImplemented
136
   * @throws InvalidRequest
137
   */
138
  public DescribeResponse describe(Session session, Identifier pid) 
139
      throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
140

    
141
    // get system metadata and construct the describe response
142
      SystemMetadata sysmeta = getSystemMetadata(session, pid);
143
      DescribeResponse describeResponse = 
144
      	new DescribeResponse(sysmeta.getFormatId(), sysmeta.getSize(), 
145
      			sysmeta.getDateSysMetadataModified(),
146
      			sysmeta.getChecksum(), sysmeta.getSerialVersion());
147

    
148
      return describeResponse;
149

    
150
  }
151
  
152
  /**
153
   * Deletes an object from the Member Node, where the object is either a 
154
   * data object or a science metadata object.
155
   * 
156
   * @param session - the Session object containing the credentials for the Subject
157
   * @param pid - The object identifier to be deleted
158
   * 
159
   * @return pid - the identifier of the object used for the deletion
160
   * 
161
   * @throws InvalidToken
162
   * @throws ServiceFailure
163
   * @throws NotAuthorized
164
   * @throws NotFound
165
   * @throws NotImplemented
166
   * @throws InvalidRequest
167
   */
168
  public Identifier delete(Session session, Identifier pid) 
169
      throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
170

    
171
      String localId = null;
172
      boolean allowed = false;
173
      String username = Constants.SUBJECT_PUBLIC;
174
      String[] groupnames = null;
175
      if (session == null) {
176
      	throw new InvalidToken("1330", "No session has been provided");
177
      } else {
178
          username = session.getSubject().getValue();
179
          if (session.getSubjectInfo() != null) {
180
              List<Group> groupList = session.getSubjectInfo().getGroupList();
181
              if (groupList != null) {
182
                  groupnames = new String[groupList.size()];
183
                  for (int i = 0; i > groupList.size(); i++) {
184
                      groupnames[i] = groupList.get(i).getGroupName();
185
                  }
186
              }
187
          }
188
      }
189

    
190
      // do we have a valid pid?
191
      if (pid == null || pid.getValue().trim().equals("")) {
192
          throw new ServiceFailure("1350", "The provided identifier was invalid.");
193
      }
194

    
195
      // check for the existing identifier
196
      try {
197
          localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
198
      } catch (McdbDocNotFoundException e) {
199
          throw new NotFound("1340", "The object with the provided " + "identifier was not found.");
200
      }
201

    
202
      // does the subject have DELETE (a D1 CHANGE_PERMISSION level) priveleges on the pid?
203
      try {
204
			allowed = isAuthorized(session, pid, Permission.CHANGE_PERMISSION);
205
		} catch (InvalidRequest e) {
206
          throw new ServiceFailure("1350", e.getDescription());
207
		}
208
          
209

    
210
      if (allowed) {
211
          try {
212
              // delete the document
213
              DocumentImpl.delete(localId, username, groupnames, null);
214
              EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, Event.DELETE.xmlValue());
215

    
216
              // archive it
217
              SystemMetadata sysMeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
218
              sysMeta.setArchived(true);
219
              HazelcastService.getInstance().getSystemMetadataMap().put(pid, sysMeta);
220
              
221
              // remove the system metadata for it
222
              //HazelcastService.getInstance().getSystemMetadataMap().remove(pid);
223
              
224
          } catch (McdbDocNotFoundException e) {
225
              throw new NotFound("1340", "The provided identifier was invalid.");
226

    
227
          } catch (SQLException e) {
228
              throw new ServiceFailure("1350", "There was a problem deleting the object." + "The error message was: " + e.getMessage());
229

    
230
          } catch (InsufficientKarmaException e) {
231
              throw new NotAuthorized("1320", "The provided identity does not have " + "permission to DELETE objects on the Member Node.");
232

    
233
          } catch (Exception e) { // for some reason DocumentImpl throws a general Exception
234
              throw new ServiceFailure("1350", "There was a problem deleting the object." + "The error message was: " + e.getMessage());
235
          }
236

    
237
      } else {
238
          throw new NotAuthorized("1320", "The provided identity does not have " + "permission to DELETE objects on the Member Node.");
239
      }
240

    
241
      return pid;
242
  }
243
  
244
  /**
245
   * Low level, "are you alive" operation. A valid ping response is 
246
   * indicated by a HTTP status of 200.
247
   * 
248
   * @return true if the service is alive
249
   * 
250
   * @throws NotImplemented
251
   * @throws ServiceFailure
252
   * @throws InsufficientResources
253
   */
254
  public Date ping() 
255
      throws NotImplemented, ServiceFailure, InsufficientResources {
256

    
257
      // test if we can get a database connection
258
      int serialNumber = -1;
259
      DBConnection dbConn = null;
260
      try {
261
          dbConn = DBConnectionPool.getDBConnection("MNodeService.ping");
262
          serialNumber = dbConn.getCheckOutSerialNumber();
263
      } catch (SQLException e) {
264
      	ServiceFailure sf = new ServiceFailure("", e.getMessage());
265
      	sf.initCause(e);
266
          throw sf;
267
      } finally {
268
          // Return the database connection
269
          DBConnectionPool.returnDBConnection(dbConn, serialNumber);
270
      }
271

    
272
      return Calendar.getInstance().getTime();
273
  }
274
  
275
  /**
276
   * Adds a new object to the Node, where the object is either a data 
277
   * object or a science metadata object. This method is called by clients 
278
   * to create new data objects on Member Nodes or internally for Coordinating
279
   * Nodes
280
   * 
281
   * @param session - the Session object containing the credentials for the Subject
282
   * @param pid - The object identifier to be created
283
   * @param object - the object bytes
284
   * @param sysmeta - the system metadata that describes the object  
285
   * 
286
   * @return pid - the object identifier created
287
   * 
288
   * @throws InvalidToken
289
   * @throws ServiceFailure
290
   * @throws NotAuthorized
291
   * @throws IdentifierNotUnique
292
   * @throws UnsupportedType
293
   * @throws InsufficientResources
294
   * @throws InvalidSystemMetadata
295
   * @throws NotImplemented
296
   * @throws InvalidRequest
297
   */
298
  public Identifier create(Session session, Identifier pid, InputStream object,
299
    SystemMetadata sysmeta) 
300
    throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, 
301
    UnsupportedType, InsufficientResources, InvalidSystemMetadata, 
302
    NotImplemented, InvalidRequest {
303

    
304
    Identifier resultPid = null;
305
    String localId = null;
306
    boolean allowed = false;
307
    
308
    // check for null session
309
    if (session == null) {
310
    	throw new InvalidToken("4894", "Session is required to WRITE to the Node.");
311
    }
312
    Subject subject = session.getSubject();
313

    
314
    Subject publicSubject = new Subject();
315
    publicSubject.setValue(Constants.SUBJECT_PUBLIC);
316
	// be sure the user is authenticated for create()
317
    if (subject == null || subject.getValue() == null || 
318
        subject.equals(publicSubject) ) {
319
      throw new NotAuthorized("1100", "The provided identity does not have " +
320
        "permission to WRITE to the Node.");
321
      
322
    }
323
    
324
    // verify that pid == SystemMetadata.getIdentifier()
325
    logMetacat.debug("Comparing pid|sysmeta_pid: " + 
326
      pid.getValue() + "|" + sysmeta.getIdentifier().getValue());
327
    if (!pid.getValue().equals(sysmeta.getIdentifier().getValue())) {
328
        throw new InvalidSystemMetadata("1180", 
329
            "The supplied system metadata is invalid. " +
330
            "The identifier " + pid.getValue() + " does not match identifier" +
331
            "in the system metadata identified by " +
332
            sysmeta.getIdentifier().getValue() + ".");
333
        
334
    }
335

    
336
    logMetacat.debug("Checking if identifier exists: " + pid.getValue());
337
    // Check that the identifier does not already exist
338
    if (IdentifierManager.getInstance().identifierExists(pid.getValue())) {
339
	    	throw new IdentifierNotUnique("1120", 
340
			          "The requested identifier " + pid.getValue() +
341
			          " is already used by another object and" +
342
			          "therefore can not be used for this object. Clients should choose" +
343
			          "a new identifier that is unique and retry the operation or " +
344
			          "use CN.reserveIdentifier() to reserve one.");
345
    	
346
    }
347
    
348
    // TODO: this probably needs to be refined more
349
    try {
350
      allowed = isAuthorized(session, pid, Permission.WRITE);
351
            
352
    } catch (NotFound e) {
353
      // The identifier doesn't exist, writing should be fine.
354
      allowed = true;
355
    }
356
    
357
    // verify checksum, only if we can reset the inputstream
358
    if (object.markSupported()) {
359
        logMetacat.debug("Checking checksum for: " + pid.getValue());
360
	    String checksumAlgorithm = sysmeta.getChecksum().getAlgorithm();
361
	    String checksumValue = sysmeta.getChecksum().getValue();
362
	    try {
363
			String computedChecksumValue = ChecksumUtil.checksum(object, checksumAlgorithm).getValue();
364
			// it's very important that we don't consume the stream
365
			object.reset();
366
			if (!computedChecksumValue.equals(checksumValue)) {
367
			    logMetacat.error("Checksum for " + pid.getValue() + " does not match system metadata, computed = " + computedChecksumValue );
368
				throw new InvalidSystemMetadata("4896", "Checksum given does not match that of the object");
369
			}
370
		} catch (Exception e) {
371
			String msg = "Error verifying checksum values";
372
	      	logMetacat.error(msg, e);
373
	        throw new ServiceFailure("1190", msg + ": " + e.getMessage());
374
		}
375
    } else {
376
    	logMetacat.warn("mark is not supported on the object's input stream - cannot verify checksum without consuming stream");
377
    }
378
    	
379
    // we have the go ahead
380
    if ( allowed ) {
381
      
382
        logMetacat.debug("Allowed to insert: " + pid.getValue());
383

    
384
      // Science metadata (XML) or science data object?
385
      // TODO: there are cases where certain object formats are science metadata
386
      // but are not XML (netCDF ...).  Handle this.
387
      if ( isScienceMetadata(sysmeta) ) {
388
        
389
        // CASE METADATA:
390
      	String objectAsXML = "";
391
        try {
392
	        objectAsXML = IOUtils.toString(object, "UTF-8");
393
	        localId = insertOrUpdateDocument(objectAsXML, pid, session, "insert");
394
	        //localId = im.getLocalId(pid.getValue());
395

    
396
        } catch (IOException e) {
397
        	String msg = "The Node is unable to create the object. " +
398
          "There was a problem converting the object to XML";
399
        	logMetacat.info(msg);
400
          throw new ServiceFailure("1190", msg + ": " + e.getMessage());
401

    
402
        }
403
                    
404
      } else {
405
	        
406
	      // DEFAULT CASE: DATA (needs to be checked and completed)
407
	      localId = insertDataObject(object, pid, session);
408
      }   
409
    
410
    }
411

    
412
    logMetacat.debug("Done inserting new object: " + pid.getValue());
413
    
414
    // save the sysmeta
415
    try {
416
      // lock and unlock of the pid happens in the subclass
417
    	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
418
    	
419
    } catch (Exception e) {
420
    	logMetacat.error("Problem creating system metadata: " + pid.getValue(), e);
421
        throw new ServiceFailure("1190", e.getMessage());
422
	}
423
    
424
    // setting the resulting identifier failed
425
    if (localId == null ) {
426
      throw new ServiceFailure("1190", "The Node is unable to create the object. ");
427
    }
428

    
429
    resultPid = pid;
430
    
431
    logMetacat.debug("create() complete for object: " + pid.getValue());
432

    
433
    return resultPid;
434
  }
435

    
436
  /**
437
   * Return the log records associated with a given event between the start and 
438
   * end dates listed given a particular Subject listed in the Session
439
   * 
440
   * @param session - the Session object containing the credentials for the Subject
441
   * @param fromDate - the start date of the desired log records
442
   * @param toDate - the end date of the desired log records
443
   * @param event - restrict log records of a specific event type
444
   * @param start - zero based offset from the first record in the 
445
   *                set of matching log records. Used to assist with 
446
   *                paging the response.
447
   * @param count - maximum number of log records to return in the response. 
448
   *                Used to assist with paging the response.
449
   * 
450
   * @return the desired log records
451
   * 
452
   * @throws InvalidToken
453
   * @throws ServiceFailure
454
   * @throws NotAuthorized
455
   * @throws InvalidRequest
456
   * @throws NotImplemented
457
   */
458
  public Log getLogRecords(Session session, Date fromDate, Date toDate, 
459
      Event event, String pidFilter, Integer start, Integer count) throws InvalidToken, ServiceFailure,
460
      NotAuthorized, InvalidRequest, NotImplemented {
461

    
462

    
463
    Log log = new Log();
464
    List<LogEntry> logs = new Vector<LogEntry>();
465
    IdentifierManager im = IdentifierManager.getInstance();
466
    EventLog el = EventLog.getInstance();
467
    if ( fromDate == null ) {
468
      logMetacat.debug("setting fromdate from null");
469
      fromDate = new Date(1);
470
    }
471
    if ( toDate == null ) {
472
      logMetacat.debug("setting todate from null");
473
      toDate = new Date();
474
    }
475

    
476
    if ( start == null ) {
477
    	start = 0;
478
    	
479
    }
480
    
481
    if ( count == null ) {
482
    	count = 1000;
483
    	
484
    }
485

    
486
    logMetacat.debug("fromDate: " + fromDate);
487
    logMetacat.debug("toDate: " + toDate);
488

    
489
    String report = el.getReport(null, null, null, null,
490
        new java.sql.Timestamp(fromDate.getTime()),
491
        new java.sql.Timestamp(toDate.getTime()), false);
492

    
493
    logMetacat.debug("report: " + report);
494

    
495
    String logEntry = "<logEntry>";
496
    String endLogEntry = "</logEntry>";
497
    int startIndex = 0;
498
    int foundIndex = report.indexOf(logEntry, startIndex);
499
    while (foundIndex != -1) {
500
      // parse out each entry
501
      int endEntryIndex = report.indexOf(endLogEntry, foundIndex);
502
      String entry = report.substring(foundIndex, endEntryIndex);
503
      logMetacat.debug("entry: " + entry);
504
      startIndex = endEntryIndex + endLogEntry.length();
505
      foundIndex = report.indexOf(logEntry, startIndex);
506

    
507
      String entryId = getLogEntryField("entryid", entry);
508
      String ipAddress = getLogEntryField("ipAddress", entry);
509
      String principal = getLogEntryField("principal", entry);
510
      String userAgent = getLogEntryField("userAgent", entry);
511
      String docid = getLogEntryField("docid", entry);
512
      String eventS = getLogEntryField("event", entry);
513
      String dateLogged = getLogEntryField("dateLogged", entry);
514

    
515
      LogEntry le = new LogEntry();
516

    
517
      // handle Metacat -> DataONE event conversion
518
      if (eventS.equalsIgnoreCase("insert")) {
519
    	  eventS = Event.CREATE.xmlValue();
520
      }
521
      Event e = Event.convert(eventS);
522
      if (e == null) { // skip any events that are not Dataone Crud events
523
          logMetacat.warn("skipping unknown event type: '" + eventS + "'");
524
          continue;
525
      }
526
      le.setEvent(e);
527
      le.setEntryId(entryId);
528
      Identifier identifier = new Identifier();
529
      try {
530
        logMetacat.debug("converting docid '" + docid + "' to a pid.");
531
        if (docid == null || docid.trim().equals("") || docid.trim().equals("null")) {
532
          continue;
533
        }
534
        String docidNoRev = DocumentUtil.getSmartDocId(docid);
535
        //docid = docid.substring(0, docid.lastIndexOf("."));
536
        int rev = DocumentUtil.getRevisionFromAccessionNumber(docid);
537
        //int rev = im.getLatestRevForLocalId(docid);
538
        String guid = im.getGUID(docidNoRev, rev);
539
        identifier.setValue(guid);
540
      } catch (Exception ex) { 
541
        // try to get the pid, if that doesn't
542
        // work, just use the local id
543
        // throw new ServiceFailure("1030",
544
        // "Error getting pid for localId " +
545
        // docid + ": " + ex.getMessage());\
546

    
547
          logMetacat.warn("could not find pid for docid '" + docid + "'");
548

    
549
        // skip it if the pid can't be found
550
        continue;
551
      }
552

    
553
      // skip if we are not allowed to read the document in question
554
      // https://redmine.dataone.org/issues/2444
555
      boolean allowed = false;
556
      try {
557
    	  allowed = isAuthorized(session, identifier, Permission.READ);
558
      } catch (NotAuthorized ignore) {}
559
      catch (NotFound nf) {
560
    	  logMetacat.warn("Could not check authorization for pid: " + identifier.getValue(), nf);
561
      }
562
      if (!allowed) {
563
    	  logMetacat.debug(Permission.READ + " not allowed on document: " + identifier.getValue());
564
    	  continue;
565
      }
566
      
567
      le.setIdentifier(identifier);
568
      le.setIpAddress(ipAddress);
569
      Date logDate = DateTimeMarshaller.deserializeDateToUTC(dateLogged);
570
      le.setDateLogged(logDate);
571
      NodeReference memberNode = new NodeReference();
572
      String nodeId = "localhost";
573
      try {
574
          nodeId = PropertyService.getProperty("dataone.nodeId");
575
      } catch (PropertyNotFoundException e1) {
576
          // TODO Auto-generated catch block
577
          e1.printStackTrace();
578
      }
579
      memberNode.setValue(nodeId);
580
      le.setNodeIdentifier(memberNode);
581
      Subject princ = new Subject();
582
      princ.setValue(principal);
583
      le.setSubject(princ);
584
      le.setUserAgent(userAgent);
585

    
586
      // event filtering?
587
      if (event == null) {
588
    	  logs.add(le);
589
      } else if (le.getEvent().equals(event)) {
590
    	  logs.add(le);
591
      }
592
    }
593
    
594
    // d1 paging
595
    int total = logs.size();
596
    if (start != null && count != null) {
597
    	int toIndex = start + count;
598
    	// do not exceed total
599
    	toIndex = Math.min(toIndex, total);
600
    	// do not start greater than total
601
    	start = Math.min(start, total);
602
    	// sub set of the list
603
    	logs = new ArrayList<LogEntry>(logs.subList(start, toIndex));
604
    }
605

    
606
    log.setLogEntryList(logs);
607
    log.setStart(start);
608
    log.setCount(logs.size());
609
    log.setTotal(total);
610
    logMetacat.info("getLogRecords");
611
    return log;
612
  }
613
    
614
  /**
615
   * Return the object identified by the given object identifier
616
   * 
617
   * @param session - the Session object containing the credentials for the Subject
618
   * @param pid - the object identifier for the given object
619
   * 
620
   * TODO: The D1 Authorization API doesn't provide information on which 
621
   * authentication system the Subject belongs to, and so it's not possible to
622
   * discern which Person or Group is a valid KNB LDAP DN.  Fix this.
623
   * 
624
   * @return inputStream - the input stream of the given object
625
   * 
626
   * @throws InvalidToken
627
   * @throws ServiceFailure
628
   * @throws NotAuthorized
629
   * @throws InvalidRequest
630
   * @throws NotImplemented
631
   */
632
  public InputStream get(Session session, Identifier pid) 
633
    throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
634
    NotImplemented {
635
    
636
    InputStream inputStream = null; // bytes to be returned
637
    handler = new MetacatHandler(new Timer());
638
    boolean allowed = false;
639
    String localId; // the metacat docid for the pid
640
    
641
    // get the local docid from Metacat
642
    try {
643
      localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
644
    
645
    } catch (McdbDocNotFoundException e) {
646
      throw new NotFound("1020", "The object specified by " + 
647
                         pid.getValue() +
648
                         " does not exist at this node.");
649
    }
650
    
651
    // check for authorization
652
    try {
653
		allowed = isAuthorized(session, pid, Permission.READ);
654
	} catch (InvalidRequest e) {
655
		throw new ServiceFailure("1030", e.getDescription());
656
	}
657
    
658
    // if the person is authorized, perform the read
659
    if (allowed) {
660
      try {
661
        inputStream = handler.read(localId);
662
      } catch (Exception e) {
663
        throw new ServiceFailure("1020", "The object specified by " + 
664
            pid.getValue() +
665
            "could not be returned due to error: " +
666
            e.getMessage());
667
      }
668
    }
669

    
670
    // if we fail to set the input stream
671
    if ( inputStream == null ) {
672
      throw new NotFound("1020", "The object specified by " + 
673
                         pid.getValue() +
674
                         "does not exist at this node.");
675
    }
676
    
677
	// log the read event
678
    String principal = Constants.SUBJECT_PUBLIC;
679
    if (session != null && session.getSubject() != null) {
680
    	principal = session.getSubject().getValue();
681
    }
682
    EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), principal, localId, "read");
683
    
684
    return inputStream;
685
  }
686

    
687
  /**
688
   * Return the system metadata for a given object
689
   * 
690
   * @param session - the Session object containing the credentials for the Subject
691
   * @param pid - the object identifier for the given object
692
   * 
693
   * @return inputStream - the input stream of the given system metadata object
694
   * 
695
   * @throws InvalidToken
696
   * @throws ServiceFailure
697
   * @throws NotAuthorized
698
   * @throws NotFound
699
   * @throws InvalidRequest
700
   * @throws NotImplemented
701
   */
702
  public SystemMetadata getSystemMetadata(Session session, Identifier pid)
703
      throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
704
      NotImplemented {
705
      
706
	  boolean isAuthorized = false;
707
	  try {
708
		isAuthorized = isAuthorized(session, pid, Permission.READ);
709
	  } catch (InvalidRequest e) {
710
		throw new ServiceFailure("1090", e.getDescription());
711
	  }
712
	  
713
      if (!isAuthorized) {
714
        throw new NotAuthorized("1400", Permission.READ + " not allowed on " + pid.getValue());  
715
      }
716
      SystemMetadata systemMetadata = null;
717
      try {
718
        systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
719
        
720
      } catch (Exception e) {
721
        // convert hazelcast RuntimeException to NotFound
722
        throw new NotFound("1420", "No record found for: " + pid.getValue());
723
        
724
      }
725
    
726
    return systemMetadata;
727
  }
728
     
729
  /**
730
   * Test if the user identified by the provided token has administrative authorization 
731
   * for the operation on the specified object.
732
   * 
733
   * @param session - the Session object containing the credentials for the Subject
734
   * @param pid - The identifer of the resource for which access is being checked
735
   * @param operation - The type of operation which is being requested for the given pid
736
   * 
737
   * @return true if the operation is allowed
738
   * 
739
   * @throws ServiceFailure
740
   * @throws InvalidToken
741
   * @throws NotFound
742
   * @throws NotAuthorized
743
   * @throws NotImplemented
744
   */
745
  protected boolean isAdminAuthorized(Session session, Identifier pid,
746
      Permission permission) 
747
      throws ServiceFailure, InvalidToken, NotAuthorized,
748
      NotImplemented {
749

    
750
      boolean allowed = false;
751
      
752
      // must have a session in order to check admin 
753
      if (session == null) {
754
         logMetacat.debug("In isAdminAuthorized(), session is null for " +
755
             "identifier " + pid.getValue() + " and permission " + 
756
             permission.toString());
757
    	   return false;
758
      }
759
      
760
      logMetacat.debug("In isAdminAuthorized(), checking CN or MN authorization for " +
761
           session.getSubject().getValue() + " on identifier " + pid.getValue());
762
      
763
      // are we allowed to do this? only CNs are allowed
764
      CNode cn = D1Client.getCN();
765
      List<Node> nodes = cn.listNodes().getNodeList();
766
      
767
      if ( nodes == null ) {
768
          throw new ServiceFailure("4852", "Couldn't get node list.");
769
  
770
      }
771
      
772
      // find the node in the node list
773
      for ( Node node : nodes ) {
774
          
775
          NodeReference nodeReference = node.getIdentifier();
776
          logMetacat.debug("In isAdminAuthorized(), Node reference is: " + nodeReference.getValue());
777
          
778
          Subject subject = session.getSubject();
779
          
780
          if (node.getType() == NodeType.CN) {
781
              List<Subject> nodeSubjects = node.getSubjectList();
782
              
783
              // check if the session subject is in the node subject list
784
              for (Subject nodeSubject : nodeSubjects) {
785
                  logMetacat.debug("In isAdminAuthorized(), comparing subjects: " +
786
                      nodeSubject.getValue() + " and " + subject.getValue());
787
                  if ( nodeSubject.equals(subject) ) {
788
                      allowed = true; // subject of session == target node subject
789
                      break;
790
                      
791
                  }
792
              }              
793
          }
794
      }
795

    
796
      
797
      return allowed;
798
  }
799
  
800
  /**
801
   * Test if the user identified by the provided token has authorization 
802
   * for the operation on the specified object.
803
   * 
804
   * @param session - the Session object containing the credentials for the Subject
805
   * @param pid - The identifer of the resource for which access is being checked
806
   * @param operation - The type of operation which is being requested for the given pid
807
   *
808
   * @return true if the operation is allowed
809
   * 
810
   * @throws ServiceFailure
811
   * @throws InvalidToken
812
   * @throws NotFound
813
   * @throws NotAuthorized
814
   * @throws NotImplemented
815
   * @throws InvalidRequest
816
   */
817
  public boolean isAuthorized(Session session, Identifier pid, Permission permission)
818
    throws ServiceFailure, InvalidToken, NotFound, NotAuthorized,
819
    NotImplemented, InvalidRequest {
820

    
821
    boolean allowed = false;
822
    
823
    if (permission == null) {
824
    	throw new InvalidRequest("1761", "Permission was not provided or is invalid");
825
    }
826
    
827
    // permissions are hierarchical
828
    List<Permission> expandedPermissions = null;
829
    
830
    // always allow CN access
831
    if ( isAdminAuthorized(session, pid, permission) ) {
832
        allowed = true;
833
        return allowed;
834
        
835
    }
836
    
837
    // for the "Verified" symbolic user
838
    Subject verifiedSubject = new Subject();
839
	verifiedSubject.setValue(Constants.SUBJECT_VERIFIED_USER);
840
    
841
    // get the subject[s] from the session
842
	List<Subject> subjects = new ArrayList<Subject>();
843
	if (session != null) {
844
		// primary subject
845
		Subject subject = session.getSubject();
846
		if (subject != null) {
847
			subjects.add(subject);
848
		}
849
		// details about the subject
850
		SubjectInfo subjectInfo = session.getSubjectInfo();
851
		if (subjectInfo != null) {
852
			// find subjectInfo for the primary subject
853
			List<Person> personList = subjectInfo.getPersonList();
854
			List<Group> groupList = subjectInfo.getGroupList();
855
			if (personList != null) {
856
				for (Person p : personList) {
857
					  // for every person listed (isVerified is transitive)
858
						logMetacat.debug("checking person");
859
						logMetacat.debug("p.getVerified(): " + p.getVerified());
860
						if (p.getVerified() != null && p.getVerified()) {
861
							// add the verified symbolic user
862
							if (!subjects.contains(verifiedSubject)) {
863
								subjects.add(verifiedSubject);
864
							}
865
						}
866
						// add the equivalent identities
867
						List<Subject> equivList = p.getEquivalentIdentityList();
868
						if (equivList != null) {
869
							for (Subject equivSubject : equivList) {
870
								subjects.add(equivSubject);
871
								// find that entry
872
								for (Person equivPerson: personList) {
873
									if (equivSubject.equals(equivPerson.getSubject())) {
874
										// transitive group membership
875
										if (equivPerson.getIsMemberOfList() != null) {
876
											for (Subject equivGroup: equivPerson.getIsMemberOfList()) {
877
												subjects.add(equivGroup);
878
											}
879
										}
880
										// TODO: is verified transitive?
881
										if (equivPerson.getVerified() != null && equivPerson.getVerified()) {
882
											// add the verified symbolic user
883
											if (!subjects.contains(verifiedSubject)) {
884
												subjects.add(verifiedSubject);
885
											}
886
										}
887
									}
888
								}
889
							}
890
						}
891
						// add the groups they are a member of
892
						List<Subject> memberOfList = p.getIsMemberOfList();
893
						if (memberOfList != null) {
894
							for (Subject g : memberOfList) {
895
								subjects.add(g);
896
							}
897
						}
898
						// look at all the Groups to see if this person has membership defined there
899
						if (groupList != null) {
900
							for (Group group: groupList) {
901
								if (group.getHasMemberList() != null) {
902
									for (Subject member: group.getHasMemberList()) {
903
										// is the person a member?
904
										if (member.equals(p.getSubject())) {
905
											// add this group as a subject to check if it is not already there
906
											if (!subjects.contains(group.getSubject())) {
907
												subjects.add(group.getSubject());
908
											}
909
										}
910
									}
911
								}
912
							}
913
						}
914
						break;
915
				}
916
			}
917
		}
918

    
919
		// add the authenticated symbolic since we have a session
920
		Subject authenticatedSubject = new Subject();
921
		authenticatedSubject.setValue(Constants.SUBJECT_AUTHENTICATED_USER);
922
		subjects.add(authenticatedSubject);
923
	}
924

    
925
    // add public subject for everyone
926
    Subject publicSubject = new Subject();
927
    publicSubject.setValue(Constants.SUBJECT_PUBLIC);
928
    subjects.add(publicSubject);
929
    
930
    // get the system metadata
931
    String pidStr = pid.getValue();
932
    SystemMetadata systemMetadata = null;
933
    try {
934
        systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
935

    
936
    } catch (Exception e) {
937
        // convert Hazelcast RuntimeException to NotFound
938
        logMetacat.error("An error occurred while getting system metadata for identifier " +
939
            pid.getValue() + ". The error message was: " + e.getMessage());
940
        throw new NotFound("1800", "No record found for " + pidStr);
941
        
942
    } 
943
    
944
    // throw not found if it was not found
945
    if (systemMetadata == null) {
946
    	throw new NotFound("1800", "No system metadata could be found for given PID: " + pidStr);
947
    }
948
	    
949
    // do we own it?
950
    for (Subject s: subjects) {
951
      logMetacat.debug("Comparing \t" + 
952
                       systemMetadata.getRightsHolder().getValue() +
953
                       " \tagainst \t" + s.getValue());
954
    	allowed = systemMetadata.getRightsHolder().equals(s);
955
    	if (allowed) {
956
    		return allowed;
957
    	}
958
    }    
959
    
960
    // otherwise check the access rules
961
    try {
962
	    List<AccessRule> allows = systemMetadata.getAccessPolicy().getAllowList();
963
	    search: // label break
964
	    for (AccessRule accessRule: allows) {
965
	      for (Subject s: subjects) {
966
	        logMetacat.debug("Checking allow access rule for subject: " + s.getValue());
967
	        if (accessRule.getSubjectList().contains(s)) {
968
	        	logMetacat.debug("Access rule contains subject: " + s.getValue());
969
	        	for (Permission p: accessRule.getPermissionList()) {
970
		        	logMetacat.debug("Checking permission: " + p.xmlValue());
971
	        		expandedPermissions = expandPermissions(p);
972
	        		allowed = expandedPermissions.contains(permission);
973
	        		if (allowed) {
974
			        	logMetacat.info("Permission granted: " + p.xmlValue() + " to " + s.getValue());
975
	        			break search; //label break
976
	        		}
977
	        	}
978
        		
979
	        }
980
	      }
981
	    }
982
    } catch (Exception e) {
983
    	// catch all for errors - safe side should be to deny the access
984
    	logMetacat.error("Problem checking authorization - defaulting to deny", e);
985
		allowed = false;
986
	  
987
    }
988
    
989
    // throw or return?
990
    if (!allowed) {
991
      throw new NotAuthorized("1820", permission + " not allowed on " + pidStr);
992
    }
993
    
994
    return allowed;
995
    
996
  }
997
  
998
  /*
999
   * parse a logEntry and get the relevant field from it
1000
   * 
1001
   * @param fieldname
1002
   * @param entry
1003
   * @return
1004
   */
1005
  private String getLogEntryField(String fieldname, String entry) {
1006
    String begin = "<" + fieldname + ">";
1007
    String end = "</" + fieldname + ">";
1008
    // logMetacat.debug("looking for " + begin + " and " + end +
1009
    // " in entry " + entry);
1010
    String s = entry.substring(entry.indexOf(begin) + begin.length(), entry
1011
        .indexOf(end));
1012
    logMetacat.debug("entry " + fieldname + " : " + s);
1013
    return s;
1014
  }
1015

    
1016
  /** 
1017
   * Determine if a given object should be treated as an XML science metadata
1018
   * object. 
1019
   * 
1020
   * @param sysmeta - the SystemMetadata describing the object
1021
   * @return true if the object should be treated as science metadata
1022
   */
1023
  public static boolean isScienceMetadata(SystemMetadata sysmeta) {
1024
    
1025
    ObjectFormat objectFormat = null;
1026
    boolean isScienceMetadata = false;
1027
    
1028
    try {
1029
      objectFormat = ObjectFormatCache.getInstance().getFormat(sysmeta.getFormatId());
1030
      if ( objectFormat.getFormatType().equals("METADATA") ) {
1031
      	isScienceMetadata = true;
1032
      	
1033
      }
1034
      
1035
       
1036
    } catch (ServiceFailure e) {
1037
      logMetacat.debug("There was a problem determining if the object identified by" + 
1038
          sysmeta.getIdentifier().getValue() + 
1039
          " is science metadata: " + e.getMessage());
1040
    
1041
    } catch (NotFound e) {
1042
      logMetacat.debug("There was a problem determining if the object identified by" + 
1043
          sysmeta.getIdentifier().getValue() + 
1044
          " is science metadata: " + e.getMessage());
1045
    
1046
    }
1047
    
1048
    return isScienceMetadata;
1049

    
1050
  }
1051
  
1052
  /**
1053
   * Insert or update an XML document into Metacat
1054
   * 
1055
   * @param xml - the XML document to insert or update
1056
   * @param pid - the identifier to be used for the resulting object
1057
   * 
1058
   * @return localId - the resulting docid of the document created or updated
1059
   * 
1060
   */
1061
  public String insertOrUpdateDocument(String xml, Identifier pid, 
1062
    Session session, String insertOrUpdate) 
1063
    throws ServiceFailure {
1064
    
1065
  	logMetacat.debug("Starting to insert xml document...");
1066
    IdentifierManager im = IdentifierManager.getInstance();
1067

    
1068
    // generate pid/localId pair for sysmeta
1069
    String localId = null;
1070
    
1071
    if(insertOrUpdate.equals("insert")) {
1072
      localId = im.generateLocalId(pid.getValue(), 1);
1073
      
1074
    } else {
1075
      //localid should already exist in the identifier table, so just find it
1076
      try {
1077
        logMetacat.debug("Updating pid " + pid.getValue());
1078
        logMetacat.debug("looking in identifier table for pid " + pid.getValue());
1079
        
1080
        localId = im.getLocalId(pid.getValue());
1081
        
1082
        logMetacat.debug("localId: " + localId);
1083
        //increment the revision
1084
        String docid = localId.substring(0, localId.lastIndexOf("."));
1085
        String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
1086
        int rev = new Integer(revS).intValue();
1087
        rev++;
1088
        docid = docid + "." + rev;
1089
        localId = docid;
1090
        logMetacat.debug("incremented localId: " + localId);
1091
      
1092
      } catch(McdbDocNotFoundException e) {
1093
        throw new ServiceFailure("1030", "D1NodeService.insertOrUpdateDocument(): " +
1094
            "pid " + pid.getValue() + 
1095
            " should have been in the identifier table, but it wasn't: " + 
1096
            e.getMessage());
1097
      
1098
      }
1099
      
1100
    }
1101

    
1102
    params = new Hashtable<String, String[]>();
1103
    String[] action = new String[1];
1104
    action[0] = insertOrUpdate;
1105
    params.put("action", action);
1106
    String[] docid = new String[1];
1107
    docid[0] = localId;
1108
    params.put("docid", docid);
1109
    String[] doctext = new String[1];
1110
    doctext[0] = xml;
1111
    params.put("doctext", doctext);
1112
    
1113
    String username = Constants.SUBJECT_PUBLIC;
1114
    String[] groupnames = null;
1115
    if (session != null ) {
1116
    	username = session.getSubject().getValue();
1117
    	if (session.getSubjectInfo() != null) {
1118
    		List<Group> groupList = session.getSubjectInfo().getGroupList();
1119
    		if (groupList != null) {
1120
    			groupnames = new String[groupList.size()];
1121
    			for (int i = 0; i > groupList.size(); i++ ) {
1122
    				groupnames[i] = groupList.get(i).getGroupName();
1123
    			}
1124
    		}
1125
    	}
1126
    }
1127
    
1128
    // do the insert or update action
1129
    handler = new MetacatHandler(new Timer());
1130
    String result = handler.handleInsertOrUpdateAction(request.getRemoteAddr(), request.getHeader("User-Agent"), null, 
1131
                        null, params, username, groupnames, false, false);
1132
    
1133
    if(result.indexOf("<error>") != -1) {
1134
    	String detailCode = "";
1135
    	if ( insertOrUpdate.equals("insert") ) {
1136
    		// make sure to remove the mapping so that subsequent attempts do not fail with IdentifierNotUnique
1137
    		im.removeMapping(pid.getValue(), localId);
1138
    		detailCode = "1190";
1139
    		
1140
    	} else if ( insertOrUpdate.equals("update") ) {
1141
    		detailCode = "1310";
1142
    		
1143
    	}
1144
        throw new ServiceFailure(detailCode, 
1145
          "Error inserting or updating document: " + result);
1146
    }
1147
    logMetacat.debug("Finsished inserting xml document with id " + localId);
1148
    
1149
    return localId;
1150
  }
1151
  
1152
  /**
1153
   * Insert a data document
1154
   * 
1155
   * @param object
1156
   * @param pid
1157
   * @param sessionData
1158
   * @throws ServiceFailure
1159
   * @returns localId of the data object inserted
1160
   */
1161
  public String insertDataObject(InputStream object, Identifier pid, 
1162
          Session session) throws ServiceFailure {
1163
      
1164
    String username = Constants.SUBJECT_PUBLIC;
1165
    String[] groupnames = null;
1166
    if (session != null ) {
1167
    	username = session.getSubject().getValue();
1168
    	if (session.getSubjectInfo() != null) {
1169
    		List<Group> groupList = session.getSubjectInfo().getGroupList();
1170
    		if (groupList != null) {
1171
    			groupnames = new String[groupList.size()];
1172
    			for (int i = 0; i > groupList.size(); i++ ) {
1173
    				groupnames[i] = groupList.get(i).getGroupName();
1174
    			}
1175
    		}
1176
    	}
1177
    }
1178
  
1179
    // generate pid/localId pair for object
1180
    logMetacat.debug("Generating a pid/localId mapping");
1181
    IdentifierManager im = IdentifierManager.getInstance();
1182
    String localId = im.generateLocalId(pid.getValue(), 1);
1183
  
1184
    // Save the data file to disk using "localId" as the name
1185
    String datafilepath = null;
1186
	try {
1187
		datafilepath = PropertyService.getProperty("application.datafilepath");
1188
	} catch (PropertyNotFoundException e) {
1189
		ServiceFailure sf = new ServiceFailure("1190", "Lookup data file path" + e.getMessage());
1190
		sf.initCause(e);
1191
		throw sf;
1192
	}
1193
    boolean locked = false;
1194
	try {
1195
		locked = DocumentImpl.getDataFileLockGrant(localId);
1196
	} catch (Exception e) {
1197
		ServiceFailure sf = new ServiceFailure("1190", "Could not lock file for writing:" + e.getMessage());
1198
		sf.initCause(e);
1199
		throw sf;
1200
	}
1201

    
1202
    logMetacat.debug("Case DATA: starting to write to disk.");
1203
	if (locked) {
1204

    
1205
          File dataDirectory = new File(datafilepath);
1206
          dataDirectory.mkdirs();
1207
  
1208
          File newFile = writeStreamToFile(dataDirectory, localId, object);
1209
  
1210
          // TODO: Check that the file size matches SystemMetadata
1211
          // long size = newFile.length();
1212
          // if (size == 0) {
1213
          //     throw new IOException("Uploaded file is 0 bytes!");
1214
          // }
1215
  
1216
          // Register the file in the database (which generates an exception
1217
          // if the localId is not acceptable or other untoward things happen
1218
          try {
1219
            logMetacat.debug("Registering document...");
1220
            DocumentImpl.registerDocument(localId, "BIN", localId,
1221
                    username, groupnames);
1222
            logMetacat.debug("Registration step completed.");
1223
            
1224
          } catch (SQLException e) {
1225
            //newFile.delete();
1226
            logMetacat.debug("SQLE: " + e.getMessage());
1227
            e.printStackTrace(System.out);
1228
            throw new ServiceFailure("1190", "Registration failed: " + 
1229
            		e.getMessage());
1230
            
1231
          } catch (AccessionNumberException e) {
1232
            //newFile.delete();
1233
            logMetacat.debug("ANE: " + e.getMessage());
1234
            e.printStackTrace(System.out);
1235
            throw new ServiceFailure("1190", "Registration failed: " + 
1236
            	e.getMessage());
1237
            
1238
          } catch (Exception e) {
1239
            //newFile.delete();
1240
            logMetacat.debug("Exception: " + e.getMessage());
1241
            e.printStackTrace(System.out);
1242
            throw new ServiceFailure("1190", "Registration failed: " + 
1243
            	e.getMessage());
1244
          }
1245
  
1246
          logMetacat.debug("Logging the creation event.");
1247
          EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, "create");
1248
  
1249
          // Schedule replication for this data file
1250
          logMetacat.debug("Scheduling replication.");
1251
          ForceReplicationHandler frh = new ForceReplicationHandler(
1252
            localId, "create", false, null);
1253
      }
1254
      
1255
      return localId;
1256
    
1257
  }
1258

    
1259
  /**
1260
   * Insert a systemMetadata document and return its localId
1261
   */
1262
  public void insertSystemMetadata(SystemMetadata sysmeta) 
1263
      throws ServiceFailure {
1264
      
1265
  	  logMetacat.debug("Starting to insert SystemMetadata...");
1266
      sysmeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
1267
      logMetacat.debug("Inserting new system metadata with modified date " + 
1268
          sysmeta.getDateSysMetadataModified());
1269
      
1270
      //insert the system metadata
1271
      try {
1272
        // note: the calling subclass handles the map hazelcast lock/unlock
1273
      	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
1274
      	
1275
      } catch (Exception e) {
1276
          throw new ServiceFailure("1190", e.getMessage());
1277
          
1278
	    }  
1279
  }
1280

    
1281
  /**
1282
   * Update a systemMetadata document
1283
   * 
1284
   * @param sysMeta - the system metadata object in the system to update
1285
   */
1286
    protected void updateSystemMetadata(SystemMetadata sysMeta)
1287
        throws ServiceFailure {
1288

    
1289
        logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
1290
        sysMeta.setDateSysMetadataModified(new Date());
1291
        try {
1292
            HazelcastService.getInstance().getSystemMetadataMap().lock(sysMeta.getIdentifier());
1293
            HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
1294

    
1295
        } catch (Exception e) {
1296
            throw new ServiceFailure("4862", e.getMessage());
1297

    
1298
        } finally {
1299
            HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
1300

    
1301
        }
1302

    
1303
    }
1304
  
1305
  /**
1306
   * Given a Permission, returns a list of all permissions that it encompasses
1307
   * Permissions are hierarchical so that WRITE also allows READ.
1308
   * @param permission
1309
   * @return list of included Permissions for the given permission
1310
   */
1311
  protected List<Permission> expandPermissions(Permission permission) {
1312
	  	List<Permission> expandedPermissions = new ArrayList<Permission>();
1313
	    if (permission.equals(Permission.READ)) {
1314
	    	expandedPermissions.add(Permission.READ);
1315
	    }
1316
	    if (permission.equals(Permission.WRITE)) {
1317
	    	expandedPermissions.add(Permission.READ);
1318
	    	expandedPermissions.add(Permission.WRITE);
1319
	    }
1320
	    if (permission.equals(Permission.CHANGE_PERMISSION)) {
1321
	    	expandedPermissions.add(Permission.READ);
1322
	    	expandedPermissions.add(Permission.WRITE);
1323
	    	expandedPermissions.add(Permission.CHANGE_PERMISSION);
1324
	    }
1325
	    return expandedPermissions;
1326
  }
1327

    
1328
  /*
1329
   * Write a stream to a file
1330
   * 
1331
   * @param dir - the directory to write to
1332
   * @param fileName - the file name to write to
1333
   * @param data - the object bytes as an input stream
1334
   * 
1335
   * @return newFile - the new file created
1336
   * 
1337
   * @throws ServiceFailure
1338
   */
1339
  private File writeStreamToFile(File dir, String fileName, InputStream data) 
1340
    throws ServiceFailure {
1341
    
1342
    File newFile = new File(dir, fileName);
1343
    logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1344

    
1345
    try {
1346
        if (newFile.createNewFile()) {
1347
          // write data stream to desired file
1348
          OutputStream os = new FileOutputStream(newFile);
1349
          long length = IOUtils.copyLarge(data, os);
1350
          os.flush();
1351
          os.close();
1352
        } else {
1353
          logMetacat.debug("File creation failed, or file already exists.");
1354
          throw new ServiceFailure("1190", "File already exists: " + fileName);
1355
        }
1356
    } catch (FileNotFoundException e) {
1357
      logMetacat.debug("FNF: " + e.getMessage());
1358
      throw new ServiceFailure("1190", "File not found: " + fileName + " " 
1359
                + e.getMessage());
1360
    } catch (IOException e) {
1361
      logMetacat.debug("IOE: " + e.getMessage());
1362
      throw new ServiceFailure("1190", "File was not written: " + fileName 
1363
                + " " + e.getMessage());
1364
    }
1365

    
1366
    return newFile;
1367
  }
1368
  
1369
}
(2-2/5)