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-30 14:20:52 -0700 (Mon, 30 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.Arrays;
35
import java.util.Calendar;
36
import java.util.Date;
37
import java.util.Hashtable;
38
import java.util.List;
39
import java.util.Timer;
40
import java.util.Vector;
41

    
42
import javax.servlet.http.HttpServletRequest;
43

    
44

    
45
import org.apache.commons.io.IOUtils;
46
import org.apache.log4j.Logger;
47
import org.dataone.client.CNode;
48
import org.dataone.client.D1Client;
49
import org.dataone.client.ObjectFormatCache;
50
import org.dataone.service.util.Constants;
51
import org.dataone.service.util.DateTimeMarshaller;
52
import org.dataone.service.exceptions.BaseException;
53
import org.dataone.service.exceptions.IdentifierNotUnique;
54
import org.dataone.service.exceptions.InsufficientResources;
55
import org.dataone.service.exceptions.InvalidRequest;
56
import org.dataone.service.exceptions.InvalidSystemMetadata;
57
import org.dataone.service.exceptions.InvalidToken;
58
import org.dataone.service.exceptions.NotAuthorized;
59
import org.dataone.service.exceptions.NotFound;
60
import org.dataone.service.exceptions.NotImplemented;
61
import org.dataone.service.exceptions.ServiceFailure;
62
import org.dataone.service.exceptions.UnsupportedType;
63
import org.dataone.service.types.v1.AccessRule;
64
import org.dataone.service.types.v1.DescribeResponse;
65
import org.dataone.service.types.v1.Event;
66
import org.dataone.service.types.v1.Identifier;
67
import org.dataone.service.types.v1.Group;
68
import org.dataone.service.types.v1.Log;
69
import org.dataone.service.types.v1.LogEntry;
70
import org.dataone.service.types.v1.Node;
71
import org.dataone.service.types.v1.NodeReference;
72
import org.dataone.service.types.v1.NodeType;
73
import org.dataone.service.types.v1.ObjectFormat;
74
import org.dataone.service.types.v1.Permission;
75
import org.dataone.service.types.v1.Replica;
76
import org.dataone.service.types.v1.Session;
77
import org.dataone.service.types.v1.Subject;
78
import org.dataone.service.types.v1.SystemMetadata;
79
import org.dataone.service.types.v1.util.AuthUtils;
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.utilities.PropertyNotFoundException;
96

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

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

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

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

    
147
      return describeResponse;
148

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
432
    return resultPid;
433
  }
434

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

    
461

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

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

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

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

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

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

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

    
514
      LogEntry le = new LogEntry();
515

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

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

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

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

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

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

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

    
686
  /**
687
   * Return the system metadata for a given object
688
   * 
689
   * @param session - the Session object containing the credentials for the Subject
690
   * @param pid - the object identifier for the given object
691
   * 
692
   * @return inputStream - the input stream of the given system metadata object
693
   * 
694
   * @throws InvalidToken
695
   * @throws ServiceFailure
696
   * @throws NotAuthorized
697
   * @throws NotFound
698
   * @throws InvalidRequest
699
   * @throws NotImplemented
700
   */
701
    public SystemMetadata getSystemMetadata(Session session, Identifier pid)
702
        throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
703
        NotImplemented {
704

    
705
        boolean isAuthorized = false;
706
        SystemMetadata systemMetadata = null;
707
        List<Replica> replicaList = null;
708
        NodeReference replicaNodeRef = null;
709
        List<Node> nodeListBySubject = null;
710
        Subject subject = null;
711
        
712
        if (session != null ) {
713
            subject = session.getSubject();
714
        }
715
        
716
        // check normal authorization
717
        BaseException originalAuthorizationException = null;
718
        if (!isAuthorized) {
719
            try {
720
                isAuthorized = isAuthorized(session, pid, Permission.READ);
721

    
722
            } catch (InvalidRequest e) {
723
                throw new ServiceFailure("1090", e.getDescription());
724
            } catch (NotAuthorized nae) {
725
            	// catch this for later
726
            	originalAuthorizationException = nae;
727
			}
728
        }
729
        
730
        // get the system metadata first because we need the replica list for auth
731
        systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
732
        
733
        // check the replica information to expand access to MNs that might need it
734
        if (!isAuthorized) {
735
        	
736
	        try {
737
	        	
738
	            // if MNs are listed as replicas, allow access
739
	            if ( systemMetadata != null ) {
740
	                replicaList = systemMetadata.getReplicaList();
741
	                // only check if there are in fact replicas listed
742
	                if ( replicaList != null ) {
743
	                    
744
	                    if ( subject != null ) {
745
	                        // get the list of nodes with a matching node subject
746
	                        try {
747
	                            nodeListBySubject = listNodesBySubject(session.getSubject());
748
	
749
	                        } catch (BaseException e) {
750
	                            // Unexpected error contacting the CN via D1Client
751
	                            String msg = "Caught an unexpected error while trying "
752
	                                    + "to potentially authorize system metadata access "
753
	                                    + "based on the session subject. The error was "
754
	                                    + e.getMessage();
755
	                            logMetacat.error(msg);
756
	                            if (logMetacat.isDebugEnabled()) {
757
	                                e.printStackTrace();
758
	
759
	                            }
760
	                            // isAuthorized is still false 
761
	                        }
762
	
763
	                    }
764
	                    if (nodeListBySubject != null) {
765
	                        // compare node ids to replica node ids
766
	                        outer: for (Replica replica : replicaList) {
767
	                            replicaNodeRef = replica.getReplicaMemberNode();
768
	
769
	                            for (Node node : nodeListBySubject) {
770
	                                if (node.getIdentifier().equals(replicaNodeRef)) {
771
	                                    // node id via session subject matches a replica node
772
	                                    isAuthorized = true;
773
	                                    break outer;
774
	                                }
775
	                            }
776
	                        }
777
	                    }
778
	                }
779
	            }
780
	            
781
	            // if we still aren't authorized, then we are done
782
	            if (!isAuthorized) {
783
	                throw new NotAuthorized("1400", Permission.READ
784
	                        + " not allowed on " + pid.getValue());
785
	            }
786

    
787
	        } catch (RuntimeException e) {
788
	        	e.printStackTrace();
789
	            // convert hazelcast RuntimeException to ServiceFailure
790
	            throw new ServiceFailure("1090", "Unexpected error getting system metadata for: " + 
791
	                pid.getValue());	
792
	        }
793
	        
794
        }
795
        
796
        // It wasn't in the map
797
        if ( systemMetadata == null ) {
798
            throw new NotFound("1420", "No record found for: " + pid.getValue());
799
        }
800
        
801
        return systemMetadata;
802
    }
803
     
804
  /**
805
   * Test if the user identified by the provided token has administrative authorization 
806
   * 
807
   * @param session - the Session object containing the credentials for the Subject
808
   * 
809
   * @return true if the user is admin
810
   * 
811
   * @throws ServiceFailure
812
   * @throws InvalidToken
813
   * @throws NotFound
814
   * @throws NotAuthorized
815
   * @throws NotImplemented
816
   */
817
  public boolean isAdminAuthorized(Session session) 
818
      throws ServiceFailure, InvalidToken, NotAuthorized,
819
      NotImplemented {
820

    
821
      boolean allowed = false;
822
      
823
      // must have a session in order to check admin 
824
      if (session == null) {
825
         logMetacat.debug("In isAdminAuthorized(), session is null ");
826
         return false;
827
      }
828
      
829
      logMetacat.debug("In isAdminAuthorized(), checking CN or MN authorization for " +
830
           session.getSubject().getValue());
831
      
832
      // are we allowed to do this? only CNs are allowed
833
      CNode cn = D1Client.getCN();
834
      List<Node> nodes = cn.listNodes().getNodeList();
835
      
836
      if ( nodes == null ) {
837
          throw new ServiceFailure("4852", "Couldn't get node list.");
838
  
839
      }
840
      
841
      // find the node in the node list
842
      for ( Node node : nodes ) {
843
          
844
          NodeReference nodeReference = node.getIdentifier();
845
          logMetacat.debug("In isAdminAuthorized(), Node reference is: " + nodeReference.getValue());
846
          
847
          Subject subject = session.getSubject();
848
          
849
          if (node.getType() == NodeType.CN) {
850
              List<Subject> nodeSubjects = node.getSubjectList();
851
              
852
              // check if the session subject is in the node subject list
853
              for (Subject nodeSubject : nodeSubjects) {
854
                  logMetacat.debug("In isAdminAuthorized(), comparing subjects: " +
855
                      nodeSubject.getValue() + " and " + subject.getValue());
856
                  if ( nodeSubject.equals(subject) ) {
857
                      allowed = true; // subject of session == target node subject
858
                      break;
859
                      
860
                  }
861
              }              
862
          }
863
      }
864

    
865
      
866
      return allowed;
867
  }
868
  
869
  /**
870
   * Test if the user identified by the provided token has authorization 
871
   * for the operation on the specified object.
872
   * 
873
   * @param session - the Session object containing the credentials for the Subject
874
   * @param pid - The identifer of the resource for which access is being checked
875
   * @param operation - The type of operation which is being requested for the given pid
876
   *
877
   * @return true if the operation is allowed
878
   * 
879
   * @throws ServiceFailure
880
   * @throws InvalidToken
881
   * @throws NotFound
882
   * @throws NotAuthorized
883
   * @throws NotImplemented
884
   * @throws InvalidRequest
885
   */
886
  public boolean isAuthorized(Session session, Identifier pid, Permission permission)
887
    throws ServiceFailure, InvalidToken, NotFound, NotAuthorized,
888
    NotImplemented, InvalidRequest {
889

    
890
    boolean allowed = false;
891
    
892
    if (permission == null) {
893
    	throw new InvalidRequest("1761", "Permission was not provided or is invalid");
894
    }
895
    
896
    // permissions are hierarchical
897
    List<Permission> expandedPermissions = null;
898
    
899
    // always allow CN access
900
    if ( isAdminAuthorized(session) ) {
901
        allowed = true;
902
        return allowed;
903
        
904
    }
905
    
906
    // get the subject[s] from the session
907
	//defer to the shared util for recursively compiling the subjects	
908
	List<Subject> subjects = Arrays.asList(AuthUtils.authorizedClientSubjects(session));
909
    
910
    // get the system metadata
911
    String pidStr = pid.getValue();
912
    SystemMetadata systemMetadata = null;
913
    try {
914
        systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
915

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

    
996
  /** 
997
   * Determine if a given object should be treated as an XML science metadata
998
   * object. 
999
   * 
1000
   * @param sysmeta - the SystemMetadata describing the object
1001
   * @return true if the object should be treated as science metadata
1002
   */
1003
  public static boolean isScienceMetadata(SystemMetadata sysmeta) {
1004
    
1005
    ObjectFormat objectFormat = null;
1006
    boolean isScienceMetadata = false;
1007
    
1008
    try {
1009
      objectFormat = ObjectFormatCache.getInstance().getFormat(sysmeta.getFormatId());
1010
      if ( objectFormat.getFormatType().equals("METADATA") ) {
1011
      	isScienceMetadata = true;
1012
      	
1013
      }
1014
      
1015
       
1016
    } catch (ServiceFailure e) {
1017
      logMetacat.debug("There was a problem determining if the object identified by" + 
1018
          sysmeta.getIdentifier().getValue() + 
1019
          " is science metadata: " + e.getMessage());
1020
    
1021
    } catch (NotFound e) {
1022
      logMetacat.debug("There was a problem determining if the object identified by" + 
1023
          sysmeta.getIdentifier().getValue() + 
1024
          " is science metadata: " + e.getMessage());
1025
    
1026
    }
1027
    
1028
    return isScienceMetadata;
1029

    
1030
  }
1031
  
1032
  /**
1033
   * Insert or update an XML document into Metacat
1034
   * 
1035
   * @param xml - the XML document to insert or update
1036
   * @param pid - the identifier to be used for the resulting object
1037
   * 
1038
   * @return localId - the resulting docid of the document created or updated
1039
   * 
1040
   */
1041
  public String insertOrUpdateDocument(String xml, Identifier pid, 
1042
    Session session, String insertOrUpdate) 
1043
    throws ServiceFailure {
1044
    
1045
  	logMetacat.debug("Starting to insert xml document...");
1046
    IdentifierManager im = IdentifierManager.getInstance();
1047

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

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

    
1182
    logMetacat.debug("Case DATA: starting to write to disk.");
1183
	if (locked) {
1184

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

    
1239
  /**
1240
   * Insert a systemMetadata document and return its localId
1241
   */
1242
  public void insertSystemMetadata(SystemMetadata sysmeta) 
1243
      throws ServiceFailure {
1244
      
1245
  	  logMetacat.debug("Starting to insert SystemMetadata...");
1246
      sysmeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
1247
      logMetacat.debug("Inserting new system metadata with modified date " + 
1248
          sysmeta.getDateSysMetadataModified());
1249
      
1250
      //insert the system metadata
1251
      try {
1252
        // note: the calling subclass handles the map hazelcast lock/unlock
1253
      	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
1254
      	
1255
      } catch (Exception e) {
1256
          throw new ServiceFailure("1190", e.getMessage());
1257
          
1258
	    }  
1259
  }
1260

    
1261
  /**
1262
   * Update a systemMetadata document
1263
   * 
1264
   * @param sysMeta - the system metadata object in the system to update
1265
   */
1266
    protected void updateSystemMetadata(SystemMetadata sysMeta)
1267
        throws ServiceFailure {
1268

    
1269
        logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
1270
        sysMeta.setDateSysMetadataModified(new Date());
1271
        try {
1272
            HazelcastService.getInstance().getSystemMetadataMap().lock(sysMeta.getIdentifier());
1273
            HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
1274

    
1275
        } catch (Exception e) {
1276
            throw new ServiceFailure("4862", e.getMessage());
1277

    
1278
        } finally {
1279
            HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
1280

    
1281
        }
1282

    
1283
    }
1284
  
1285
  /**
1286
   * Given a Permission, returns a list of all permissions that it encompasses
1287
   * Permissions are hierarchical so that WRITE also allows READ.
1288
   * @param permission
1289
   * @return list of included Permissions for the given permission
1290
   */
1291
  protected List<Permission> expandPermissions(Permission permission) {
1292
	  	List<Permission> expandedPermissions = new ArrayList<Permission>();
1293
	    if (permission.equals(Permission.READ)) {
1294
	    	expandedPermissions.add(Permission.READ);
1295
	    }
1296
	    if (permission.equals(Permission.WRITE)) {
1297
	    	expandedPermissions.add(Permission.READ);
1298
	    	expandedPermissions.add(Permission.WRITE);
1299
	    }
1300
	    if (permission.equals(Permission.CHANGE_PERMISSION)) {
1301
	    	expandedPermissions.add(Permission.READ);
1302
	    	expandedPermissions.add(Permission.WRITE);
1303
	    	expandedPermissions.add(Permission.CHANGE_PERMISSION);
1304
	    }
1305
	    return expandedPermissions;
1306
  }
1307

    
1308
  /*
1309
   * Write a stream to a file
1310
   * 
1311
   * @param dir - the directory to write to
1312
   * @param fileName - the file name to write to
1313
   * @param data - the object bytes as an input stream
1314
   * 
1315
   * @return newFile - the new file created
1316
   * 
1317
   * @throws ServiceFailure
1318
   */
1319
  private File writeStreamToFile(File dir, String fileName, InputStream data) 
1320
    throws ServiceFailure {
1321
    
1322
    File newFile = new File(dir, fileName);
1323
    logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1324

    
1325
    try {
1326
        if (newFile.createNewFile()) {
1327
          // write data stream to desired file
1328
          OutputStream os = new FileOutputStream(newFile);
1329
          long length = IOUtils.copyLarge(data, os);
1330
          os.flush();
1331
          os.close();
1332
        } else {
1333
          logMetacat.debug("File creation failed, or file already exists.");
1334
          throw new ServiceFailure("1190", "File already exists: " + fileName);
1335
        }
1336
    } catch (FileNotFoundException e) {
1337
      logMetacat.debug("FNF: " + e.getMessage());
1338
      throw new ServiceFailure("1190", "File not found: " + fileName + " " 
1339
                + e.getMessage());
1340
    } catch (IOException e) {
1341
      logMetacat.debug("IOE: " + e.getMessage());
1342
      throw new ServiceFailure("1190", "File was not written: " + fileName 
1343
                + " " + e.getMessage());
1344
    }
1345

    
1346
    return newFile;
1347
  }
1348

    
1349
  /*
1350
   * Returns a list of nodes that have been registered with the DataONE infrastructure
1351
   * that match the given session subject
1352
   * @return nodes - List of nodes from the registry with a matching session subject
1353
   * 
1354
   * @throws ServiceFailure
1355
   * @throws NotImplemented
1356
   */
1357
  protected List<Node> listNodesBySubject(Subject subject) 
1358
      throws ServiceFailure, NotImplemented {
1359
      List<Node> nodeList = new ArrayList<Node>();
1360
      
1361
      CNode cn = D1Client.getCN();
1362
      List<Node> nodes = cn.listNodes().getNodeList();
1363
      
1364
      // find the node in the node list
1365
      for ( Node node : nodes ) {
1366
          
1367
          List<Subject> nodeSubjects = node.getSubjectList();
1368
          if (nodeSubjects != null) {    
1369
	          // check if the session subject is in the node subject list
1370
	          for (Subject nodeSubject : nodeSubjects) {
1371
	              if ( nodeSubject.equals(subject) ) { // subject of session == node subject
1372
	                  nodeList.add(node);  
1373
	              }                              
1374
	          }
1375
          }
1376
      }
1377
      
1378
      return nodeList;
1379
      
1380
  }
1381

    
1382

    
1383
}
(2-2/5)