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: cjones $'
7
 *     '$Date: 2012-06-05 14:07:13 -0700 (Tue, 05 Jun 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.Set;
40
import java.util.Timer;
41
import java.util.Vector;
42

    
43
import javax.servlet.http.HttpServletRequest;
44

    
45

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

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

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

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

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

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

    
148
      return describeResponse;
149

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

    
171
      String localId = null;
172
      if (session == null) {
173
      	throw new InvalidToken("1330", "No session has been provided");
174
      }
175
      // just for logging purposes
176
      String username = session.getSubject().getValue();
177

    
178
      // do we have a valid pid?
179
      if (pid == null || pid.getValue().trim().equals("")) {
180
          throw new ServiceFailure("1350", "The provided identifier was invalid.");
181
      }
182

    
183
      // check for the existing identifier
184
      try {
185
          localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
186
      } catch (McdbDocNotFoundException e) {
187
          throw new NotFound("1340", "The object with the provided " + "identifier was not found.");
188
      }
189
      
190
      try {
191
          // delete the document, as admin
192
          DocumentImpl.delete(localId, null, null, null, true);
193
          EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, Event.DELETE.xmlValue());
194

    
195
          // archive it
196
          SystemMetadata sysMeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
197
          sysMeta.setArchived(true);
198
          sysMeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
199
          HazelcastService.getInstance().getSystemMetadataMap().put(pid, sysMeta);
200
          
201
      } catch (McdbDocNotFoundException e) {
202
          throw new NotFound("1340", "The provided identifier was invalid.");
203

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

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

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

    
214
      return pid;
215
  }
216
  
217
  /**
218
   * Low level, "are you alive" operation. A valid ping response is 
219
   * indicated by a HTTP status of 200.
220
   * 
221
   * @return true if the service is alive
222
   * 
223
   * @throws NotImplemented
224
   * @throws ServiceFailure
225
   * @throws InsufficientResources
226
   */
227
  public Date ping() 
228
      throws NotImplemented, ServiceFailure, InsufficientResources {
229

    
230
      // test if we can get a database connection
231
      int serialNumber = -1;
232
      DBConnection dbConn = null;
233
      try {
234
          dbConn = DBConnectionPool.getDBConnection("MNodeService.ping");
235
          serialNumber = dbConn.getCheckOutSerialNumber();
236
      } catch (SQLException e) {
237
      	ServiceFailure sf = new ServiceFailure("", e.getMessage());
238
      	sf.initCause(e);
239
          throw sf;
240
      } finally {
241
          // Return the database connection
242
          DBConnectionPool.returnDBConnection(dbConn, serialNumber);
243
      }
244

    
245
      return Calendar.getInstance().getTime();
246
  }
247
  
248
  /**
249
   * Adds a new object to the Node, where the object is either a data 
250
   * object or a science metadata object. This method is called by clients 
251
   * to create new data objects on Member Nodes or internally for Coordinating
252
   * Nodes
253
   * 
254
   * @param session - the Session object containing the credentials for the Subject
255
   * @param pid - The object identifier to be created
256
   * @param object - the object bytes
257
   * @param sysmeta - the system metadata that describes the object  
258
   * 
259
   * @return pid - the object identifier created
260
   * 
261
   * @throws InvalidToken
262
   * @throws ServiceFailure
263
   * @throws NotAuthorized
264
   * @throws IdentifierNotUnique
265
   * @throws UnsupportedType
266
   * @throws InsufficientResources
267
   * @throws InvalidSystemMetadata
268
   * @throws NotImplemented
269
   * @throws InvalidRequest
270
   */
271
  public Identifier create(Session session, Identifier pid, InputStream object,
272
    SystemMetadata sysmeta) 
273
    throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, 
274
    UnsupportedType, InsufficientResources, InvalidSystemMetadata, 
275
    NotImplemented, InvalidRequest {
276

    
277
    Identifier resultPid = null;
278
    String localId = null;
279
    boolean allowed = false;
280
    
281
    // check for null session
282
    if (session == null) {
283
    	throw new InvalidToken("4894", "Session is required to WRITE to the Node.");
284
    }
285
    Subject subject = session.getSubject();
286

    
287
    Subject publicSubject = new Subject();
288
    publicSubject.setValue(Constants.SUBJECT_PUBLIC);
289
	// be sure the user is authenticated for create()
290
    if (subject == null || subject.getValue() == null || 
291
        subject.equals(publicSubject) ) {
292
      throw new NotAuthorized("1100", "The provided identity does not have " +
293
        "permission to WRITE to the Node.");
294
      
295
    }
296
    
297
    // verify that pid == SystemMetadata.getIdentifier()
298
    logMetacat.debug("Comparing pid|sysmeta_pid: " + 
299
      pid.getValue() + "|" + sysmeta.getIdentifier().getValue());
300
    if (!pid.getValue().equals(sysmeta.getIdentifier().getValue())) {
301
        throw new InvalidSystemMetadata("1180", 
302
            "The supplied system metadata is invalid. " +
303
            "The identifier " + pid.getValue() + " does not match identifier" +
304
            "in the system metadata identified by " +
305
            sysmeta.getIdentifier().getValue() + ".");
306
        
307
    }
308

    
309
    logMetacat.debug("Checking if identifier exists: " + pid.getValue());
310
    // Check that the identifier does not already exist
311
    if (IdentifierManager.getInstance().identifierExists(pid.getValue())) {
312
	    	throw new IdentifierNotUnique("1120", 
313
			          "The requested identifier " + pid.getValue() +
314
			          " is already used by another object and" +
315
			          "therefore can not be used for this object. Clients should choose" +
316
			          "a new identifier that is unique and retry the operation or " +
317
			          "use CN.reserveIdentifier() to reserve one.");
318
    	
319
    }
320
    
321
    // TODO: this probably needs to be refined more
322
    try {
323
      allowed = isAuthorized(session, pid, Permission.WRITE);
324
            
325
    } catch (NotFound e) {
326
      // The identifier doesn't exist, writing should be fine.
327
      allowed = true;
328
    }
329
    
330
    // verify checksum, only if we can reset the inputstream
331
    if (object.markSupported()) {
332
        logMetacat.debug("Checking checksum for: " + pid.getValue());
333
	    String checksumAlgorithm = sysmeta.getChecksum().getAlgorithm();
334
	    String checksumValue = sysmeta.getChecksum().getValue();
335
	    try {
336
			String computedChecksumValue = ChecksumUtil.checksum(object, checksumAlgorithm).getValue();
337
			// it's very important that we don't consume the stream
338
			object.reset();
339
			if (!computedChecksumValue.equals(checksumValue)) {
340
			    logMetacat.error("Checksum for " + pid.getValue() + " does not match system metadata, computed = " + computedChecksumValue );
341
				throw new InvalidSystemMetadata("4896", "Checksum given does not match that of the object");
342
			}
343
		} catch (Exception e) {
344
			String msg = "Error verifying checksum values";
345
	      	logMetacat.error(msg, e);
346
	        throw new ServiceFailure("1190", msg + ": " + e.getMessage());
347
		}
348
    } else {
349
    	logMetacat.warn("mark is not supported on the object's input stream - cannot verify checksum without consuming stream");
350
    }
351
    	
352
    // we have the go ahead
353
    if ( allowed ) {
354
      
355
        logMetacat.debug("Allowed to insert: " + pid.getValue());
356

    
357
      // Science metadata (XML) or science data object?
358
      // TODO: there are cases where certain object formats are science metadata
359
      // but are not XML (netCDF ...).  Handle this.
360
      if ( isScienceMetadata(sysmeta) ) {
361
        
362
        // CASE METADATA:
363
      	String objectAsXML = "";
364
        try {
365
	        objectAsXML = IOUtils.toString(object, "UTF-8");
366
	        localId = insertOrUpdateDocument(objectAsXML, pid, session, "insert");
367
	        //localId = im.getLocalId(pid.getValue());
368

    
369
        } catch (IOException e) {
370
        	String msg = "The Node is unable to create the object. " +
371
          "There was a problem converting the object to XML";
372
        	logMetacat.info(msg);
373
          throw new ServiceFailure("1190", msg + ": " + e.getMessage());
374

    
375
        }
376
                    
377
      } else {
378
	        
379
	      // DEFAULT CASE: DATA (needs to be checked and completed)
380
	      localId = insertDataObject(object, pid, session);
381
      }   
382
    
383
    }
384

    
385
    logMetacat.debug("Done inserting new object: " + pid.getValue());
386
    
387
    // save the sysmeta
388
    try {
389
      // lock and unlock of the pid happens in the subclass
390
    	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
391
    	
392
    } catch (Exception e) {
393
    	logMetacat.error("Problem creating system metadata: " + pid.getValue(), e);
394
        throw new ServiceFailure("1190", e.getMessage());
395
	}
396
    
397
    // setting the resulting identifier failed
398
    if (localId == null ) {
399
      throw new ServiceFailure("1190", "The Node is unable to create the object. ");
400
    }
401

    
402
    resultPid = pid;
403
    
404
    logMetacat.debug("create() complete for object: " + pid.getValue());
405

    
406
    return resultPid;
407
  }
408

    
409
  /**
410
   * Return the log records associated with a given event between the start and 
411
   * end dates listed given a particular Subject listed in the Session
412
   * 
413
   * @param session - the Session object containing the credentials for the Subject
414
   * @param fromDate - the start date of the desired log records
415
   * @param toDate - the end date of the desired log records
416
   * @param event - restrict log records of a specific event type
417
   * @param start - zero based offset from the first record in the 
418
   *                set of matching log records. Used to assist with 
419
   *                paging the response.
420
   * @param count - maximum number of log records to return in the response. 
421
   *                Used to assist with paging the response.
422
   * 
423
   * @return the desired log records
424
   * 
425
   * @throws InvalidToken
426
   * @throws ServiceFailure
427
   * @throws NotAuthorized
428
   * @throws InvalidRequest
429
   * @throws NotImplemented
430
   */
431
  public Log getLogRecords(Session session, Date fromDate, Date toDate, 
432
      Event event, String pidFilter, Integer start, Integer count) throws InvalidToken, ServiceFailure,
433
      NotAuthorized, InvalidRequest, NotImplemented {
434

    
435
	  // only admin access to this method
436
	  // see https://redmine.dataone.org/issues/2855
437
	  if (!isAdminAuthorized(session)) {
438
		  throw new NotAuthorized("1460", "Only the CN or admin is allowed to harvest logs from this node");
439
		  
440
	  }
441
	  
442
    Log log = new Log();
443
    List<LogEntry> logs = new Vector<LogEntry>();
444
    IdentifierManager im = IdentifierManager.getInstance();
445
    EventLog el = EventLog.getInstance();
446
    if ( fromDate == null ) {
447
      logMetacat.debug("setting fromdate from null");
448
      fromDate = new Date(1);
449
    }
450
    if ( toDate == null ) {
451
      logMetacat.debug("setting todate from null");
452
      toDate = new Date();
453
    }
454

    
455
    if ( start == null ) {
456
    	start = 0;
457
    	
458
    }
459
    
460
    if ( count == null ) {
461
    	count = 1000;
462
    	
463
    }
464

    
465
    String[] filterDocid = null;
466
    if (pidFilter != null) {
467
		try {
468
	      String localId = im.getLocalId(pidFilter);
469
	      filterDocid = new String[] {localId};
470
	    } catch (Exception ex) { 
471
	    	String msg = "Could not find localId for given pidFilter '" + pidFilter + "'";
472
	        logMetacat.warn(msg, ex);
473
	        //throw new InvalidRequest("1480", msg);
474
	    }
475
    }
476
    
477
    logMetacat.debug("fromDate: " + fromDate);
478
    logMetacat.debug("toDate: " + toDate);
479

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

    
484
    logMetacat.debug("report: " + report);
485
    
486
    NodeReference memberNode = new NodeReference();
487
    String nodeId = "localhost";
488
    try {
489
        nodeId = PropertyService.getProperty("dataone.nodeId");
490
    } catch (PropertyNotFoundException e1) {
491
        // TODO Auto-generated catch block
492
        e1.printStackTrace();
493
    }
494
    memberNode.setValue(nodeId);
495

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

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

    
516
      LogEntry le = new LogEntry();
517

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

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

    
550
        // skip it if the pid can't be found
551
        continue;
552
      }
553
      
554
      le.setIdentifier(identifier);
555
      le.setIpAddress(ipAddress);
556
      Date logDate = DateTimeMarshaller.deserializeDateToUTC(dateLogged);
557
      le.setDateLogged(logDate);
558
      le.setNodeIdentifier(memberNode);
559
      Subject princ = new Subject();
560
      princ.setValue(principal);
561
      le.setSubject(princ);
562
      le.setUserAgent(userAgent);
563

    
564
      // event filtering?
565
      if (event == null) {
566
    	  logs.add(le);
567
      } else if (le.getEvent().equals(event)) {
568
    	  logs.add(le);
569
      }
570
    }
571
    
572
    // d1 paging
573
    int total = logs.size();
574
    if (start != null && count != null) {
575
    	int toIndex = start + count;
576
    	// do not exceed total
577
    	toIndex = Math.min(toIndex, total);
578
    	// do not start greater than total
579
    	start = Math.min(start, total);
580
    	// sub set of the list
581
    	logs = new ArrayList<LogEntry>(logs.subList(start, toIndex));
582
    }
583

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

    
648
    // if we fail to set the input stream
649
    if ( inputStream == null ) {
650
      throw new NotFound("1020", "The object specified by " + 
651
                         pid.getValue() +
652
                         "does not exist at this node.");
653
    }
654
    
655
	// log the read event
656
    String principal = Constants.SUBJECT_PUBLIC;
657
    if (session != null && session.getSubject() != null) {
658
    	principal = session.getSubject().getValue();
659
    }
660
    EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), principal, localId, "read");
661
    
662
    return inputStream;
663
  }
664

    
665
  /**
666
   * Return the system metadata for a given object
667
   * 
668
   * @param session - the Session object containing the credentials for the Subject
669
   * @param pid - the object identifier for the given object
670
   * 
671
   * @return inputStream - the input stream of the given system metadata object
672
   * 
673
   * @throws InvalidToken
674
   * @throws ServiceFailure
675
   * @throws NotAuthorized
676
   * @throws NotFound
677
   * @throws InvalidRequest
678
   * @throws NotImplemented
679
   */
680
    public SystemMetadata getSystemMetadata(Session session, Identifier pid)
681
        throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
682
        NotImplemented {
683

    
684
        boolean isAuthorized = false;
685
        SystemMetadata systemMetadata = null;
686
        List<Replica> replicaList = null;
687
        NodeReference replicaNodeRef = null;
688
        List<Node> nodeListBySubject = null;
689
        Subject subject = null;
690
        
691
        if (session != null ) {
692
            subject = session.getSubject();
693
        }
694
        
695
        // check normal authorization
696
        BaseException originalAuthorizationException = null;
697
        if (!isAuthorized) {
698
            try {
699
                isAuthorized = isAuthorized(session, pid, Permission.READ);
700

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

    
766
	        } catch (RuntimeException e) {
767
	        	e.printStackTrace();
768
	            // convert hazelcast RuntimeException to ServiceFailure
769
	            throw new ServiceFailure("1090", "Unexpected error getting system metadata for: " + 
770
	                pid.getValue());	
771
	        }
772
	        
773
        }
774
        
775
        // It wasn't in the map
776
        if ( systemMetadata == null ) {
777
            throw new NotFound("1420", "No record found for: " + pid.getValue());
778
        }
779
        
780
        return systemMetadata;
781
    }
782
     
783
  /**
784
   * Test if the user identified by the provided token has administrative authorization 
785
   * 
786
   * @param session - the Session object containing the credentials for the Subject
787
   * 
788
   * @return true if the user is admin
789
   * 
790
   * @throws ServiceFailure
791
   * @throws InvalidToken
792
   * @throws NotFound
793
   * @throws NotAuthorized
794
   * @throws NotImplemented
795
   */
796
  public boolean isAdminAuthorized(Session session) 
797
      throws ServiceFailure, InvalidToken, NotAuthorized,
798
      NotImplemented {
799

    
800
      boolean allowed = false;
801
      
802
      // must have a session in order to check admin 
803
      if (session == null) {
804
         logMetacat.debug("In isAdminAuthorized(), session is null ");
805
         return false;
806
      }
807
      
808
      logMetacat.debug("In isAdminAuthorized(), checking CN or MN authorization for " +
809
           session.getSubject().getValue());
810
      
811
      // are we allowed to do this? only CNs are allowed
812
      CNode cn = D1Client.getCN();
813
      List<Node> nodes = cn.listNodes().getNodeList();
814
      
815
      if ( nodes == null ) {
816
          throw new ServiceFailure("4852", "Couldn't get node list.");
817
  
818
      }
819
      
820
      // find the node in the node list
821
      for ( Node node : nodes ) {
822
          
823
          NodeReference nodeReference = node.getIdentifier();
824
          logMetacat.debug("In isAdminAuthorized(), Node reference is: " + nodeReference.getValue());
825
          
826
          Subject subject = session.getSubject();
827
          
828
          if (node.getType() == NodeType.CN) {
829
              List<Subject> nodeSubjects = node.getSubjectList();
830
              
831
              // check if the session subject is in the node subject list
832
              for (Subject nodeSubject : nodeSubjects) {
833
                  logMetacat.debug("In isAdminAuthorized(), comparing subjects: " +
834
                      nodeSubject.getValue() + " and " + subject.getValue());
835
                  if ( nodeSubject.equals(subject) ) {
836
                      allowed = true; // subject of session == target node subject
837
                      break;
838
                      
839
                  }
840
              }              
841
          }
842
      }
843

    
844
      
845
      return allowed;
846
  }
847
  
848
  /**
849
   * Test if the user identified by the provided token has administrative authorization 
850
   * on this node because they are calling themselves
851
   * 
852
   * @param session - the Session object containing the credentials for the Subject
853
   * 
854
   * @return true if the user is this node
855
   * @throws ServiceFailure 
856
   * @throws NotImplemented 
857
   */
858
  public boolean isNodeAdmin(Session session) throws NotImplemented, ServiceFailure {
859

    
860
      boolean allowed = false;
861
      
862
      // must have a session in order to check admin 
863
      if (session == null) {
864
         logMetacat.debug("In isNodeAdmin(), session is null ");
865
         return false;
866
      }
867
      
868
      logMetacat.debug("In isNodeAdmin(), MN authorization for " +
869
           session.getSubject().getValue());
870
      
871
      Node node = MNodeService.getInstance(request).getCapabilities();
872
      NodeReference nodeReference = node.getIdentifier();
873
      logMetacat.debug("In isNodeAdmin(), Node reference is: " + nodeReference.getValue());
874
      
875
      Subject subject = session.getSubject();
876
      
877
      if (node.getType() == NodeType.MN) {
878
          List<Subject> nodeSubjects = node.getSubjectList();
879
          
880
          // check if the session subject is in the node subject list
881
          for (Subject nodeSubject : nodeSubjects) {
882
              logMetacat.debug("In isNodeAdmin(), comparing subjects: " +
883
                  nodeSubject.getValue() + " and " + subject.getValue());
884
              if ( nodeSubject.equals(subject) ) {
885
                  allowed = true; // subject of session == this node's subect
886
                  break;
887
              }
888
          }              
889
      }
890
      
891
      return allowed;
892
  }
893
  
894
  /**
895
   * Test if the user identified by the provided token has authorization 
896
   * for the operation on the specified object.
897
   * 
898
   * @param session - the Session object containing the credentials for the Subject
899
   * @param pid - The identifer of the resource for which access is being checked
900
   * @param operation - The type of operation which is being requested for the given pid
901
   *
902
   * @return true if the operation is allowed
903
   * 
904
   * @throws ServiceFailure
905
   * @throws InvalidToken
906
   * @throws NotFound
907
   * @throws NotAuthorized
908
   * @throws NotImplemented
909
   * @throws InvalidRequest
910
   */
911
  public boolean isAuthorized(Session session, Identifier pid, Permission permission)
912
    throws ServiceFailure, InvalidToken, NotFound, NotAuthorized,
913
    NotImplemented, InvalidRequest {
914

    
915
    boolean allowed = false;
916
    
917
    if (permission == null) {
918
    	throw new InvalidRequest("1761", "Permission was not provided or is invalid");
919
    }
920
    
921
    // permissions are hierarchical
922
    List<Permission> expandedPermissions = null;
923
    
924
    // always allow CN access
925
    if ( isAdminAuthorized(session) ) {
926
        allowed = true;
927
        return allowed;
928
        
929
    }
930
    
931
    // get the subject[s] from the session
932
	//defer to the shared util for recursively compiling the subjects	
933
	Set<Subject> subjects = AuthUtils.authorizedClientSubjects(session);
934
    
935
    // get the system metadata
936
    String pidStr = pid.getValue();
937
    SystemMetadata systemMetadata = null;
938
    try {
939
        systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
940

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

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

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

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

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

    
1207
    logMetacat.debug("Case DATA: starting to write to disk.");
1208
	if (locked) {
1209

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

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

    
1286
  /**
1287
   * Update a systemMetadata document
1288
   * 
1289
   * @param sysMeta - the system metadata object in the system to update
1290
   */
1291
    protected void updateSystemMetadata(SystemMetadata sysMeta)
1292
        throws ServiceFailure {
1293

    
1294
        logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
1295
        sysMeta.setDateSysMetadataModified(new Date());
1296
        try {
1297
            HazelcastService.getInstance().getSystemMetadataMap().lock(sysMeta.getIdentifier());
1298
            HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
1299

    
1300
        } catch (Exception e) {
1301
            throw new ServiceFailure("4862", e.getMessage());
1302

    
1303
        } finally {
1304
            HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
1305

    
1306
        }
1307

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

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

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

    
1371
    return newFile;
1372
  }
1373

    
1374
  /*
1375
   * Returns a list of nodes that have been registered with the DataONE infrastructure
1376
   * that match the given session subject
1377
   * @return nodes - List of nodes from the registry with a matching session subject
1378
   * 
1379
   * @throws ServiceFailure
1380
   * @throws NotImplemented
1381
   */
1382
  protected List<Node> listNodesBySubject(Subject subject) 
1383
      throws ServiceFailure, NotImplemented {
1384
      List<Node> nodeList = new ArrayList<Node>();
1385
      
1386
      CNode cn = D1Client.getCN();
1387
      List<Node> nodes = cn.listNodes().getNodeList();
1388
      
1389
      // find the node in the node list
1390
      for ( Node node : nodes ) {
1391
          
1392
          List<Subject> nodeSubjects = node.getSubjectList();
1393
          if (nodeSubjects != null) {    
1394
	          // check if the session subject is in the node subject list
1395
	          for (Subject nodeSubject : nodeSubjects) {
1396
	              if ( nodeSubject.equals(subject) ) { // subject of session == node subject
1397
	                  nodeList.add(node);  
1398
	              }                              
1399
	          }
1400
          }
1401
      }
1402
      
1403
      return nodeList;
1404
      
1405
  }
1406

    
1407
  /**
1408
   * Archives an object, where the object is either a 
1409
   * data object or a science metadata object.
1410
   * 
1411
   * @param session - the Session object containing the credentials for the Subject
1412
   * @param pid - The object identifier to be archived
1413
   * 
1414
   * @return pid - the identifier of the object used for the archiving
1415
   * 
1416
   * @throws InvalidToken
1417
   * @throws ServiceFailure
1418
   * @throws NotAuthorized
1419
   * @throws NotFound
1420
   * @throws NotImplemented
1421
   * @throws InvalidRequest
1422
   */
1423
  public Identifier archive(Session session, Identifier pid) 
1424
      throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
1425

    
1426
      String localId = null;
1427
      boolean allowed = false;
1428
      String username = Constants.SUBJECT_PUBLIC;
1429
      String[] groupnames = null;
1430
      if (session == null) {
1431
      	throw new InvalidToken("1330", "No session has been provided");
1432
      } else {
1433
          username = session.getSubject().getValue();
1434
          if (session.getSubjectInfo() != null) {
1435
              List<Group> groupList = session.getSubjectInfo().getGroupList();
1436
              if (groupList != null) {
1437
                  groupnames = new String[groupList.size()];
1438
                  for (int i = 0; i > groupList.size(); i++) {
1439
                      groupnames[i] = groupList.get(i).getGroupName();
1440
                  }
1441
              }
1442
          }
1443
      }
1444

    
1445
      // do we have a valid pid?
1446
      if (pid == null || pid.getValue().trim().equals("")) {
1447
          throw new ServiceFailure("1350", "The provided identifier was invalid.");
1448
      }
1449

    
1450
      // check for the existing identifier
1451
      try {
1452
          localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
1453
      } catch (McdbDocNotFoundException e) {
1454
          throw new NotFound("1340", "The object with the provided " + "identifier was not found.");
1455
      }
1456

    
1457
      // does the subject have archive (a D1 CHANGE_PERMISSION level) privileges on the pid?
1458
      try {
1459
			allowed = isAuthorized(session, pid, Permission.CHANGE_PERMISSION);
1460
		} catch (InvalidRequest e) {
1461
          throw new ServiceFailure("1350", e.getDescription());
1462
		}
1463
          
1464

    
1465
      if (allowed) {
1466
          try {
1467
              // archive the document
1468
              DocumentImpl.delete(localId, null, null, null, false);
1469
              EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, Event.DELETE.xmlValue());
1470

    
1471
              // archive it
1472
              SystemMetadata sysMeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
1473
              sysMeta.setArchived(true);
1474
              sysMeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
1475
              HazelcastService.getInstance().getSystemMetadataMap().put(pid, sysMeta);
1476
              
1477
          } catch (McdbDocNotFoundException e) {
1478
              throw new NotFound("1340", "The provided identifier was invalid.");
1479

    
1480
          } catch (SQLException e) {
1481
              throw new ServiceFailure("1350", "There was a problem archiving the object." + "The error message was: " + e.getMessage());
1482

    
1483
          } catch (InsufficientKarmaException e) {
1484
              throw new NotAuthorized("1320", "The provided identity does not have " + "permission to archive this object.");
1485

    
1486
          } catch (Exception e) { // for some reason DocumentImpl throws a general Exception
1487
              throw new ServiceFailure("1350", "There was a problem archiving the object." + "The error message was: " + e.getMessage());
1488
          }
1489

    
1490
      } else {
1491
          throw new NotAuthorized("1320", "The provided identity does not have " + "permission to archive the object on the Node.");
1492
      }
1493

    
1494
      return pid;
1495
  }
1496
  
1497
  public Identifier archive(Identifier pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
1498
	  return archive(null, pid);
1499
  }
1500

    
1501

    
1502
}
(2-2/5)