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

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

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

    
41
import javax.servlet.http.HttpServletRequest;
42

    
43
import org.apache.commons.io.IOUtils;
44
import org.apache.log4j.Logger;
45
import org.dataone.client.CNode;
46
import org.dataone.client.D1Client;
47
import org.dataone.client.ObjectFormatCache;
48
import org.dataone.service.exceptions.BaseException;
49
import org.dataone.service.exceptions.IdentifierNotUnique;
50
import org.dataone.service.exceptions.InsufficientResources;
51
import org.dataone.service.exceptions.InvalidRequest;
52
import org.dataone.service.exceptions.InvalidSystemMetadata;
53
import org.dataone.service.exceptions.InvalidToken;
54
import org.dataone.service.exceptions.NotAuthorized;
55
import org.dataone.service.exceptions.NotFound;
56
import org.dataone.service.exceptions.NotImplemented;
57
import org.dataone.service.exceptions.ServiceFailure;
58
import org.dataone.service.exceptions.UnsupportedType;
59
import org.dataone.service.types.v1.AccessRule;
60
import org.dataone.service.types.v1.DescribeResponse;
61
import org.dataone.service.types.v1.Event;
62
import org.dataone.service.types.v1.Group;
63
import org.dataone.service.types.v1.Identifier;
64
import org.dataone.service.types.v1.Log;
65
import org.dataone.service.types.v1.Node;
66
import org.dataone.service.types.v1.NodeReference;
67
import org.dataone.service.types.v1.NodeType;
68
import org.dataone.service.types.v1.ObjectFormat;
69
import org.dataone.service.types.v1.Permission;
70
import org.dataone.service.types.v1.Replica;
71
import org.dataone.service.types.v1.Session;
72
import org.dataone.service.types.v1.Subject;
73
import org.dataone.service.types.v1.SystemMetadata;
74
import org.dataone.service.types.v1.util.AuthUtils;
75
import org.dataone.service.types.v1.util.ChecksumUtil;
76
import org.dataone.service.util.Constants;
77

    
78
import edu.ucsb.nceas.metacat.AccessionNumberException;
79
import edu.ucsb.nceas.metacat.DocumentImpl;
80
import edu.ucsb.nceas.metacat.EventLog;
81
import edu.ucsb.nceas.metacat.IdentifierManager;
82
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
83
import edu.ucsb.nceas.metacat.MetacatHandler;
84
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
85
import edu.ucsb.nceas.metacat.database.DBConnection;
86
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
87
import edu.ucsb.nceas.metacat.dataone.hazelcast.HazelcastService;
88
import edu.ucsb.nceas.metacat.properties.PropertyService;
89
import edu.ucsb.nceas.metacat.replication.ForceReplicationHandler;
90
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
91

    
92
public abstract class D1NodeService {
93
  
94
  private static Logger logMetacat = Logger.getLogger(D1NodeService.class);
95

    
96
  /** For logging the operations */
97
  protected HttpServletRequest request;
98
  
99
  /* reference to the metacat handler */
100
  protected MetacatHandler handler;
101
  
102
  /* parameters set in the incoming request */
103
  private Hashtable<String, String[]> params;
104
  
105
  /**
106
   * limit paged results sets to a configured maximum
107
   */
108
  protected static int MAXIMUM_DB_RECORD_COUNT = 7000;
109
  
110
  static {
111
		try {
112
			MAXIMUM_DB_RECORD_COUNT = Integer.valueOf(PropertyService.getProperty("database.webResultsetSize"));
113
		} catch (Exception e) {
114
			logMetacat.warn("Could not set MAXIMUM_DB_RECORD_COUNT", e);
115
		}
116
	}
117
  
118
  /**
119
   * out-of-band session object to be used when not passed in as a method parameter
120
   */
121
  protected Session session;
122

    
123
  /**
124
   * Constructor - used to set the metacatUrl from a subclass extending D1NodeService
125
   * 
126
   * @param metacatUrl - the URL of the metacat service, including the ending /d1
127
   */
128
  public D1NodeService(HttpServletRequest request) {
129
		this.request = request;
130
	}
131

    
132
  /**
133
   * retrieve the out-of-band session
134
   * @return
135
   */
136
  	public Session getSession() {
137
		return session;
138
	}
139
  	
140
  	/**
141
  	 * Set the out-of-band session
142
  	 * @param session
143
  	 */
144
	public void setSession(Session session) {
145
		this.session = session;
146
	}
147

    
148
  /**
149
   * This method provides a lighter weight mechanism than 
150
   * getSystemMetadata() for a client to determine basic 
151
   * properties of the referenced object.
152
   * 
153
   * @param session - the Session object containing the credentials for the Subject
154
   * @param pid - the identifier of the object to be described
155
   * 
156
   * @return describeResponse - A set of values providing a basic description 
157
   *                            of the object.
158
   * 
159
   * @throws InvalidToken
160
   * @throws ServiceFailure
161
   * @throws NotAuthorized
162
   * @throws NotFound
163
   * @throws NotImplemented
164
   * @throws InvalidRequest
165
   */
166
  public DescribeResponse describe(Session session, Identifier pid) 
167
      throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
168

    
169
    // get system metadata and construct the describe response
170
      SystemMetadata sysmeta = getSystemMetadata(session, pid);
171
      DescribeResponse describeResponse = 
172
      	new DescribeResponse(sysmeta.getFormatId(), sysmeta.getSize(), 
173
      			sysmeta.getDateSysMetadataModified(),
174
      			sysmeta.getChecksum(), sysmeta.getSerialVersion());
175

    
176
      return describeResponse;
177

    
178
  }
179
  
180
  /**
181
   * Deletes an object from the Member Node, where the object is either a 
182
   * data object or a science metadata object.
183
   * 
184
   * @param session - the Session object containing the credentials for the Subject
185
   * @param pid - The object identifier to be deleted
186
   * 
187
   * @return pid - the identifier of the object used for the deletion
188
   * 
189
   * @throws InvalidToken
190
   * @throws ServiceFailure
191
   * @throws NotAuthorized
192
   * @throws NotFound
193
   * @throws NotImplemented
194
   * @throws InvalidRequest
195
   */
196
  public Identifier delete(Session session, Identifier pid) 
197
      throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
198

    
199
      String localId = null;
200
      if (session == null) {
201
      	throw new InvalidToken("1330", "No session has been provided");
202
      }
203
      // just for logging purposes
204
      String username = session.getSubject().getValue();
205

    
206
      // do we have a valid pid?
207
      if (pid == null || pid.getValue().trim().equals("")) {
208
          throw new ServiceFailure("1350", "The provided identifier was invalid.");
209
      }
210

    
211
      // check for the existing identifier
212
      try {
213
          localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
214
      } catch (McdbDocNotFoundException e) {
215
          throw new NotFound("1340", "The object with the provided " + "identifier was not found.");
216
      }
217
      
218
      try {
219
          // delete the document, as admin
220
          DocumentImpl.delete(localId, null, null, null, true);
221
          EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, Event.DELETE.xmlValue());
222

    
223
          // archive it
224
          // DocumentImpl.delete() now sets this
225
          // see https://redmine.dataone.org/issues/3406
226
//          SystemMetadata sysMeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
227
//          sysMeta.setArchived(true);
228
//          sysMeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
229
//          HazelcastService.getInstance().getSystemMetadataMap().put(pid, sysMeta);
230
          
231
      } catch (McdbDocNotFoundException e) {
232
          throw new NotFound("1340", "The provided identifier was invalid.");
233

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

    
237
      } catch (InsufficientKarmaException e) {
238
          if ( logMetacat.isDebugEnabled() ) {
239
              e.printStackTrace();
240
          }
241
          throw new NotAuthorized("1320", "The provided identity does not have " + "permission to DELETE objects on the Member Node.");
242
      
243
      } catch (Exception e) { // for some reason DocumentImpl throws a general Exception
244
          throw new ServiceFailure("1350", "There was a problem deleting the object." + "The error message was: " + e.getMessage());
245
      }
246

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

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

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

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

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

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

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

    
407
        } catch (IOException e) {
408
        	String msg = "The Node is unable to create the object. " +
409
          "There was a problem converting the object to XML";
410
        	logMetacat.info(msg);
411
          throw new ServiceFailure("1190", msg + ": " + e.getMessage());
412

    
413
        }
414
                    
415
      } else {
416
	        
417
	      // DEFAULT CASE: DATA (needs to be checked and completed)
418
	      localId = insertDataObject(object, pid, session);
419
      }   
420
    
421
    }
422

    
423
    logMetacat.debug("Done inserting new object: " + pid.getValue());
424
    
425
    // save the sysmeta
426
    try {
427
    	// lock and unlock of the pid happens in the subclass
428
    	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
429
    	// submit for indexing
430
        HazelcastService.getInstance().getIndexQueue().add(sysmeta);
431
    } catch (Exception e) {
432
    	logMetacat.error("Problem creating system metadata: " + pid.getValue(), e);
433
        throw new ServiceFailure("1190", e.getMessage());
434
	}
435
    
436
    // setting the resulting identifier failed
437
    if (localId == null ) {
438
      throw new ServiceFailure("1190", "The Node is unable to create the object. ");
439
    }
440

    
441
    resultPid = pid;
442
    
443
    logMetacat.debug("create() complete for object: " + pid.getValue());
444

    
445
    return resultPid;
446
  }
447

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

    
474
	  // only admin access to this method
475
	  // see https://redmine.dataone.org/issues/2855
476
	  if (!isAdminAuthorized(session)) {
477
		  throw new NotAuthorized("1460", "Only the CN or admin is allowed to harvest logs from this node");
478
	  }
479
	  
480
    IdentifierManager im = IdentifierManager.getInstance();
481
    EventLog el = EventLog.getInstance();
482
    if ( fromDate == null ) {
483
      logMetacat.debug("setting fromdate from null");
484
      fromDate = new Date(1);
485
    }
486
    if ( toDate == null ) {
487
      logMetacat.debug("setting todate from null");
488
      toDate = new Date();
489
    }
490

    
491
    if ( start == null ) {
492
    	start = 0;	
493
    }
494
    
495
    if ( count == null ) {
496
    	count = 1000;
497
    }
498
    
499
    // safeguard against large requests
500
    if (count > MAXIMUM_DB_RECORD_COUNT) {
501
    	count = MAXIMUM_DB_RECORD_COUNT;
502
    }
503

    
504
    String[] filterDocid = null;
505
    if (pidFilter != null) {
506
		try {
507
	      String localId = im.getLocalId(pidFilter);
508
	      filterDocid = new String[] {localId};
509
	    } catch (Exception ex) { 
510
	    	String msg = "Could not find localId for given pidFilter '" + pidFilter + "'";
511
	        logMetacat.warn(msg, ex);
512
	        //throw new InvalidRequest("1480", msg);
513
	    }
514
    }
515
    
516
    logMetacat.debug("fromDate: " + fromDate);
517
    logMetacat.debug("toDate: " + toDate);
518

    
519
    Log log = el.getD1Report(null, null, filterDocid, event,
520
        new java.sql.Timestamp(fromDate.getTime()),
521
        new java.sql.Timestamp(toDate.getTime()), false, start, count);
522
    
523
    logMetacat.info("getLogRecords");
524
    return log;
525
  }
526
    
527
  /**
528
   * Return the object identified by the given object identifier
529
   * 
530
   * @param session - the Session object containing the credentials for the Subject
531
   * @param pid - the object identifier for the given object
532
   * 
533
   * TODO: The D1 Authorization API doesn't provide information on which 
534
   * authentication system the Subject belongs to, and so it's not possible to
535
   * discern which Person or Group is a valid KNB LDAP DN.  Fix this.
536
   * 
537
   * @return inputStream - the input stream of the given object
538
   * 
539
   * @throws InvalidToken
540
   * @throws ServiceFailure
541
   * @throws NotAuthorized
542
   * @throws InvalidRequest
543
   * @throws NotImplemented
544
   */
545
  public InputStream get(Session session, Identifier pid) 
546
    throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
547
    NotImplemented {
548
    
549
    InputStream inputStream = null; // bytes to be returned
550
    handler = new MetacatHandler(new Timer());
551
    boolean allowed = false;
552
    String localId; // the metacat docid for the pid
553
    
554
    // get the local docid from Metacat
555
    try {
556
      localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
557
    
558
    } catch (McdbDocNotFoundException e) {
559
      throw new NotFound("1020", "The object specified by " + 
560
                         pid.getValue() +
561
                         " does not exist at this node.");
562
    }
563
    
564
    // check for authorization
565
    try {
566
		allowed = isAuthorized(session, pid, Permission.READ);
567
	} catch (InvalidRequest e) {
568
		throw new ServiceFailure("1030", e.getDescription());
569
	}
570
    
571
    // if the person is authorized, perform the read
572
    if (allowed) {
573
      try {
574
        inputStream = handler.read(localId);
575
      } catch (Exception e) {
576
        throw new NotFound("1020", "The object specified by " + 
577
            pid.getValue() +
578
            "could not be returned due to error: " +
579
            e.getMessage());
580
      }
581
    }
582

    
583
    // if we fail to set the input stream
584
    if ( inputStream == null ) {
585
      throw new NotFound("1020", "The object specified by " + 
586
                         pid.getValue() +
587
                         "does not exist at this node.");
588
    }
589
    
590
	// log the read event
591
    String principal = Constants.SUBJECT_PUBLIC;
592
    if (session != null && session.getSubject() != null) {
593
    	principal = session.getSubject().getValue();
594
    }
595
    EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), principal, localId, "read");
596
    
597
    return inputStream;
598
  }
599

    
600
  /**
601
   * Return the system metadata for a given object
602
   * 
603
   * @param session - the Session object containing the credentials for the Subject
604
   * @param pid - the object identifier for the given object
605
   * 
606
   * @return inputStream - the input stream of the given system metadata object
607
   * 
608
   * @throws InvalidToken
609
   * @throws ServiceFailure
610
   * @throws NotAuthorized
611
   * @throws NotFound
612
   * @throws InvalidRequest
613
   * @throws NotImplemented
614
   */
615
    public SystemMetadata getSystemMetadata(Session session, Identifier pid)
616
        throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
617
        NotImplemented {
618

    
619
        boolean isAuthorized = false;
620
        SystemMetadata systemMetadata = null;
621
        List<Replica> replicaList = null;
622
        NodeReference replicaNodeRef = null;
623
        List<Node> nodeListBySubject = null;
624
        Subject subject = null;
625
        
626
        if (session != null ) {
627
            subject = session.getSubject();
628
        }
629
        
630
        // check normal authorization
631
        BaseException originalAuthorizationException = null;
632
        if (!isAuthorized) {
633
            try {
634
                isAuthorized = isAuthorized(session, pid, Permission.READ);
635

    
636
            } catch (InvalidRequest e) {
637
                throw new ServiceFailure("1090", e.getDescription());
638
            } catch (NotAuthorized nae) {
639
            	// catch this for later
640
            	originalAuthorizationException = nae;
641
			}
642
        }
643
        
644
        // get the system metadata first because we need the replica list for auth
645
        systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
646
        
647
        // check the replica information to expand access to MNs that might need it
648
        if (!isAuthorized) {
649
        	
650
	        try {
651
	        	
652
	            // if MNs are listed as replicas, allow access
653
	            if ( systemMetadata != null ) {
654
	                replicaList = systemMetadata.getReplicaList();
655
	                // only check if there are in fact replicas listed
656
	                if ( replicaList != null ) {
657
	                    
658
	                    if ( subject != null ) {
659
	                        // get the list of nodes with a matching node subject
660
	                        try {
661
	                            nodeListBySubject = listNodesBySubject(session.getSubject());
662
	
663
	                        } catch (BaseException e) {
664
	                            // Unexpected error contacting the CN via D1Client
665
	                            String msg = "Caught an unexpected error while trying "
666
	                                    + "to potentially authorize system metadata access "
667
	                                    + "based on the session subject. The error was "
668
	                                    + e.getMessage();
669
	                            logMetacat.error(msg);
670
	                            if (logMetacat.isDebugEnabled()) {
671
	                                e.printStackTrace();
672
	
673
	                            }
674
	                            // isAuthorized is still false 
675
	                        }
676
	
677
	                    }
678
	                    if (nodeListBySubject != null) {
679
	                        // compare node ids to replica node ids
680
	                        outer: for (Replica replica : replicaList) {
681
	                            replicaNodeRef = replica.getReplicaMemberNode();
682
	
683
	                            for (Node node : nodeListBySubject) {
684
	                                if (node.getIdentifier().equals(replicaNodeRef)) {
685
	                                    // node id via session subject matches a replica node
686
	                                    isAuthorized = true;
687
	                                    break outer;
688
	                                }
689
	                            }
690
	                        }
691
	                    }
692
	                }
693
	            }
694
	            
695
	            // if we still aren't authorized, then we are done
696
	            if (!isAuthorized) {
697
	                throw new NotAuthorized("1400", Permission.READ
698
	                        + " not allowed on " + pid.getValue());
699
	            }
700

    
701
	        } catch (RuntimeException e) {
702
	        	e.printStackTrace();
703
	            // convert hazelcast RuntimeException to ServiceFailure
704
	            throw new ServiceFailure("1090", "Unexpected error getting system metadata for: " + 
705
	                pid.getValue());	
706
	        }
707
	        
708
        }
709
        
710
        // It wasn't in the map
711
        if ( systemMetadata == null ) {
712
            throw new NotFound("1420", "No record found for: " + pid.getValue());
713
        }
714
        
715
        return systemMetadata;
716
    }
717
     
718
    
719
    /**
720
     * Test if the specified session represents the authoritative member node for the
721
     * given object specified by the identifier. According the the DataONE documentation, 
722
     * the authoritative member node has all the rights of the *rightsHolder*.
723
     * @param session - the Session object containing the credentials for the Subject
724
     * @param pid - the Identifier of the data object
725
     * @return true if the session represents the authoritative mn.
726
     * @throws ServiceFailure 
727
     * @throws NotImplemented 
728
     */
729
    public boolean isAuthoritativeMNodeAdmin(Session session, Identifier pid) {
730
        boolean allowed = false;
731
        //check the parameters
732
        if(session == null) {
733
            logMetacat.debug("D1NodeService.isAuthoritativeMNodeAdmin - the session object is null and return false.");
734
            return allowed;
735
        } else if (pid == null || pid.getValue() == null || pid.getValue().trim().equals("")) {
736
            logMetacat.debug("D1NodeService.isAuthoritativeMNodeAdmin - the Identifier object is null (not being specified) and return false.");
737
            return allowed;
738
        }
739
        
740
        //Get the subject from the session
741
        Subject subject = session.getSubject();
742
        if(subject != null) {
743
            //Get the authoritative member node info from the system metadata
744
            SystemMetadata sysMeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
745
            if(sysMeta != null) {
746
                NodeReference authoritativeMNode = sysMeta.getAuthoritativeMemberNode();
747
                if(authoritativeMNode != null) {
748
                        CNode cn = null;
749
                        try {
750
                            cn = D1Client.getCN();
751
                        } catch (ServiceFailure e) {
752
                            logMetacat.error("D1NodeService.isAuthoritativeMNodeAdmin - couldn't connect to the CN since "+
753
                                            e.getDescription()+ ". The false value will be returned for the AuthoritativeMNodeAdmin.");
754
                            return allowed;
755
                        }
756
                        
757
                        if(cn != null) {
758
                            List<Node> nodes = null;
759
                            try {
760
                                nodes = cn.listNodes().getNodeList();
761
                            } catch (NotImplemented e) {
762
                                logMetacat.error("D1NodeService.isAuthoritativeMNodeAdmin - couldn't get the member nodes list from the CN since "+e.getDescription()+ 
763
                                                ". The false value will be returned for the AuthoritativeMNodeAdmin.");
764
                                return allowed;
765
                            } catch (ServiceFailure ee) {
766
                                logMetacat.error("D1NodeService.isAuthoritativeMNodeAdmin - couldn't get the member nodes list from the CN since "+ee.getDescription()+ 
767
                                                ". The false value will be returned for the AuthoritativeMNodeAdmin.");
768
                                return allowed;
769
                            }
770
                            if(nodes != null) {
771
                                for(Node node : nodes) {
772
                                    //find the authoritative node and get its subjects
773
                                    if (node.getType() == NodeType.MN && node.getIdentifier() != null && node.getIdentifier().equals(authoritativeMNode)) {
774
                                        List<Subject> nodeSubjects = node.getSubjectList();
775
                                        if(nodeSubjects != null) {
776
                                            // check if the session subject is in the node subject list
777
                                            for (Subject nodeSubject : nodeSubjects) {
778
                                                logMetacat.debug("D1NodeService.isAuthoritativeMNodeAdmin(), comparing subjects: " +
779
                                                    nodeSubject.getValue() + " and " + subject.getValue());
780
                                                if ( nodeSubject != null && nodeSubject.equals(subject) ) {
781
                                                    allowed = true; // subject of session == target node subject
782
                                                    break;
783
                                                }
784
                                            }              
785
                                        }
786
                                      
787
                                    }
788
                                }
789
                            }
790
                        }
791
                }
792
            }
793
        }
794
        return allowed;
795
    }
796
    
797
    
798
  /**
799
   * Test if the user identified by the provided token has administrative authorization 
800
   * 
801
   * @param session - the Session object containing the credentials for the Subject
802
   * 
803
   * @return true if the user is admin
804
   * 
805
   * @throws ServiceFailure
806
   * @throws InvalidToken
807
   * @throws NotFound
808
   * @throws NotAuthorized
809
   * @throws NotImplemented
810
   */
811
  public boolean isAdminAuthorized(Session session) 
812
      throws ServiceFailure, InvalidToken, NotAuthorized,
813
      NotImplemented {
814

    
815
      boolean allowed = false;
816
      
817
      // must have a session in order to check admin 
818
      if (session == null) {
819
         logMetacat.debug("In isAdminAuthorized(), session is null ");
820
         return false;
821
      }
822
      
823
      logMetacat.debug("In isAdminAuthorized(), checking CN or MN authorization for " +
824
           session.getSubject().getValue());
825
      
826
      // check if this is the node calling itself (MN)
827
      allowed = isNodeAdmin(session);
828
      
829
      // check the CN list
830
      if (!allowed) {
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 administrative authorization 
870
   * on this node because they are calling themselves
871
   * 
872
   * @param session - the Session object containing the credentials for the Subject
873
   * 
874
   * @return true if the user is this node
875
   * @throws ServiceFailure 
876
   * @throws NotImplemented 
877
   */
878
  public boolean isNodeAdmin(Session session) throws NotImplemented, ServiceFailure {
879

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

    
935
    boolean allowed = false;
936
    
937
    if (permission == null) {
938
    	throw new InvalidRequest("1761", "Permission was not provided or is invalid");
939
    }
940
    
941
    // permissions are hierarchical
942
    List<Permission> expandedPermissions = null;
943
    
944
    // always allow CN access
945
    if ( isAdminAuthorized(session) ) {
946
        allowed = true;
947
        return allowed;
948
        
949
    }
950
    
951
    // the authoritative member node of the pid always has the access as well.
952
    if (isAuthoritativeMNodeAdmin(session, pid)) {
953
        allowed = true;
954
        return allowed;
955
    }
956
    
957
    // get the subject[s] from the session
958
	//defer to the shared util for recursively compiling the subjects	
959
	Set<Subject> subjects = AuthUtils.authorizedClientSubjects(session);
960
    
961
	// track the identities we have checked against
962
	StringBuffer includedSubjects = new StringBuffer();
963
    	
964
    // get the system metadata
965
    String pidStr = pid.getValue();
966
    SystemMetadata systemMetadata = null;
967
    try {
968
        systemMetadata = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
969

    
970
    } catch (Exception e) {
971
        // convert Hazelcast RuntimeException to NotFound
972
        logMetacat.error("An error occurred while getting system metadata for identifier " +
973
            pid.getValue() + ". The error message was: " + e.getMessage());
974
        throw new NotFound("1800", "No record found for " + pidStr);
975
        
976
    } 
977
    
978
    // throw not found if it was not found
979
    if (systemMetadata == null) {
980
    	throw new NotFound("1800", "No system metadata could be found for given PID: " + pidStr);
981
    }
982
	    
983
    // do we own it?
984
    for (Subject s: subjects) {
985
      logMetacat.debug("Comparing \t" + 
986
                       systemMetadata.getRightsHolder().getValue() +
987
                       " \tagainst \t" + s.getValue());
988
      	includedSubjects.append(s.getValue() + "; ");
989
    	allowed = systemMetadata.getRightsHolder().equals(s);
990
    	if (allowed) {
991
    		return allowed;
992
    	}
993
    }    
994
    
995
    // otherwise check the access rules
996
    try {
997
	    List<AccessRule> allows = systemMetadata.getAccessPolicy().getAllowList();
998
	    search: // label break
999
	    for (AccessRule accessRule: allows) {
1000
	      for (Subject s: subjects) {
1001
	        logMetacat.debug("Checking allow access rule for subject: " + s.getValue());
1002
	        if (accessRule.getSubjectList().contains(s)) {
1003
	        	logMetacat.debug("Access rule contains subject: " + s.getValue());
1004
	        	for (Permission p: accessRule.getPermissionList()) {
1005
		        	logMetacat.debug("Checking permission: " + p.xmlValue());
1006
	        		expandedPermissions = expandPermissions(p);
1007
	        		allowed = expandedPermissions.contains(permission);
1008
	        		if (allowed) {
1009
			        	logMetacat.info("Permission granted: " + p.xmlValue() + " to " + s.getValue());
1010
	        			break search; //label break
1011
	        		}
1012
	        	}
1013
        		
1014
	        }
1015
	      }
1016
	    }
1017
    } catch (Exception e) {
1018
    	// catch all for errors - safe side should be to deny the access
1019
    	logMetacat.error("Problem checking authorization - defaulting to deny", e);
1020
		allowed = false;
1021
	  
1022
    }
1023
    
1024
    // throw or return?
1025
    if (!allowed) {
1026
      throw new NotAuthorized("1820", permission + " not allowed on " + pidStr + " for subject[s]: " + includedSubjects.toString() );
1027
    }
1028
    
1029
    return allowed;
1030
    
1031
  }
1032
  
1033
  /*
1034
   * parse a logEntry and get the relevant field from it
1035
   * 
1036
   * @param fieldname
1037
   * @param entry
1038
   * @return
1039
   */
1040
  private String getLogEntryField(String fieldname, String entry) {
1041
    String begin = "<" + fieldname + ">";
1042
    String end = "</" + fieldname + ">";
1043
    // logMetacat.debug("looking for " + begin + " and " + end +
1044
    // " in entry " + entry);
1045
    String s = entry.substring(entry.indexOf(begin) + begin.length(), entry
1046
        .indexOf(end));
1047
    logMetacat.debug("entry " + fieldname + " : " + s);
1048
    return s;
1049
  }
1050

    
1051
  /** 
1052
   * Determine if a given object should be treated as an XML science metadata
1053
   * object. 
1054
   * 
1055
   * @param sysmeta - the SystemMetadata describing the object
1056
   * @return true if the object should be treated as science metadata
1057
   */
1058
  public static boolean isScienceMetadata(SystemMetadata sysmeta) {
1059
    
1060
    ObjectFormat objectFormat = null;
1061
    boolean isScienceMetadata = false;
1062
    
1063
    try {
1064
      objectFormat = ObjectFormatCache.getInstance().getFormat(sysmeta.getFormatId());
1065
      if ( objectFormat.getFormatType().equals("METADATA") ) {
1066
      	isScienceMetadata = true;
1067
      	
1068
      }
1069
      
1070
       
1071
    } catch (ServiceFailure e) {
1072
      logMetacat.debug("There was a problem determining if the object identified by" + 
1073
          sysmeta.getIdentifier().getValue() + 
1074
          " is science metadata: " + e.getMessage());
1075
    
1076
    } catch (NotFound e) {
1077
      logMetacat.debug("There was a problem determining if the object identified by" + 
1078
          sysmeta.getIdentifier().getValue() + 
1079
          " is science metadata: " + e.getMessage());
1080
    
1081
    }
1082
    
1083
    return isScienceMetadata;
1084

    
1085
  }
1086
  
1087
  /**
1088
   * Check fro whitespace in the given pid.
1089
   * null pids are also invalid by default
1090
   * @param pid
1091
   * @return
1092
   */
1093
  public static boolean isValidIdentifier(Identifier pid) {
1094
	  if (pid != null && pid.getValue() != null && pid.getValue().length() > 0) {
1095
		  return !pid.getValue().matches(".*\\s+.*");
1096
	  } 
1097
	  return false;
1098
  }
1099
  
1100
  
1101
  /**
1102
   * Insert or update an XML document into Metacat
1103
   * 
1104
   * @param xml - the XML document to insert or update
1105
   * @param pid - the identifier to be used for the resulting object
1106
   * 
1107
   * @return localId - the resulting docid of the document created or updated
1108
   * 
1109
   */
1110
  public String insertOrUpdateDocument(String xml, Identifier pid, 
1111
    Session session, String insertOrUpdate) 
1112
    throws ServiceFailure {
1113
    
1114
  	logMetacat.debug("Starting to insert xml document...");
1115
    IdentifierManager im = IdentifierManager.getInstance();
1116

    
1117
    // generate pid/localId pair for sysmeta
1118
    String localId = null;
1119
    
1120
    if(insertOrUpdate.equals("insert")) {
1121
      localId = im.generateLocalId(pid.getValue(), 1);
1122
      
1123
    } else {
1124
      //localid should already exist in the identifier table, so just find it
1125
      try {
1126
        logMetacat.debug("Updating pid " + pid.getValue());
1127
        logMetacat.debug("looking in identifier table for pid " + pid.getValue());
1128
        
1129
        localId = im.getLocalId(pid.getValue());
1130
        
1131
        logMetacat.debug("localId: " + localId);
1132
        //increment the revision
1133
        String docid = localId.substring(0, localId.lastIndexOf("."));
1134
        String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
1135
        int rev = new Integer(revS).intValue();
1136
        rev++;
1137
        docid = docid + "." + rev;
1138
        localId = docid;
1139
        logMetacat.debug("incremented localId: " + localId);
1140
      
1141
      } catch(McdbDocNotFoundException e) {
1142
        throw new ServiceFailure("1030", "D1NodeService.insertOrUpdateDocument(): " +
1143
            "pid " + pid.getValue() + 
1144
            " should have been in the identifier table, but it wasn't: " + 
1145
            e.getMessage());
1146
      
1147
      }
1148
      
1149
    }
1150

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

    
1251
    logMetacat.debug("Case DATA: starting to write to disk.");
1252
	if (locked) {
1253

    
1254
          File dataDirectory = new File(datafilepath);
1255
          dataDirectory.mkdirs();
1256
  
1257
          File newFile = writeStreamToFile(dataDirectory, localId, object);
1258
  
1259
          // TODO: Check that the file size matches SystemMetadata
1260
          // long size = newFile.length();
1261
          // if (size == 0) {
1262
          //     throw new IOException("Uploaded file is 0 bytes!");
1263
          // }
1264
  
1265
          // Register the file in the database (which generates an exception
1266
          // if the localId is not acceptable or other untoward things happen
1267
          try {
1268
            logMetacat.debug("Registering document...");
1269
            DocumentImpl.registerDocument(localId, "BIN", localId,
1270
                    username, groupnames);
1271
            logMetacat.debug("Registration step completed.");
1272
            
1273
          } catch (SQLException e) {
1274
            //newFile.delete();
1275
            logMetacat.debug("SQLE: " + e.getMessage());
1276
            e.printStackTrace(System.out);
1277
            throw new ServiceFailure("1190", "Registration failed: " + 
1278
            		e.getMessage());
1279
            
1280
          } catch (AccessionNumberException e) {
1281
            //newFile.delete();
1282
            logMetacat.debug("ANE: " + e.getMessage());
1283
            e.printStackTrace(System.out);
1284
            throw new ServiceFailure("1190", "Registration failed: " + 
1285
            	e.getMessage());
1286
            
1287
          } catch (Exception e) {
1288
            //newFile.delete();
1289
            logMetacat.debug("Exception: " + e.getMessage());
1290
            e.printStackTrace(System.out);
1291
            throw new ServiceFailure("1190", "Registration failed: " + 
1292
            	e.getMessage());
1293
          }
1294
  
1295
          logMetacat.debug("Logging the creation event.");
1296
          EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, "create");
1297
  
1298
          // Schedule replication for this data file, the "insert" action is important here!
1299
          logMetacat.debug("Scheduling replication.");
1300
          ForceReplicationHandler frh = new ForceReplicationHandler(localId, "insert", false, null);
1301
      }
1302
      
1303
      return localId;
1304
    
1305
  }
1306

    
1307
  /**
1308
   * Insert a systemMetadata document and return its localId
1309
   */
1310
  public void insertSystemMetadata(SystemMetadata sysmeta) 
1311
      throws ServiceFailure {
1312
      
1313
  	  logMetacat.debug("Starting to insert SystemMetadata...");
1314
      sysmeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
1315
      logMetacat.debug("Inserting new system metadata with modified date " + 
1316
          sysmeta.getDateSysMetadataModified());
1317
      
1318
      //insert the system metadata
1319
      try {
1320
        // note: the calling subclass handles the map hazelcast lock/unlock
1321
      	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
1322
      	// submit for indexing
1323
        HazelcastService.getInstance().getIndexQueue().add(sysmeta);
1324
      } catch (Exception e) {
1325
          throw new ServiceFailure("1190", e.getMessage());
1326
          
1327
	    }  
1328
  }
1329

    
1330
  /**
1331
   * Update a systemMetadata document
1332
   * 
1333
   * @param sysMeta - the system metadata object in the system to update
1334
   */
1335
    protected void updateSystemMetadata(SystemMetadata sysMeta)
1336
        throws ServiceFailure {
1337

    
1338
        logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
1339
        sysMeta.setDateSysMetadataModified(new Date());
1340
        try {
1341
            HazelcastService.getInstance().getSystemMetadataMap().lock(sysMeta.getIdentifier());
1342
            HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
1343
            // submit for indexing
1344
            HazelcastService.getInstance().getIndexQueue().add(sysMeta);
1345
        } catch (Exception e) {
1346
            throw new ServiceFailure("4862", e.getMessage());
1347

    
1348
        } finally {
1349
            HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
1350

    
1351
        }
1352

    
1353
    }
1354
  
1355
  /**
1356
   * Given a Permission, returns a list of all permissions that it encompasses
1357
   * Permissions are hierarchical so that WRITE also allows READ.
1358
   * @param permission
1359
   * @return list of included Permissions for the given permission
1360
   */
1361
  protected List<Permission> expandPermissions(Permission permission) {
1362
	  	List<Permission> expandedPermissions = new ArrayList<Permission>();
1363
	    if (permission.equals(Permission.READ)) {
1364
	    	expandedPermissions.add(Permission.READ);
1365
	    }
1366
	    if (permission.equals(Permission.WRITE)) {
1367
	    	expandedPermissions.add(Permission.READ);
1368
	    	expandedPermissions.add(Permission.WRITE);
1369
	    }
1370
	    if (permission.equals(Permission.CHANGE_PERMISSION)) {
1371
	    	expandedPermissions.add(Permission.READ);
1372
	    	expandedPermissions.add(Permission.WRITE);
1373
	    	expandedPermissions.add(Permission.CHANGE_PERMISSION);
1374
	    }
1375
	    return expandedPermissions;
1376
  }
1377

    
1378
  /*
1379
   * Write a stream to a file
1380
   * 
1381
   * @param dir - the directory to write to
1382
   * @param fileName - the file name to write to
1383
   * @param data - the object bytes as an input stream
1384
   * 
1385
   * @return newFile - the new file created
1386
   * 
1387
   * @throws ServiceFailure
1388
   */
1389
  private File writeStreamToFile(File dir, String fileName, InputStream data) 
1390
    throws ServiceFailure {
1391
    
1392
    File newFile = new File(dir, fileName);
1393
    logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1394

    
1395
    try {
1396
        if (newFile.createNewFile()) {
1397
          // write data stream to desired file
1398
          OutputStream os = new FileOutputStream(newFile);
1399
          long length = IOUtils.copyLarge(data, os);
1400
          os.flush();
1401
          os.close();
1402
        } else {
1403
          logMetacat.debug("File creation failed, or file already exists.");
1404
          throw new ServiceFailure("1190", "File already exists: " + fileName);
1405
        }
1406
    } catch (FileNotFoundException e) {
1407
      logMetacat.debug("FNF: " + e.getMessage());
1408
      throw new ServiceFailure("1190", "File not found: " + fileName + " " 
1409
                + e.getMessage());
1410
    } catch (IOException e) {
1411
      logMetacat.debug("IOE: " + e.getMessage());
1412
      throw new ServiceFailure("1190", "File was not written: " + fileName 
1413
                + " " + e.getMessage());
1414
    }
1415

    
1416
    return newFile;
1417
  }
1418

    
1419
  /*
1420
   * Returns a list of nodes that have been registered with the DataONE infrastructure
1421
   * that match the given session subject
1422
   * @return nodes - List of nodes from the registry with a matching session subject
1423
   * 
1424
   * @throws ServiceFailure
1425
   * @throws NotImplemented
1426
   */
1427
  protected List<Node> listNodesBySubject(Subject subject) 
1428
      throws ServiceFailure, NotImplemented {
1429
      List<Node> nodeList = new ArrayList<Node>();
1430
      
1431
      CNode cn = D1Client.getCN();
1432
      List<Node> nodes = cn.listNodes().getNodeList();
1433
      
1434
      // find the node in the node list
1435
      for ( Node node : nodes ) {
1436
          
1437
          List<Subject> nodeSubjects = node.getSubjectList();
1438
          if (nodeSubjects != null) {    
1439
	          // check if the session subject is in the node subject list
1440
	          for (Subject nodeSubject : nodeSubjects) {
1441
	              if ( nodeSubject.equals(subject) ) { // subject of session == node subject
1442
	                  nodeList.add(node);  
1443
	              }                              
1444
	          }
1445
          }
1446
      }
1447
      
1448
      return nodeList;
1449
      
1450
  }
1451

    
1452
  /**
1453
   * Archives an object, where the object is either a 
1454
   * data object or a science metadata object.
1455
   * 
1456
   * @param session - the Session object containing the credentials for the Subject
1457
   * @param pid - The object identifier to be archived
1458
   * 
1459
   * @return pid - the identifier of the object used for the archiving
1460
   * 
1461
   * @throws InvalidToken
1462
   * @throws ServiceFailure
1463
   * @throws NotAuthorized
1464
   * @throws NotFound
1465
   * @throws NotImplemented
1466
   * @throws InvalidRequest
1467
   */
1468
  public Identifier archive(Session session, Identifier pid) 
1469
      throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
1470

    
1471
      String localId = null;
1472
      boolean allowed = false;
1473
      String username = Constants.SUBJECT_PUBLIC;
1474
      String[] groupnames = null;
1475
      if (session == null) {
1476
      	throw new InvalidToken("1330", "No session has been provided");
1477
      } else {
1478
          username = session.getSubject().getValue();
1479
          if (session.getSubjectInfo() != null) {
1480
              List<Group> groupList = session.getSubjectInfo().getGroupList();
1481
              if (groupList != null) {
1482
                  groupnames = new String[groupList.size()];
1483
                  for (int i = 0; i < groupList.size(); i++) {
1484
                      groupnames[i] = groupList.get(i).getGroupName();
1485
                  }
1486
              }
1487
          }
1488
      }
1489

    
1490
      // do we have a valid pid?
1491
      if (pid == null || pid.getValue().trim().equals("")) {
1492
          throw new ServiceFailure("1350", "The provided identifier was invalid.");
1493
      }
1494

    
1495
      // check for the existing identifier
1496
      try {
1497
          localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
1498
      } catch (McdbDocNotFoundException e) {
1499
          throw new NotFound("1340", "The object with the provided " + "identifier was not found.");
1500
      }
1501

    
1502
      // does the subject have archive (a D1 CHANGE_PERMISSION level) privileges on the pid?
1503
      try {
1504
			allowed = isAuthorized(session, pid, Permission.CHANGE_PERMISSION);
1505
		} catch (InvalidRequest e) {
1506
          throw new ServiceFailure("1350", e.getDescription());
1507
		}
1508
          
1509

    
1510
      if (allowed) {
1511
          try {
1512
              // archive the document
1513
              DocumentImpl.delete(localId, null, null, null, false);
1514
              EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, Event.DELETE.xmlValue());
1515

    
1516
              // archive it
1517
              SystemMetadata sysMeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
1518
              sysMeta.setArchived(true);
1519
              sysMeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
1520
              HazelcastService.getInstance().getSystemMetadataMap().put(pid, sysMeta);
1521
              // submit for indexing
1522
              // DocumentImpl call above should do this.
1523
              // see: https://projects.ecoinformatics.org/ecoinfo/issues/6030
1524
              //HazelcastService.getInstance().getIndexQueue().add(sysMeta);
1525
              
1526
          } catch (McdbDocNotFoundException e) {
1527
              throw new NotFound("1340", "The provided identifier was invalid.");
1528

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

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

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

    
1539
      } else {
1540
          throw new NotAuthorized("1320", "The provided identity does not have " + "permission to archive the object on the Node.");
1541
      }
1542

    
1543
      return pid;
1544
  }
1545
  
1546
  public Identifier archive(Identifier pid) throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
1547
	  return archive(null, pid);
1548
  }
1549

    
1550

    
1551
}
(2-2/6)