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: 2014-10-14 18:11:14 -0700 (Tue, 14 Oct 2014) $'
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
import java.util.concurrent.locks.Lock;
41

    
42
import javax.servlet.http.HttpServletRequest;
43

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

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

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

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

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

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

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

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

    
178
      return describeResponse;
179

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
444
    resultPid = pid;
445
    
446
    logMetacat.debug("create() complete for object: " + pid.getValue());
447

    
448
    return resultPid;
449
  }
450

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

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

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

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

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

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

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

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

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

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

    
818
      boolean allowed = false;
819
      
820
      // must have a session in order to check admin 
821
      if (session == null) {
822
         logMetacat.debug("In isAdminAuthorized(), session is null ");
823
         return false;
824
      }
825
      
826
      logMetacat.debug("In isAdminAuthorized(), checking CN or MN authorization for " +
827
           session.getSubject().getValue());
828
      
829
      // check if this is the node calling itself (MN)
830
      allowed = isNodeAdmin(session);
831
      
832
      // check the CN list
833
      if (!allowed) {
834
	      List<Node> nodes = null;
835

    
836
    	  try {
837
		      // are we allowed to do this? only CNs are allowed
838
		      CNode cn = D1Client.getCN();
839
		      nodes = cn.listNodes().getNodeList();
840
    	  }
841
	      catch (Throwable e) {
842
	    	  logMetacat.warn(e.getMessage());
843
	    	  return false;  
844
	      }
845
		      
846
	      if ( nodes == null ) {
847
	    	  return false;
848
	          //throw new ServiceFailure("4852", "Couldn't get node list.");
849
	      }
850
	      
851
	      // find the node in the node list
852
	      for ( Node node : nodes ) {
853
	          
854
	          NodeReference nodeReference = node.getIdentifier();
855
	          logMetacat.debug("In isAdminAuthorized(), Node reference is: " + nodeReference.getValue());
856
	          
857
	          Subject subject = session.getSubject();
858
	          
859
	          if (node.getType() == NodeType.CN) {
860
	              List<Subject> nodeSubjects = node.getSubjectList();
861
	              
862
	              // check if the session subject is in the node subject list
863
	              for (Subject nodeSubject : nodeSubjects) {
864
	                  logMetacat.debug("In isAdminAuthorized(), comparing subjects: " +
865
	                      nodeSubject.getValue() + " and " + subject.getValue());
866
	                  if ( nodeSubject.equals(subject) ) {
867
	                      allowed = true; // subject of session == target node subject
868
	                      break;
869
	                      
870
	                  }
871
	              }              
872
	          }
873
	      }
874
      }
875
      
876
      return allowed;
877
  }
878
  
879
  /**
880
   * Test if the user identified by the provided token has administrative authorization 
881
   * on this node because they are calling themselves
882
   * 
883
   * @param session - the Session object containing the credentials for the Subject
884
   * 
885
   * @return true if the user is this node
886
   * @throws ServiceFailure 
887
   * @throws NotImplemented 
888
   */
889
  public boolean isNodeAdmin(Session session) throws NotImplemented, ServiceFailure {
890

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

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

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

    
1074
  /** 
1075
   * Determine if a given object should be treated as an XML science metadata
1076
   * object. 
1077
   * 
1078
   * @param sysmeta - the SystemMetadata describing the object
1079
   * @return true if the object should be treated as science metadata
1080
   */
1081
  public static boolean isScienceMetadata(SystemMetadata sysmeta) {
1082
    
1083
    ObjectFormat objectFormat = null;
1084
    boolean isScienceMetadata = false;
1085
    
1086
    try {
1087
      objectFormat = ObjectFormatCache.getInstance().getFormat(sysmeta.getFormatId());
1088
      if ( objectFormat.getFormatType().equals("METADATA") ) {
1089
      	isScienceMetadata = true;
1090
      	
1091
      }
1092
      
1093
       
1094
    } catch (ServiceFailure e) {
1095
      logMetacat.debug("There was a problem determining if the object identified by" + 
1096
          sysmeta.getIdentifier().getValue() + 
1097
          " is science metadata: " + e.getMessage());
1098
    
1099
    } catch (NotFound e) {
1100
      logMetacat.debug("There was a problem determining if the object identified by" + 
1101
          sysmeta.getIdentifier().getValue() + 
1102
          " is science metadata: " + e.getMessage());
1103
    
1104
    }
1105
    
1106
    return isScienceMetadata;
1107

    
1108
  }
1109
  
1110
  /**
1111
   * Check fro whitespace in the given pid.
1112
   * null pids are also invalid by default
1113
   * @param pid
1114
   * @return
1115
   */
1116
  public static boolean isValidIdentifier(Identifier pid) {
1117
	  if (pid != null && pid.getValue() != null && pid.getValue().length() > 0) {
1118
		  return !pid.getValue().matches(".*\\s+.*");
1119
	  } 
1120
	  return false;
1121
  }
1122
  
1123
  
1124
  /**
1125
   * Insert or update an XML document into Metacat
1126
   * 
1127
   * @param xml - the XML document to insert or update
1128
   * @param pid - the identifier to be used for the resulting object
1129
   * 
1130
   * @return localId - the resulting docid of the document created or updated
1131
   * 
1132
   */
1133
  public String insertOrUpdateDocument(String xml, Identifier pid, 
1134
    Session session, String insertOrUpdate) 
1135
    throws ServiceFailure {
1136
    
1137
  	logMetacat.debug("Starting to insert xml document...");
1138
    IdentifierManager im = IdentifierManager.getInstance();
1139

    
1140
    // generate pid/localId pair for sysmeta
1141
    String localId = null;
1142
    
1143
    if(insertOrUpdate.equals("insert")) {
1144
      localId = im.generateLocalId(pid.getValue(), 1);
1145
      
1146
    } else {
1147
      //localid should already exist in the identifier table, so just find it
1148
      try {
1149
        logMetacat.debug("Updating pid " + pid.getValue());
1150
        logMetacat.debug("looking in identifier table for pid " + pid.getValue());
1151
        
1152
        localId = im.getLocalId(pid.getValue());
1153
        
1154
        logMetacat.debug("localId: " + localId);
1155
        //increment the revision
1156
        String docid = localId.substring(0, localId.lastIndexOf("."));
1157
        String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
1158
        int rev = new Integer(revS).intValue();
1159
        rev++;
1160
        docid = docid + "." + rev;
1161
        localId = docid;
1162
        logMetacat.debug("incremented localId: " + localId);
1163
      
1164
      } catch(McdbDocNotFoundException e) {
1165
        throw new ServiceFailure("1030", "D1NodeService.insertOrUpdateDocument(): " +
1166
            "pid " + pid.getValue() + 
1167
            " should have been in the identifier table, but it wasn't: " + 
1168
            e.getMessage());
1169
      
1170
      }
1171
      
1172
    }
1173

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

    
1274
    logMetacat.debug("Case DATA: starting to write to disk.");
1275
	if (locked) {
1276

    
1277
          File dataDirectory = new File(datafilepath);
1278
          dataDirectory.mkdirs();
1279
  
1280
          File newFile = writeStreamToFile(dataDirectory, localId, object);
1281
  
1282
          // TODO: Check that the file size matches SystemMetadata
1283
          // long size = newFile.length();
1284
          // if (size == 0) {
1285
          //     throw new IOException("Uploaded file is 0 bytes!");
1286
          // }
1287
  
1288
          // Register the file in the database (which generates an exception
1289
          // if the localId is not acceptable or other untoward things happen
1290
          try {
1291
            logMetacat.debug("Registering document...");
1292
            DocumentImpl.registerDocument(localId, "BIN", localId,
1293
                    username, groupnames);
1294
            logMetacat.debug("Registration step completed.");
1295
            
1296
          } catch (SQLException e) {
1297
            //newFile.delete();
1298
            logMetacat.debug("SQLE: " + e.getMessage());
1299
            e.printStackTrace(System.out);
1300
            throw new ServiceFailure("1190", "Registration failed: " + 
1301
            		e.getMessage());
1302
            
1303
          } catch (AccessionNumberException e) {
1304
            //newFile.delete();
1305
            logMetacat.debug("ANE: " + e.getMessage());
1306
            e.printStackTrace(System.out);
1307
            throw new ServiceFailure("1190", "Registration failed: " + 
1308
            	e.getMessage());
1309
            
1310
          } catch (Exception e) {
1311
            //newFile.delete();
1312
            logMetacat.debug("Exception: " + e.getMessage());
1313
            e.printStackTrace(System.out);
1314
            throw new ServiceFailure("1190", "Registration failed: " + 
1315
            	e.getMessage());
1316
          }
1317
  
1318
          logMetacat.debug("Logging the creation event.");
1319
          EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, "create");
1320
  
1321
          // Schedule replication for this data file, the "insert" action is important here!
1322
          logMetacat.debug("Scheduling replication.");
1323
          ForceReplicationHandler frh = new ForceReplicationHandler(localId, "insert", false, null);
1324
      }
1325
      
1326
      return localId;
1327
    
1328
  }
1329

    
1330
  /**
1331
   * Insert a systemMetadata document and return its localId
1332
   */
1333
  public void insertSystemMetadata(SystemMetadata sysmeta) 
1334
      throws ServiceFailure {
1335
      
1336
  	  logMetacat.debug("Starting to insert SystemMetadata...");
1337
      sysmeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
1338
      logMetacat.debug("Inserting new system metadata with modified date " + 
1339
          sysmeta.getDateSysMetadataModified());
1340
      
1341
      //insert the system metadata
1342
      try {
1343
        // note: the calling subclass handles the map hazelcast lock/unlock
1344
      	HazelcastService.getInstance().getSystemMetadataMap().put(sysmeta.getIdentifier(), sysmeta);
1345
      	// submit for indexing
1346
        MetacatSolrIndex.getInstance().submit(sysmeta.getIdentifier(), sysmeta, null, true);
1347
      } catch (Exception e) {
1348
          throw new ServiceFailure("1190", e.getMessage());
1349
          
1350
	    }  
1351
  }
1352

    
1353
  /**
1354
   * Update a systemMetadata document
1355
   * 
1356
   * @param sysMeta - the system metadata object in the system to update
1357
   */
1358
    protected void updateSystemMetadata(SystemMetadata sysMeta)
1359
        throws ServiceFailure {
1360

    
1361
        logMetacat.debug("D1NodeService.updateSystemMetadata() called.");
1362
        sysMeta.setDateSysMetadataModified(new Date());
1363
        try {
1364
            HazelcastService.getInstance().getSystemMetadataMap().lock(sysMeta.getIdentifier());
1365
            HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
1366
            // submit for indexing
1367
            MetacatSolrIndex.getInstance().submit(sysMeta.getIdentifier(), sysMeta, null, true);
1368
        } catch (Exception e) {
1369
            throw new ServiceFailure("4862", e.getMessage());
1370

    
1371
        } finally {
1372
            HazelcastService.getInstance().getSystemMetadataMap().unlock(sysMeta.getIdentifier());
1373

    
1374
        }
1375

    
1376
    }
1377
    
1378
	public boolean updateSystemMetadata(Session session, Identifier pid,
1379
			SystemMetadata sysmeta) throws NotImplemented, NotAuthorized,
1380
			ServiceFailure, InvalidRequest, InvalidSystemMetadata, InvalidToken {
1381
		
1382
		// The lock to be used for this identifier
1383
      Lock lock = null;
1384

    
1385
      // TODO: control who can call this?
1386
      if (session == null) {
1387
          //TODO: many of the thrown exceptions do not use the correct error codes
1388
          //check these against the docs and correct them
1389
          throw new NotAuthorized("4861", "No Session - could not authorize for registration." +
1390
                  "  If you are not logged in, please do so and retry the request.");
1391
      }
1392
      
1393
      // verify that guid == SystemMetadata.getIdentifier()
1394
      logMetacat.debug("Comparing guid|sysmeta_guid: " + pid.getValue() + 
1395
          "|" + sysmeta.getIdentifier().getValue());
1396
      
1397
      if (!pid.getValue().equals(sysmeta.getIdentifier().getValue())) {
1398
          throw new InvalidRequest("4863", 
1399
              "The identifier in method call (" + pid.getValue() + 
1400
              ") does not match identifier in system metadata (" +
1401
              sysmeta.getIdentifier().getValue() + ").");
1402
      }
1403

    
1404
      // do the actual update
1405
      this.updateSystemMetadata(sysmeta);
1406
      
1407
      try {
1408
    	  String localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
1409
    	  EventLog.getInstance().log(request.getRemoteAddr(), 
1410
    	          request.getHeader("User-Agent"), session.getSubject().getValue(), 
1411
    	          localId, "updateSystemMetadata");
1412
      } catch (McdbDocNotFoundException e) {
1413
    	  // do nothing, no localId to log with
1414
    	  logMetacat.warn("Could not log 'updateSystemMetadata' event because no localId was found for pid: " + pid.getValue());
1415
      }
1416
      
1417
      return true;
1418
	}
1419
  
1420
  /**
1421
   * Given a Permission, returns a list of all permissions that it encompasses
1422
   * Permissions are hierarchical so that WRITE also allows READ.
1423
   * @param permission
1424
   * @return list of included Permissions for the given permission
1425
   */
1426
  protected List<Permission> expandPermissions(Permission permission) {
1427
	  	List<Permission> expandedPermissions = new ArrayList<Permission>();
1428
	    if (permission.equals(Permission.READ)) {
1429
	    	expandedPermissions.add(Permission.READ);
1430
	    }
1431
	    if (permission.equals(Permission.WRITE)) {
1432
	    	expandedPermissions.add(Permission.READ);
1433
	    	expandedPermissions.add(Permission.WRITE);
1434
	    }
1435
	    if (permission.equals(Permission.CHANGE_PERMISSION)) {
1436
	    	expandedPermissions.add(Permission.READ);
1437
	    	expandedPermissions.add(Permission.WRITE);
1438
	    	expandedPermissions.add(Permission.CHANGE_PERMISSION);
1439
	    }
1440
	    return expandedPermissions;
1441
  }
1442

    
1443
  /*
1444
   * Write a stream to a file
1445
   * 
1446
   * @param dir - the directory to write to
1447
   * @param fileName - the file name to write to
1448
   * @param data - the object bytes as an input stream
1449
   * 
1450
   * @return newFile - the new file created
1451
   * 
1452
   * @throws ServiceFailure
1453
   */
1454
  private File writeStreamToFile(File dir, String fileName, InputStream data) 
1455
    throws ServiceFailure {
1456
    
1457
    File newFile = new File(dir, fileName);
1458
    logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1459

    
1460
    try {
1461
        if (newFile.createNewFile()) {
1462
          // write data stream to desired file
1463
          OutputStream os = new FileOutputStream(newFile);
1464
          long length = IOUtils.copyLarge(data, os);
1465
          os.flush();
1466
          os.close();
1467
        } else {
1468
          logMetacat.debug("File creation failed, or file already exists.");
1469
          throw new ServiceFailure("1190", "File already exists: " + fileName);
1470
        }
1471
    } catch (FileNotFoundException e) {
1472
      logMetacat.debug("FNF: " + e.getMessage());
1473
      throw new ServiceFailure("1190", "File not found: " + fileName + " " 
1474
                + e.getMessage());
1475
    } catch (IOException e) {
1476
      logMetacat.debug("IOE: " + e.getMessage());
1477
      throw new ServiceFailure("1190", "File was not written: " + fileName 
1478
                + " " + e.getMessage());
1479
    }
1480

    
1481
    return newFile;
1482
  }
1483

    
1484
  /*
1485
   * Returns a list of nodes that have been registered with the DataONE infrastructure
1486
   * that match the given session subject
1487
   * @return nodes - List of nodes from the registry with a matching session subject
1488
   * 
1489
   * @throws ServiceFailure
1490
   * @throws NotImplemented
1491
   */
1492
  protected List<Node> listNodesBySubject(Subject subject) 
1493
      throws ServiceFailure, NotImplemented {
1494
      List<Node> nodeList = new ArrayList<Node>();
1495
      
1496
      CNode cn = D1Client.getCN();
1497
      List<Node> nodes = cn.listNodes().getNodeList();
1498
      
1499
      // find the node in the node list
1500
      for ( Node node : nodes ) {
1501
          
1502
          List<Subject> nodeSubjects = node.getSubjectList();
1503
          if (nodeSubjects != null) {    
1504
	          // check if the session subject is in the node subject list
1505
	          for (Subject nodeSubject : nodeSubjects) {
1506
	              if ( nodeSubject.equals(subject) ) { // subject of session == node subject
1507
	                  nodeList.add(node);  
1508
	              }                              
1509
	          }
1510
          }
1511
      }
1512
      
1513
      return nodeList;
1514
      
1515
  }
1516

    
1517
  /**
1518
   * Archives an object, where the object is either a 
1519
   * data object or a science metadata object.
1520
   * 
1521
   * @param session - the Session object containing the credentials for the Subject
1522
   * @param pid - The object identifier to be archived
1523
   * 
1524
   * @return pid - the identifier of the object used for the archiving
1525
   * 
1526
   * @throws InvalidToken
1527
   * @throws ServiceFailure
1528
   * @throws NotAuthorized
1529
   * @throws NotFound
1530
   * @throws NotImplemented
1531
   * @throws InvalidRequest
1532
   */
1533
  public Identifier archive(Session session, Identifier pid) 
1534
      throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, NotImplemented {
1535

    
1536
      String localId = null;
1537
      boolean allowed = false;
1538
      String username = Constants.SUBJECT_PUBLIC;
1539
      String[] groupnames = null;
1540
      if (session == null) {
1541
      	throw new InvalidToken("1330", "No session has been provided");
1542
      } else {
1543
          username = session.getSubject().getValue();
1544
          if (session.getSubjectInfo() != null) {
1545
              List<Group> groupList = session.getSubjectInfo().getGroupList();
1546
              if (groupList != null) {
1547
                  groupnames = new String[groupList.size()];
1548
                  for (int i = 0; i < groupList.size(); i++) {
1549
                      groupnames[i] = groupList.get(i).getGroupName();
1550
                  }
1551
              }
1552
          }
1553
      }
1554

    
1555
      // do we have a valid pid?
1556
      if (pid == null || pid.getValue().trim().equals("")) {
1557
          throw new ServiceFailure("1350", "The provided identifier was invalid.");
1558
      }
1559

    
1560
      // check for the existing identifier
1561
      try {
1562
          localId = IdentifierManager.getInstance().getLocalId(pid.getValue());
1563
      } catch (McdbDocNotFoundException e) {
1564
          throw new NotFound("1340", "The object with the provided " + "identifier was not found.");
1565
      }
1566

    
1567
      // does the subject have archive (a D1 CHANGE_PERMISSION level) privileges on the pid?
1568
      try {
1569
			allowed = isAuthorized(session, pid, Permission.CHANGE_PERMISSION);
1570
		} catch (InvalidRequest e) {
1571
          throw new ServiceFailure("1350", e.getDescription());
1572
		}
1573
          
1574

    
1575
      if (allowed) {
1576
          try {
1577
              // archive the document
1578
              DocumentImpl.delete(localId, null, null, null, false);
1579
              EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), username, localId, Event.DELETE.xmlValue());
1580

    
1581
              // archive it
1582
              SystemMetadata sysMeta = HazelcastService.getInstance().getSystemMetadataMap().get(pid);
1583
              sysMeta.setArchived(true);
1584
              sysMeta.setDateSysMetadataModified(Calendar.getInstance().getTime());
1585
              HazelcastService.getInstance().getSystemMetadataMap().put(pid, sysMeta);
1586
              // submit for indexing
1587
              // DocumentImpl call above should do this.
1588
              // see: https://projects.ecoinformatics.org/ecoinfo/issues/6030
1589
              //HazelcastService.getInstance().getIndexQueue().add(sysMeta);
1590
              
1591
          } catch (McdbDocNotFoundException e) {
1592
              throw new NotFound("1340", "The provided identifier was invalid.");
1593

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

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

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

    
1604
      } else {
1605
          throw new NotAuthorized("1320", "The provided identity does not have " + "permission to archive the object on the Node.");
1606
      }
1607

    
1608
      return pid;
1609
  }
1610

    
1611

    
1612
}
(2-2/7)