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-01 10:47:05 -0700 (Tue, 01 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
      boolean allowed = false;
173
      String username = Constants.SUBJECT_PUBLIC;
174
      String[] groupnames = null;
175
      if (session == null) {
176
      	throw new InvalidToken("1330", "No session has been provided");
177
      } else {
178
          username = session.getSubject().getValue();
179
          if (session.getSubjectInfo() != null) {
180
              List<Group> groupList = session.getSubjectInfo().getGroupList();
181
              if (groupList != null) {
182
                  groupnames = new String[groupList.size()];
183
                  for (int i = 0; i > groupList.size(); i++) {
184
                      groupnames[i] = groupList.get(i).getGroupName();
185
                  }
186
              }
187
          }
188
      }
189

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
431
    return resultPid;
432
  }
433

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

    
460

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

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

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

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

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

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

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

    
513
      LogEntry le = new LogEntry();
514

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1280
        }
1281

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

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

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

    
1345
    return newFile;
1346
  }
1347

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

    
1381
/**
1382
   * Archives an object, where the object is either a 
1383
   * data object or a science metadata object.
1384
   * 
1385
   * @param session - the Session object containing the credentials for the Subject
1386
   * @param pid - The object identifier to be archived
1387
   * 
1388
   * @return pid - the identifier of the object used for the archiving
1389
   * 
1390
   * @throws InvalidToken
1391
   * @throws ServiceFailure
1392
   * @throws NotAuthorized
1393
   * @throws NotFound
1394
   * @throws NotImplemented
1395
   * @throws InvalidRequest
1396
   */
1397
  public Identifier archive(Session session, Identifier pid) 
1398
      throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
1399

    
1400
      String localId = null;
1401
      boolean allowed = false;
1402
      String username = Constants.SUBJECT_PUBLIC;
1403
      String[] groupnames = null;
1404
      if (session == null) {
1405
      	throw new InvalidToken("1330", "No session has been provided");
1406
      } else {
1407
          username = session.getSubject().getValue();
1408
          if (session.getSubjectInfo() != null) {
1409
              List<Group> groupList = session.getSubjectInfo().getGroupList();
1410
              if (groupList != null) {
1411
                  groupnames = new String[groupList.size()];
1412
                  for (int i = 0; i > groupList.size(); i++) {
1413
                      groupnames[i] = groupList.get(i).getGroupName();
1414
                  }
1415
              }
1416
          }
1417
      }
1418

    
1419
      // do we have a valid pid?
1420
      if (pid == null || pid.getValue().trim().equals("")) {
1421
          throw new ServiceFailure("1350", "The provided identifier was invalid.");
1422
      }
1423

    
1424
      // check for the existing identifier
1425
      try {
1426
          localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
1427
      } catch (McdbDocNotFoundException e) {
1428
          throw new NotFound("1340", "The object with the provided " + "identifier was not found.");
1429
      }
1430

    
1431
      // does the subject have archive (a D1 CHANGE_PERMISSION level) privileges on the pid?
1432
      try {
1433
			allowed = isAuthorized(session, pid, Permission.CHANGE_PERMISSION);
1434
		} catch (InvalidRequest e) {
1435
          throw new ServiceFailure("1350", e.getDescription());
1436
		}
1437
          
1438

    
1439
      if (allowed) {
1440
          try {
1441
              // archive the document
1442
              DocumentImpl.delete(localId, username, groupnames, null, false);
1443
              EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, Event.DELETE.xmlValue());
1444

    
1445
              // archive it
1446
              SystemMetadata sysMeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
1447
              sysMeta.setArchived(true);
1448
              sysMeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
1449
              HazelcastService.getInstance().getSystemMetadataMap().put(pid, sysMeta);
1450
              
1451
          } catch (McdbDocNotFoundException e) {
1452
              throw new NotFound("1340", "The provided identifier was invalid.");
1453

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

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

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

    
1464
      } else {
1465
          throw new NotAuthorized("1320", "The provided identity does not have " + "permission to archive the object on the Node.");
1466
      }
1467

    
1468
      return pid;
1469
  }
1470

    
1471

    
1472
}
(2-2/5)