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-05-23 09:57:32 -0700 (Wed, 23 May 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

    
436
    Log log = new Log();
437
    List<LogEntry> logs = new Vector<LogEntry>();
438
    IdentifierManager im = IdentifierManager.getInstance();
439
    EventLog el = EventLog.getInstance();
440
    if ( fromDate == null ) {
441
      logMetacat.debug("setting fromdate from null");
442
      fromDate = new Date(1);
443
    }
444
    if ( toDate == null ) {
445
      logMetacat.debug("setting todate from null");
446
      toDate = new Date();
447
    }
448

    
449
    if ( start == null ) {
450
    	start = 0;
451
    	
452
    }
453
    
454
    if ( count == null ) {
455
    	count = 1000;
456
    	
457
    }
458

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

    
474
    String report = el.getReport(null, null, filterDocid, null,
475
        new java.sql.Timestamp(fromDate.getTime()),
476
        new java.sql.Timestamp(toDate.getTime()), false);
477

    
478
    logMetacat.debug("report: " + report);
479

    
480
    String logEntry = "<logEntry>";
481
    String endLogEntry = "</logEntry>";
482
    int startIndex = 0;
483
    int foundIndex = report.indexOf(logEntry, startIndex);
484
    while (foundIndex != -1) {
485
      // parse out each entry
486
      int endEntryIndex = report.indexOf(endLogEntry, foundIndex);
487
      String entry = report.substring(foundIndex, endEntryIndex);
488
      logMetacat.debug("entry: " + entry);
489
      startIndex = endEntryIndex + endLogEntry.length();
490
      foundIndex = report.indexOf(logEntry, startIndex);
491

    
492
      String entryId = getLogEntryField("entryid", entry);
493
      String ipAddress = getLogEntryField("ipAddress", entry);
494
      String principal = getLogEntryField("principal", entry);
495
      String userAgent = getLogEntryField("userAgent", entry);
496
      String docid = getLogEntryField("docid", entry);
497
      String eventS = getLogEntryField("event", entry);
498
      String dateLogged = getLogEntryField("dateLogged", entry);
499

    
500
      LogEntry le = new LogEntry();
501

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

    
532
          logMetacat.warn("could not find pid for docid '" + docid + "'");
533

    
534
        // skip it if the pid can't be found
535
        continue;
536
      }
537

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

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

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

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

    
672
  /**
673
   * Return the system metadata for a given object
674
   * 
675
   * @param session - the Session object containing the credentials for the Subject
676
   * @param pid - the object identifier for the given object
677
   * 
678
   * @return inputStream - the input stream of the given system metadata object
679
   * 
680
   * @throws InvalidToken
681
   * @throws ServiceFailure
682
   * @throws NotAuthorized
683
   * @throws NotFound
684
   * @throws InvalidRequest
685
   * @throws NotImplemented
686
   */
687
    public SystemMetadata getSystemMetadata(Session session, Identifier pid)
688
        throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
689
        NotImplemented {
690

    
691
        boolean isAuthorized = false;
692
        SystemMetadata systemMetadata = null;
693
        List<Replica> replicaList = null;
694
        NodeReference replicaNodeRef = null;
695
        List<Node> nodeListBySubject = null;
696
        Subject subject = null;
697
        
698
        if (session != null ) {
699
            subject = session.getSubject();
700
        }
701
        
702
        // check normal authorization
703
        BaseException originalAuthorizationException = null;
704
        if (!isAuthorized) {
705
            try {
706
                isAuthorized = isAuthorized(session, pid, Permission.READ);
707

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

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

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

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

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

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

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

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

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

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

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

    
1214
    logMetacat.debug("Case DATA: starting to write to disk.");
1215
	if (locked) {
1216

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

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

    
1293
  /**
1294
   * Update a systemMetadata document
1295
   * 
1296
   * @param sysMeta - the system metadata object in the system to update
1297
   */
1298
    protected void updateSystemMetadata(SystemMetadata sysMeta)
1299
        throws ServiceFailure {
1300

    
1301
        logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
1302
        sysMeta.setDateSysMetadataModified(new Date());
1303
        try {
1304
            HazelcastService.getInstance().getSystemMetadataMap().lock(sysMeta.getIdentifier());
1305
            HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
1306

    
1307
        } catch (Exception e) {
1308
            throw new ServiceFailure("4862", e.getMessage());
1309

    
1310
        } finally {
1311
            HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
1312

    
1313
        }
1314

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

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

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

    
1378
    return newFile;
1379
  }
1380

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

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

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

    
1452
      // do we have a valid pid?
1453
      if (pid == null || pid.getValue().trim().equals("")) {
1454
          throw new ServiceFailure("1350", "The provided identifier was invalid.");
1455
      }
1456

    
1457
      // check for the existing identifier
1458
      try {
1459
          localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
1460
      } catch (McdbDocNotFoundException e) {
1461
          throw new NotFound("1340", "The object with the provided " + "identifier was not found.");
1462
      }
1463

    
1464
      // does the subject have archive (a D1 CHANGE_PERMISSION level) privileges on the pid?
1465
      try {
1466
			allowed = isAuthorized(session, pid, Permission.CHANGE_PERMISSION);
1467
		} catch (InvalidRequest e) {
1468
          throw new ServiceFailure("1350", e.getDescription());
1469
		}
1470
          
1471

    
1472
      if (allowed) {
1473
          try {
1474
              // archive the document
1475
              DocumentImpl.delete(localId, username, groupnames, null, false);
1476
              EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, Event.DELETE.xmlValue());
1477

    
1478
              // archive it
1479
              SystemMetadata sysMeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
1480
              sysMeta.setArchived(true);
1481
              sysMeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
1482
              HazelcastService.getInstance().getSystemMetadataMap().put(pid, sysMeta);
1483
              
1484
          } catch (McdbDocNotFoundException e) {
1485
              throw new NotFound("1340", "The provided identifier was invalid.");
1486

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

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

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

    
1497
      } else {
1498
          throw new NotAuthorized("1320", "The provided identity does not have " + "permission to archive the object on the Node.");
1499
      }
1500

    
1501
      return pid;
1502
  }
1503
  
1504
  public Identifier archive(Identifier pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
1505
	  return archive(null, pid);
1506
  }
1507

    
1508

    
1509
}
(2-2/5)