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 11:14:28 -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
      if (session == null) {
174
      	throw new InvalidToken("1330", "No session has been provided");
175
      }
176
      // just for logging purposes
177
      String username = session.getSubject().getValue();
178

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

    
184
      // check for the existing identifier
185
      try {
186
          localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
187
      } catch (McdbDocNotFoundException e) {
188
          throw new NotFound("1340", "The object with the provided " + "identifier was not found.");
189
      }
190

    
191
      // only admin is allowed a full delete
192
      allowed = isAdminAuthorized(session);
193
      if (!allowed) { 
194
          throw new NotAuthorized("1320", "The provided identity does not have " + "permission to DELETE objects on the Member Node.");
195
      }
196
      
197
      try {
198
          // delete the document, as admin
199
          DocumentImpl.delete(localId, null, null, null, true);
200
          EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, Event.DELETE.xmlValue());
201

    
202
          // archive it
203
          SystemMetadata sysMeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
204
          sysMeta.setArchived(true);
205
          sysMeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
206
          HazelcastService.getInstance().getSystemMetadataMap().put(pid, sysMeta);
207
          
208
      } catch (McdbDocNotFoundException e) {
209
          throw new NotFound("1340", "The provided identifier was invalid.");
210

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

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

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

    
221
      return pid;
222
  }
223
  
224
  /**
225
   * Low level, "are you alive" operation. A valid ping response is 
226
   * indicated by a HTTP status of 200.
227
   * 
228
   * @return true if the service is alive
229
   * 
230
   * @throws NotImplemented
231
   * @throws ServiceFailure
232
   * @throws InsufficientResources
233
   */
234
  public Date ping() 
235
      throws NotImplemented, ServiceFailure, InsufficientResources {
236

    
237
      // test if we can get a database connection
238
      int serialNumber = -1;
239
      DBConnection dbConn = null;
240
      try {
241
          dbConn = DBConnectionPool.getDBConnection("MNodeService.ping");
242
          serialNumber = dbConn.getCheckOutSerialNumber();
243
      } catch (SQLException e) {
244
      	ServiceFailure sf = new ServiceFailure("", e.getMessage());
245
      	sf.initCause(e);
246
          throw sf;
247
      } finally {
248
          // Return the database connection
249
          DBConnectionPool.returnDBConnection(dbConn, serialNumber);
250
      }
251

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

    
284
    Identifier resultPid = null;
285
    String localId = null;
286
    boolean allowed = false;
287
    
288
    // check for null session
289
    if (session == null) {
290
    	throw new InvalidToken("4894", "Session is required to WRITE to the Node.");
291
    }
292
    Subject subject = session.getSubject();
293

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

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

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

    
376
        } catch (IOException e) {
377
        	String msg = "The Node is unable to create the object. " +
378
          "There was a problem converting the object to XML";
379
        	logMetacat.info(msg);
380
          throw new ServiceFailure("1190", msg + ": " + e.getMessage());
381

    
382
        }
383
                    
384
      } else {
385
	        
386
	      // DEFAULT CASE: DATA (needs to be checked and completed)
387
	      localId = insertDataObject(object, pid, session);
388
      }   
389
    
390
    }
391

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

    
409
    resultPid = pid;
410
    
411
    logMetacat.debug("create() complete for object: " + pid.getValue());
412

    
413
    return resultPid;
414
  }
415

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

    
442

    
443
    Log log = new Log();
444
    List<LogEntry> logs = new Vector<LogEntry>();
445
    IdentifierManager im = IdentifierManager.getInstance();
446
    EventLog el = EventLog.getInstance();
447
    if ( fromDate == null ) {
448
      logMetacat.debug("setting fromdate from null");
449
      fromDate = new Date(1);
450
    }
451
    if ( toDate == null ) {
452
      logMetacat.debug("setting todate from null");
453
      toDate = new Date();
454
    }
455

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

    
466
    logMetacat.debug("fromDate: " + fromDate);
467
    logMetacat.debug("toDate: " + toDate);
468

    
469
    String report = el.getReport(null, null, null, null,
470
        new java.sql.Timestamp(fromDate.getTime()),
471
        new java.sql.Timestamp(toDate.getTime()), false);
472

    
473
    logMetacat.debug("report: " + report);
474

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

    
487
      String entryId = getLogEntryField("entryid", entry);
488
      String ipAddress = getLogEntryField("ipAddress", entry);
489
      String principal = getLogEntryField("principal", entry);
490
      String userAgent = getLogEntryField("userAgent", entry);
491
      String docid = getLogEntryField("docid", entry);
492
      String eventS = getLogEntryField("event", entry);
493
      String dateLogged = getLogEntryField("dateLogged", entry);
494

    
495
      LogEntry le = new LogEntry();
496

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

    
527
          logMetacat.warn("could not find pid for docid '" + docid + "'");
528

    
529
        // skip it if the pid can't be found
530
        continue;
531
      }
532

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

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

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

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

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

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

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

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

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

    
846
      
847
      return allowed;
848
  }
849
  
850
  /**
851
   * Test if the user identified by the provided token has authorization 
852
   * for the operation on the specified object.
853
   * 
854
   * @param session - the Session object containing the credentials for the Subject
855
   * @param pid - The identifer of the resource for which access is being checked
856
   * @param operation - The type of operation which is being requested for the given pid
857
   *
858
   * @return true if the operation is allowed
859
   * 
860
   * @throws ServiceFailure
861
   * @throws InvalidToken
862
   * @throws NotFound
863
   * @throws NotAuthorized
864
   * @throws NotImplemented
865
   * @throws InvalidRequest
866
   */
867
  public boolean isAuthorized(Session session, Identifier pid, Permission permission)
868
    throws ServiceFailure, InvalidToken, NotFound, NotAuthorized,
869
    NotImplemented, InvalidRequest {
870

    
871
    boolean allowed = false;
872
    
873
    if (permission == null) {
874
    	throw new InvalidRequest("1761", "Permission was not provided or is invalid");
875
    }
876
    
877
    // permissions are hierarchical
878
    List<Permission> expandedPermissions = null;
879
    
880
    // always allow CN access
881
    if ( isAdminAuthorized(session) ) {
882
        allowed = true;
883
        return allowed;
884
        
885
    }
886
    
887
    // get the subject[s] from the session
888
	//defer to the shared util for recursively compiling the subjects	
889
	Set<Subject> subjects = AuthUtils.authorizedClientSubjects(session);
890
    
891
    // get the system metadata
892
    String pidStr = pid.getValue();
893
    SystemMetadata systemMetadata = null;
894
    try {
895
        systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
896

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

    
977
  /** 
978
   * Determine if a given object should be treated as an XML science metadata
979
   * object. 
980
   * 
981
   * @param sysmeta - the SystemMetadata describing the object
982
   * @return true if the object should be treated as science metadata
983
   */
984
  public static boolean isScienceMetadata(SystemMetadata sysmeta) {
985
    
986
    ObjectFormat objectFormat = null;
987
    boolean isScienceMetadata = false;
988
    
989
    try {
990
      objectFormat = ObjectFormatCache.getInstance().getFormat(sysmeta.getFormatId());
991
      if ( objectFormat.getFormatType().equals("METADATA") ) {
992
      	isScienceMetadata = true;
993
      	
994
      }
995
      
996
       
997
    } catch (ServiceFailure e) {
998
      logMetacat.debug("There was a problem determining if the object identified by" + 
999
          sysmeta.getIdentifier().getValue() + 
1000
          " is science metadata: " + e.getMessage());
1001
    
1002
    } catch (NotFound e) {
1003
      logMetacat.debug("There was a problem determining if the object identified by" + 
1004
          sysmeta.getIdentifier().getValue() + 
1005
          " is science metadata: " + e.getMessage());
1006
    
1007
    }
1008
    
1009
    return isScienceMetadata;
1010

    
1011
  }
1012
  
1013
  /**
1014
   * Insert or update an XML document into Metacat
1015
   * 
1016
   * @param xml - the XML document to insert or update
1017
   * @param pid - the identifier to be used for the resulting object
1018
   * 
1019
   * @return localId - the resulting docid of the document created or updated
1020
   * 
1021
   */
1022
  public String insertOrUpdateDocument(String xml, Identifier pid, 
1023
    Session session, String insertOrUpdate) 
1024
    throws ServiceFailure {
1025
    
1026
  	logMetacat.debug("Starting to insert xml document...");
1027
    IdentifierManager im = IdentifierManager.getInstance();
1028

    
1029
    // generate pid/localId pair for sysmeta
1030
    String localId = null;
1031
    
1032
    if(insertOrUpdate.equals("insert")) {
1033
      localId = im.generateLocalId(pid.getValue(), 1);
1034
      
1035
    } else {
1036
      //localid should already exist in the identifier table, so just find it
1037
      try {
1038
        logMetacat.debug("Updating pid " + pid.getValue());
1039
        logMetacat.debug("looking in identifier table for pid " + pid.getValue());
1040
        
1041
        localId = im.getLocalId(pid.getValue());
1042
        
1043
        logMetacat.debug("localId: " + localId);
1044
        //increment the revision
1045
        String docid = localId.substring(0, localId.lastIndexOf("."));
1046
        String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
1047
        int rev = new Integer(revS).intValue();
1048
        rev++;
1049
        docid = docid + "." + rev;
1050
        localId = docid;
1051
        logMetacat.debug("incremented localId: " + localId);
1052
      
1053
      } catch(McdbDocNotFoundException e) {
1054
        throw new ServiceFailure("1030", "D1NodeService.insertOrUpdateDocument(): " +
1055
            "pid " + pid.getValue() + 
1056
            " should have been in the identifier table, but it wasn't: " + 
1057
            e.getMessage());
1058
      
1059
      }
1060
      
1061
    }
1062

    
1063
    params = new Hashtable<String, String[]>();
1064
    String[] action = new String[1];
1065
    action[0] = insertOrUpdate;
1066
    params.put("action", action);
1067
    String[] docid = new String[1];
1068
    docid[0] = localId;
1069
    params.put("docid", docid);
1070
    String[] doctext = new String[1];
1071
    doctext[0] = xml;
1072
    params.put("doctext", doctext);
1073
    
1074
    String username = Constants.SUBJECT_PUBLIC;
1075
    String[] groupnames = null;
1076
    if (session != null ) {
1077
    	username = session.getSubject().getValue();
1078
    	if (session.getSubjectInfo() != null) {
1079
    		List<Group> groupList = session.getSubjectInfo().getGroupList();
1080
    		if (groupList != null) {
1081
    			groupnames = new String[groupList.size()];
1082
    			for (int i = 0; i > groupList.size(); i++ ) {
1083
    				groupnames[i] = groupList.get(i).getGroupName();
1084
    			}
1085
    		}
1086
    	}
1087
    }
1088
    
1089
    // do the insert or update action
1090
    handler = new MetacatHandler(new Timer());
1091
    String result = handler.handleInsertOrUpdateAction(request.getRemoteAddr(), request.getHeader("User-Agent"), null, 
1092
                        null, params, username, groupnames, false, false);
1093
    
1094
    if(result.indexOf("<error>") != -1) {
1095
    	String detailCode = "";
1096
    	if ( insertOrUpdate.equals("insert") ) {
1097
    		// make sure to remove the mapping so that subsequent attempts do not fail with IdentifierNotUnique
1098
    		im.removeMapping(pid.getValue(), localId);
1099
    		detailCode = "1190";
1100
    		
1101
    	} else if ( insertOrUpdate.equals("update") ) {
1102
    		detailCode = "1310";
1103
    		
1104
    	}
1105
        throw new ServiceFailure(detailCode, 
1106
          "Error inserting or updating document: " + result);
1107
    }
1108
    logMetacat.debug("Finsished inserting xml document with id " + localId);
1109
    
1110
    return localId;
1111
  }
1112
  
1113
  /**
1114
   * Insert a data document
1115
   * 
1116
   * @param object
1117
   * @param pid
1118
   * @param sessionData
1119
   * @throws ServiceFailure
1120
   * @returns localId of the data object inserted
1121
   */
1122
  public String insertDataObject(InputStream object, Identifier pid, 
1123
          Session session) throws ServiceFailure {
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
    // generate pid/localId pair for object
1141
    logMetacat.debug("Generating a pid/localId mapping");
1142
    IdentifierManager im = IdentifierManager.getInstance();
1143
    String localId = im.generateLocalId(pid.getValue(), 1);
1144
  
1145
    // Save the data file to disk using "localId" as the name
1146
    String datafilepath = null;
1147
	try {
1148
		datafilepath = PropertyService.getProperty("application.datafilepath");
1149
	} catch (PropertyNotFoundException e) {
1150
		ServiceFailure sf = new ServiceFailure("1190", "Lookup data file path" + e.getMessage());
1151
		sf.initCause(e);
1152
		throw sf;
1153
	}
1154
    boolean locked = false;
1155
	try {
1156
		locked = DocumentImpl.getDataFileLockGrant(localId);
1157
	} catch (Exception e) {
1158
		ServiceFailure sf = new ServiceFailure("1190", "Could not lock file for writing:" + e.getMessage());
1159
		sf.initCause(e);
1160
		throw sf;
1161
	}
1162

    
1163
    logMetacat.debug("Case DATA: starting to write to disk.");
1164
	if (locked) {
1165

    
1166
          File dataDirectory = new File(datafilepath);
1167
          dataDirectory.mkdirs();
1168
  
1169
          File newFile = writeStreamToFile(dataDirectory, localId, object);
1170
  
1171
          // TODO: Check that the file size matches SystemMetadata
1172
          // long size = newFile.length();
1173
          // if (size == 0) {
1174
          //     throw new IOException("Uploaded file is 0 bytes!");
1175
          // }
1176
  
1177
          // Register the file in the database (which generates an exception
1178
          // if the localId is not acceptable or other untoward things happen
1179
          try {
1180
            logMetacat.debug("Registering document...");
1181
            DocumentImpl.registerDocument(localId, "BIN", localId,
1182
                    username, groupnames);
1183
            logMetacat.debug("Registration step completed.");
1184
            
1185
          } catch (SQLException e) {
1186
            //newFile.delete();
1187
            logMetacat.debug("SQLE: " + e.getMessage());
1188
            e.printStackTrace(System.out);
1189
            throw new ServiceFailure("1190", "Registration failed: " + 
1190
            		e.getMessage());
1191
            
1192
          } catch (AccessionNumberException e) {
1193
            //newFile.delete();
1194
            logMetacat.debug("ANE: " + e.getMessage());
1195
            e.printStackTrace(System.out);
1196
            throw new ServiceFailure("1190", "Registration failed: " + 
1197
            	e.getMessage());
1198
            
1199
          } catch (Exception e) {
1200
            //newFile.delete();
1201
            logMetacat.debug("Exception: " + e.getMessage());
1202
            e.printStackTrace(System.out);
1203
            throw new ServiceFailure("1190", "Registration failed: " + 
1204
            	e.getMessage());
1205
          }
1206
  
1207
          logMetacat.debug("Logging the creation event.");
1208
          EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, "create");
1209
  
1210
          // Schedule replication for this data file
1211
          logMetacat.debug("Scheduling replication.");
1212
          ForceReplicationHandler frh = new ForceReplicationHandler(
1213
            localId, "create", false, null);
1214
      }
1215
      
1216
      return localId;
1217
    
1218
  }
1219

    
1220
  /**
1221
   * Insert a systemMetadata document and return its localId
1222
   */
1223
  public void insertSystemMetadata(SystemMetadata sysmeta) 
1224
      throws ServiceFailure {
1225
      
1226
  	  logMetacat.debug("Starting to insert SystemMetadata...");
1227
      sysmeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
1228
      logMetacat.debug("Inserting new system metadata with modified date " + 
1229
          sysmeta.getDateSysMetadataModified());
1230
      
1231
      //insert the system metadata
1232
      try {
1233
        // note: the calling subclass handles the map hazelcast lock/unlock
1234
      	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
1235
      	
1236
      } catch (Exception e) {
1237
          throw new ServiceFailure("1190", e.getMessage());
1238
          
1239
	    }  
1240
  }
1241

    
1242
  /**
1243
   * Update a systemMetadata document
1244
   * 
1245
   * @param sysMeta - the system metadata object in the system to update
1246
   */
1247
    protected void updateSystemMetadata(SystemMetadata sysMeta)
1248
        throws ServiceFailure {
1249

    
1250
        logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
1251
        sysMeta.setDateSysMetadataModified(new Date());
1252
        try {
1253
            HazelcastService.getInstance().getSystemMetadataMap().lock(sysMeta.getIdentifier());
1254
            HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
1255

    
1256
        } catch (Exception e) {
1257
            throw new ServiceFailure("4862", e.getMessage());
1258

    
1259
        } finally {
1260
            HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
1261

    
1262
        }
1263

    
1264
    }
1265
  
1266
  /**
1267
   * Given a Permission, returns a list of all permissions that it encompasses
1268
   * Permissions are hierarchical so that WRITE also allows READ.
1269
   * @param permission
1270
   * @return list of included Permissions for the given permission
1271
   */
1272
  protected List<Permission> expandPermissions(Permission permission) {
1273
	  	List<Permission> expandedPermissions = new ArrayList<Permission>();
1274
	    if (permission.equals(Permission.READ)) {
1275
	    	expandedPermissions.add(Permission.READ);
1276
	    }
1277
	    if (permission.equals(Permission.WRITE)) {
1278
	    	expandedPermissions.add(Permission.READ);
1279
	    	expandedPermissions.add(Permission.WRITE);
1280
	    }
1281
	    if (permission.equals(Permission.CHANGE_PERMISSION)) {
1282
	    	expandedPermissions.add(Permission.READ);
1283
	    	expandedPermissions.add(Permission.WRITE);
1284
	    	expandedPermissions.add(Permission.CHANGE_PERMISSION);
1285
	    }
1286
	    return expandedPermissions;
1287
  }
1288

    
1289
  /*
1290
   * Write a stream to a file
1291
   * 
1292
   * @param dir - the directory to write to
1293
   * @param fileName - the file name to write to
1294
   * @param data - the object bytes as an input stream
1295
   * 
1296
   * @return newFile - the new file created
1297
   * 
1298
   * @throws ServiceFailure
1299
   */
1300
  private File writeStreamToFile(File dir, String fileName, InputStream data) 
1301
    throws ServiceFailure {
1302
    
1303
    File newFile = new File(dir, fileName);
1304
    logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1305

    
1306
    try {
1307
        if (newFile.createNewFile()) {
1308
          // write data stream to desired file
1309
          OutputStream os = new FileOutputStream(newFile);
1310
          long length = IOUtils.copyLarge(data, os);
1311
          os.flush();
1312
          os.close();
1313
        } else {
1314
          logMetacat.debug("File creation failed, or file already exists.");
1315
          throw new ServiceFailure("1190", "File already exists: " + fileName);
1316
        }
1317
    } catch (FileNotFoundException e) {
1318
      logMetacat.debug("FNF: " + e.getMessage());
1319
      throw new ServiceFailure("1190", "File not found: " + fileName + " " 
1320
                + e.getMessage());
1321
    } catch (IOException e) {
1322
      logMetacat.debug("IOE: " + e.getMessage());
1323
      throw new ServiceFailure("1190", "File was not written: " + fileName 
1324
                + " " + e.getMessage());
1325
    }
1326

    
1327
    return newFile;
1328
  }
1329

    
1330
  /*
1331
   * Returns a list of nodes that have been registered with the DataONE infrastructure
1332
   * that match the given session subject
1333
   * @return nodes - List of nodes from the registry with a matching session subject
1334
   * 
1335
   * @throws ServiceFailure
1336
   * @throws NotImplemented
1337
   */
1338
  protected List<Node> listNodesBySubject(Subject subject) 
1339
      throws ServiceFailure, NotImplemented {
1340
      List<Node> nodeList = new ArrayList<Node>();
1341
      
1342
      CNode cn = D1Client.getCN();
1343
      List<Node> nodes = cn.listNodes().getNodeList();
1344
      
1345
      // find the node in the node list
1346
      for ( Node node : nodes ) {
1347
          
1348
          List<Subject> nodeSubjects = node.getSubjectList();
1349
          if (nodeSubjects != null) {    
1350
	          // check if the session subject is in the node subject list
1351
	          for (Subject nodeSubject : nodeSubjects) {
1352
	              if ( nodeSubject.equals(subject) ) { // subject of session == node subject
1353
	                  nodeList.add(node);  
1354
	              }                              
1355
	          }
1356
          }
1357
      }
1358
      
1359
      return nodeList;
1360
      
1361
  }
1362

    
1363
/**
1364
   * Archives an object, where the object is either a 
1365
   * data object or a science metadata object.
1366
   * 
1367
   * @param session - the Session object containing the credentials for the Subject
1368
   * @param pid - The object identifier to be archived
1369
   * 
1370
   * @return pid - the identifier of the object used for the archiving
1371
   * 
1372
   * @throws InvalidToken
1373
   * @throws ServiceFailure
1374
   * @throws NotAuthorized
1375
   * @throws NotFound
1376
   * @throws NotImplemented
1377
   * @throws InvalidRequest
1378
   */
1379
  public Identifier archive(Session session, Identifier pid) 
1380
      throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
1381

    
1382
      String localId = null;
1383
      boolean allowed = false;
1384
      String username = Constants.SUBJECT_PUBLIC;
1385
      String[] groupnames = null;
1386
      if (session == null) {
1387
      	throw new InvalidToken("1330", "No session has been provided");
1388
      } else {
1389
          username = session.getSubject().getValue();
1390
          if (session.getSubjectInfo() != null) {
1391
              List<Group> groupList = session.getSubjectInfo().getGroupList();
1392
              if (groupList != null) {
1393
                  groupnames = new String[groupList.size()];
1394
                  for (int i = 0; i > groupList.size(); i++) {
1395
                      groupnames[i] = groupList.get(i).getGroupName();
1396
                  }
1397
              }
1398
          }
1399
      }
1400

    
1401
      // do we have a valid pid?
1402
      if (pid == null || pid.getValue().trim().equals("")) {
1403
          throw new ServiceFailure("1350", "The provided identifier was invalid.");
1404
      }
1405

    
1406
      // check for the existing identifier
1407
      try {
1408
          localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
1409
      } catch (McdbDocNotFoundException e) {
1410
          throw new NotFound("1340", "The object with the provided " + "identifier was not found.");
1411
      }
1412

    
1413
      // does the subject have archive (a D1 CHANGE_PERMISSION level) privileges on the pid?
1414
      try {
1415
			allowed = isAuthorized(session, pid, Permission.CHANGE_PERMISSION);
1416
		} catch (InvalidRequest e) {
1417
          throw new ServiceFailure("1350", e.getDescription());
1418
		}
1419
          
1420

    
1421
      if (allowed) {
1422
          try {
1423
              // archive the document
1424
              DocumentImpl.delete(localId, username, groupnames, null, false);
1425
              EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, Event.DELETE.xmlValue());
1426

    
1427
              // archive it
1428
              SystemMetadata sysMeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
1429
              sysMeta.setArchived(true);
1430
              sysMeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
1431
              HazelcastService.getInstance().getSystemMetadataMap().put(pid, sysMeta);
1432
              
1433
          } catch (McdbDocNotFoundException e) {
1434
              throw new NotFound("1340", "The provided identifier was invalid.");
1435

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

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

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

    
1446
      } else {
1447
          throw new NotAuthorized("1320", "The provided identity does not have " + "permission to archive the object on the Node.");
1448
      }
1449

    
1450
      return pid;
1451
  }
1452

    
1453

    
1454
}
(2-2/5)