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-19 14:04:10 -0700 (Thu, 19 Apr 2012) $'
8
 *
9
 * This program is free software; you can redistribute it and/or modify
10
 * it under the terms of the GNU General Public License as published by
11
 * the Free Software Foundation; either version 2 of the License, or
12
 * (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program; if not, write to the Free Software
21
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22
 */
23

    
24
package edu.ucsb.nceas.metacat.dataone;
25

    
26
import java.io.File;
27
import java.io.FileNotFoundException;
28
import java.io.FileOutputStream;
29
import java.io.IOException;
30
import java.io.InputStream;
31
import java.io.OutputStream;
32
import java.sql.SQLException;
33
import java.util.ArrayList;
34
import java.util.Calendar;
35
import java.util.Date;
36
import java.util.Hashtable;
37
import java.util.List;
38
import java.util.Timer;
39
import java.util.Vector;
40

    
41
import javax.servlet.http.HttpServletRequest;
42

    
43

    
44
import org.apache.commons.io.IOUtils;
45
import org.apache.log4j.Logger;
46
import org.dataone.client.CNode;
47
import org.dataone.client.D1Client;
48
import org.dataone.client.ObjectFormatCache;
49
import org.dataone.service.util.Constants;
50
import org.dataone.service.util.DateTimeMarshaller;
51
import org.dataone.service.exceptions.BaseException;
52
import org.dataone.service.exceptions.IdentifierNotUnique;
53
import org.dataone.service.exceptions.InsufficientResources;
54
import org.dataone.service.exceptions.InvalidRequest;
55
import org.dataone.service.exceptions.InvalidSystemMetadata;
56
import org.dataone.service.exceptions.InvalidToken;
57
import org.dataone.service.exceptions.NotAuthorized;
58
import org.dataone.service.exceptions.NotFound;
59
import org.dataone.service.exceptions.NotImplemented;
60
import org.dataone.service.exceptions.ServiceFailure;
61
import org.dataone.service.exceptions.UnsupportedType;
62
import org.dataone.service.types.v1.AccessPolicy;
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.NodeList;
72
import org.dataone.service.types.v1.NodeReference;
73
import org.dataone.service.types.v1.NodeType;
74
import org.dataone.service.types.v1.ObjectFormat;
75
import org.dataone.service.types.v1.Permission;
76
import org.dataone.service.types.v1.Person;
77
import org.dataone.service.types.v1.Replica;
78
import org.dataone.service.types.v1.ReplicationStatus;
79
import org.dataone.service.types.v1.Session;
80
import org.dataone.service.types.v1.Subject;
81
import org.dataone.service.types.v1.SubjectInfo;
82
import org.dataone.service.types.v1.SubjectList;
83
import org.dataone.service.types.v1.SystemMetadata;
84
import org.dataone.service.types.v1.util.ChecksumUtil;
85

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

    
102
public abstract class D1NodeService {
103
  
104
  private static Logger logMetacat = Logger.getLogger(D1NodeService.class);
105

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

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

    
145
    // get system metadata and construct the describe response
146
      SystemMetadata sysmeta = getSystemMetadata(session, pid);
147
      DescribeResponse describeResponse = 
148
      	new DescribeResponse(sysmeta.getFormatId(), sysmeta.getSize(), 
149
      			sysmeta.getDateSysMetadataModified(),
150
      			sysmeta.getChecksum(), sysmeta.getSerialVersion());
151

    
152
      return describeResponse;
153

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

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

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

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

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

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

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

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

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

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

    
241
      } else {
242
          throw new NotAuthorized("1320", "The provided identity does not have " + "permission to DELETE objects on the Member Node.");
243
      }
244

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

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

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

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

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

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

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

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

    
406
        }
407
                    
408
      } else {
409
	        
410
	      // DEFAULT CASE: DATA (needs to be checked and completed)
411
	      localId = insertDataObject(object, pid, session);
412
      }   
413
    
414
    }
415

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

    
433
    resultPid = pid;
434
    
435
    logMetacat.debug("create() complete for object: " + pid.getValue());
436

    
437
    return resultPid;
438
  }
439

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

    
466

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

    
480
    if ( start == null ) {
481
    	start = 0;
482
    	
483
    }
484
    
485
    if ( count == null ) {
486
    	count = 1000;
487
    	
488
    }
489

    
490
    logMetacat.debug("fromDate: " + fromDate);
491
    logMetacat.debug("toDate: " + toDate);
492

    
493
    String report = el.getReport(null, null, null, null,
494
        new java.sql.Timestamp(fromDate.getTime()),
495
        new java.sql.Timestamp(toDate.getTime()), false);
496

    
497
    logMetacat.debug("report: " + report);
498

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

    
511
      String entryId = getLogEntryField("entryid", entry);
512
      String ipAddress = getLogEntryField("ipAddress", entry);
513
      String principal = getLogEntryField("principal", entry);
514
      String userAgent = getLogEntryField("userAgent", entry);
515
      String docid = getLogEntryField("docid", entry);
516
      String eventS = getLogEntryField("event", entry);
517
      String dateLogged = getLogEntryField("dateLogged", entry);
518

    
519
      LogEntry le = new LogEntry();
520

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

    
551
          logMetacat.warn("could not find pid for docid '" + docid + "'");
552

    
553
        // skip it if the pid can't be found
554
        continue;
555
      }
556

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

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

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

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

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

    
710
        boolean isAuthorized = false;
711
        SystemMetadata systemMetadata = null;
712
        List<Replica> replicaList = null;
713
        NodeReference replicaNodeRef = null;
714
        List<Node> nodeListBySubject = null;
715
        Subject subject = null;
716
        
717
        if (session != null ) {
718
            subject = session.getSubject();
719
        }
720
        
721
        try {
722
            // get the system metadata first because we need the replica list for auth
723
            systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
724

    
725
            // if MNs are listed as replicas, allow access
726
            if ( systemMetadata != null ) {
727
                replicaList = systemMetadata.getReplicaList();
728
                // only check if there are in fact replicas listed
729
                if ( replicaList != null ) {
730
                    
731
                    if ( subject != null ) {
732
                        // get the list of nodes with a matching node subject
733
                        try {
734
                            nodeListBySubject = listNodesBySubject(session
735
                                    .getSubject());
736

    
737
                        } catch (BaseException e) {
738
                            // Unexpected error contacting the CN via D1Client
739
                            String msg = "Caught an unexpected error while trying "
740
                                    + "to potentially authorize system metadata access "
741
                                    + "based on the session subject. The error was "
742
                                    + e.getMessage();
743
                            logMetacat.error(msg);
744
                            if (logMetacat.isDebugEnabled()) {
745
                                e.printStackTrace();
746

    
747
                            }
748
                            // isAuthorized is still false 
749
                        }
750

    
751
                    }
752
                    if (nodeListBySubject != null) {
753
                        // compare node ids to replica node ids
754
                        outer: for (Replica replica : replicaList) {
755
                            replicaNodeRef = replica.getReplicaMemberNode();
756

    
757
                            for (Node node : nodeListBySubject) {
758
                                if (node.getIdentifier().equals(replicaNodeRef)) {
759
                                    // node id via session subject matches a replica node
760
                                    isAuthorized = true;
761
                                    break outer;
762
                                }
763
                            }
764
                        }
765
                    }
766
                }
767
            }
768
            
769
            if (!isAuthorized) {
770
                try {
771
                    isAuthorized = isAuthorized(session, pid, Permission.READ);
772

    
773
                } catch (InvalidRequest e) {
774
                    throw new ServiceFailure("1090", e.getDescription());
775

    
776
                }
777
            }
778
            
779
            if (!isAuthorized) {
780
                throw new NotAuthorized("1400", Permission.READ
781
                        + " not allowed on " + pid.getValue());
782
            }
783
        
784
        } catch (RuntimeException e) {
785
        	e.printStackTrace();
786
            // convert hazelcast RuntimeException to ServiceFailure
787
            throw new ServiceFailure("1090", "Unexpected error getting system metadata for: " + 
788
                pid.getValue());
789

    
790
        }
791

    
792
        // It wasn't in the map
793
        if ( systemMetadata == null ) {
794
            throw new NotFound("1420", "No record found for: " + pid.getValue());
795

    
796
        }
797
        
798
        return systemMetadata;
799
    }
800
     
801
  /**
802
   * Test if the user identified by the provided token has administrative authorization 
803
   * 
804
   * @param session - the Session object containing the credentials for the Subject
805
   * 
806
   * @return true if the user is admin
807
   * 
808
   * @throws ServiceFailure
809
   * @throws InvalidToken
810
   * @throws NotFound
811
   * @throws NotAuthorized
812
   * @throws NotImplemented
813
   */
814
  public boolean isAdminAuthorized(Session session) 
815
      throws ServiceFailure, InvalidToken, NotAuthorized,
816
      NotImplemented {
817

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

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

    
887
    boolean allowed = false;
888
    
889
    if (permission == null) {
890
    	throw new InvalidRequest("1761", "Permission was not provided or is invalid");
891
    }
892
    
893
    // permissions are hierarchical
894
    List<Permission> expandedPermissions = null;
895
    
896
    // always allow CN access
897
    if ( isAdminAuthorized(session) ) {
898
        allowed = true;
899
        return allowed;
900
        
901
    }
902
    
903
    // for the "Verified" symbolic user
904
    Subject verifiedSubject = new Subject();
905
	verifiedSubject.setValue(Constants.SUBJECT_VERIFIED_USER);
906
    
907
    // get the subject[s] from the session
908
	List<Subject> subjects = new ArrayList<Subject>();
909
	if (session != null) {
910
		// primary subject
911
		Subject subject = session.getSubject();
912
		if (subject != null) {
913
			subjects.add(subject);
914
		}
915
		// details about the subject
916
		SubjectInfo subjectInfo = session.getSubjectInfo();
917
		if (subjectInfo != null) {
918
			// find subjectInfo for the primary subject
919
			List<Person> personList = subjectInfo.getPersonList();
920
			List<Group> groupList = subjectInfo.getGroupList();
921
			if (personList != null) {
922
				for (Person p : personList) {
923
					  // for every person listed (isVerified is transitive)
924
						logMetacat.debug("checking person");
925
						logMetacat.debug("p.getVerified(): " + p.getVerified());
926
						if (p.getVerified() != null && p.getVerified()) {
927
							// add the verified symbolic user
928
							if (!subjects.contains(verifiedSubject)) {
929
								subjects.add(verifiedSubject);
930
							}
931
						}
932
						// add the equivalent identities
933
						List<Subject> equivList = p.getEquivalentIdentityList();
934
						if (equivList != null) {
935
							for (Subject equivSubject : equivList) {
936
								subjects.add(equivSubject);
937
								// find that entry
938
								for (Person equivPerson: personList) {
939
									if (equivSubject.equals(equivPerson.getSubject())) {
940
										// transitive group membership
941
										if (equivPerson.getIsMemberOfList() != null) {
942
											for (Subject equivGroup: equivPerson.getIsMemberOfList()) {
943
												subjects.add(equivGroup);
944
											}
945
										}
946
										// TODO: is verified transitive?
947
										if (equivPerson.getVerified() != null && equivPerson.getVerified()) {
948
											// add the verified symbolic user
949
											if (!subjects.contains(verifiedSubject)) {
950
												subjects.add(verifiedSubject);
951
											}
952
										}
953
									}
954
								}
955
							}
956
						}
957
						// add the groups they are a member of
958
						List<Subject> memberOfList = p.getIsMemberOfList();
959
						if (memberOfList != null) {
960
							for (Subject g : memberOfList) {
961
								subjects.add(g);
962
							}
963
						}
964
						// look at all the Groups to see if this person has membership defined there
965
						if (groupList != null) {
966
							for (Group group: groupList) {
967
								if (group.getHasMemberList() != null) {
968
									for (Subject member: group.getHasMemberList()) {
969
										// is the person a member?
970
										if (member.equals(p.getSubject())) {
971
											// add this group as a subject to check if it is not already there
972
											if (!subjects.contains(group.getSubject())) {
973
												subjects.add(group.getSubject());
974
											}
975
										}
976
									}
977
								}
978
							}
979
						}
980
						break;
981
				}
982
			}
983
		}
984

    
985
		// add the authenticated symbolic since we have a session
986
		Subject authenticatedSubject = new Subject();
987
		authenticatedSubject.setValue(Constants.SUBJECT_AUTHENTICATED_USER);
988
		subjects.add(authenticatedSubject);
989
	}
990

    
991
    // add public subject for everyone
992
    Subject publicSubject = new Subject();
993
    publicSubject.setValue(Constants.SUBJECT_PUBLIC);
994
    subjects.add(publicSubject);
995
    
996
    // get the system metadata
997
    String pidStr = pid.getValue();
998
    SystemMetadata systemMetadata = null;
999
    try {
1000
        systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
1001

    
1002
    } catch (Exception e) {
1003
        // convert Hazelcast RuntimeException to NotFound
1004
        logMetacat.error("An error occurred while getting system metadata for identifier " +
1005
            pid.getValue() + ". The error message was: " + e.getMessage());
1006
        throw new NotFound("1800", "No record found for " + pidStr);
1007
        
1008
    } 
1009
    
1010
    // throw not found if it was not found
1011
    if (systemMetadata == null) {
1012
    	throw new NotFound("1800", "No system metadata could be found for given PID: " + pidStr);
1013
    }
1014
	    
1015
    // do we own it?
1016
    for (Subject s: subjects) {
1017
      logMetacat.debug("Comparing \t" + 
1018
                       systemMetadata.getRightsHolder().getValue() +
1019
                       " \tagainst \t" + s.getValue());
1020
    	allowed = systemMetadata.getRightsHolder().equals(s);
1021
    	if (allowed) {
1022
    		return allowed;
1023
    	}
1024
    }    
1025
    
1026
    // otherwise check the access rules
1027
    try {
1028
	    List<AccessRule> allows = systemMetadata.getAccessPolicy().getAllowList();
1029
	    search: // label break
1030
	    for (AccessRule accessRule: allows) {
1031
	      for (Subject s: subjects) {
1032
	        logMetacat.debug("Checking allow access rule for subject: " + s.getValue());
1033
	        if (accessRule.getSubjectList().contains(s)) {
1034
	        	logMetacat.debug("Access rule contains subject: " + s.getValue());
1035
	        	for (Permission p: accessRule.getPermissionList()) {
1036
		        	logMetacat.debug("Checking permission: " + p.xmlValue());
1037
	        		expandedPermissions = expandPermissions(p);
1038
	        		allowed = expandedPermissions.contains(permission);
1039
	        		if (allowed) {
1040
			        	logMetacat.info("Permission granted: " + p.xmlValue() + " to " + s.getValue());
1041
	        			break search; //label break
1042
	        		}
1043
	        	}
1044
        		
1045
	        }
1046
	      }
1047
	    }
1048
    } catch (Exception e) {
1049
    	// catch all for errors - safe side should be to deny the access
1050
    	logMetacat.error("Problem checking authorization - defaulting to deny", e);
1051
		allowed = false;
1052
	  
1053
    }
1054
    
1055
    // throw or return?
1056
    if (!allowed) {
1057
      throw new NotAuthorized("1820", permission + " not allowed on " + pidStr);
1058
    }
1059
    
1060
    return allowed;
1061
    
1062
  }
1063
  
1064
  /*
1065
   * parse a logEntry and get the relevant field from it
1066
   * 
1067
   * @param fieldname
1068
   * @param entry
1069
   * @return
1070
   */
1071
  private String getLogEntryField(String fieldname, String entry) {
1072
    String begin = "<" + fieldname + ">";
1073
    String end = "</" + fieldname + ">";
1074
    // logMetacat.debug("looking for " + begin + " and " + end +
1075
    // " in entry " + entry);
1076
    String s = entry.substring(entry.indexOf(begin) + begin.length(), entry
1077
        .indexOf(end));
1078
    logMetacat.debug("entry " + fieldname + " : " + s);
1079
    return s;
1080
  }
1081

    
1082
  /** 
1083
   * Determine if a given object should be treated as an XML science metadata
1084
   * object. 
1085
   * 
1086
   * @param sysmeta - the SystemMetadata describing the object
1087
   * @return true if the object should be treated as science metadata
1088
   */
1089
  public static boolean isScienceMetadata(SystemMetadata sysmeta) {
1090
    
1091
    ObjectFormat objectFormat = null;
1092
    boolean isScienceMetadata = false;
1093
    
1094
    try {
1095
      objectFormat = ObjectFormatCache.getInstance().getFormat(sysmeta.getFormatId());
1096
      if ( objectFormat.getFormatType().equals("METADATA") ) {
1097
      	isScienceMetadata = true;
1098
      	
1099
      }
1100
      
1101
       
1102
    } catch (ServiceFailure e) {
1103
      logMetacat.debug("There was a problem determining if the object identified by" + 
1104
          sysmeta.getIdentifier().getValue() + 
1105
          " is science metadata: " + e.getMessage());
1106
    
1107
    } catch (NotFound e) {
1108
      logMetacat.debug("There was a problem determining if the object identified by" + 
1109
          sysmeta.getIdentifier().getValue() + 
1110
          " is science metadata: " + e.getMessage());
1111
    
1112
    }
1113
    
1114
    return isScienceMetadata;
1115

    
1116
  }
1117
  
1118
  /**
1119
   * Insert or update an XML document into Metacat
1120
   * 
1121
   * @param xml - the XML document to insert or update
1122
   * @param pid - the identifier to be used for the resulting object
1123
   * 
1124
   * @return localId - the resulting docid of the document created or updated
1125
   * 
1126
   */
1127
  public String insertOrUpdateDocument(String xml, Identifier pid, 
1128
    Session session, String insertOrUpdate) 
1129
    throws ServiceFailure {
1130
    
1131
  	logMetacat.debug("Starting to insert xml document...");
1132
    IdentifierManager im = IdentifierManager.getInstance();
1133

    
1134
    // generate pid/localId pair for sysmeta
1135
    String localId = null;
1136
    
1137
    if(insertOrUpdate.equals("insert")) {
1138
      localId = im.generateLocalId(pid.getValue(), 1);
1139
      
1140
    } else {
1141
      //localid should already exist in the identifier table, so just find it
1142
      try {
1143
        logMetacat.debug("Updating pid " + pid.getValue());
1144
        logMetacat.debug("looking in identifier table for pid " + pid.getValue());
1145
        
1146
        localId = im.getLocalId(pid.getValue());
1147
        
1148
        logMetacat.debug("localId: " + localId);
1149
        //increment the revision
1150
        String docid = localId.substring(0, localId.lastIndexOf("."));
1151
        String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
1152
        int rev = new Integer(revS).intValue();
1153
        rev++;
1154
        docid = docid + "." + rev;
1155
        localId = docid;
1156
        logMetacat.debug("incremented localId: " + localId);
1157
      
1158
      } catch(McdbDocNotFoundException e) {
1159
        throw new ServiceFailure("1030", "D1NodeService.insertOrUpdateDocument(): " +
1160
            "pid " + pid.getValue() + 
1161
            " should have been in the identifier table, but it wasn't: " + 
1162
            e.getMessage());
1163
      
1164
      }
1165
      
1166
    }
1167

    
1168
    params = new Hashtable<String, String[]>();
1169
    String[] action = new String[1];
1170
    action[0] = insertOrUpdate;
1171
    params.put("action", action);
1172
    String[] docid = new String[1];
1173
    docid[0] = localId;
1174
    params.put("docid", docid);
1175
    String[] doctext = new String[1];
1176
    doctext[0] = xml;
1177
    params.put("doctext", doctext);
1178
    
1179
    String username = Constants.SUBJECT_PUBLIC;
1180
    String[] groupnames = null;
1181
    if (session != null ) {
1182
    	username = session.getSubject().getValue();
1183
    	if (session.getSubjectInfo() != null) {
1184
    		List<Group> groupList = session.getSubjectInfo().getGroupList();
1185
    		if (groupList != null) {
1186
    			groupnames = new String[groupList.size()];
1187
    			for (int i = 0; i > groupList.size(); i++ ) {
1188
    				groupnames[i] = groupList.get(i).getGroupName();
1189
    			}
1190
    		}
1191
    	}
1192
    }
1193
    
1194
    // do the insert or update action
1195
    handler = new MetacatHandler(new Timer());
1196
    String result = handler.handleInsertOrUpdateAction(request.getRemoteAddr(), request.getHeader("User-Agent"), null, 
1197
                        null, params, username, groupnames, false, false);
1198
    
1199
    if(result.indexOf("<error>") != -1) {
1200
    	String detailCode = "";
1201
    	if ( insertOrUpdate.equals("insert") ) {
1202
    		// make sure to remove the mapping so that subsequent attempts do not fail with IdentifierNotUnique
1203
    		im.removeMapping(pid.getValue(), localId);
1204
    		detailCode = "1190";
1205
    		
1206
    	} else if ( insertOrUpdate.equals("update") ) {
1207
    		detailCode = "1310";
1208
    		
1209
    	}
1210
        throw new ServiceFailure(detailCode, 
1211
          "Error inserting or updating document: " + result);
1212
    }
1213
    logMetacat.debug("Finsished inserting xml document with id " + localId);
1214
    
1215
    return localId;
1216
  }
1217
  
1218
  /**
1219
   * Insert a data document
1220
   * 
1221
   * @param object
1222
   * @param pid
1223
   * @param sessionData
1224
   * @throws ServiceFailure
1225
   * @returns localId of the data object inserted
1226
   */
1227
  public String insertDataObject(InputStream object, Identifier pid, 
1228
          Session session) throws ServiceFailure {
1229
      
1230
    String username = Constants.SUBJECT_PUBLIC;
1231
    String[] groupnames = null;
1232
    if (session != null ) {
1233
    	username = session.getSubject().getValue();
1234
    	if (session.getSubjectInfo() != null) {
1235
    		List<Group> groupList = session.getSubjectInfo().getGroupList();
1236
    		if (groupList != null) {
1237
    			groupnames = new String[groupList.size()];
1238
    			for (int i = 0; i > groupList.size(); i++ ) {
1239
    				groupnames[i] = groupList.get(i).getGroupName();
1240
    			}
1241
    		}
1242
    	}
1243
    }
1244
  
1245
    // generate pid/localId pair for object
1246
    logMetacat.debug("Generating a pid/localId mapping");
1247
    IdentifierManager im = IdentifierManager.getInstance();
1248
    String localId = im.generateLocalId(pid.getValue(), 1);
1249
  
1250
    // Save the data file to disk using "localId" as the name
1251
    String datafilepath = null;
1252
	try {
1253
		datafilepath = PropertyService.getProperty("application.datafilepath");
1254
	} catch (PropertyNotFoundException e) {
1255
		ServiceFailure sf = new ServiceFailure("1190", "Lookup data file path" + e.getMessage());
1256
		sf.initCause(e);
1257
		throw sf;
1258
	}
1259
    boolean locked = false;
1260
	try {
1261
		locked = DocumentImpl.getDataFileLockGrant(localId);
1262
	} catch (Exception e) {
1263
		ServiceFailure sf = new ServiceFailure("1190", "Could not lock file for writing:" + e.getMessage());
1264
		sf.initCause(e);
1265
		throw sf;
1266
	}
1267

    
1268
    logMetacat.debug("Case DATA: starting to write to disk.");
1269
	if (locked) {
1270

    
1271
          File dataDirectory = new File(datafilepath);
1272
          dataDirectory.mkdirs();
1273
  
1274
          File newFile = writeStreamToFile(dataDirectory, localId, object);
1275
  
1276
          // TODO: Check that the file size matches SystemMetadata
1277
          // long size = newFile.length();
1278
          // if (size == 0) {
1279
          //     throw new IOException("Uploaded file is 0 bytes!");
1280
          // }
1281
  
1282
          // Register the file in the database (which generates an exception
1283
          // if the localId is not acceptable or other untoward things happen
1284
          try {
1285
            logMetacat.debug("Registering document...");
1286
            DocumentImpl.registerDocument(localId, "BIN", localId,
1287
                    username, groupnames);
1288
            logMetacat.debug("Registration step completed.");
1289
            
1290
          } catch (SQLException e) {
1291
            //newFile.delete();
1292
            logMetacat.debug("SQLE: " + e.getMessage());
1293
            e.printStackTrace(System.out);
1294
            throw new ServiceFailure("1190", "Registration failed: " + 
1295
            		e.getMessage());
1296
            
1297
          } catch (AccessionNumberException e) {
1298
            //newFile.delete();
1299
            logMetacat.debug("ANE: " + e.getMessage());
1300
            e.printStackTrace(System.out);
1301
            throw new ServiceFailure("1190", "Registration failed: " + 
1302
            	e.getMessage());
1303
            
1304
          } catch (Exception e) {
1305
            //newFile.delete();
1306
            logMetacat.debug("Exception: " + e.getMessage());
1307
            e.printStackTrace(System.out);
1308
            throw new ServiceFailure("1190", "Registration failed: " + 
1309
            	e.getMessage());
1310
          }
1311
  
1312
          logMetacat.debug("Logging the creation event.");
1313
          EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, "create");
1314
  
1315
          // Schedule replication for this data file
1316
          logMetacat.debug("Scheduling replication.");
1317
          ForceReplicationHandler frh = new ForceReplicationHandler(
1318
            localId, "create", false, null);
1319
      }
1320
      
1321
      return localId;
1322
    
1323
  }
1324

    
1325
  /**
1326
   * Insert a systemMetadata document and return its localId
1327
   */
1328
  public void insertSystemMetadata(SystemMetadata sysmeta) 
1329
      throws ServiceFailure {
1330
      
1331
  	  logMetacat.debug("Starting to insert SystemMetadata...");
1332
      sysmeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
1333
      logMetacat.debug("Inserting new system metadata with modified date " + 
1334
          sysmeta.getDateSysMetadataModified());
1335
      
1336
      //insert the system metadata
1337
      try {
1338
        // note: the calling subclass handles the map hazelcast lock/unlock
1339
      	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
1340
      	
1341
      } catch (Exception e) {
1342
          throw new ServiceFailure("1190", e.getMessage());
1343
          
1344
	    }  
1345
  }
1346

    
1347
  /**
1348
   * Update a systemMetadata document
1349
   * 
1350
   * @param sysMeta - the system metadata object in the system to update
1351
   */
1352
    protected void updateSystemMetadata(SystemMetadata sysMeta)
1353
        throws ServiceFailure {
1354

    
1355
        logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
1356
        sysMeta.setDateSysMetadataModified(new Date());
1357
        try {
1358
            HazelcastService.getInstance().getSystemMetadataMap().lock(sysMeta.getIdentifier());
1359
            HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
1360

    
1361
        } catch (Exception e) {
1362
            throw new ServiceFailure("4862", e.getMessage());
1363

    
1364
        } finally {
1365
            HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
1366

    
1367
        }
1368

    
1369
    }
1370
  
1371
  /**
1372
   * Given a Permission, returns a list of all permissions that it encompasses
1373
   * Permissions are hierarchical so that WRITE also allows READ.
1374
   * @param permission
1375
   * @return list of included Permissions for the given permission
1376
   */
1377
  protected List<Permission> expandPermissions(Permission permission) {
1378
	  	List<Permission> expandedPermissions = new ArrayList<Permission>();
1379
	    if (permission.equals(Permission.READ)) {
1380
	    	expandedPermissions.add(Permission.READ);
1381
	    }
1382
	    if (permission.equals(Permission.WRITE)) {
1383
	    	expandedPermissions.add(Permission.READ);
1384
	    	expandedPermissions.add(Permission.WRITE);
1385
	    }
1386
	    if (permission.equals(Permission.CHANGE_PERMISSION)) {
1387
	    	expandedPermissions.add(Permission.READ);
1388
	    	expandedPermissions.add(Permission.WRITE);
1389
	    	expandedPermissions.add(Permission.CHANGE_PERMISSION);
1390
	    }
1391
	    return expandedPermissions;
1392
  }
1393

    
1394
  /*
1395
   * Write a stream to a file
1396
   * 
1397
   * @param dir - the directory to write to
1398
   * @param fileName - the file name to write to
1399
   * @param data - the object bytes as an input stream
1400
   * 
1401
   * @return newFile - the new file created
1402
   * 
1403
   * @throws ServiceFailure
1404
   */
1405
  private File writeStreamToFile(File dir, String fileName, InputStream data) 
1406
    throws ServiceFailure {
1407
    
1408
    File newFile = new File(dir, fileName);
1409
    logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1410

    
1411
    try {
1412
        if (newFile.createNewFile()) {
1413
          // write data stream to desired file
1414
          OutputStream os = new FileOutputStream(newFile);
1415
          long length = IOUtils.copyLarge(data, os);
1416
          os.flush();
1417
          os.close();
1418
        } else {
1419
          logMetacat.debug("File creation failed, or file already exists.");
1420
          throw new ServiceFailure("1190", "File already exists: " + fileName);
1421
        }
1422
    } catch (FileNotFoundException e) {
1423
      logMetacat.debug("FNF: " + e.getMessage());
1424
      throw new ServiceFailure("1190", "File not found: " + fileName + " " 
1425
                + e.getMessage());
1426
    } catch (IOException e) {
1427
      logMetacat.debug("IOE: " + e.getMessage());
1428
      throw new ServiceFailure("1190", "File was not written: " + fileName 
1429
                + " " + e.getMessage());
1430
    }
1431

    
1432
    return newFile;
1433
  }
1434

    
1435
  /*
1436
   * Returns a list of nodes that have been registered with the DataONE infrastructure
1437
   * that match the given session subject
1438
   * @return nodes - List of nodes from the registry with a matching session subject
1439
   * 
1440
   * @throws ServiceFailure
1441
   * @throws NotImplemented
1442
   */
1443
  protected List<Node> listNodesBySubject(Subject subject) 
1444
      throws ServiceFailure, NotImplemented {
1445
      List<Node> nodeList = new ArrayList<Node>();
1446
      
1447
      CNode cn = D1Client.getCN();
1448
      List<Node> nodes = cn.listNodes().getNodeList();
1449
      
1450
      // find the node in the node list
1451
      for ( Node node : nodes ) {
1452
          
1453
          List<Subject> nodeSubjects = node.getSubjectList();
1454
          if (nodeSubjects != null) {    
1455
	          // check if the session subject is in the node subject list
1456
	          for (Subject nodeSubject : nodeSubjects) {
1457
	              if ( nodeSubject.equals(subject) ) { // subject of session == node subject
1458
	                  nodeList.add(node);  
1459
	              }                              
1460
	          }
1461
          }
1462
      }
1463
      
1464
      return nodeList;
1465
      
1466
  }
1467

    
1468

    
1469
}
(2-2/5)