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-03-28 11:08:59 -0700 (Wed, 28 Mar 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...");
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
	    String checksumAlgorithm = sysmeta.getChecksum().getAlgorithm();
360
	    String checksumValue = sysmeta.getChecksum().getValue();
361
	    try {
362
			String computedChecksumValue = ChecksumUtil.checksum(object, checksumAlgorithm).getValue();
363
			// it's very important that we don't consume the stream
364
			object.reset();
365
			if (!computedChecksumValue.equals(checksumValue)) {
366
				throw new InvalidSystemMetadata("4896", "Checksum given does not match that of the object");
367
			}
368
		} catch (Exception e) {
369
			String msg = "Error verifying checksum values";
370
	      	logMetacat.error(msg, e);
371
	        throw new ServiceFailure("1190", msg + ": " + e.getMessage());
372
		}
373
    } else {
374
    	logMetacat.warn("mark is not supported on the object's input stream - cannot verify checksum without consuming stream");
375
    }
376
    	
377
    // we have the go ahead
378
    if ( allowed ) {
379
      
380
      // Science metadata (XML) or science data object?
381
      // TODO: there are cases where certain object formats are science metadata
382
      // but are not XML (netCDF ...).  Handle this.
383
      if ( isScienceMetadata(sysmeta) ) {
384
        
385
        // CASE METADATA:
386
      	String objectAsXML = "";
387
        try {
388
	        objectAsXML = IOUtils.toString(object, "UTF-8");
389
	        localId = insertOrUpdateDocument(objectAsXML, pid, session, "insert");
390
	        //localId = im.getLocalId(pid.getValue());
391

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

    
398
        }
399
                    
400
      } else {
401
	        
402
	      // DEFAULT CASE: DATA (needs to be checked and completed)
403
	      localId = insertDataObject(object, pid, session);
404
      }   
405
    
406
    }
407

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

    
423
    resultPid = pid;
424
    
425
    return resultPid;
426
  }
427

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

    
454

    
455
    Log log = new Log();
456
    List<LogEntry> logs = new Vector<LogEntry>();
457
    IdentifierManager im = IdentifierManager.getInstance();
458
    EventLog el = EventLog.getInstance();
459
    if ( fromDate == null ) {
460
      logMetacat.debug("setting fromdate from null");
461
      fromDate = new Date(1);
462
    }
463
    if ( toDate == null ) {
464
      logMetacat.debug("setting todate from null");
465
      toDate = new Date();
466
    }
467

    
468
    if ( start == null ) {
469
    	start = 0;
470
    	
471
    }
472
    
473
    if ( count == null ) {
474
    	count = 1000;
475
    	
476
    }
477

    
478
    logMetacat.debug("fromDate: " + fromDate);
479
    logMetacat.debug("toDate: " + toDate);
480

    
481
    String report = el.getReport(null, null, null, null,
482
        new java.sql.Timestamp(fromDate.getTime()),
483
        new java.sql.Timestamp(toDate.getTime()), false);
484

    
485
    logMetacat.debug("report: " + report);
486

    
487
    String logEntry = "<logEntry>";
488
    String endLogEntry = "</logEntry>";
489
    int startIndex = 0;
490
    int foundIndex = report.indexOf(logEntry, startIndex);
491
    while (foundIndex != -1) {
492
      // parse out each entry
493
      int endEntryIndex = report.indexOf(endLogEntry, foundIndex);
494
      String entry = report.substring(foundIndex, endEntryIndex);
495
      logMetacat.debug("entry: " + entry);
496
      startIndex = endEntryIndex + endLogEntry.length();
497
      foundIndex = report.indexOf(logEntry, startIndex);
498

    
499
      String entryId = getLogEntryField("entryid", entry);
500
      String ipAddress = getLogEntryField("ipAddress", entry);
501
      String principal = getLogEntryField("principal", entry);
502
      String userAgent = getLogEntryField("userAgent", entry);
503
      String docid = getLogEntryField("docid", entry);
504
      String eventS = getLogEntryField("event", entry);
505
      String dateLogged = getLogEntryField("dateLogged", entry);
506

    
507
      LogEntry le = new LogEntry();
508

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

    
539
          logMetacat.warn("could not find pid for docid '" + docid + "'");
540

    
541
        // skip it if the pid can't be found
542
        continue;
543
      }
544

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

    
578
      // event filtering?
579
      if (event == null) {
580
    	  logs.add(le);
581
      } else if (le.getEvent().equals(event)) {
582
    	  logs.add(le);
583
      }
584
    }
585
    
586
    // d1 paging
587
    int total = logs.size();
588
    if (start != null && count != null) {
589
    	int toIndex = start + count;
590
    	// do not exceed total
591
    	toIndex = Math.min(toIndex, total);
592
    	// do not start greater than total
593
    	start = Math.min(start, total);
594
    	// sub set of the list
595
    	logs = new ArrayList<LogEntry>(logs.subList(start, toIndex));
596
    }
597

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

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

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

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

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

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

    
911
		// add the authenticated symbolic since we have a session
912
		Subject authenticatedSubject = new Subject();
913
		authenticatedSubject.setValue(Constants.SUBJECT_AUTHENTICATED_USER);
914
		subjects.add(authenticatedSubject);
915
	}
916

    
917
    // add public subject for everyone
918
    Subject publicSubject = new Subject();
919
    publicSubject.setValue(Constants.SUBJECT_PUBLIC);
920
    subjects.add(publicSubject);
921
    
922
    // get the system metadata
923
    String pidStr = pid.getValue();
924
    SystemMetadata systemMetadata = null;
925
    try {
926
        systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
927

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

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

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

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

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

    
1194
    logMetacat.debug("Case DATA: starting to write to disk.");
1195
	if (locked) {
1196

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

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

    
1273
  /**
1274
   * Update a systemMetadata document
1275
   * 
1276
   * @param sysMeta - the system metadata object in the system to update
1277
   */
1278
    protected void updateSystemMetadata(SystemMetadata sysMeta)
1279
        throws ServiceFailure {
1280

    
1281
        logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
1282
        sysMeta.setDateSysMetadataModified(new Date());
1283
        try {
1284
            HazelcastService.getInstance().getSystemMetadataMap().lock(sysMeta.getIdentifier());
1285
            HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
1286

    
1287
        } catch (Exception e) {
1288
            throw new ServiceFailure("4862", e.getMessage());
1289

    
1290
        } finally {
1291
            HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
1292

    
1293
        }
1294

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

    
1320
  /*
1321
   * Write a stream to a file
1322
   * 
1323
   * @param dir - the directory to write to
1324
   * @param fileName - the file name to write to
1325
   * @param data - the object bytes as an input stream
1326
   * 
1327
   * @return newFile - the new file created
1328
   * 
1329
   * @throws ServiceFailure
1330
   */
1331
  private File writeStreamToFile(File dir, String fileName, InputStream data) 
1332
    throws ServiceFailure {
1333
    
1334
    File newFile = new File(dir, fileName);
1335
    logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1336

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

    
1358
    return newFile;
1359
  }
1360
  
1361
}
(2-2/5)